_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
f54bd6b92377e033d5121d69268b3f79a9e911410dbfb49a92a873c9c9077ad0
nikodemus/SBCL
pack.lisp
;;;; This file contains the implementation-independent code for Pack phase in the compiler . Pack is responsible for assigning TNs to ;;;; storage allocations or "register allocation". 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!C") ;;; for debugging: some parameters controlling which optimizations we ;;; attempt (defvar *pack-assign-costs* t) (defvar *pack-optimize-saves* t) FIXME : Perhaps should be renamed to SB - TWEAK and these should be made conditional on SB - TWEAK . (declaim (ftype (function (component) index) ir2-block-count)) ;;;; conflict determination Return true if the element at the specified offset in SB has a conflict with TN : -- If a component - live TN (: COMPONENT kind ) , then iterate over all the blocks . If the element at OFFSET is used anywhere in ;;; any of the component's blocks (always-live /= 0), then there ;;; is a conflict. -- If TN is global ( true ) , then iterate over the blocks TN is live in ( using TN - GLOBAL - CONFLICTS ) . If the TN is live ;;; everywhere in the block (:LIVE), then there is a conflict ;;; if the element at offset is used anywhere in the block ( Always - Live /= 0 ) . Otherwise , we use the local TN number for TN in block to find whether TN has a conflict at Offset in ;;; that block. -- If TN is local , then we just check for a conflict in the block ;;; it is local to. (defun offset-conflicts-in-sb (tn sb offset) (declare (type tn tn) (type finite-sb sb) (type index offset)) (let ((confs (tn-global-conflicts tn)) (kind (tn-kind tn))) (cond ((eq kind :component) (let ((loc-live (svref (finite-sb-always-live sb) offset))) (dotimes (i (ir2-block-count *component-being-compiled*) nil) (when (/= (sbit loc-live i) 0) (return t))))) (confs (let ((loc-confs (svref (finite-sb-conflicts sb) offset)) (loc-live (svref (finite-sb-always-live sb) offset))) (do ((conf confs (global-conflicts-next-tnwise conf))) ((null conf) nil) (let* ((block (global-conflicts-block conf)) (num (ir2-block-number block))) (if (eq (global-conflicts-kind conf) :live) (when (/= (sbit loc-live num) 0) (return t)) (when (/= (sbit (svref loc-confs num) (global-conflicts-number conf)) 0) (return t))))))) (t (/= (sbit (svref (svref (finite-sb-conflicts sb) offset) (ir2-block-number (tn-local tn))) (tn-local-number tn)) 0))))) Return true if TN has a conflict in SC at the specified offset . (defun conflicts-in-sc (tn sc offset) (declare (type tn tn) (type sc sc) (type index offset)) (let ((sb (sc-sb sc))) (dotimes (i (sc-element-size sc) nil) (when (offset-conflicts-in-sb tn sb (+ offset i)) (return t))))) Add TN 's conflicts into the conflicts for the location at OFFSET in SC . We iterate over each location in TN , adding to the ;;; conflicts for that location: -- If TN is a : COMPONENT TN , then iterate over all the blocks , ;;; setting all of the local conflict bits and the always-live bit. This records a conflict with any TN that has a LTN number in ;;; the block, as well as with :ALWAYS-LIVE and :ENVIRONMENT TNs. -- If TN is global , then iterate over the blocks TN is live in . In ;;; addition to setting the always-live bit to represent the conflict ;;; with TNs live throughout the block, we also set bits in the local conflicts . If TN is : ALWAYS - LIVE in the block , we set all ;;; the bits, otherwise we OR in the local conflict bits. -- If the TN is local , then we just do the block it is local to , ;;; setting always-live and OR'ing in the local conflicts. (defun add-location-conflicts (tn sc offset optimize) (declare (type tn tn) (type sc sc) (type index offset)) (let ((confs (tn-global-conflicts tn)) (sb (sc-sb sc)) (kind (tn-kind tn))) (dotimes (i (sc-element-size sc)) (declare (type index i)) (let* ((this-offset (+ offset i)) (loc-confs (svref (finite-sb-conflicts sb) this-offset)) (loc-live (svref (finite-sb-always-live sb) this-offset))) (cond ((eq kind :component) (dotimes (num (ir2-block-count *component-being-compiled*)) (declare (type index num)) (setf (sbit loc-live num) 1) (set-bit-vector (svref loc-confs num)))) (confs (do ((conf confs (global-conflicts-next-tnwise conf))) ((null conf)) (let* ((block (global-conflicts-block conf)) (num (ir2-block-number block)) (local-confs (svref loc-confs num))) (declare (type local-tn-bit-vector local-confs)) (setf (sbit loc-live num) 1) (if (eq (global-conflicts-kind conf) :live) (set-bit-vector local-confs) (bit-ior local-confs (global-conflicts-conflicts conf) t))))) (t (let ((num (ir2-block-number (tn-local tn)))) (setf (sbit loc-live num) 1) (bit-ior (the local-tn-bit-vector (svref loc-confs num)) (tn-local-conflicts tn) t)))) ;; Calculating ALWAYS-LIVE-COUNT is moderately expensive, and ;; currently the information isn't used unless (> SPEED ;; COMPILE-SPEED). (when optimize (setf (svref (finite-sb-always-live-count sb) this-offset) (find-location-usage sb this-offset)))))) (values)) A rought measure of how much a given OFFSET in SB is currently ;; used. Current implementation counts the amount of blocks where the ;; offset has been marked as ALWAYS-LIVE. (defun find-location-usage (sb offset) (declare (optimize speed)) (declare (type sb sb) (type index offset)) (let* ((always-live (svref (finite-sb-always-live sb) offset))) (declare (simple-bit-vector always-live)) (count 1 always-live))) ;;; Return the total number of IR2-BLOCKs in COMPONENT. (defun ir2-block-count (component) (declare (type component component)) (do ((2block (block-info (block-next (component-head component))) (ir2-block-next 2block))) ((null 2block) (error "What? No ir2 blocks have a non-nil number?")) (when (ir2-block-number 2block) (return (1+ (ir2-block-number 2block)))))) ;;; Ensure that the conflicts vectors for each :FINITE SB are large ;;; enough for the number of blocks allocated. Also clear any old ;;; conflicts and reset the current size to the initial size. (defun init-sb-vectors (component) (let ((nblocks (ir2-block-count component))) (dolist (sb *backend-sb-list*) (unless (eq (sb-kind sb) :non-packed) (let* ((conflicts (finite-sb-conflicts sb)) (always-live (finite-sb-always-live sb)) (always-live-count (finite-sb-always-live-count sb)) (max-locs (length conflicts)) (last-count (finite-sb-last-block-count sb))) (unless (zerop max-locs) (let ((current-size (length (the simple-vector (svref conflicts 0))))) (cond ((> nblocks current-size) (let ((new-size (max nblocks (* current-size 2)))) (declare (type index new-size)) (dotimes (i max-locs) (declare (type index i)) (let ((new-vec (make-array new-size))) (let ((old (svref conflicts i))) (declare (simple-vector old)) (dotimes (j current-size) (declare (type index j)) (setf (svref new-vec j) (clear-bit-vector (svref old j))))) (do ((j current-size (1+ j))) ((= j new-size)) (declare (type index j)) (setf (svref new-vec j) (make-array local-tn-limit :element-type 'bit :initial-element 0))) (setf (svref conflicts i) new-vec)) (setf (svref always-live i) (make-array new-size :element-type 'bit :initial-element 0)) (setf (svref always-live-count i) 0)))) (t (dotimes (i (finite-sb-current-size sb)) (declare (type index i)) (let ((conf (svref conflicts i))) (declare (simple-vector conf)) (dotimes (j last-count) (declare (type index j)) (clear-bit-vector (svref conf j)))) (clear-bit-vector (svref always-live i)) (setf (svref always-live-count i) 0)))))) (setf (finite-sb-last-block-count sb) nblocks) (setf (finite-sb-current-size sb) (sb-size sb)) (setf (finite-sb-last-offset sb) 0)))))) Expand the : UNBOUNDED SB backing SC by either the initial size or the SC element size , whichever is larger . If NEEDED - SIZE is ;;; larger, then use that size. (defun grow-sc (sc &optional (needed-size 0)) (declare (type sc sc) (type index needed-size)) (let* ((sb (sc-sb sc)) (size (finite-sb-current-size sb)) (align-mask (1- (sc-alignment sc))) (inc (max (sb-size sb) (+ (sc-element-size sc) (- (logandc2 (+ size align-mask) align-mask) size)) (- needed-size size))) (new-size (+ size inc)) (conflicts (finite-sb-conflicts sb)) (block-size (if (zerop (length conflicts)) (ir2-block-count *component-being-compiled*) (length (the simple-vector (svref conflicts 0)))))) (declare (type index inc new-size)) (aver (eq (sb-kind sb) :unbounded)) (when (> new-size (length conflicts)) (let ((new-conf (make-array new-size))) (replace new-conf conflicts) (do ((i size (1+ i))) ((= i new-size)) (declare (type index i)) (let ((loc-confs (make-array block-size))) (dotimes (j block-size) (setf (svref loc-confs j) (make-array local-tn-limit :initial-element 0 :element-type 'bit))) (setf (svref new-conf i) loc-confs))) (setf (finite-sb-conflicts sb) new-conf)) (let ((new-live (make-array new-size))) (replace new-live (finite-sb-always-live sb)) (do ((i size (1+ i))) ((= i new-size)) (setf (svref new-live i) (make-array block-size :initial-element 0 :element-type 'bit))) (setf (finite-sb-always-live sb) new-live)) (let ((new-live-count (make-array new-size))) (declare (optimize speed)) ;; FILL deftransform (replace new-live-count (finite-sb-always-live-count sb)) (fill new-live-count 0 :start size) (setf (finite-sb-always-live-count sb) new-live-count)) (let ((new-tns (make-array new-size :initial-element nil))) (replace new-tns (finite-sb-live-tns sb)) (fill (finite-sb-live-tns sb) nil) (setf (finite-sb-live-tns sb) new-tns))) (setf (finite-sb-current-size sb) new-size)) (values)) ;;;; internal errors ;;; Give someone a hard time because there isn't any load function defined to move from SRC to DEST . (defun no-load-fun-error (src dest) (let* ((src-sc (tn-sc src)) (src-name (sc-name src-sc)) (dest-sc (tn-sc dest)) (dest-name (sc-name dest-sc))) (cond ((eq (sb-kind (sc-sb src-sc)) :non-packed) (unless (member src-sc (sc-constant-scs dest-sc)) (error "loading from an invalid constant SC?~@ VM definition inconsistent, try recompiling.")) (error "no load function defined to load SC ~S ~ from its constant SC ~S" dest-name src-name)) ((member src-sc (sc-alternate-scs dest-sc)) (error "no load function defined to load SC ~S from its ~ alternate SC ~S" dest-name src-name)) ((member dest-sc (sc-alternate-scs src-sc)) (error "no load function defined to save SC ~S in its ~ alternate SC ~S" src-name dest-name)) (t ;; FIXME: "VM definition is inconsistent" shouldn't be a possibility in SBCL . (error "loading to/from SCs that aren't alternates?~@ VM definition is inconsistent, try recompiling."))))) Called when we failed to pack TN . If RESTRICTED is true , then we are restricted to pack TN in its SC . (defun failed-to-pack-error (tn restricted) (declare (type tn tn)) (let* ((sc (tn-sc tn)) (scs (cons sc (sc-alternate-scs sc)))) (cond (restricted (error "failed to pack restricted TN ~S in its SC ~S" tn (sc-name sc))) (t (aver (not (find :unbounded scs :key (lambda (x) (sb-kind (sc-sb x)))))) (let ((ptype (tn-primitive-type tn))) (cond (ptype (aver (member (sc-number sc) (primitive-type-scs ptype))) (error "SC ~S doesn't have any :UNBOUNDED alternate SCs, but is~@ a SC for primitive-type ~S." (sc-name sc) (primitive-type-name ptype))) (t (error "SC ~S doesn't have any :UNBOUNDED alternate SCs." (sc-name sc))))))))) Return a list of format arguments describing how TN is used in OP 's VOP . (defun describe-tn-use (loc tn op) (let* ((vop (tn-ref-vop op)) (args (vop-args vop)) (results (vop-results vop)) (name (with-output-to-string (stream) (print-tn-guts tn stream))) (2comp (component-info *component-being-compiled*)) temp) (cond ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-tn)) `("~2D: ~A (~:R argument)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn results :key #'tn-ref-tn)) `("~2D: ~A (~:R result)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-load-tn)) `("~2D: ~A (~:R argument load TN)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn results :key #'tn-ref-load-tn)) `("~2D: ~A (~:R result load TN)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn (vop-temps vop) :key #'tn-ref-tn)) `("~2D: ~A (temporary ~A)" ,loc ,name ,(operand-parse-name (elt (vop-parse-temps (vop-parse-or-lose (vop-info-name (vop-info vop)))) temp)))) ((eq (tn-kind tn) :component) `("~2D: ~A (component live)" ,loc ,name)) ((position-in #'tn-next tn (ir2-component-wired-tns 2comp)) `("~2D: ~A (wired)" ,loc ,name)) ((position-in #'tn-next tn (ir2-component-restricted-tns 2comp)) `("~2D: ~A (restricted)" ,loc ,name)) (t `("~2D: not referenced?" ,loc))))) If load TN packing fails , try to give a helpful error message . We find a TN in each location that conflicts , and print it . (defun failed-to-pack-load-tn-error (scs op) (declare (list scs) (type tn-ref op)) (collect ((used) (unused)) (dolist (sc scs) (let* ((sb (sc-sb sc)) (confs (finite-sb-live-tns sb))) (aver (eq (sb-kind sb) :finite)) (dolist (el (sc-locations sc)) (declare (type index el)) (let ((conf (load-tn-conflicts-in-sc op sc el t))) (if conf (used (describe-tn-use el conf op)) (do ((i el (1+ i)) (end (+ el (sc-element-size sc)))) ((= i end) (unused el)) (declare (type index i end)) (let ((victim (svref confs i))) (when victim (used (describe-tn-use el victim op)) (return t))))))))) (multiple-value-bind (arg-p n more-p costs load-scs incon) (get-operand-info op) (declare (ignore costs load-scs)) (aver (not more-p)) , or ~:;,~]~ } ~ ] to~@ the ~S VOP,~@ ~:[since all SC elements are in use:~:{~%~@?~}~%~;~ ~:*but these SC elements are not in use:~% ~S~%Bug?~*~]~ ~:[~;~@ Current cost info inconsistent with that in effect at compile ~ time. Recompile.~%Compilation order may be incorrect.~]" (mapcar #'sc-name scs) n arg-p (vop-info-name (vop-info (tn-ref-vop op))) (unused) (used) incon)))) ;;; This is called when none of the SCs that we can load OP into are ;;; allowed by OP's primitive-type. (defun no-load-scs-allowed-by-primitive-type-error (ref) (declare (type tn-ref ref)) (let* ((tn (tn-ref-tn ref)) (ptype (tn-primitive-type tn))) (multiple-value-bind (arg-p pos more-p costs load-scs incon) (get-operand-info ref) (declare (ignore costs)) (aver (not more-p)) ] to VOP:~ ~% ~S,~@ since the TN's primitive type ~S doesn't allow any of the SCs~@ allowed by the operand restriction:~% ~S~ ~:[~;~@ Current cost info inconsistent with that in effect at compile ~ time. Recompile.~%Compilation order may be incorrect.~]" tn pos arg-p (template-name (vop-info (tn-ref-vop ref))) (primitive-type-name ptype) (mapcar #'sc-name (listify-restrictions load-scs)) incon)))) ;;;; register saving Do stuff to note that TN is spilled at VOP for the debugger 's benefit . (defun note-spilled-tn (tn vop) (when (and (tn-leaf tn) (vop-save-set vop)) (let ((2comp (component-info *component-being-compiled*))) (setf (gethash tn (ir2-component-spilled-tns 2comp)) t) (pushnew tn (gethash vop (ir2-component-spilled-vops 2comp))))) (values)) Make a save TN for TN , pack it , and return it . We copy various conflict information from the TN so that pack does the right ;;; thing. (defun pack-save-tn (tn) (declare (type tn tn)) (let ((res (make-tn 0 :save nil nil))) (dolist (alt (sc-alternate-scs (tn-sc tn)) (error "no unbounded alternate for SC ~S" (sc-name (tn-sc tn)))) (when (eq (sb-kind (sc-sb alt)) :unbounded) (setf (tn-save-tn tn) res) (setf (tn-save-tn res) tn) (setf (tn-sc res) alt) (pack-tn res t nil) (return res))))) Find the load function for moving from SRC to DEST and emit a MOVE - OPERAND VOP with that function as its info arg . (defun emit-operand-load (node block src dest before) (declare (type node node) (type ir2-block block) (type tn src dest) (type (or vop null) before)) (emit-load-template node block (template-or-lose 'move-operand) src dest (list (or (svref (sc-move-funs (tn-sc dest)) (sc-number (tn-sc src))) (no-load-fun-error src dest))) before) (values)) Find the preceding use of the VOP NAME in the emit order , starting with VOP . We must find the VOP in the same IR1 block . (defun reverse-find-vop (name vop) (do* ((block (vop-block vop) (ir2-block-prev block)) (last vop (ir2-block-last-vop block))) (nil) (aver (eq (ir2-block-block block) (ir2-block-block (vop-block vop)))) (do ((current last (vop-prev current))) ((null current)) (when (eq (vop-info-name (vop-info current)) name) (return-from reverse-find-vop current))))) For TNs that have other than one writer , we save the TN before ;;; each call. If a local call (MOVE-ARGS is :LOCAL-CALL), then we ;;; scan back for the ALLOCATE-FRAME VOP, and emit the save there. ;;; This is necessary because in a self-recursive local call, the ;;; registers holding the current arguments may get trashed by setting ;;; up the call arguments. The ALLOCATE-FRAME VOP marks a place at ;;; which the values are known to be good. (defun save-complex-writer-tn (tn vop) (let ((save (or (tn-save-tn tn) (pack-save-tn tn))) (node (vop-node vop)) (block (vop-block vop)) (next (vop-next vop))) (when (eq (tn-kind save) :specified-save) (setf (tn-kind save) :save)) (aver (eq (tn-kind save) :save)) (emit-operand-load node block tn save (if (eq (vop-info-move-args (vop-info vop)) :local-call) (reverse-find-vop 'allocate-frame vop) vop)) (emit-operand-load node block save tn next))) Return a VOP after which is an OK place to save the value of TN . ;;; For correctness, it is only required that this location be after ;;; any possible write and before any possible restore location. ;;; In practice , we return the unique writer VOP , but give up if the TN is ever read by a VOP with MOVE - ARGS : LOCAL - CALL . This prevents ;;; us from being confused by non-tail local calls. ;;; ;;; When looking for writes, we have to ignore uses of MOVE-OPERAND, ;;; since they will correspond to restores that we have already done. (defun find-single-writer (tn) (declare (type tn tn)) (do ((write (tn-writes tn) (tn-ref-next write)) (res nil)) ((null write) (when (and res (do ((read (tn-reads tn) (tn-ref-next read))) ((not read) t) (when (eq (vop-info-move-args (vop-info (tn-ref-vop read))) :local-call) (return nil)))) (tn-ref-vop res))) (unless (eq (vop-info-name (vop-info (tn-ref-vop write))) 'move-operand) (when res (return nil)) (setq res write)))) Try to save TN at a single location . If we succeed , return T , otherwise NIL . (defun save-single-writer-tn (tn) (declare (type tn tn)) (let* ((old-save (tn-save-tn tn)) (save (or old-save (pack-save-tn tn))) (writer (find-single-writer tn))) (when (and writer (or (not old-save) (eq (tn-kind old-save) :specified-save))) (emit-operand-load (vop-node writer) (vop-block writer) tn save (vop-next writer)) (setf (tn-kind save) :save-once) t))) Restore a TN with a : SAVE - ONCE save TN . (defun restore-single-writer-tn (tn vop) (declare (type tn) (type vop vop)) (let ((save (tn-save-tn tn))) (aver (eq (tn-kind save) :save-once)) (emit-operand-load (vop-node vop) (vop-block vop) save tn (vop-next vop))) (values)) Save a single TN that needs to be saved , choosing save - once if ;;; appropriate. This is also called by SPILL-AND-PACK-LOAD-TN. (defun basic-save-tn (tn vop) (declare (type tn tn) (type vop vop)) (let ((save (tn-save-tn tn))) (cond ((and save (eq (tn-kind save) :save-once)) (restore-single-writer-tn tn vop)) ((save-single-writer-tn tn) (restore-single-writer-tn tn vop)) (t (save-complex-writer-tn tn vop)))) (values)) Scan over the VOPs in BLOCK , emiting saving code for TNs noted in the codegen info that are packed into saved SCs . (defun emit-saves (block) (declare (type ir2-block block)) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (when (eq (vop-info-save-p (vop-info vop)) t) (do-live-tns (tn (vop-save-set vop) block) (when (and (sc-save-p (tn-sc tn)) (not (eq (tn-kind tn) :component))) (basic-save-tn tn vop))))) (values)) ;;;; optimized saving Save TN if it is n't a single - writer TN that has already been saved . If multi - write , we insert the save BEFORE the specified VOP . CONTEXT is a VOP used to tell which node / block to use for the new VOP . (defun save-if-necessary (tn before context) (declare (type tn tn) (type (or vop null) before) (type vop context)) (let ((save (tn-save-tn tn))) (when (eq (tn-kind save) :specified-save) (setf (tn-kind save) :save)) (aver (member (tn-kind save) '(:save :save-once))) (unless (eq (tn-kind save) :save-once) (or (save-single-writer-tn tn) (emit-operand-load (vop-node context) (vop-block context) tn save before)))) (values)) Load the TN from its save location , allocating one if necessary . The load is inserted BEFORE the specified VOP . CONTEXT is a VOP used to tell which node / block to use for the new VOP . (defun restore-tn (tn before context) (declare (type tn tn) (type (or vop null) before) (type vop context)) (let ((save (or (tn-save-tn tn) (pack-save-tn tn)))) (emit-operand-load (vop-node context) (vop-block context) save tn before)) (values)) ;;; Start scanning backward at the end of BLOCK, looking which TNs are ;;; live and looking for places where we have to save. We manipulate two sets : SAVES and RESTORES . ;;; ;;; SAVES is a set of all the TNs that have to be saved because they ;;; are restored after some call. We normally delay saving until the ;;; beginning of the block, but we must save immediately if we see a write of the saved TN . We also immediately save all TNs and exit ;;; when we see a NOTE-ENVIRONMENT-START VOP, since saves can't be ;;; done before the environment is properly initialized. ;;; RESTORES is a set of all the TNs read ( and not written ) between ;;; here and the next call, i.e. the set of TNs that must be restored when we reach the next ( earlier ) call VOP . Unlike SAVES , this set ;;; is cleared when we do the restoring after a call. Any TNs that were in RESTORES are moved into SAVES to ensure that they are ;;; saved at some point. ;;; SAVES and RESTORES are represented using both a list and a ;;; bit-vector so that we can quickly iterate and test for membership. The incoming SAVES and RESTORES args are used for computing these ;;; sets (the initial contents are ignored.) ;;; When we hit a VOP with : COMPUTE - ONLY SAVE - P ( an internal error ;;; location), we pretend that all live TNs were read, unless (= speed 3 ) , in which case we mark all the TNs that are live but not ;;; restored as spilled. (defun optimized-emit-saves-block (block saves restores) (declare (type ir2-block block) (type simple-bit-vector saves restores)) (let ((1block (ir2-block-block block)) (saves-list ()) (restores-list ()) (skipping nil)) (declare (list saves-list restores-list)) (clear-bit-vector saves) (clear-bit-vector restores) (do-live-tns (tn (ir2-block-live-in block) block) (when (and (sc-save-p (tn-sc tn)) (not (eq (tn-kind tn) :component))) (let ((num (tn-number tn))) (setf (sbit restores num) 1) (push tn restores-list)))) (do ((block block (ir2-block-prev block)) (prev nil block)) ((not (eq (ir2-block-block block) 1block)) (aver (not skipping)) (dolist (save saves-list) (let ((start (ir2-block-start-vop prev))) (save-if-necessary save start start))) prev) (do ((vop (ir2-block-last-vop block) (vop-prev vop))) ((null vop)) (let ((info (vop-info vop))) (case (vop-info-name info) (allocate-frame (aver skipping) (setq skipping nil)) (note-environment-start (aver (not skipping)) (dolist (save saves-list) (save-if-necessary save (vop-next vop) vop)) (return-from optimized-emit-saves-block block))) (unless skipping (do ((write (vop-results vop) (tn-ref-across write))) ((null write)) (let* ((tn (tn-ref-tn write)) (num (tn-number tn))) (unless (zerop (sbit restores num)) (setf (sbit restores num) 0) (setq restores-list (delete tn restores-list :test #'eq))) (unless (zerop (sbit saves num)) (setf (sbit saves num) 0) (save-if-necessary tn (vop-next vop) vop) (setq saves-list (delete tn saves-list :test #'eq)))))) (macrolet ((save-note-read (tn) `(let* ((tn ,tn) (num (tn-number tn))) (when (and (sc-save-p (tn-sc tn)) (zerop (sbit restores num)) (not (eq (tn-kind tn) :component))) (setf (sbit restores num) 1) (push tn restores-list))))) (case (vop-info-save-p info) ((t) (dolist (tn restores-list) (restore-tn tn (vop-next vop) vop) (let ((num (tn-number tn))) (when (zerop (sbit saves num)) (push tn saves-list) (setf (sbit saves num) 1)))) (setq restores-list nil) (clear-bit-vector restores)) (:compute-only (cond ((policy (vop-node vop) (= speed 3)) (do-live-tns (tn (vop-save-set vop) block) (when (zerop (sbit restores (tn-number tn))) (note-spilled-tn tn vop)))) (t (do-live-tns (tn (vop-save-set vop) block) (save-note-read tn)))))) (if (eq (vop-info-move-args info) :local-call) (setq skipping t) (do ((read (vop-args vop) (tn-ref-across read))) ((null read)) (save-note-read (tn-ref-tn read)))))))))) ;;; This is like EMIT-SAVES, only different. We avoid redundant saving ;;; within the block, and don't restore values that aren't used before ;;; the next call. This function is just the top level loop over the ;;; blocks in the component, which locates blocks that need saving ;;; done. (defun optimized-emit-saves (component) (declare (type component component)) (let* ((gtn-count (1+ (ir2-component-global-tn-counter (component-info component)))) (saves (make-array gtn-count :element-type 'bit)) (restores (make-array gtn-count :element-type 'bit)) (block (ir2-block-prev (block-info (component-tail component)))) (head (block-info (component-head component)))) (loop (when (eq block head) (return)) (when (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop) nil) (when (eq (vop-info-save-p (vop-info vop)) t) (return t))) (setq block (optimized-emit-saves-block block saves restores))) (setq block (ir2-block-prev block))))) ;;; Iterate over the normal TNs, finding the cost of packing on the ;;; stack in units of the number of references. We count all references as +1 , and subtract out REGISTER - SAVE - PENALTY for each ;;; place where we would have to save a register. (defun assign-tn-costs (component) (do-ir2-blocks (block component) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (when (eq (vop-info-save-p (vop-info vop)) t) (do-live-tns (tn (vop-save-set vop) block) (decf (tn-cost tn) *backend-register-save-penalty*))))) (do ((tn (ir2-component-normal-tns (component-info component)) (tn-next tn))) ((null tn)) (let ((cost (tn-cost tn))) (declare (fixnum cost)) (do ((ref (tn-reads tn) (tn-ref-next ref))) ((null ref)) (incf cost)) (do ((ref (tn-writes tn) (tn-ref-next ref))) ((null ref)) (incf cost)) (setf (tn-cost tn) cost)))) ;;; Iterate over the normal TNs, storing the depth of the deepest loop that the TN is used in TN - LOOP - DEPTH . (defun assign-tn-depths (component) (when *loop-analyze* (do-ir2-blocks (block component) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (flet ((find-all-tns (head-fun) (collect ((tns)) (do ((ref (funcall head-fun vop) (tn-ref-across ref))) ((null ref)) (tns (tn-ref-tn ref))) (tns)))) (dolist (tn (nconc (find-all-tns #'vop-args) (find-all-tns #'vop-results) (find-all-tns #'vop-temps) What does " references in this VOP ;; mean"? Probably something that isn't ;; useful in this context, since these TN - REFs are linked with TN - REF - NEXT instead of TN - REF - ACROSS . --JES 2004 - 09 - 11 ;; (find-all-tns #'vop-refs) )) (setf (tn-loop-depth tn) (max (tn-loop-depth tn) (let* ((ir1-block (ir2-block-block (vop-block vop))) (loop (block-loop ir1-block))) (if loop (loop-depth loop) 0)))))))))) load TN packing ;;; These variables indicate the last location at which we computed the Live - TNs . They hold the BLOCK and VOP values that were passed ;;; to COMPUTE-LIVE-TNS. (defvar *live-block*) (defvar *live-vop*) ;;; If we unpack some TNs, then we mark all affected blocks by ;;; sticking them in this hash-table. This is initially null. We ;;; create the hashtable if we do any unpacking. (defvar *repack-blocks*) (declaim (type list *repack-blocks*)) ;;; Set the LIVE-TNS vectors in all :FINITE SBs to represent the TNs ;;; live at the end of BLOCK. (defun init-live-tns (block) (dolist (sb *backend-sb-list*) (when (eq (sb-kind sb) :finite) (fill (finite-sb-live-tns sb) nil))) (do-live-tns (tn (ir2-block-live-in block) block) (let* ((sc (tn-sc tn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) : we can have " live " TNs that are neither read ;; to nor written from, due to more aggressive (type- ;; directed) constant propagation. Such TNs will never ;; be assigned an offset nor be in conflict with anything. ;; ;; Ideally, it seems to me we could make sure these TNs are never allocated in the first place in ;; ASSIGN-LAMBDA-VAR-TNS. (if (tn-offset tn) (do ((offset (tn-offset tn) (1+ offset)) (end (+ (tn-offset tn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (setf (svref (finite-sb-live-tns sb) offset) tn)) (assert (and (null (tn-reads tn)) (null (tn-writes tn)))))))) (setq *live-block* block) (setq *live-vop* (ir2-block-last-vop block)) (values)) ;;; Set the LIVE-TNs in :FINITE SBs to represent the TNs live immediately after the evaluation of VOP in BLOCK , excluding results of the VOP . If VOP is null , then compute the live TNs at ;;; the beginning of the block. Sequential calls on the same block must be in reverse VOP order . (defun compute-live-tns (block vop) (declare (type ir2-block block) (type vop vop)) (unless (eq block *live-block*) (init-live-tns block)) (do ((current *live-vop* (vop-prev current))) ((eq current vop) (do ((res (vop-results vop) (tn-ref-across res))) ((null res)) (let* ((tn (tn-ref-tn res)) (sc (tn-sc tn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) (do ((offset (tn-offset tn) (1+ offset)) (end (+ (tn-offset tn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (setf (svref (finite-sb-live-tns sb) offset) nil)))))) (do ((ref (vop-refs current) (tn-ref-next-ref ref))) ((null ref)) (let ((ltn (tn-ref-load-tn ref))) (when ltn (let* ((sc (tn-sc ltn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) (let ((tns (finite-sb-live-tns sb))) (do ((offset (tn-offset ltn) (1+ offset)) (end (+ (tn-offset ltn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (aver (null (svref tns offset))))))))) (let* ((tn (tn-ref-tn ref)) (sc (tn-sc tn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) (let ((tns (finite-sb-live-tns sb))) (do ((offset (tn-offset tn) (1+ offset)) (end (+ (tn-offset tn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (if (tn-ref-write-p ref) (setf (svref tns offset) nil) (let ((old (svref tns offset))) (aver (or (null old) (eq old tn))) (setf (svref tns offset) tn))))))))) (setq *live-vop* vop) (values)) This is kind of like OFFSET - CONFLICTS - IN - SB , except that it uses the VOP refs to determine whether a Load - TN for OP could be packed ;;; in the specified location, disregarding conflicts with TNs not referenced by this VOP . There is a conflict if either : 1 . The reference is a result , and the same location is either : ;;; -- Used by some other result. ;;; -- Used in any way after the reference (exclusive). 2 . The reference is an argument , and the same location is either : ;;; -- Used by some other argument. ;;; -- Used in any way before the reference (exclusive). ;;; In 1 ( and 2 ) above , the first bullet corresponds to result - result ;;; (and argument-argument) conflicts. We need this case because there are n't any TN - REFs to represent the implicit reading of results or ;;; writing of arguments. ;;; The second bullet corresponds to conflicts with temporaries or ;;; between arguments and results. ;;; ;;; We consider both the TN-REF-TN and the TN-REF-LOAD-TN (if any) to ;;; be referenced simultaneously and in the same way. This causes load - TNs to appear live to the beginning ( or end ) of the VOP , as ;;; appropriate. ;;; We return a conflicting TN if there is a conflict . (defun load-tn-offset-conflicts-in-sb (op sb offset) (declare (type tn-ref op) (type finite-sb sb) (type index offset)) (aver (eq (sb-kind sb) :finite)) (let ((vop (tn-ref-vop op))) (labels ((tn-overlaps (tn) (let ((sc (tn-sc tn)) (tn-offset (tn-offset tn))) (when (and (eq (sc-sb sc) sb) (<= tn-offset offset) (< offset (the index (+ tn-offset (sc-element-size sc))))) tn))) (same (ref) (let ((tn (tn-ref-tn ref)) (ltn (tn-ref-load-tn ref))) (or (tn-overlaps tn) (and ltn (tn-overlaps ltn))))) (is-op (ops) (do ((ops ops (tn-ref-across ops))) ((null ops) nil) (let ((found (same ops))) (when (and found (not (eq ops op))) (return found))))) (is-ref (refs end) (do ((refs refs (tn-ref-next-ref refs))) ((eq refs end) nil) (let ((found (same refs))) (when found (return found)))))) (declare (inline is-op is-ref tn-overlaps)) (if (tn-ref-write-p op) (or (is-op (vop-results vop)) (is-ref (vop-refs vop) op)) (or (is-op (vop-args vop)) (is-ref (tn-ref-next-ref op) nil)))))) Iterate over all the elements in the SB that would be allocated by allocating a TN in SC at Offset , checking for conflict with load - TNs or other TNs ( live in the LIVE - TNS , which must be set ;;; up.) We also return true if there aren't enough locations after Offset to hold a TN in SC . If Ignore - Live is true , then we ignore the live - TNs , considering only references within Op 's VOP . ;;; We return a conflicting TN , or : OVERFLOW if the TN wo n't fit . (defun load-tn-conflicts-in-sc (op sc offset ignore-live) (let* ((sb (sc-sb sc)) (size (finite-sb-current-size sb))) (do ((i offset (1+ i)) (end (+ offset (sc-element-size sc)))) ((= i end) nil) (declare (type index i end)) (let ((res (or (when (>= i size) :overflow) (and (not ignore-live) (svref (finite-sb-live-tns sb) i)) (load-tn-offset-conflicts-in-sb op sb i)))) (when res (return res)))))) If a load - TN for OP is targeted to a legal location in SC , then return the offset , otherwise return NIL . We see whether the target ;;; of the operand is packed, and try that location. There isn't any ;;; need to chain down the target path, since everything is packed ;;; now. ;;; We require the target to be in SC ( and not merely to overlap with SC ) . This prevents SC information from being lost in load TNs ( we wo n't pack a load TN in ANY - REG when it is targeted to a DESCRIPTOR - REG . ) This should n't hurt the code as long as all relevant overlapping SCs are allowed in the operand SC ;;; restriction. (defun find-load-tn-target (op sc) (declare (inline member)) (let ((target (tn-ref-target op))) (when target (let* ((tn (tn-ref-tn target)) (loc (tn-offset tn))) (if (and (eq (tn-sc tn) sc) (member (the index loc) (sc-locations sc)) (not (load-tn-conflicts-in-sc op sc loc nil))) loc nil))))) Select a legal location for a load TN for Op in SC . We just iterate over the SC 's locations . If we ca n't find a legal location , return NIL . (defun select-load-tn-location (op sc) (declare (type tn-ref op) (type sc sc)) Check any target location first . (let ((target (tn-ref-target op))) (when target (let* ((tn (tn-ref-tn target)) (loc (tn-offset tn))) (when (and (eq (sc-sb sc) (sc-sb (tn-sc tn))) (member (the index loc) (sc-locations sc)) (not (load-tn-conflicts-in-sc op sc loc nil))) (return-from select-load-tn-location loc))))) (dolist (loc (sc-locations sc) nil) (unless (load-tn-conflicts-in-sc op sc loc nil) (return loc)))) (defevent unpack-tn "Unpacked a TN to satisfy operand SC restriction.") Make TN 's location the same as for its save TN ( allocating a save TN if necessary . ) Delete any save / restore code that has been emitted thus far . all blocks containing references as needing ;;; to be repacked. (defun unpack-tn (tn) (event unpack-tn) (let ((stn (or (tn-save-tn tn) (pack-save-tn tn)))) (setf (tn-sc tn) (tn-sc stn)) (setf (tn-offset tn) (tn-offset stn)) (flet ((zot (refs) (do ((ref refs (tn-ref-next ref))) ((null ref)) (let ((vop (tn-ref-vop ref))) (if (eq (vop-info-name (vop-info vop)) 'move-operand) (delete-vop vop) (pushnew (vop-block vop) *repack-blocks*)))))) (zot (tn-reads tn)) (zot (tn-writes tn)))) (values)) (defevent unpack-fallback "Unpacked some operand TN.") ;;; This is called by PACK-LOAD-TN where there isn't any location free that we can pack into . What we do is move some live TN in one of ;;; the specified SCs to memory, then mark all blocks that reference the TN as needing repacking . If we succeed , we throw to UNPACKED - TN . If we fail , we return NIL . ;;; We can unpack any live TN that appears in the NORMAL - TNs list ;;; (isn't wired or restricted.) We prefer to unpack TNs that are not used by the VOP . If we ca n't find any such TN , then we unpack some argument or result TN . The only way we can fail is if all locations in SC are used by load - TNs or temporaries in VOP . (defun unpack-for-load-tn (sc op) (declare (type sc sc) (type tn-ref op)) (let ((sb (sc-sb sc)) (normal-tns (ir2-component-normal-tns (component-info *component-being-compiled*))) (node (vop-node (tn-ref-vop op))) (fallback nil)) (flet ((unpack-em (victims) (pushnew (vop-block (tn-ref-vop op)) *repack-blocks*) (dolist (victim victims) (event unpack-tn node) (unpack-tn victim)) (throw 'unpacked-tn nil))) (dolist (loc (sc-locations sc)) (declare (type index loc)) (block SKIP (collect ((victims nil adjoin)) (do ((i loc (1+ i)) (end (+ loc (sc-element-size sc)))) ((= i end)) (declare (type index i end)) (let ((victim (svref (finite-sb-live-tns sb) i))) (when victim (unless (find-in #'tn-next victim normal-tns) (return-from SKIP)) (victims victim)))) (let ((conf (load-tn-conflicts-in-sc op sc loc t))) (cond ((not conf) (unpack-em (victims))) ((eq conf :overflow)) ((not fallback) (cond ((find conf (victims)) (setq fallback (victims))) ((find-in #'tn-next conf normal-tns) (setq fallback (list conf)))))))))) (when fallback (event unpack-fallback node) (unpack-em fallback)))) nil) Try to pack a load TN in the SCs indicated by Load - SCs . If we run out of SCs , then we unpack some TN and try again . We return the packed load TN . ;;; ;;; Note: we allow a Load-TN to be packed in the target location even if that location is in a SC not allowed by the primitive type . ( The SC must still be allowed by the operand restriction . ) This ;;; makes move VOPs more efficient, since we won't do a move from the ;;; stack into a non-descriptor any-reg through a descriptor argument ;;; load-TN. This does give targeting some real semantics, making it ;;; not a pure advisory to pack. It allows pack to do some packing it ;;; wouldn't have done before. (defun pack-load-tn (load-scs op) (declare (type sc-vector load-scs) (type tn-ref op)) (let ((vop (tn-ref-vop op))) (compute-live-tns (vop-block vop) vop)) (let* ((tn (tn-ref-tn op)) (ptype (tn-primitive-type tn)) (scs (svref load-scs (sc-number (tn-sc tn))))) (let ((current-scs scs) (allowed ())) (loop (cond ((null current-scs) (unless allowed (no-load-scs-allowed-by-primitive-type-error op)) (dolist (sc allowed) (unpack-for-load-tn sc op)) (failed-to-pack-load-tn-error allowed op)) (t (let* ((sc (svref *backend-sc-numbers* (pop current-scs))) (target (find-load-tn-target op sc))) (when (or target (sc-allowed-by-primitive-type sc ptype)) (let ((loc (or target (select-load-tn-location op sc)))) (when loc (let ((res (make-tn 0 :load nil sc))) (setf (tn-offset res) loc) (return res)))) (push sc allowed))))))))) Scan a list of load - SCs vectors and a list of TN - REFS threaded by TN - REF - ACROSS . When we find a reference whose TN does n't satisfy ;;; the restriction, we pack a Load-TN and load the operand into it. ;;; If a load-tn has already been allocated, we can assume that the ;;; restriction is satisfied. #!-sb-fluid (declaim (inline check-operand-restrictions)) (defun check-operand-restrictions (scs ops) (declare (list scs) (type (or tn-ref null) ops)) Check the targeted operands first . (do ((scs scs (cdr scs)) (op ops (tn-ref-across op))) ((null scs)) (let ((target (tn-ref-target op))) (when target (let* ((load-tn (tn-ref-load-tn op)) (load-scs (svref (car scs) (sc-number (tn-sc (or load-tn (tn-ref-tn op))))))) (if load-tn (aver (eq load-scs t)) (unless (eq load-scs t) (setf (tn-ref-load-tn op) (pack-load-tn (car scs) op)))))))) (do ((scs scs (cdr scs)) (op ops (tn-ref-across op))) ((null scs)) (let ((target (tn-ref-target op))) (unless target (let* ((load-tn (tn-ref-load-tn op)) (load-scs (svref (car scs) (sc-number (tn-sc (or load-tn (tn-ref-tn op))))))) (if load-tn (aver (eq load-scs t)) (unless (eq load-scs t) (setf (tn-ref-load-tn op) (pack-load-tn (car scs) op)))))))) (values)) Scan the VOPs in BLOCK , looking for operands whose SC restrictions are n't satisfied . We do the results first , since they are ;;; evaluated later, and our conflict analysis is a backward scan. (defun pack-load-tns (block) (catch 'unpacked-tn (let ((*live-block* nil) (*live-vop* nil)) (do ((vop (ir2-block-last-vop block) (vop-prev vop))) ((null vop)) (let ((info (vop-info vop))) (check-operand-restrictions (vop-info-result-load-scs info) (vop-results vop)) (check-operand-restrictions (vop-info-arg-load-scs info) (vop-args vop)))))) (values)) ;;;; targeting ;;; Link the TN-REFS READ and WRITE together using the TN-REF-TARGET ;;; when this seems like a good idea. Currently we always do, as this ;;; increases the success of load-TN targeting. (defun target-if-desirable (read write) (declare (type tn-ref read write)) As per the comments at the definition of TN - REF - TARGET , read and write refs are always paired , with in the read pointing to ;; the write and vice versa. (aver (eq (tn-ref-write-p read) (not (tn-ref-write-p write)))) (setf (tn-ref-target read) write) (setf (tn-ref-target write) read)) If TN can be packed into SC so as to honor a preference to TARGET , then return the offset to pack at , otherwise return NIL . ;;; must be already packed. (defun check-ok-target (target tn sc) (declare (type tn target tn) (type sc sc) (inline member)) (let* ((loc (tn-offset target)) (target-sc (tn-sc target)) (target-sb (sc-sb target-sc))) (declare (type index loc)) ;; We can honor a preference if: -- TARGET 's location is in SC 's locations . -- The element sizes of the two SCs are the same . -- TN does n't conflict with target 's location . (if (and (eq target-sb (sc-sb sc)) (or (eq (sb-kind target-sb) :unbounded) (member loc (sc-locations sc))) (= (sc-element-size target-sc) (sc-element-size sc)) (not (conflicts-in-sc tn sc loc)) (zerop (mod loc (sc-alignment sc)))) loc nil))) Scan along the target path from TN , looking at readers or writers . When we find a packed TN , return CHECK - OK - TARGET of that TN . If there is no target , or if the TN has multiple readers ( writers ) , then we return NIL . We also always return NIL after 10 iterations ;;; to get around potential circularity problems. ;;; FIXME : ( 30 minutes of reverse engineering ? ) It 'd be nice to ;;; rewrite the header comment here to explain the interface and its ;;; motivation, and move remarks about implementation details (like 10 ! ) inside . (defun find-ok-target-offset (tn sc) (declare (type tn tn) (type sc sc)) (flet ((frob-slot (slot-fun) (declare (type function slot-fun)) (let ((count 10) (current tn)) (declare (type index count)) (loop (let ((refs (funcall slot-fun current))) (unless (and (plusp count) refs (not (tn-ref-next refs))) (return nil)) (let ((target (tn-ref-target refs))) (unless target (return nil)) (setq current (tn-ref-tn target)) (when (tn-offset current) (return (check-ok-target current tn sc))) (decf count))))))) until DYNAMIC - EXTENT works (or (frob-slot #'tn-reads) (frob-slot #'tn-writes)))) ;;;; location selection Select some location for TN in SC , returning the offset if we ;;; succeed, and NIL if we fail. ;;; For : UNBOUNDED SCs just find the smallest correctly aligned offset where the TN does n't conflict with the TNs that have already been packed . For : FINITE SCs try to pack the TN into the most heavily used locations first ( as estimated in FIND - LOCATION - USAGE ) . ;;; ;;; Historically SELECT-LOCATION tried did the opposite and tried to ;;; distribute the TNs evenly across the available locations. At least ;;; on register-starved architectures (x86) this seems to be a bad strategy . -- JES 2004 - 09 - 11 (defun select-location (tn sc &key use-reserved-locs optimize) (declare (type tn tn) (type sc sc) (inline member)) (let* ((sb (sc-sb sc)) (element-size (sc-element-size sc)) (alignment (sc-alignment sc)) (align-mask (1- alignment)) (size (finite-sb-current-size sb))) (flet ((attempt-location (start-offset) (dotimes (i element-size (return-from select-location start-offset)) (declare (type index i)) (let ((offset (+ start-offset i))) (when (offset-conflicts-in-sb tn sb offset) (return (logandc2 (the index (+ (the index (1+ offset)) align-mask)) align-mask))))))) (if (eq (sb-kind sb) :unbounded) (loop with offset = 0 until (> (+ offset element-size) size) do (setf offset (attempt-location offset))) (let ((locations (sc-locations sc))) (when optimize (setf locations (stable-sort (copy-list locations) #'> :key (lambda (location-offset) (loop for offset from location-offset repeat element-size maximize (svref (finite-sb-always-live-count sb) offset)))))) (dolist (offset locations) (when (or use-reserved-locs (not (member offset (sc-reserve-locations sc)))) (attempt-location offset)))))))) If a save TN , return the saved TN , otherwise return TN . This is useful for getting the conflicts of a TN that might be a save TN . (defun original-tn (tn) (declare (type tn tn)) (if (member (tn-kind tn) '(:save :save-once :specified-save)) (tn-save-tn tn) tn)) ;;;; pack interface Attempt to pack TN in all possible SCs , first in the SC chosen by ;;; representation selection, then in the alternate SCs in the order they were specified in the SC definition . If the TN - COST is ;;; negative, then we don't attempt to pack in SCs that must be saved. If Restricted , then we can only pack in TN - SC , not in any ;;; Alternate-SCs. ;;; If we are attempting to pack in the SC of the save TN for a TN with a : SPECIFIED - SAVE TN , then we pack in that location , instead ;;; of allocating a new stack location. (defun pack-tn (tn restricted optimize) (declare (type tn tn)) (let* ((original (original-tn tn)) (fsc (tn-sc tn)) (alternates (unless restricted (sc-alternate-scs fsc))) (save (tn-save-tn tn)) (specified-save-sc (when (and save (eq (tn-kind save) :specified-save)) (tn-sc save)))) (do ((sc fsc (pop alternates))) ((null sc) (failed-to-pack-error tn restricted)) (when (eq sc specified-save-sc) (unless (tn-offset save) (pack-tn save nil optimize)) (setf (tn-offset tn) (tn-offset save)) (setf (tn-sc tn) (tn-sc save)) (return)) (when (or restricted (not (and (minusp (tn-cost tn)) (sc-save-p sc)))) (let ((loc (or (find-ok-target-offset original sc) (select-location original sc) (and restricted (select-location original sc :use-reserved-locs t)) (when (eq (sb-kind (sc-sb sc)) :unbounded) (grow-sc sc) (or (select-location original sc) (error "failed to pack after growing SC?")))))) (when loc (add-location-conflicts original sc loc optimize) (setf (tn-sc tn) sc) (setf (tn-offset tn) loc) (return)))))) (values)) Pack a wired TN , checking that the offset is in bounds for the SB , and that the TN does n't conflict with some other TN already packed in that location . If the TN is wired to a location beyond the end of a : , then grow the SB enough to hold the TN . ;;; # # # Checking for conflicts is disabled for : SPECIFIED - SAVE TNs . ;;; This is kind of a hack to make specifying wired stack save ;;; locations for local call arguments (such as OLD-FP) work, since ;;; the caller and callee OLD-FP save locations may conflict when the ;;; save locations don't really (due to being in different frames.) (defun pack-wired-tn (tn optimize) (declare (type tn tn)) (let* ((sc (tn-sc tn)) (sb (sc-sb sc)) (offset (tn-offset tn)) (end (+ offset (sc-element-size sc))) (original (original-tn tn))) (when (> end (finite-sb-current-size sb)) (unless (eq (sb-kind sb) :unbounded) (error "~S is wired to a location that is out of bounds." tn)) (grow-sc sc end)) ;; For non-x86 ports the presence of a save-tn associated with a ;; tn is used to identify the old-fp and return-pc tns. It depends ;; on the old-fp and return-pc being passed in registers. #!-(or x86 x86-64) (when (and (not (eq (tn-kind tn) :specified-save)) (conflicts-in-sc original sc offset)) (error "~S is wired to a location that it conflicts with." tn)) ;; Use the above check, but only print a verbose warning. This can ;; be helpful for debugging the x86 port. #+nil (when (and (not (eq (tn-kind tn) :specified-save)) (conflicts-in-sc original sc offset)) (format t "~&* Pack-wired-tn possible conflict:~% ~ tn: ~S; tn-kind: ~S~% ~ sc: ~S~% ~ sb: ~S; sb-name: ~S; sb-kind: ~S~% ~ offset: ~S; end: ~S~% ~ original ~S~% ~ tn-save-tn: ~S; tn-kind of tn-save-tn: ~S~%" tn (tn-kind tn) sc sb (sb-name sb) (sb-kind sb) offset end original (tn-save-tn tn) (tn-kind (tn-save-tn tn)))) ;; On the x86 ports the old-fp and return-pc are often passed on ;; the stack so the above hack for the other ports does not always ;; work. Here the old-fp and return-pc tns are identified by being ;; on the stack in their standard save locations. #!+(or x86 x86-64) (when (and (not (eq (tn-kind tn) :specified-save)) (not (and (string= (sb-name sb) "STACK") (or (= offset 0) (= offset 1)))) (conflicts-in-sc original sc offset)) (error "~S is wired to a location that it conflicts with." tn)) (add-location-conflicts original sc offset optimize))) (defevent repack-block "Repacked a block due to TN unpacking.") : Prior to SBCL version 0.8.9.xx , this function was known as PACK - BEFORE - GC - HOOK , but was non - functional since approximately version 0.8.3.xx since the removal of GC hooks from the system . This currently ( as of 2004 - 04 - 12 ) runs now after every call to PACK , rather than -- as was originally intended -- once per GC ;;; cycle; this is probably non-optimal, and might require tuning, ;;; maybe to be called when the data structures exceed a certain size, or maybe once every N times . The is that this rewrite has done nothing to improve the reentrance or threadsafety of the ;;; compiler; it still fails to be callable from several threads at ;;; the same time. ;;; ;;; Brief experiments indicate that during a compilation cycle this causes about 10 % more consing , and takes about 1%-2 % more time . ;;; -- CSR , 2004 - 04 - 12 (defun clean-up-pack-structures () (dolist (sb *backend-sb-list*) (unless (eq (sb-kind sb) :non-packed) (let ((size (sb-size sb))) (fill (finite-sb-always-live sb) nil) (setf (finite-sb-always-live sb) (make-array size :initial-element #-sb-xc #* ;; The cross-compiler isn't very good at ;; dumping specialized arrays, so we delay ;; construction of this SIMPLE-BIT-VECTOR ;; until runtime. #+sb-xc (make-array 0 :element-type 'bit))) (setf (finite-sb-always-live-count sb) (make-array size :initial-element #-sb-xc #* ;; Ibid #+sb-xc (make-array 0 :element-type 'fixnum))) (fill (finite-sb-conflicts sb) nil) (setf (finite-sb-conflicts sb) (make-array size :initial-element '#())) (fill (finite-sb-live-tns sb) nil) (setf (finite-sb-live-tns sb) (make-array size :initial-element nil)))))) (defun pack (component) (unwind-protect (let ((optimize nil) (2comp (component-info component))) (init-sb-vectors component) ;; Determine whether we want to do more expensive packing by ;; checking whether any blocks in the component have (> SPEED ;; COMPILE-SPEED). ;; ;; FIXME: This means that a declaration can have a minor ;; effect even outside its scope, and as the packing is done ;; component-globally it'd be tricky to use strict scoping. I ;; think this is still acceptable since it's just a tradeoff ;; between compilation speed and allocation quality and ;; doesn't affect the semantics of the generated code in any way . -- JES 2004 - 10 - 06 (do-ir2-blocks (block component) (when (policy (block-last (ir2-block-block block)) (> speed compilation-speed)) (setf optimize t) (return))) ;; Call the target functions. (do-ir2-blocks (block component) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (let ((target-fun (vop-info-target-fun (vop-info vop)))) (when target-fun (funcall target-fun vop))))) Pack wired TNs first . (do ((tn (ir2-component-wired-tns 2comp) (tn-next tn))) ((null tn)) (pack-wired-tn tn optimize)) ;; Pack restricted component TNs. (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn))) ((null tn)) (when (eq (tn-kind tn) :component) (pack-tn tn t optimize))) ;; Pack other restricted TNs. (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn))) ((null tn)) (unless (tn-offset tn) (pack-tn tn t optimize))) ;; Assign costs to normal TNs so we know which ones should ;; always be packed on the stack. (when *pack-assign-costs* (assign-tn-costs component) (assign-tn-depths component)) ;; Allocate normal TNs, starting with the TNs that are used ;; in deep loops. (collect ((tns)) (do-ir2-blocks (block component) (let ((ltns (ir2-block-local-tns block))) (do ((i (1- (ir2-block-local-tn-count block)) (1- i))) ((minusp i)) (declare (fixnum i)) (let ((tn (svref ltns i))) (unless (or (null tn) (eq tn :more) (tn-offset tn)) ;; If loop analysis has been disabled we might as ;; well revert to the old behaviour of just ;; packing TNs linearly as they appear. (unless *loop-analyze* (pack-tn tn nil optimize)) (tns tn)))))) (dolist (tn (stable-sort (tns) (lambda (a b) (cond ((> (tn-loop-depth a) (tn-loop-depth b)) t) ((= (tn-loop-depth a) (tn-loop-depth b)) (> (tn-cost a) (tn-cost b))) (t nil))))) (unless (tn-offset tn) (pack-tn tn nil optimize)))) Pack any leftover normal TNs . This is to deal with : MORE TNs , which could possibly not appear in any local TN map . (do ((tn (ir2-component-normal-tns 2comp) (tn-next tn))) ((null tn)) (unless (tn-offset tn) (pack-tn tn nil optimize))) Do load TN packing and emit saves . (let ((*repack-blocks* nil)) (cond ((and optimize *pack-optimize-saves*) (optimized-emit-saves component) (do-ir2-blocks (block component) (pack-load-tns block))) (t (do-ir2-blocks (block component) (emit-saves block) (pack-load-tns block)))) (loop (unless *repack-blocks* (return)) (let ((orpb *repack-blocks*)) (setq *repack-blocks* nil) (dolist (block orpb) (event repack-block) (pack-load-tns block))))) (values)) (clean-up-pack-structures)))
null
https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/src/compiler/pack.lisp
lisp
This file contains the implementation-independent code for Pack storage allocations or "register allocation". 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. for debugging: some parameters controlling which optimizations we attempt conflict determination any of the component's blocks (always-live /= 0), then there is a conflict. everywhere in the block (:LIVE), then there is a conflict if the element at offset is used anywhere in the block that block. it is local to. conflicts for that location: setting all of the local conflict bits and the always-live bit. the block, as well as with :ALWAYS-LIVE and :ENVIRONMENT TNs. addition to setting the always-live bit to represent the conflict with TNs live throughout the block, we also set bits in the the bits, otherwise we OR in the local conflict bits. setting always-live and OR'ing in the local conflicts. Calculating ALWAYS-LIVE-COUNT is moderately expensive, and currently the information isn't used unless (> SPEED COMPILE-SPEED). used. Current implementation counts the amount of blocks where the offset has been marked as ALWAYS-LIVE. Return the total number of IR2-BLOCKs in COMPONENT. Ensure that the conflicts vectors for each :FINITE SB are large enough for the number of blocks allocated. Also clear any old conflicts and reset the current size to the initial size. larger, then use that size. FILL deftransform internal errors Give someone a hard time because there isn't any load function FIXME: "VM definition is inconsistent" shouldn't be a ,~]~ } ~ ~ ~@ This is called when none of the SCs that we can load OP into are allowed by OP's primitive-type. ~@ register saving thing. each call. If a local call (MOVE-ARGS is :LOCAL-CALL), then we scan back for the ALLOCATE-FRAME VOP, and emit the save there. This is necessary because in a self-recursive local call, the registers holding the current arguments may get trashed by setting up the call arguments. The ALLOCATE-FRAME VOP marks a place at which the values are known to be good. For correctness, it is only required that this location be after any possible write and before any possible restore location. us from being confused by non-tail local calls. When looking for writes, we have to ignore uses of MOVE-OPERAND, since they will correspond to restores that we have already done. appropriate. This is also called by SPILL-AND-PACK-LOAD-TN. optimized saving Start scanning backward at the end of BLOCK, looking which TNs are live and looking for places where we have to save. We manipulate SAVES is a set of all the TNs that have to be saved because they are restored after some call. We normally delay saving until the beginning of the block, but we must save immediately if we see a when we see a NOTE-ENVIRONMENT-START VOP, since saves can't be done before the environment is properly initialized. here and the next call, i.e. the set of TNs that must be restored is cleared when we do the restoring after a call. Any TNs that saved at some point. bit-vector so that we can quickly iterate and test for membership. sets (the initial contents are ignored.) location), we pretend that all live TNs were read, unless (= speed restored as spilled. This is like EMIT-SAVES, only different. We avoid redundant saving within the block, and don't restore values that aren't used before the next call. This function is just the top level loop over the blocks in the component, which locates blocks that need saving done. Iterate over the normal TNs, finding the cost of packing on the stack in units of the number of references. We count all place where we would have to save a register. Iterate over the normal TNs, storing the depth of the deepest loop mean"? Probably something that isn't useful in this context, since these (find-all-tns #'vop-refs) These variables indicate the last location at which we computed to COMPUTE-LIVE-TNS. If we unpack some TNs, then we mark all affected blocks by sticking them in this hash-table. This is initially null. We create the hashtable if we do any unpacking. Set the LIVE-TNS vectors in all :FINITE SBs to represent the TNs live at the end of BLOCK. to nor written from, due to more aggressive (type- directed) constant propagation. Such TNs will never be assigned an offset nor be in conflict with anything. Ideally, it seems to me we could make sure these TNs ASSIGN-LAMBDA-VAR-TNS. Set the LIVE-TNs in :FINITE SBs to represent the TNs live the beginning of the block. Sequential calls on the same block in the specified location, disregarding conflicts with TNs not -- Used by some other result. -- Used in any way after the reference (exclusive). -- Used by some other argument. -- Used in any way before the reference (exclusive). (and argument-argument) conflicts. We need this case because there writing of arguments. between arguments and results. We consider both the TN-REF-TN and the TN-REF-LOAD-TN (if any) to be referenced simultaneously and in the same way. This causes appropriate. up.) We also return true if there aren't enough locations after of the operand is packed, and try that location. There isn't any need to chain down the target path, since everything is packed now. restriction. to be repacked. This is called by PACK-LOAD-TN where there isn't any location free the specified SCs to memory, then mark all blocks that reference (isn't wired or restricted.) We prefer to unpack TNs that are not Note: we allow a Load-TN to be packed in the target location even makes move VOPs more efficient, since we won't do a move from the stack into a non-descriptor any-reg through a descriptor argument load-TN. This does give targeting some real semantics, making it not a pure advisory to pack. It allows pack to do some packing it wouldn't have done before. the restriction, we pack a Load-TN and load the operand into it. If a load-tn has already been allocated, we can assume that the restriction is satisfied. evaluated later, and our conflict analysis is a backward scan. targeting Link the TN-REFS READ and WRITE together using the TN-REF-TARGET when this seems like a good idea. Currently we always do, as this increases the success of load-TN targeting. the write and vice versa. must be already packed. We can honor a preference if: to get around potential circularity problems. rewrite the header comment here to explain the interface and its motivation, and move remarks about implementation details (like location selection succeed, and NIL if we fail. Historically SELECT-LOCATION tried did the opposite and tried to distribute the TNs evenly across the available locations. At least on register-starved architectures (x86) this seems to be a bad pack interface representation selection, then in the alternate SCs in the order negative, then we don't attempt to pack in SCs that must be saved. Alternate-SCs. of allocating a new stack location. This is kind of a hack to make specifying wired stack save locations for local call arguments (such as OLD-FP) work, since the caller and callee OLD-FP save locations may conflict when the save locations don't really (due to being in different frames.) For non-x86 ports the presence of a save-tn associated with a tn is used to identify the old-fp and return-pc tns. It depends on the old-fp and return-pc being passed in registers. Use the above check, but only print a verbose warning. This can be helpful for debugging the x86 port. tn-kind: ~S~% ~ sb-name: ~S; sb-kind: ~S~% ~ end: ~S~% ~ tn-kind of tn-save-tn: ~S~%" On the x86 ports the old-fp and return-pc are often passed on the stack so the above hack for the other ports does not always work. Here the old-fp and return-pc tns are identified by being on the stack in their standard save locations. cycle; this is probably non-optimal, and might require tuning, maybe to be called when the data structures exceed a certain size, compiler; it still fails to be callable from several threads at the same time. Brief experiments indicate that during a compilation cycle this The cross-compiler isn't very good at dumping specialized arrays, so we delay construction of this SIMPLE-BIT-VECTOR until runtime. Ibid Determine whether we want to do more expensive packing by checking whether any blocks in the component have (> SPEED COMPILE-SPEED). FIXME: This means that a declaration can have a minor effect even outside its scope, and as the packing is done component-globally it'd be tricky to use strict scoping. I think this is still acceptable since it's just a tradeoff between compilation speed and allocation quality and doesn't affect the semantics of the generated code in any Call the target functions. Pack restricted component TNs. Pack other restricted TNs. Assign costs to normal TNs so we know which ones should always be packed on the stack. Allocate normal TNs, starting with the TNs that are used in deep loops. If loop analysis has been disabled we might as well revert to the old behaviour of just packing TNs linearly as they appear.
phase in the compiler . Pack is responsible for assigning TNs to 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!C") (defvar *pack-assign-costs* t) (defvar *pack-optimize-saves* t) FIXME : Perhaps should be renamed to SB - TWEAK and these should be made conditional on SB - TWEAK . (declaim (ftype (function (component) index) ir2-block-count)) Return true if the element at the specified offset in SB has a conflict with TN : -- If a component - live TN (: COMPONENT kind ) , then iterate over all the blocks . If the element at OFFSET is used anywhere in -- If TN is global ( true ) , then iterate over the blocks TN is live in ( using TN - GLOBAL - CONFLICTS ) . If the TN is live ( Always - Live /= 0 ) . Otherwise , we use the local TN number for TN in block to find whether TN has a conflict at Offset in -- If TN is local , then we just check for a conflict in the block (defun offset-conflicts-in-sb (tn sb offset) (declare (type tn tn) (type finite-sb sb) (type index offset)) (let ((confs (tn-global-conflicts tn)) (kind (tn-kind tn))) (cond ((eq kind :component) (let ((loc-live (svref (finite-sb-always-live sb) offset))) (dotimes (i (ir2-block-count *component-being-compiled*) nil) (when (/= (sbit loc-live i) 0) (return t))))) (confs (let ((loc-confs (svref (finite-sb-conflicts sb) offset)) (loc-live (svref (finite-sb-always-live sb) offset))) (do ((conf confs (global-conflicts-next-tnwise conf))) ((null conf) nil) (let* ((block (global-conflicts-block conf)) (num (ir2-block-number block))) (if (eq (global-conflicts-kind conf) :live) (when (/= (sbit loc-live num) 0) (return t)) (when (/= (sbit (svref loc-confs num) (global-conflicts-number conf)) 0) (return t))))))) (t (/= (sbit (svref (svref (finite-sb-conflicts sb) offset) (ir2-block-number (tn-local tn))) (tn-local-number tn)) 0))))) Return true if TN has a conflict in SC at the specified offset . (defun conflicts-in-sc (tn sc offset) (declare (type tn tn) (type sc sc) (type index offset)) (let ((sb (sc-sb sc))) (dotimes (i (sc-element-size sc) nil) (when (offset-conflicts-in-sb tn sb (+ offset i)) (return t))))) Add TN 's conflicts into the conflicts for the location at OFFSET in SC . We iterate over each location in TN , adding to the -- If TN is a : COMPONENT TN , then iterate over all the blocks , This records a conflict with any TN that has a LTN number in -- If TN is global , then iterate over the blocks TN is live in . In local conflicts . If TN is : ALWAYS - LIVE in the block , we set all -- If the TN is local , then we just do the block it is local to , (defun add-location-conflicts (tn sc offset optimize) (declare (type tn tn) (type sc sc) (type index offset)) (let ((confs (tn-global-conflicts tn)) (sb (sc-sb sc)) (kind (tn-kind tn))) (dotimes (i (sc-element-size sc)) (declare (type index i)) (let* ((this-offset (+ offset i)) (loc-confs (svref (finite-sb-conflicts sb) this-offset)) (loc-live (svref (finite-sb-always-live sb) this-offset))) (cond ((eq kind :component) (dotimes (num (ir2-block-count *component-being-compiled*)) (declare (type index num)) (setf (sbit loc-live num) 1) (set-bit-vector (svref loc-confs num)))) (confs (do ((conf confs (global-conflicts-next-tnwise conf))) ((null conf)) (let* ((block (global-conflicts-block conf)) (num (ir2-block-number block)) (local-confs (svref loc-confs num))) (declare (type local-tn-bit-vector local-confs)) (setf (sbit loc-live num) 1) (if (eq (global-conflicts-kind conf) :live) (set-bit-vector local-confs) (bit-ior local-confs (global-conflicts-conflicts conf) t))))) (t (let ((num (ir2-block-number (tn-local tn)))) (setf (sbit loc-live num) 1) (bit-ior (the local-tn-bit-vector (svref loc-confs num)) (tn-local-conflicts tn) t)))) (when optimize (setf (svref (finite-sb-always-live-count sb) this-offset) (find-location-usage sb this-offset)))))) (values)) A rought measure of how much a given OFFSET in SB is currently (defun find-location-usage (sb offset) (declare (optimize speed)) (declare (type sb sb) (type index offset)) (let* ((always-live (svref (finite-sb-always-live sb) offset))) (declare (simple-bit-vector always-live)) (count 1 always-live))) (defun ir2-block-count (component) (declare (type component component)) (do ((2block (block-info (block-next (component-head component))) (ir2-block-next 2block))) ((null 2block) (error "What? No ir2 blocks have a non-nil number?")) (when (ir2-block-number 2block) (return (1+ (ir2-block-number 2block)))))) (defun init-sb-vectors (component) (let ((nblocks (ir2-block-count component))) (dolist (sb *backend-sb-list*) (unless (eq (sb-kind sb) :non-packed) (let* ((conflicts (finite-sb-conflicts sb)) (always-live (finite-sb-always-live sb)) (always-live-count (finite-sb-always-live-count sb)) (max-locs (length conflicts)) (last-count (finite-sb-last-block-count sb))) (unless (zerop max-locs) (let ((current-size (length (the simple-vector (svref conflicts 0))))) (cond ((> nblocks current-size) (let ((new-size (max nblocks (* current-size 2)))) (declare (type index new-size)) (dotimes (i max-locs) (declare (type index i)) (let ((new-vec (make-array new-size))) (let ((old (svref conflicts i))) (declare (simple-vector old)) (dotimes (j current-size) (declare (type index j)) (setf (svref new-vec j) (clear-bit-vector (svref old j))))) (do ((j current-size (1+ j))) ((= j new-size)) (declare (type index j)) (setf (svref new-vec j) (make-array local-tn-limit :element-type 'bit :initial-element 0))) (setf (svref conflicts i) new-vec)) (setf (svref always-live i) (make-array new-size :element-type 'bit :initial-element 0)) (setf (svref always-live-count i) 0)))) (t (dotimes (i (finite-sb-current-size sb)) (declare (type index i)) (let ((conf (svref conflicts i))) (declare (simple-vector conf)) (dotimes (j last-count) (declare (type index j)) (clear-bit-vector (svref conf j)))) (clear-bit-vector (svref always-live i)) (setf (svref always-live-count i) 0)))))) (setf (finite-sb-last-block-count sb) nblocks) (setf (finite-sb-current-size sb) (sb-size sb)) (setf (finite-sb-last-offset sb) 0)))))) Expand the : UNBOUNDED SB backing SC by either the initial size or the SC element size , whichever is larger . If NEEDED - SIZE is (defun grow-sc (sc &optional (needed-size 0)) (declare (type sc sc) (type index needed-size)) (let* ((sb (sc-sb sc)) (size (finite-sb-current-size sb)) (align-mask (1- (sc-alignment sc))) (inc (max (sb-size sb) (+ (sc-element-size sc) (- (logandc2 (+ size align-mask) align-mask) size)) (- needed-size size))) (new-size (+ size inc)) (conflicts (finite-sb-conflicts sb)) (block-size (if (zerop (length conflicts)) (ir2-block-count *component-being-compiled*) (length (the simple-vector (svref conflicts 0)))))) (declare (type index inc new-size)) (aver (eq (sb-kind sb) :unbounded)) (when (> new-size (length conflicts)) (let ((new-conf (make-array new-size))) (replace new-conf conflicts) (do ((i size (1+ i))) ((= i new-size)) (declare (type index i)) (let ((loc-confs (make-array block-size))) (dotimes (j block-size) (setf (svref loc-confs j) (make-array local-tn-limit :initial-element 0 :element-type 'bit))) (setf (svref new-conf i) loc-confs))) (setf (finite-sb-conflicts sb) new-conf)) (let ((new-live (make-array new-size))) (replace new-live (finite-sb-always-live sb)) (do ((i size (1+ i))) ((= i new-size)) (setf (svref new-live i) (make-array block-size :initial-element 0 :element-type 'bit))) (setf (finite-sb-always-live sb) new-live)) (let ((new-live-count (make-array new-size))) (replace new-live-count (finite-sb-always-live-count sb)) (fill new-live-count 0 :start size) (setf (finite-sb-always-live-count sb) new-live-count)) (let ((new-tns (make-array new-size :initial-element nil))) (replace new-tns (finite-sb-live-tns sb)) (fill (finite-sb-live-tns sb) nil) (setf (finite-sb-live-tns sb) new-tns))) (setf (finite-sb-current-size sb) new-size)) (values)) defined to move from SRC to DEST . (defun no-load-fun-error (src dest) (let* ((src-sc (tn-sc src)) (src-name (sc-name src-sc)) (dest-sc (tn-sc dest)) (dest-name (sc-name dest-sc))) (cond ((eq (sb-kind (sc-sb src-sc)) :non-packed) (unless (member src-sc (sc-constant-scs dest-sc)) (error "loading from an invalid constant SC?~@ VM definition inconsistent, try recompiling.")) (error "no load function defined to load SC ~S ~ from its constant SC ~S" dest-name src-name)) ((member src-sc (sc-alternate-scs dest-sc)) (error "no load function defined to load SC ~S from its ~ alternate SC ~S" dest-name src-name)) ((member dest-sc (sc-alternate-scs src-sc)) (error "no load function defined to save SC ~S in its ~ alternate SC ~S" src-name dest-name)) (t possibility in SBCL . (error "loading to/from SCs that aren't alternates?~@ VM definition is inconsistent, try recompiling."))))) Called when we failed to pack TN . If RESTRICTED is true , then we are restricted to pack TN in its SC . (defun failed-to-pack-error (tn restricted) (declare (type tn tn)) (let* ((sc (tn-sc tn)) (scs (cons sc (sc-alternate-scs sc)))) (cond (restricted (error "failed to pack restricted TN ~S in its SC ~S" tn (sc-name sc))) (t (aver (not (find :unbounded scs :key (lambda (x) (sb-kind (sc-sb x)))))) (let ((ptype (tn-primitive-type tn))) (cond (ptype (aver (member (sc-number sc) (primitive-type-scs ptype))) (error "SC ~S doesn't have any :UNBOUNDED alternate SCs, but is~@ a SC for primitive-type ~S." (sc-name sc) (primitive-type-name ptype))) (t (error "SC ~S doesn't have any :UNBOUNDED alternate SCs." (sc-name sc))))))))) Return a list of format arguments describing how TN is used in OP 's VOP . (defun describe-tn-use (loc tn op) (let* ((vop (tn-ref-vop op)) (args (vop-args vop)) (results (vop-results vop)) (name (with-output-to-string (stream) (print-tn-guts tn stream))) (2comp (component-info *component-being-compiled*)) temp) (cond ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-tn)) `("~2D: ~A (~:R argument)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn results :key #'tn-ref-tn)) `("~2D: ~A (~:R result)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-load-tn)) `("~2D: ~A (~:R argument load TN)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn results :key #'tn-ref-load-tn)) `("~2D: ~A (~:R result load TN)" ,loc ,name ,(1+ temp))) ((setq temp (position-in #'tn-ref-across tn (vop-temps vop) :key #'tn-ref-tn)) `("~2D: ~A (temporary ~A)" ,loc ,name ,(operand-parse-name (elt (vop-parse-temps (vop-parse-or-lose (vop-info-name (vop-info vop)))) temp)))) ((eq (tn-kind tn) :component) `("~2D: ~A (component live)" ,loc ,name)) ((position-in #'tn-next tn (ir2-component-wired-tns 2comp)) `("~2D: ~A (wired)" ,loc ,name)) ((position-in #'tn-next tn (ir2-component-restricted-tns 2comp)) `("~2D: ~A (restricted)" ,loc ,name)) (t `("~2D: not referenced?" ,loc))))) If load TN packing fails , try to give a helpful error message . We find a TN in each location that conflicts , and print it . (defun failed-to-pack-load-tn-error (scs op) (declare (list scs) (type tn-ref op)) (collect ((used) (unused)) (dolist (sc scs) (let* ((sb (sc-sb sc)) (confs (finite-sb-live-tns sb))) (aver (eq (sb-kind sb) :finite)) (dolist (el (sc-locations sc)) (declare (type index el)) (let ((conf (load-tn-conflicts-in-sc op sc el t))) (if conf (used (describe-tn-use el conf op)) (do ((i el (1+ i)) (end (+ el (sc-element-size sc)))) ((= i end) (unused el)) (declare (type index i end)) (let ((victim (svref confs i))) (when victim (used (describe-tn-use el victim op)) (return t))))))))) (multiple-value-bind (arg-p n more-p costs load-scs incon) (get-operand-info op) (declare (ignore costs load-scs)) (aver (not more-p)) ] to~@ the ~S VOP,~@ ~:*but these SC elements are not in use:~% ~S~%Bug?~*~]~ Current cost info inconsistent with that in effect at compile ~ time. Recompile.~%Compilation order may be incorrect.~]" (mapcar #'sc-name scs) n arg-p (vop-info-name (vop-info (tn-ref-vop op))) (unused) (used) incon)))) (defun no-load-scs-allowed-by-primitive-type-error (ref) (declare (type tn-ref ref)) (let* ((tn (tn-ref-tn ref)) (ptype (tn-primitive-type tn))) (multiple-value-bind (arg-p pos more-p costs load-scs incon) (get-operand-info ref) (declare (ignore costs)) (aver (not more-p)) ] to VOP:~ ~% ~S,~@ since the TN's primitive type ~S doesn't allow any of the SCs~@ allowed by the operand restriction:~% ~S~ Current cost info inconsistent with that in effect at compile ~ time. Recompile.~%Compilation order may be incorrect.~]" tn pos arg-p (template-name (vop-info (tn-ref-vop ref))) (primitive-type-name ptype) (mapcar #'sc-name (listify-restrictions load-scs)) incon)))) Do stuff to note that TN is spilled at VOP for the debugger 's benefit . (defun note-spilled-tn (tn vop) (when (and (tn-leaf tn) (vop-save-set vop)) (let ((2comp (component-info *component-being-compiled*))) (setf (gethash tn (ir2-component-spilled-tns 2comp)) t) (pushnew tn (gethash vop (ir2-component-spilled-vops 2comp))))) (values)) Make a save TN for TN , pack it , and return it . We copy various conflict information from the TN so that pack does the right (defun pack-save-tn (tn) (declare (type tn tn)) (let ((res (make-tn 0 :save nil nil))) (dolist (alt (sc-alternate-scs (tn-sc tn)) (error "no unbounded alternate for SC ~S" (sc-name (tn-sc tn)))) (when (eq (sb-kind (sc-sb alt)) :unbounded) (setf (tn-save-tn tn) res) (setf (tn-save-tn res) tn) (setf (tn-sc res) alt) (pack-tn res t nil) (return res))))) Find the load function for moving from SRC to DEST and emit a MOVE - OPERAND VOP with that function as its info arg . (defun emit-operand-load (node block src dest before) (declare (type node node) (type ir2-block block) (type tn src dest) (type (or vop null) before)) (emit-load-template node block (template-or-lose 'move-operand) src dest (list (or (svref (sc-move-funs (tn-sc dest)) (sc-number (tn-sc src))) (no-load-fun-error src dest))) before) (values)) Find the preceding use of the VOP NAME in the emit order , starting with VOP . We must find the VOP in the same IR1 block . (defun reverse-find-vop (name vop) (do* ((block (vop-block vop) (ir2-block-prev block)) (last vop (ir2-block-last-vop block))) (nil) (aver (eq (ir2-block-block block) (ir2-block-block (vop-block vop)))) (do ((current last (vop-prev current))) ((null current)) (when (eq (vop-info-name (vop-info current)) name) (return-from reverse-find-vop current))))) For TNs that have other than one writer , we save the TN before (defun save-complex-writer-tn (tn vop) (let ((save (or (tn-save-tn tn) (pack-save-tn tn))) (node (vop-node vop)) (block (vop-block vop)) (next (vop-next vop))) (when (eq (tn-kind save) :specified-save) (setf (tn-kind save) :save)) (aver (eq (tn-kind save) :save)) (emit-operand-load node block tn save (if (eq (vop-info-move-args (vop-info vop)) :local-call) (reverse-find-vop 'allocate-frame vop) vop)) (emit-operand-load node block save tn next))) Return a VOP after which is an OK place to save the value of TN . In practice , we return the unique writer VOP , but give up if the TN is ever read by a VOP with MOVE - ARGS : LOCAL - CALL . This prevents (defun find-single-writer (tn) (declare (type tn tn)) (do ((write (tn-writes tn) (tn-ref-next write)) (res nil)) ((null write) (when (and res (do ((read (tn-reads tn) (tn-ref-next read))) ((not read) t) (when (eq (vop-info-move-args (vop-info (tn-ref-vop read))) :local-call) (return nil)))) (tn-ref-vop res))) (unless (eq (vop-info-name (vop-info (tn-ref-vop write))) 'move-operand) (when res (return nil)) (setq res write)))) Try to save TN at a single location . If we succeed , return T , otherwise NIL . (defun save-single-writer-tn (tn) (declare (type tn tn)) (let* ((old-save (tn-save-tn tn)) (save (or old-save (pack-save-tn tn))) (writer (find-single-writer tn))) (when (and writer (or (not old-save) (eq (tn-kind old-save) :specified-save))) (emit-operand-load (vop-node writer) (vop-block writer) tn save (vop-next writer)) (setf (tn-kind save) :save-once) t))) Restore a TN with a : SAVE - ONCE save TN . (defun restore-single-writer-tn (tn vop) (declare (type tn) (type vop vop)) (let ((save (tn-save-tn tn))) (aver (eq (tn-kind save) :save-once)) (emit-operand-load (vop-node vop) (vop-block vop) save tn (vop-next vop))) (values)) Save a single TN that needs to be saved , choosing save - once if (defun basic-save-tn (tn vop) (declare (type tn tn) (type vop vop)) (let ((save (tn-save-tn tn))) (cond ((and save (eq (tn-kind save) :save-once)) (restore-single-writer-tn tn vop)) ((save-single-writer-tn tn) (restore-single-writer-tn tn vop)) (t (save-complex-writer-tn tn vop)))) (values)) Scan over the VOPs in BLOCK , emiting saving code for TNs noted in the codegen info that are packed into saved SCs . (defun emit-saves (block) (declare (type ir2-block block)) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (when (eq (vop-info-save-p (vop-info vop)) t) (do-live-tns (tn (vop-save-set vop) block) (when (and (sc-save-p (tn-sc tn)) (not (eq (tn-kind tn) :component))) (basic-save-tn tn vop))))) (values)) Save TN if it is n't a single - writer TN that has already been saved . If multi - write , we insert the save BEFORE the specified VOP . CONTEXT is a VOP used to tell which node / block to use for the new VOP . (defun save-if-necessary (tn before context) (declare (type tn tn) (type (or vop null) before) (type vop context)) (let ((save (tn-save-tn tn))) (when (eq (tn-kind save) :specified-save) (setf (tn-kind save) :save)) (aver (member (tn-kind save) '(:save :save-once))) (unless (eq (tn-kind save) :save-once) (or (save-single-writer-tn tn) (emit-operand-load (vop-node context) (vop-block context) tn save before)))) (values)) Load the TN from its save location , allocating one if necessary . The load is inserted BEFORE the specified VOP . CONTEXT is a VOP used to tell which node / block to use for the new VOP . (defun restore-tn (tn before context) (declare (type tn tn) (type (or vop null) before) (type vop context)) (let ((save (or (tn-save-tn tn) (pack-save-tn tn)))) (emit-operand-load (vop-node context) (vop-block context) save tn before)) (values)) two sets : SAVES and RESTORES . write of the saved TN . We also immediately save all TNs and exit RESTORES is a set of all the TNs read ( and not written ) between when we reach the next ( earlier ) call VOP . Unlike SAVES , this set were in RESTORES are moved into SAVES to ensure that they are SAVES and RESTORES are represented using both a list and a The incoming SAVES and RESTORES args are used for computing these When we hit a VOP with : COMPUTE - ONLY SAVE - P ( an internal error 3 ) , in which case we mark all the TNs that are live but not (defun optimized-emit-saves-block (block saves restores) (declare (type ir2-block block) (type simple-bit-vector saves restores)) (let ((1block (ir2-block-block block)) (saves-list ()) (restores-list ()) (skipping nil)) (declare (list saves-list restores-list)) (clear-bit-vector saves) (clear-bit-vector restores) (do-live-tns (tn (ir2-block-live-in block) block) (when (and (sc-save-p (tn-sc tn)) (not (eq (tn-kind tn) :component))) (let ((num (tn-number tn))) (setf (sbit restores num) 1) (push tn restores-list)))) (do ((block block (ir2-block-prev block)) (prev nil block)) ((not (eq (ir2-block-block block) 1block)) (aver (not skipping)) (dolist (save saves-list) (let ((start (ir2-block-start-vop prev))) (save-if-necessary save start start))) prev) (do ((vop (ir2-block-last-vop block) (vop-prev vop))) ((null vop)) (let ((info (vop-info vop))) (case (vop-info-name info) (allocate-frame (aver skipping) (setq skipping nil)) (note-environment-start (aver (not skipping)) (dolist (save saves-list) (save-if-necessary save (vop-next vop) vop)) (return-from optimized-emit-saves-block block))) (unless skipping (do ((write (vop-results vop) (tn-ref-across write))) ((null write)) (let* ((tn (tn-ref-tn write)) (num (tn-number tn))) (unless (zerop (sbit restores num)) (setf (sbit restores num) 0) (setq restores-list (delete tn restores-list :test #'eq))) (unless (zerop (sbit saves num)) (setf (sbit saves num) 0) (save-if-necessary tn (vop-next vop) vop) (setq saves-list (delete tn saves-list :test #'eq)))))) (macrolet ((save-note-read (tn) `(let* ((tn ,tn) (num (tn-number tn))) (when (and (sc-save-p (tn-sc tn)) (zerop (sbit restores num)) (not (eq (tn-kind tn) :component))) (setf (sbit restores num) 1) (push tn restores-list))))) (case (vop-info-save-p info) ((t) (dolist (tn restores-list) (restore-tn tn (vop-next vop) vop) (let ((num (tn-number tn))) (when (zerop (sbit saves num)) (push tn saves-list) (setf (sbit saves num) 1)))) (setq restores-list nil) (clear-bit-vector restores)) (:compute-only (cond ((policy (vop-node vop) (= speed 3)) (do-live-tns (tn (vop-save-set vop) block) (when (zerop (sbit restores (tn-number tn))) (note-spilled-tn tn vop)))) (t (do-live-tns (tn (vop-save-set vop) block) (save-note-read tn)))))) (if (eq (vop-info-move-args info) :local-call) (setq skipping t) (do ((read (vop-args vop) (tn-ref-across read))) ((null read)) (save-note-read (tn-ref-tn read)))))))))) (defun optimized-emit-saves (component) (declare (type component component)) (let* ((gtn-count (1+ (ir2-component-global-tn-counter (component-info component)))) (saves (make-array gtn-count :element-type 'bit)) (restores (make-array gtn-count :element-type 'bit)) (block (ir2-block-prev (block-info (component-tail component)))) (head (block-info (component-head component)))) (loop (when (eq block head) (return)) (when (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop) nil) (when (eq (vop-info-save-p (vop-info vop)) t) (return t))) (setq block (optimized-emit-saves-block block saves restores))) (setq block (ir2-block-prev block))))) references as +1 , and subtract out REGISTER - SAVE - PENALTY for each (defun assign-tn-costs (component) (do-ir2-blocks (block component) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (when (eq (vop-info-save-p (vop-info vop)) t) (do-live-tns (tn (vop-save-set vop) block) (decf (tn-cost tn) *backend-register-save-penalty*))))) (do ((tn (ir2-component-normal-tns (component-info component)) (tn-next tn))) ((null tn)) (let ((cost (tn-cost tn))) (declare (fixnum cost)) (do ((ref (tn-reads tn) (tn-ref-next ref))) ((null ref)) (incf cost)) (do ((ref (tn-writes tn) (tn-ref-next ref))) ((null ref)) (incf cost)) (setf (tn-cost tn) cost)))) that the TN is used in TN - LOOP - DEPTH . (defun assign-tn-depths (component) (when *loop-analyze* (do-ir2-blocks (block component) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (flet ((find-all-tns (head-fun) (collect ((tns)) (do ((ref (funcall head-fun vop) (tn-ref-across ref))) ((null ref)) (tns (tn-ref-tn ref))) (tns)))) (dolist (tn (nconc (find-all-tns #'vop-args) (find-all-tns #'vop-results) (find-all-tns #'vop-temps) What does " references in this VOP TN - REFs are linked with TN - REF - NEXT instead of TN - REF - ACROSS . --JES 2004 - 09 - 11 )) (setf (tn-loop-depth tn) (max (tn-loop-depth tn) (let* ((ir1-block (ir2-block-block (vop-block vop))) (loop (block-loop ir1-block))) (if loop (loop-depth loop) 0)))))))))) load TN packing the Live - TNs . They hold the BLOCK and VOP values that were passed (defvar *live-block*) (defvar *live-vop*) (defvar *repack-blocks*) (declaim (type list *repack-blocks*)) (defun init-live-tns (block) (dolist (sb *backend-sb-list*) (when (eq (sb-kind sb) :finite) (fill (finite-sb-live-tns sb) nil))) (do-live-tns (tn (ir2-block-live-in block) block) (let* ((sc (tn-sc tn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) : we can have " live " TNs that are neither read are never allocated in the first place in (if (tn-offset tn) (do ((offset (tn-offset tn) (1+ offset)) (end (+ (tn-offset tn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (setf (svref (finite-sb-live-tns sb) offset) tn)) (assert (and (null (tn-reads tn)) (null (tn-writes tn)))))))) (setq *live-block* block) (setq *live-vop* (ir2-block-last-vop block)) (values)) immediately after the evaluation of VOP in BLOCK , excluding results of the VOP . If VOP is null , then compute the live TNs at must be in reverse VOP order . (defun compute-live-tns (block vop) (declare (type ir2-block block) (type vop vop)) (unless (eq block *live-block*) (init-live-tns block)) (do ((current *live-vop* (vop-prev current))) ((eq current vop) (do ((res (vop-results vop) (tn-ref-across res))) ((null res)) (let* ((tn (tn-ref-tn res)) (sc (tn-sc tn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) (do ((offset (tn-offset tn) (1+ offset)) (end (+ (tn-offset tn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (setf (svref (finite-sb-live-tns sb) offset) nil)))))) (do ((ref (vop-refs current) (tn-ref-next-ref ref))) ((null ref)) (let ((ltn (tn-ref-load-tn ref))) (when ltn (let* ((sc (tn-sc ltn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) (let ((tns (finite-sb-live-tns sb))) (do ((offset (tn-offset ltn) (1+ offset)) (end (+ (tn-offset ltn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (aver (null (svref tns offset))))))))) (let* ((tn (tn-ref-tn ref)) (sc (tn-sc tn)) (sb (sc-sb sc))) (when (eq (sb-kind sb) :finite) (let ((tns (finite-sb-live-tns sb))) (do ((offset (tn-offset tn) (1+ offset)) (end (+ (tn-offset tn) (sc-element-size sc)))) ((= offset end)) (declare (type index offset end)) (if (tn-ref-write-p ref) (setf (svref tns offset) nil) (let ((old (svref tns offset))) (aver (or (null old) (eq old tn))) (setf (svref tns offset) tn))))))))) (setq *live-vop* vop) (values)) This is kind of like OFFSET - CONFLICTS - IN - SB , except that it uses the VOP refs to determine whether a Load - TN for OP could be packed referenced by this VOP . There is a conflict if either : 1 . The reference is a result , and the same location is either : 2 . The reference is an argument , and the same location is either : In 1 ( and 2 ) above , the first bullet corresponds to result - result are n't any TN - REFs to represent the implicit reading of results or The second bullet corresponds to conflicts with temporaries or load - TNs to appear live to the beginning ( or end ) of the VOP , as We return a conflicting TN if there is a conflict . (defun load-tn-offset-conflicts-in-sb (op sb offset) (declare (type tn-ref op) (type finite-sb sb) (type index offset)) (aver (eq (sb-kind sb) :finite)) (let ((vop (tn-ref-vop op))) (labels ((tn-overlaps (tn) (let ((sc (tn-sc tn)) (tn-offset (tn-offset tn))) (when (and (eq (sc-sb sc) sb) (<= tn-offset offset) (< offset (the index (+ tn-offset (sc-element-size sc))))) tn))) (same (ref) (let ((tn (tn-ref-tn ref)) (ltn (tn-ref-load-tn ref))) (or (tn-overlaps tn) (and ltn (tn-overlaps ltn))))) (is-op (ops) (do ((ops ops (tn-ref-across ops))) ((null ops) nil) (let ((found (same ops))) (when (and found (not (eq ops op))) (return found))))) (is-ref (refs end) (do ((refs refs (tn-ref-next-ref refs))) ((eq refs end) nil) (let ((found (same refs))) (when found (return found)))))) (declare (inline is-op is-ref tn-overlaps)) (if (tn-ref-write-p op) (or (is-op (vop-results vop)) (is-ref (vop-refs vop) op)) (or (is-op (vop-args vop)) (is-ref (tn-ref-next-ref op) nil)))))) Iterate over all the elements in the SB that would be allocated by allocating a TN in SC at Offset , checking for conflict with load - TNs or other TNs ( live in the LIVE - TNS , which must be set Offset to hold a TN in SC . If Ignore - Live is true , then we ignore the live - TNs , considering only references within Op 's VOP . We return a conflicting TN , or : OVERFLOW if the TN wo n't fit . (defun load-tn-conflicts-in-sc (op sc offset ignore-live) (let* ((sb (sc-sb sc)) (size (finite-sb-current-size sb))) (do ((i offset (1+ i)) (end (+ offset (sc-element-size sc)))) ((= i end) nil) (declare (type index i end)) (let ((res (or (when (>= i size) :overflow) (and (not ignore-live) (svref (finite-sb-live-tns sb) i)) (load-tn-offset-conflicts-in-sb op sb i)))) (when res (return res)))))) If a load - TN for OP is targeted to a legal location in SC , then return the offset , otherwise return NIL . We see whether the target We require the target to be in SC ( and not merely to overlap with SC ) . This prevents SC information from being lost in load TNs ( we wo n't pack a load TN in ANY - REG when it is targeted to a DESCRIPTOR - REG . ) This should n't hurt the code as long as all relevant overlapping SCs are allowed in the operand SC (defun find-load-tn-target (op sc) (declare (inline member)) (let ((target (tn-ref-target op))) (when target (let* ((tn (tn-ref-tn target)) (loc (tn-offset tn))) (if (and (eq (tn-sc tn) sc) (member (the index loc) (sc-locations sc)) (not (load-tn-conflicts-in-sc op sc loc nil))) loc nil))))) Select a legal location for a load TN for Op in SC . We just iterate over the SC 's locations . If we ca n't find a legal location , return NIL . (defun select-load-tn-location (op sc) (declare (type tn-ref op) (type sc sc)) Check any target location first . (let ((target (tn-ref-target op))) (when target (let* ((tn (tn-ref-tn target)) (loc (tn-offset tn))) (when (and (eq (sc-sb sc) (sc-sb (tn-sc tn))) (member (the index loc) (sc-locations sc)) (not (load-tn-conflicts-in-sc op sc loc nil))) (return-from select-load-tn-location loc))))) (dolist (loc (sc-locations sc) nil) (unless (load-tn-conflicts-in-sc op sc loc nil) (return loc)))) (defevent unpack-tn "Unpacked a TN to satisfy operand SC restriction.") Make TN 's location the same as for its save TN ( allocating a save TN if necessary . ) Delete any save / restore code that has been emitted thus far . all blocks containing references as needing (defun unpack-tn (tn) (event unpack-tn) (let ((stn (or (tn-save-tn tn) (pack-save-tn tn)))) (setf (tn-sc tn) (tn-sc stn)) (setf (tn-offset tn) (tn-offset stn)) (flet ((zot (refs) (do ((ref refs (tn-ref-next ref))) ((null ref)) (let ((vop (tn-ref-vop ref))) (if (eq (vop-info-name (vop-info vop)) 'move-operand) (delete-vop vop) (pushnew (vop-block vop) *repack-blocks*)))))) (zot (tn-reads tn)) (zot (tn-writes tn)))) (values)) (defevent unpack-fallback "Unpacked some operand TN.") that we can pack into . What we do is move some live TN in one of the TN as needing repacking . If we succeed , we throw to UNPACKED - TN . If we fail , we return NIL . We can unpack any live TN that appears in the NORMAL - TNs list used by the VOP . If we ca n't find any such TN , then we unpack some argument or result TN . The only way we can fail is if all locations in SC are used by load - TNs or temporaries in VOP . (defun unpack-for-load-tn (sc op) (declare (type sc sc) (type tn-ref op)) (let ((sb (sc-sb sc)) (normal-tns (ir2-component-normal-tns (component-info *component-being-compiled*))) (node (vop-node (tn-ref-vop op))) (fallback nil)) (flet ((unpack-em (victims) (pushnew (vop-block (tn-ref-vop op)) *repack-blocks*) (dolist (victim victims) (event unpack-tn node) (unpack-tn victim)) (throw 'unpacked-tn nil))) (dolist (loc (sc-locations sc)) (declare (type index loc)) (block SKIP (collect ((victims nil adjoin)) (do ((i loc (1+ i)) (end (+ loc (sc-element-size sc)))) ((= i end)) (declare (type index i end)) (let ((victim (svref (finite-sb-live-tns sb) i))) (when victim (unless (find-in #'tn-next victim normal-tns) (return-from SKIP)) (victims victim)))) (let ((conf (load-tn-conflicts-in-sc op sc loc t))) (cond ((not conf) (unpack-em (victims))) ((eq conf :overflow)) ((not fallback) (cond ((find conf (victims)) (setq fallback (victims))) ((find-in #'tn-next conf normal-tns) (setq fallback (list conf)))))))))) (when fallback (event unpack-fallback node) (unpack-em fallback)))) nil) Try to pack a load TN in the SCs indicated by Load - SCs . If we run out of SCs , then we unpack some TN and try again . We return the packed load TN . if that location is in a SC not allowed by the primitive type . ( The SC must still be allowed by the operand restriction . ) This (defun pack-load-tn (load-scs op) (declare (type sc-vector load-scs) (type tn-ref op)) (let ((vop (tn-ref-vop op))) (compute-live-tns (vop-block vop) vop)) (let* ((tn (tn-ref-tn op)) (ptype (tn-primitive-type tn)) (scs (svref load-scs (sc-number (tn-sc tn))))) (let ((current-scs scs) (allowed ())) (loop (cond ((null current-scs) (unless allowed (no-load-scs-allowed-by-primitive-type-error op)) (dolist (sc allowed) (unpack-for-load-tn sc op)) (failed-to-pack-load-tn-error allowed op)) (t (let* ((sc (svref *backend-sc-numbers* (pop current-scs))) (target (find-load-tn-target op sc))) (when (or target (sc-allowed-by-primitive-type sc ptype)) (let ((loc (or target (select-load-tn-location op sc)))) (when loc (let ((res (make-tn 0 :load nil sc))) (setf (tn-offset res) loc) (return res)))) (push sc allowed))))))))) Scan a list of load - SCs vectors and a list of TN - REFS threaded by TN - REF - ACROSS . When we find a reference whose TN does n't satisfy #!-sb-fluid (declaim (inline check-operand-restrictions)) (defun check-operand-restrictions (scs ops) (declare (list scs) (type (or tn-ref null) ops)) Check the targeted operands first . (do ((scs scs (cdr scs)) (op ops (tn-ref-across op))) ((null scs)) (let ((target (tn-ref-target op))) (when target (let* ((load-tn (tn-ref-load-tn op)) (load-scs (svref (car scs) (sc-number (tn-sc (or load-tn (tn-ref-tn op))))))) (if load-tn (aver (eq load-scs t)) (unless (eq load-scs t) (setf (tn-ref-load-tn op) (pack-load-tn (car scs) op)))))))) (do ((scs scs (cdr scs)) (op ops (tn-ref-across op))) ((null scs)) (let ((target (tn-ref-target op))) (unless target (let* ((load-tn (tn-ref-load-tn op)) (load-scs (svref (car scs) (sc-number (tn-sc (or load-tn (tn-ref-tn op))))))) (if load-tn (aver (eq load-scs t)) (unless (eq load-scs t) (setf (tn-ref-load-tn op) (pack-load-tn (car scs) op)))))))) (values)) Scan the VOPs in BLOCK , looking for operands whose SC restrictions are n't satisfied . We do the results first , since they are (defun pack-load-tns (block) (catch 'unpacked-tn (let ((*live-block* nil) (*live-vop* nil)) (do ((vop (ir2-block-last-vop block) (vop-prev vop))) ((null vop)) (let ((info (vop-info vop))) (check-operand-restrictions (vop-info-result-load-scs info) (vop-results vop)) (check-operand-restrictions (vop-info-arg-load-scs info) (vop-args vop)))))) (values)) (defun target-if-desirable (read write) (declare (type tn-ref read write)) As per the comments at the definition of TN - REF - TARGET , read and write refs are always paired , with in the read pointing to (aver (eq (tn-ref-write-p read) (not (tn-ref-write-p write)))) (setf (tn-ref-target read) write) (setf (tn-ref-target write) read)) If TN can be packed into SC so as to honor a preference to TARGET , then return the offset to pack at , otherwise return NIL . (defun check-ok-target (target tn sc) (declare (type tn target tn) (type sc sc) (inline member)) (let* ((loc (tn-offset target)) (target-sc (tn-sc target)) (target-sb (sc-sb target-sc))) (declare (type index loc)) -- TARGET 's location is in SC 's locations . -- The element sizes of the two SCs are the same . -- TN does n't conflict with target 's location . (if (and (eq target-sb (sc-sb sc)) (or (eq (sb-kind target-sb) :unbounded) (member loc (sc-locations sc))) (= (sc-element-size target-sc) (sc-element-size sc)) (not (conflicts-in-sc tn sc loc)) (zerop (mod loc (sc-alignment sc)))) loc nil))) Scan along the target path from TN , looking at readers or writers . When we find a packed TN , return CHECK - OK - TARGET of that TN . If there is no target , or if the TN has multiple readers ( writers ) , then we return NIL . We also always return NIL after 10 iterations FIXME : ( 30 minutes of reverse engineering ? ) It 'd be nice to 10 ! ) inside . (defun find-ok-target-offset (tn sc) (declare (type tn tn) (type sc sc)) (flet ((frob-slot (slot-fun) (declare (type function slot-fun)) (let ((count 10) (current tn)) (declare (type index count)) (loop (let ((refs (funcall slot-fun current))) (unless (and (plusp count) refs (not (tn-ref-next refs))) (return nil)) (let ((target (tn-ref-target refs))) (unless target (return nil)) (setq current (tn-ref-tn target)) (when (tn-offset current) (return (check-ok-target current tn sc))) (decf count))))))) until DYNAMIC - EXTENT works (or (frob-slot #'tn-reads) (frob-slot #'tn-writes)))) Select some location for TN in SC , returning the offset if we For : UNBOUNDED SCs just find the smallest correctly aligned offset where the TN does n't conflict with the TNs that have already been packed . For : FINITE SCs try to pack the TN into the most heavily used locations first ( as estimated in FIND - LOCATION - USAGE ) . strategy . -- JES 2004 - 09 - 11 (defun select-location (tn sc &key use-reserved-locs optimize) (declare (type tn tn) (type sc sc) (inline member)) (let* ((sb (sc-sb sc)) (element-size (sc-element-size sc)) (alignment (sc-alignment sc)) (align-mask (1- alignment)) (size (finite-sb-current-size sb))) (flet ((attempt-location (start-offset) (dotimes (i element-size (return-from select-location start-offset)) (declare (type index i)) (let ((offset (+ start-offset i))) (when (offset-conflicts-in-sb tn sb offset) (return (logandc2 (the index (+ (the index (1+ offset)) align-mask)) align-mask))))))) (if (eq (sb-kind sb) :unbounded) (loop with offset = 0 until (> (+ offset element-size) size) do (setf offset (attempt-location offset))) (let ((locations (sc-locations sc))) (when optimize (setf locations (stable-sort (copy-list locations) #'> :key (lambda (location-offset) (loop for offset from location-offset repeat element-size maximize (svref (finite-sb-always-live-count sb) offset)))))) (dolist (offset locations) (when (or use-reserved-locs (not (member offset (sc-reserve-locations sc)))) (attempt-location offset)))))))) If a save TN , return the saved TN , otherwise return TN . This is useful for getting the conflicts of a TN that might be a save TN . (defun original-tn (tn) (declare (type tn tn)) (if (member (tn-kind tn) '(:save :save-once :specified-save)) (tn-save-tn tn) tn)) Attempt to pack TN in all possible SCs , first in the SC chosen by they were specified in the SC definition . If the TN - COST is If Restricted , then we can only pack in TN - SC , not in any If we are attempting to pack in the SC of the save TN for a TN with a : SPECIFIED - SAVE TN , then we pack in that location , instead (defun pack-tn (tn restricted optimize) (declare (type tn tn)) (let* ((original (original-tn tn)) (fsc (tn-sc tn)) (alternates (unless restricted (sc-alternate-scs fsc))) (save (tn-save-tn tn)) (specified-save-sc (when (and save (eq (tn-kind save) :specified-save)) (tn-sc save)))) (do ((sc fsc (pop alternates))) ((null sc) (failed-to-pack-error tn restricted)) (when (eq sc specified-save-sc) (unless (tn-offset save) (pack-tn save nil optimize)) (setf (tn-offset tn) (tn-offset save)) (setf (tn-sc tn) (tn-sc save)) (return)) (when (or restricted (not (and (minusp (tn-cost tn)) (sc-save-p sc)))) (let ((loc (or (find-ok-target-offset original sc) (select-location original sc) (and restricted (select-location original sc :use-reserved-locs t)) (when (eq (sb-kind (sc-sb sc)) :unbounded) (grow-sc sc) (or (select-location original sc) (error "failed to pack after growing SC?")))))) (when loc (add-location-conflicts original sc loc optimize) (setf (tn-sc tn) sc) (setf (tn-offset tn) loc) (return)))))) (values)) Pack a wired TN , checking that the offset is in bounds for the SB , and that the TN does n't conflict with some other TN already packed in that location . If the TN is wired to a location beyond the end of a : , then grow the SB enough to hold the TN . # # # Checking for conflicts is disabled for : SPECIFIED - SAVE TNs . (defun pack-wired-tn (tn optimize) (declare (type tn tn)) (let* ((sc (tn-sc tn)) (sb (sc-sb sc)) (offset (tn-offset tn)) (end (+ offset (sc-element-size sc))) (original (original-tn tn))) (when (> end (finite-sb-current-size sb)) (unless (eq (sb-kind sb) :unbounded) (error "~S is wired to a location that is out of bounds." tn)) (grow-sc sc end)) #!-(or x86 x86-64) (when (and (not (eq (tn-kind tn) :specified-save)) (conflicts-in-sc original sc offset)) (error "~S is wired to a location that it conflicts with." tn)) #+nil (when (and (not (eq (tn-kind tn) :specified-save)) (conflicts-in-sc original sc offset)) (format t "~&* Pack-wired-tn possible conflict:~% ~ sc: ~S~% ~ original ~S~% ~ tn (tn-kind tn) sc sb (sb-name sb) (sb-kind sb) offset end original (tn-save-tn tn) (tn-kind (tn-save-tn tn)))) #!+(or x86 x86-64) (when (and (not (eq (tn-kind tn) :specified-save)) (not (and (string= (sb-name sb) "STACK") (or (= offset 0) (= offset 1)))) (conflicts-in-sc original sc offset)) (error "~S is wired to a location that it conflicts with." tn)) (add-location-conflicts original sc offset optimize))) (defevent repack-block "Repacked a block due to TN unpacking.") : Prior to SBCL version 0.8.9.xx , this function was known as PACK - BEFORE - GC - HOOK , but was non - functional since approximately version 0.8.3.xx since the removal of GC hooks from the system . This currently ( as of 2004 - 04 - 12 ) runs now after every call to PACK , rather than -- as was originally intended -- once per GC or maybe once every N times . The is that this rewrite has done nothing to improve the reentrance or threadsafety of the causes about 10 % more consing , and takes about 1%-2 % more time . -- CSR , 2004 - 04 - 12 (defun clean-up-pack-structures () (dolist (sb *backend-sb-list*) (unless (eq (sb-kind sb) :non-packed) (let ((size (sb-size sb))) (fill (finite-sb-always-live sb) nil) (setf (finite-sb-always-live sb) (make-array size :initial-element #-sb-xc #* #+sb-xc (make-array 0 :element-type 'bit))) (setf (finite-sb-always-live-count sb) (make-array size :initial-element #-sb-xc #* #+sb-xc (make-array 0 :element-type 'fixnum))) (fill (finite-sb-conflicts sb) nil) (setf (finite-sb-conflicts sb) (make-array size :initial-element '#())) (fill (finite-sb-live-tns sb) nil) (setf (finite-sb-live-tns sb) (make-array size :initial-element nil)))))) (defun pack (component) (unwind-protect (let ((optimize nil) (2comp (component-info component))) (init-sb-vectors component) way . -- JES 2004 - 10 - 06 (do-ir2-blocks (block component) (when (policy (block-last (ir2-block-block block)) (> speed compilation-speed)) (setf optimize t) (return))) (do-ir2-blocks (block component) (do ((vop (ir2-block-start-vop block) (vop-next vop))) ((null vop)) (let ((target-fun (vop-info-target-fun (vop-info vop)))) (when target-fun (funcall target-fun vop))))) Pack wired TNs first . (do ((tn (ir2-component-wired-tns 2comp) (tn-next tn))) ((null tn)) (pack-wired-tn tn optimize)) (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn))) ((null tn)) (when (eq (tn-kind tn) :component) (pack-tn tn t optimize))) (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn))) ((null tn)) (unless (tn-offset tn) (pack-tn tn t optimize))) (when *pack-assign-costs* (assign-tn-costs component) (assign-tn-depths component)) (collect ((tns)) (do-ir2-blocks (block component) (let ((ltns (ir2-block-local-tns block))) (do ((i (1- (ir2-block-local-tn-count block)) (1- i))) ((minusp i)) (declare (fixnum i)) (let ((tn (svref ltns i))) (unless (or (null tn) (eq tn :more) (tn-offset tn)) (unless *loop-analyze* (pack-tn tn nil optimize)) (tns tn)))))) (dolist (tn (stable-sort (tns) (lambda (a b) (cond ((> (tn-loop-depth a) (tn-loop-depth b)) t) ((= (tn-loop-depth a) (tn-loop-depth b)) (> (tn-cost a) (tn-cost b))) (t nil))))) (unless (tn-offset tn) (pack-tn tn nil optimize)))) Pack any leftover normal TNs . This is to deal with : MORE TNs , which could possibly not appear in any local TN map . (do ((tn (ir2-component-normal-tns 2comp) (tn-next tn))) ((null tn)) (unless (tn-offset tn) (pack-tn tn nil optimize))) Do load TN packing and emit saves . (let ((*repack-blocks* nil)) (cond ((and optimize *pack-optimize-saves*) (optimized-emit-saves component) (do-ir2-blocks (block component) (pack-load-tns block))) (t (do-ir2-blocks (block component) (emit-saves block) (pack-load-tns block)))) (loop (unless *repack-blocks* (return)) (let ((orpb *repack-blocks*)) (setq *repack-blocks* nil) (dolist (block orpb) (event repack-block) (pack-load-tns block))))) (values)) (clean-up-pack-structures)))
52a516c86da3c474f6b382168556813cef707f291fa23eabe219c9a2d7202507
facebookarchive/pfff
alias_type.ml
type list2 = int list type use_list2 = | Constructor of list2 let f = function | Constructor [] -> 1 | _ -> 2
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/tests/ml/cmt/alias_type.ml
ocaml
type list2 = int list type use_list2 = | Constructor of list2 let f = function | Constructor [] -> 1 | _ -> 2
122e4261439e84ae48a832a50da7b4d171b7fa333941300bdfc4f5bb5cb874a9
roman01la/clojurescript-workshop
assignment.cljs
Develop Clojure 's data to JSON converter ;; which handles strings, numbers, booleans, keywords and vectors ;; using protocols ;; test (to-json [:keyword "string" 1 true false [:nested [:vector]]]) " [ \"keyword\ " , \"string\ " , 1 , true , false , [ \"nested\ " , [ \"vector\ " ] ] ] "
null
https://raw.githubusercontent.com/roman01la/clojurescript-workshop/48b02266d65cae8113edd4ce34c4ab282ad256d1/11.protocols_and_named_data_types/assignment.cljs
clojure
which handles strings, numbers, booleans, keywords and vectors using protocols test
Develop Clojure 's data to JSON converter (to-json [:keyword "string" 1 true false [:nested [:vector]]]) " [ \"keyword\ " , \"string\ " , 1 , true , false , [ \"nested\ " , [ \"vector\ " ] ] ] "
da765f091f30ed9e05b8f5eea55d89651101fdcf3a6c6728040f804e63f5d0cf
dotemacs/pdfboxing
common.clj
(ns pdfboxing.common (:require [clojure.java.io :as io]) (:import (java.io File) (org.apache.pdfbox.pdmodel PDDocument) (org.apache.pdfbox.io RandomAccessFile) (org.apache.pdfbox.pdfparser PDFParser))) (defn try-get-as-pdf "Try and get the pdf-file-or-path as a PDF. Returns nil if pdf-file-or-path could not be loaded as a PDF." [pdf-file-or-path] (let [^File pdf-file (io/as-file pdf-file-or-path) random-access-file (RandomAccessFile. pdf-file "r") parser (PDFParser. random-access-file)] (try (.parse parser) (.getPDDocument parser) (catch Exception _)))) (defn is-pdf? "Confirm that the PDF supplied is really a PDF" [pdf-file-or-path] (if-let [pdf (try-get-as-pdf pdf-file-or-path)] (try (not (nil? pdf)) (finally (.close pdf))) false)) (defn load-pdf "Load a given PDF only after checking if it really is a PDF" [pdf-file-or-path] (if-let [pdf (try-get-as-pdf pdf-file-or-path)] pdf (throw (IllegalArgumentException. (format "%s is not a PDF file" pdf-file-or-path))))) (defprotocol PDFDocument "return an object from which text can be extracted" (obtain-document [source])) (extend-protocol PDFDocument (class (byte-array 0)) (obtain-document [source] (PDDocument/load source)) String (obtain-document [source] (load-pdf source)) File (obtain-document [source] (load-pdf source)) PDDocument (obtain-document [source] source)) (defn get-form "Obtain AcroForm from a open `doc`, opened with obtain-document" [doc] (-> doc .getDocumentCatalog .getAcroForm))
null
https://raw.githubusercontent.com/dotemacs/pdfboxing/3dafff7102d99df072b09626c9349ba3a9719bf6/src/pdfboxing/common.clj
clojure
(ns pdfboxing.common (:require [clojure.java.io :as io]) (:import (java.io File) (org.apache.pdfbox.pdmodel PDDocument) (org.apache.pdfbox.io RandomAccessFile) (org.apache.pdfbox.pdfparser PDFParser))) (defn try-get-as-pdf "Try and get the pdf-file-or-path as a PDF. Returns nil if pdf-file-or-path could not be loaded as a PDF." [pdf-file-or-path] (let [^File pdf-file (io/as-file pdf-file-or-path) random-access-file (RandomAccessFile. pdf-file "r") parser (PDFParser. random-access-file)] (try (.parse parser) (.getPDDocument parser) (catch Exception _)))) (defn is-pdf? "Confirm that the PDF supplied is really a PDF" [pdf-file-or-path] (if-let [pdf (try-get-as-pdf pdf-file-or-path)] (try (not (nil? pdf)) (finally (.close pdf))) false)) (defn load-pdf "Load a given PDF only after checking if it really is a PDF" [pdf-file-or-path] (if-let [pdf (try-get-as-pdf pdf-file-or-path)] pdf (throw (IllegalArgumentException. (format "%s is not a PDF file" pdf-file-or-path))))) (defprotocol PDFDocument "return an object from which text can be extracted" (obtain-document [source])) (extend-protocol PDFDocument (class (byte-array 0)) (obtain-document [source] (PDDocument/load source)) String (obtain-document [source] (load-pdf source)) File (obtain-document [source] (load-pdf source)) PDDocument (obtain-document [source] source)) (defn get-form "Obtain AcroForm from a open `doc`, opened with obtain-document" [doc] (-> doc .getDocumentCatalog .getAcroForm))
59f8ced7588d2f5ce2db459e3ed98a82197241e56c45efefbdd439d5cb5b2a53
lspitzner/exference
MonadLoops.hs
module Control.Monad.Loops where whileM : : Control . Monad . Monad m = > m Data . Bool . m a - > m [ a ] whileM' :: (Control.Monad.Monad m, Control.Monad.MonadPlus f) => m Data.Bool.Bool -> m a -> m (f a) iterateWhile :: Control.Monad.Monad m => (a -> Bool) -> m a -> m a -- this is evil, prove-wise iterateM_ :: Control.Monad.Monad m => (a -> m a) -> a -> m b untilM : : Control . Monad . Monad m = > m a - > m Data . Bool . m [ a ] untilM' :: (Control.Monad.Monad m, Control.Monad.MonadPlus f) => m a -> m Data.Bool.Bool -> m (f a) -- this is evil, in it discards results iterateWhile : : Control . Monad . Monad m = > ( a - > Data . Bool . ) - > m a - > m a concatM :: Control.Monad.Monad m => [a -> m a] -> a -> m a
null
https://raw.githubusercontent.com/lspitzner/exference/d8a336f8b9df905e54173339f78ba892daa3f688/environment/MonadLoops.hs
haskell
this is evil, prove-wise this is evil, in it discards results
module Control.Monad.Loops where whileM : : Control . Monad . Monad m = > m Data . Bool . m a - > m [ a ] whileM' :: (Control.Monad.Monad m, Control.Monad.MonadPlus f) => m Data.Bool.Bool -> m a -> m (f a) iterateWhile :: Control.Monad.Monad m => (a -> Bool) -> m a -> m a iterateM_ :: Control.Monad.Monad m => (a -> m a) -> a -> m b untilM : : Control . Monad . Monad m = > m a - > m Data . Bool . m [ a ] untilM' :: (Control.Monad.Monad m, Control.Monad.MonadPlus f) => m a -> m Data.Bool.Bool -> m (f a) iterateWhile : : Control . Monad . Monad m = > ( a - > Data . Bool . ) - > m a - > m a concatM :: Control.Monad.Monad m => [a -> m a] -> a -> m a
3dda983ae818db6aedbae865a02ba404e9ae827279ab84226564694eb0fe669b
shirok/Gauche
libmacbase.scm
;;; ;;; libmacbase.scm - macro basic staff ;;; Copyright ( c ) 2000 - 2022 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; 3. Neither the name of the authors nor the names of its contributors ;;; may be used to endorse or promote products derived from this ;;; software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (select-module gauche.internal) (use util.match) (inline-stub (declcode (.include "gauche/priv/macroP.h"))) ;; This file defines lower level layer of macro system. ;; Initialization of compile.scm depends on this file. ;;; Macro expansion utilities ;;; ;; macroexpand FORM [ENV/FLAG] ;; macroexpand-1 FORM [ENV/FLAG] ;; ENV/FLAG can be: ;; #f - we expand it in the current runtime env, run unravel-syntax on output ;; #t - we expand it in the current runtime env ;; #<module> - use it as the toplevel env. ;; API (define-in-module gauche (macroexpand form :optional (env/flag #f)) (%do-macroexpand form env/flag #f)) ;; API (define-in-module gauche (macroexpand-1 form :optional (env/flag #f)) (%do-macroexpand form env/flag #t)) (define (%do-macroexpand form env/flag once?) (let* ([env (cond [(boolean? env/flag) (vm-current-module)] [(module? env/flag) env/flag] [else (error "argument must be a boolean or a module, but got:" env/flag)])] [r (%internal-macro-expand form (make-cenv env) once?)]) (if (eq? env/flag #f) (unravel-syntax r) r))) (select-module gauche) ;; API ;; This strips all syntactic information (lossy) (define-cproc unwrap-syntax (form :optional (to_immutable::<boolean> #f)) (return (Scm_UnwrapSyntax2 form to_immutable))) ;; API ;; Unwrap only if obj is an identifier. (define-cproc unwrap-syntax-1 (obj) (if (SCM_IDENTIFIERP obj) (return (SCM_OBJ (Scm_UnwrapIdentifier (SCM_IDENTIFIER obj)))) (return obj))) ;; API ;; This preserves identity of local identifiers by suffixing it. ;; The identity of toplevel identifiers are still not preserved across modules. (select-module gauche.internal) (define-in-module gauche (unravel-syntax form) (define id->sym (let1 tab (make-hash-table 'eq?) ; identifier -> symbol (^[id] (or (hash-table-get tab id #f) (let1 nam (unwrap-syntax id) (if (global-identifier=? id (make-identifier nam (vm-current-module) '())) (begin (hash-table-put! tab id nam) nam) (let1 num ($ hash-table-fold tab (^[i _ c] (if (eq? (unwrap-syntax i) nam) (+ c 1) c)) 0) (rlet1 sym (symbol-append nam "." num) (hash-table-put! tab id sym))))))))) (define (rec form) (cond [(wrapped-identifier? form) (id->sym form)] [(pair? form) (cons (rec (car form)) (rec (cdr form)))] [(vector? form) (vector-map rec form)] [else form])) (rec form)) (select-module gauche.internal) (inline-stub (declare-stub-type <macro> "ScmMacro*" "macro" "SCM_MACROP" "SCM_MACRO" "SCM_OBJ") ) ;; These are used in the compiler, and hidden inside gauche.internal. (define-cproc macro? (obj) ::<boolean> SCM_MACROP) (define-cproc syntax? (obj) ::<boolean> SCM_SYNTAXP) ;;; Macro object ;;; (select-module gauche) (inline-stub (define-cclass <macro> "ScmMacro*" "Scm_MacroClass" (c "SCM_CLASS_DEFAULT_CPL") ((name :setter #f) (transformer :setter #f) (info-alist :c-name "info_alist" :setter #f) (flags :type <ulong> :setter #f)) (printer (Scm_Printf port "#<macro %A>" (-> (SCM_MACRO obj) name))))) ;;; ;;; Transformer interface ;;; NB : % make - macro - transformer is in libalpha.scm (select-module gauche.internal) (define-cproc compile-syntax-rules (name src ellipsis literals rules mod env) Scm_CompileSyntaxRules) (define-cproc macro-transformer (mac::<macro>) Scm_MacroTransformer) (define-cproc macro-name (mac::<macro>) Scm_MacroName) (define-cproc identifier-macro? (mac::<macro>) ::<boolean> (return (logand (-> mac flags) SCM_MACRO_IDENTIFIER))) Macro expand tracer ;; *trace-macro* can be #f (default - no trace), #t (trace all macros), ;; or a list of symbols/regexp (trace macros whose name that matches) (define *trace-macro* #f) (define (%macro-traced? mac) (or (eq? *trace-macro* #t) (and-let1 macname (unwrap-syntax (macro-name mac)) (find (^z (cond [(symbol? z) (eq? z macname)] [(regexp? z) (z (symbol->string macname))] [else #f])) *trace-macro*)))) (define (call-macro-expander mac expr cenv) (let* ([r ((macro-transformer mac) expr cenv)] [out (if (and (pair? r) (not (eq? expr r))) (rlet1 p (if (extended-pair? r) r (extended-cons (car r) (cdr r))) (pair-attribute-set! p 'original expr)) r)]) (when (and *trace-macro* (%macro-traced? mac)) NB : We need to apply unravel - syntax on expr and out at once , ;; so that we can correspond the identifiers from input and output. (let1 unraveled (unravel-syntax (cons expr out)) (display "Macro input>>>\n" (current-trace-port)) (pprint (car unraveled) :port (current-trace-port) :level #f :length #f) (display "\nMacro output<<<\n" (current-trace-port)) (pprint (cdr unraveled) :port (current-trace-port) :level #f :length #f) (display "\n" (current-trace-port)) (flush (current-trace-port)))) out)) (define (call-id-macro-expander mac cenv) (unless (identifier-macro? mac) (error "Non-identifier-macro can't appear in this context:" mac)) (call-macro-expander mac mac cenv)) (define-cproc make-syntax (name::<symbol> module::<module> proc) Scm_MakeSyntax) (define-cproc call-syntax-handler (syn program cenv) (SCM_ASSERT (SCM_SYNTAXP syn)) (return (Scm_VMApply2 (-> (SCM_SYNTAX syn) handler) program cenv))) (define-cproc syntax-handler (syn) (SCM_ASSERT (SCM_SYNTAXP syn)) (return (-> (SCM_SYNTAX syn) handler))) (define-in-module gauche (trace-macro . args) ;; force resolving autoload of pprint before changing *trace-macro*; otherwise, ;; autoloading pprint can trigger macro tracing which needs pprint. (procedure? pprint) (match args [() #f] ;just show current traces [(#t) (set! *trace-macro* #t)] ;trace all macros [(#f) (set! *trace-macro* #f)] ;untrace all macros [(objs ...) (unless (every (^x (or (symbol? x) (regexp? x))) objs) (error "Argument(s) of trace-macro should be a \ boolean, or symbols or regexps, but got:" args)) (and-let1 ms (cond [(not *trace-macro*) '()] [(list? *trace-macro*) *trace-macro*] [else #f]) ;; if we're tracing all macros, no need to ;; add symbols. (set! *trace-macro* (delete-duplicates (append objs ms))))]) *trace-macro*) (define-in-module gauche (untrace-macro . args) (match args [() (set! *trace-macro* #f)] ;untrace all [(sym ...) (when (list? *trace-macro*) (let1 ms (remove (cute member <> sym) *trace-macro*) (set! *trace-macro* (if (null? ms) #f ms))))]) *trace-macro*)
null
https://raw.githubusercontent.com/shirok/Gauche/c1354197084f83941d3f13cdd6e2335e8e9332ee/src/libmacbase.scm
scheme
libmacbase.scm - macro basic staff Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the authors nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This file defines lower level layer of macro system. Initialization of compile.scm depends on this file. macroexpand FORM [ENV/FLAG] macroexpand-1 FORM [ENV/FLAG] ENV/FLAG can be: #f - we expand it in the current runtime env, run unravel-syntax on output #t - we expand it in the current runtime env #<module> - use it as the toplevel env. API API API This strips all syntactic information (lossy) API Unwrap only if obj is an identifier. API This preserves identity of local identifiers by suffixing it. The identity of toplevel identifiers are still not preserved across modules. identifier -> symbol These are used in the compiler, and hidden inside gauche.internal. Transformer interface *trace-macro* can be #f (default - no trace), #t (trace all macros), or a list of symbols/regexp (trace macros whose name that matches) so that we can correspond the identifiers from input and output. force resolving autoload of pprint before changing *trace-macro*; otherwise, autoloading pprint can trigger macro tracing which needs pprint. just show current traces trace all macros untrace all macros if we're tracing all macros, no need to add symbols. untrace all
Copyright ( c ) 2000 - 2022 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING (select-module gauche.internal) (use util.match) (inline-stub (declcode (.include "gauche/priv/macroP.h"))) Macro expansion utilities (define-in-module gauche (macroexpand form :optional (env/flag #f)) (%do-macroexpand form env/flag #f)) (define-in-module gauche (macroexpand-1 form :optional (env/flag #f)) (%do-macroexpand form env/flag #t)) (define (%do-macroexpand form env/flag once?) (let* ([env (cond [(boolean? env/flag) (vm-current-module)] [(module? env/flag) env/flag] [else (error "argument must be a boolean or a module, but got:" env/flag)])] [r (%internal-macro-expand form (make-cenv env) once?)]) (if (eq? env/flag #f) (unravel-syntax r) r))) (select-module gauche) (define-cproc unwrap-syntax (form :optional (to_immutable::<boolean> #f)) (return (Scm_UnwrapSyntax2 form to_immutable))) (define-cproc unwrap-syntax-1 (obj) (if (SCM_IDENTIFIERP obj) (return (SCM_OBJ (Scm_UnwrapIdentifier (SCM_IDENTIFIER obj)))) (return obj))) (select-module gauche.internal) (define-in-module gauche (unravel-syntax form) (define id->sym (^[id] (or (hash-table-get tab id #f) (let1 nam (unwrap-syntax id) (if (global-identifier=? id (make-identifier nam (vm-current-module) '())) (begin (hash-table-put! tab id nam) nam) (let1 num ($ hash-table-fold tab (^[i _ c] (if (eq? (unwrap-syntax i) nam) (+ c 1) c)) 0) (rlet1 sym (symbol-append nam "." num) (hash-table-put! tab id sym))))))))) (define (rec form) (cond [(wrapped-identifier? form) (id->sym form)] [(pair? form) (cons (rec (car form)) (rec (cdr form)))] [(vector? form) (vector-map rec form)] [else form])) (rec form)) (select-module gauche.internal) (inline-stub (declare-stub-type <macro> "ScmMacro*" "macro" "SCM_MACROP" "SCM_MACRO" "SCM_OBJ") ) (define-cproc macro? (obj) ::<boolean> SCM_MACROP) (define-cproc syntax? (obj) ::<boolean> SCM_SYNTAXP) Macro object (select-module gauche) (inline-stub (define-cclass <macro> "ScmMacro*" "Scm_MacroClass" (c "SCM_CLASS_DEFAULT_CPL") ((name :setter #f) (transformer :setter #f) (info-alist :c-name "info_alist" :setter #f) (flags :type <ulong> :setter #f)) (printer (Scm_Printf port "#<macro %A>" (-> (SCM_MACRO obj) name))))) NB : % make - macro - transformer is in libalpha.scm (select-module gauche.internal) (define-cproc compile-syntax-rules (name src ellipsis literals rules mod env) Scm_CompileSyntaxRules) (define-cproc macro-transformer (mac::<macro>) Scm_MacroTransformer) (define-cproc macro-name (mac::<macro>) Scm_MacroName) (define-cproc identifier-macro? (mac::<macro>) ::<boolean> (return (logand (-> mac flags) SCM_MACRO_IDENTIFIER))) Macro expand tracer (define *trace-macro* #f) (define (%macro-traced? mac) (or (eq? *trace-macro* #t) (and-let1 macname (unwrap-syntax (macro-name mac)) (find (^z (cond [(symbol? z) (eq? z macname)] [(regexp? z) (z (symbol->string macname))] [else #f])) *trace-macro*)))) (define (call-macro-expander mac expr cenv) (let* ([r ((macro-transformer mac) expr cenv)] [out (if (and (pair? r) (not (eq? expr r))) (rlet1 p (if (extended-pair? r) r (extended-cons (car r) (cdr r))) (pair-attribute-set! p 'original expr)) r)]) (when (and *trace-macro* (%macro-traced? mac)) NB : We need to apply unravel - syntax on expr and out at once , (let1 unraveled (unravel-syntax (cons expr out)) (display "Macro input>>>\n" (current-trace-port)) (pprint (car unraveled) :port (current-trace-port) :level #f :length #f) (display "\nMacro output<<<\n" (current-trace-port)) (pprint (cdr unraveled) :port (current-trace-port) :level #f :length #f) (display "\n" (current-trace-port)) (flush (current-trace-port)))) out)) (define (call-id-macro-expander mac cenv) (unless (identifier-macro? mac) (error "Non-identifier-macro can't appear in this context:" mac)) (call-macro-expander mac mac cenv)) (define-cproc make-syntax (name::<symbol> module::<module> proc) Scm_MakeSyntax) (define-cproc call-syntax-handler (syn program cenv) (SCM_ASSERT (SCM_SYNTAXP syn)) (return (Scm_VMApply2 (-> (SCM_SYNTAX syn) handler) program cenv))) (define-cproc syntax-handler (syn) (SCM_ASSERT (SCM_SYNTAXP syn)) (return (-> (SCM_SYNTAX syn) handler))) (define-in-module gauche (trace-macro . args) (procedure? pprint) (match args [(objs ...) (unless (every (^x (or (symbol? x) (regexp? x))) objs) (error "Argument(s) of trace-macro should be a \ boolean, or symbols or regexps, but got:" args)) (and-let1 ms (cond [(not *trace-macro*) '()] [(list? *trace-macro*) *trace-macro*] (set! *trace-macro* (delete-duplicates (append objs ms))))]) *trace-macro*) (define-in-module gauche (untrace-macro . args) (match args [(sym ...) (when (list? *trace-macro*) (let1 ms (remove (cute member <> sym) *trace-macro*) (set! *trace-macro* (if (null? ms) #f ms))))]) *trace-macro*)
6ef8589299159a9e968cdf09be0c46488a0b8618c552deb3690cae97e2af54fa
prg-titech/baccaml
m.ml
(* customized version of Map *) module M = struct include Map.Make (struct type t = Id.t let compare = compare end) let rec find_greedy key env = let open Option in let rec find_greedy' key env = match find_opt key env with | Some v' -> find_greedy' v' env | None -> some key in match find_opt key env with | Some v' -> find_greedy' v' env | None -> none [@@ocamlformat "disable"] end include M let add_list xys env = List.fold_left (fun env (x, y) -> add x y env) env xys let add_list2 xs ys env = List.fold_left2 (fun env x y -> add x y env) env xs ys let to_list m = M.fold (fun key elem acc -> acc @ [ key, elem ]) m []
null
https://raw.githubusercontent.com/prg-titech/baccaml/a3b95e996a995b5004ca897a4b6419edfee590aa/base/m.ml
ocaml
customized version of Map
module M = struct include Map.Make (struct type t = Id.t let compare = compare end) let rec find_greedy key env = let open Option in let rec find_greedy' key env = match find_opt key env with | Some v' -> find_greedy' v' env | None -> some key in match find_opt key env with | Some v' -> find_greedy' v' env | None -> none [@@ocamlformat "disable"] end include M let add_list xys env = List.fold_left (fun env (x, y) -> add x y env) env xys let add_list2 xs ys env = List.fold_left2 (fun env x y -> add x y env) env xs ys let to_list m = M.fold (fun key elem acc -> acc @ [ key, elem ]) m []
c46a83d48444d67cadd6dacb1750bbccfb5888c553beabef7f024afe12c99d0c
snmsts/cl-langserver
slynk-loader.lisp
;;;; -*- indent-tabs-mode: nil -*- ;;; slynk-loader.lisp --- Compile and load the backend . ;;; Created 2003 , < > ;;; ;;; This code has been placed in the Public Domain. All warranties ;;; are disclaimed. ;;; ;; If you want customize the source- or fasl-directory you can set ;; ls-loader:*source-directory* resp. ls-loader:*fasl-directory* ;; before loading this files. ;; E.g.: ;; ;; (load ".../slynk-loader.lisp") ;; (setq ls-loader::*fasl-directory* "/tmp/fasl/") ;; (ls-loader:init) (cl:defpackage :ls-loader (:use :cl) (:export #:init #:dump-image #:*source-directory* #:*fasl-directory* #:*load-path*)) (cl:in-package :ls-loader) (defvar *source-directory* (make-pathname :name nil :type nil :defaults (or *load-pathname* *default-pathname-defaults*)) "The directory where to look for the source.") (defvar *load-path* (list *source-directory*) "A list of directories to search for modules.") (defparameter *sysdep-files* #+cmu '(slynk-source-path-parser slynk-source-file-cache (backend cmucl)) #+scl '(slynk-source-path-parser slynk-source-file-cache (backend scl)) #+sbcl '(slynk-source-path-parser slynk-source-file-cache (backend sbcl)) #+clozure '(metering (backend ccl)) #+lispworks '((backend lispworks)) #+allegro '((backend allegro)) #+clisp '(xref metering (backend clisp)) #+armedbear '((backend abcl)) #+cormanlisp '((backend corman)) #+ecl '(slynk-source-path-parser slynk-source-file-cache (backend ecl)) #+clasp '((backend clasp)) #+mkcl '((backend mkcl))) (defparameter *implementation-features* '(:allegro :lispworks :sbcl :clozure :cmu :clisp :ccl :corman :cormanlisp :armedbear :gcl :ecl :scl :mkcl :clasp)) (defparameter *os-features* '(:macosx :linux :windows :mswindows :win32 :solaris :darwin :sunos :hpux :unix)) (defparameter *architecture-features* '(:powerpc :ppc :x86 :x86-64 :x86_64 :amd64 :i686 :i586 :i486 :pc386 :iapx386 :sparc64 :sparc :hppa64 :hppa :arm :armv5l :armv6l :armv7l :arm64 :pentium3 :pentium4 :mips :mipsel :java-1.4 :java-1.5 :java-1.6 :java-1.7)) (defun q (s) (read-from-string s)) #+ecl (defun ecl-version-string () (format nil "~A~@[-~A~]" (lisp-implementation-version) (when (find-symbol "LISP-IMPLEMENTATION-VCS-ID" :ext) (let ((vcs-id (funcall (q "ext:lisp-implementation-vcs-id")))) (when (>= (length vcs-id) 8) (subseq vcs-id 0 8)))))) #+clasp (defun clasp-version-string () (format nil "~A~@[-~A~]" (lisp-implementation-version) (core:lisp-implementation-id))) (defun lisp-version-string () #+(or clozure cmu) (substitute-if #\_ (lambda (x) (find x " /")) (lisp-implementation-version)) #+(or cormanlisp scl mkcl) (lisp-implementation-version) #+sbcl (format nil "~a~:[~;-no-threads~]" (lisp-implementation-version) #+sb-thread nil #-sb-thread t) #+lispworks (lisp-implementation-version) #+allegro (format nil "~@{~a~}" excl::*common-lisp-version-number* ANSI vs MoDeRn (if (member :smp *features*) "s" "") (if (member :64bit *features*) "-64bit" "") (excl:ics-target-case (:-ics "") (:+ics "-ics"))) #+clisp (let ((s (lisp-implementation-version))) (subseq s 0 (position #\space s))) #+armedbear (lisp-implementation-version) #+ecl (ecl-version-string) ) (defun unique-dir-name () "Return a name that can be used as a directory name that is unique to a Lisp implementation, Lisp implementation version, operating system, and hardware architecture." (flet ((first-of (features) (loop for f in features when (find f *features*) return it)) (maybe-warn (value fstring &rest args) (cond (value) (t (apply #'warn fstring args) "unknown")))) (let ((lisp (maybe-warn (first-of *implementation-features*) "No implementation feature found in ~a." *implementation-features*)) (os (maybe-warn (first-of *os-features*) "No os feature found in ~a." *os-features*)) (arch (maybe-warn (first-of *architecture-features*) "No architecture feature found in ~a." *architecture-features*)) (version (maybe-warn (lisp-version-string) "Don't know how to get Lisp ~ implementation version."))) (format nil "~(~@{~a~^-~}~)" lisp version os arch)))) (defun file-newer-p (new-file old-file) "Returns true if NEW-FILE is newer than OLD-FILE." (> (file-write-date new-file) (file-write-date old-file))) (defun sly-version-string () ;; Duplicate in slynk.lisp, who uses it to negotiate versions between sly / slynk . We use it to figure out where to put . "Return a string identifying the SLY version. Return nil if nothing appropriate is available." (ignore-errors (with-open-file (s (make-pathname :name "sly" :type "el" :directory (butlast (pathname-directory this-file) 1) :defaults this-file)) (let ((seq (make-array 200 :element-type 'character :initial-element #\null))) (read-sequence seq s :end 200) (let* ((beg (search ";; Version:" seq)) (end (position #\NewLine seq :start beg)) (middle (position #\Space seq :from-end t :end end))) (subseq seq (1+ middle) end)))))) (defun default-fasl-dir () (merge-pathnames (make-pathname :directory `(:relative ".sly" "fasl" ,@(if (sly-version-string) (list (sly-version-string))) ,(unique-dir-name))) (user-homedir-pathname))) (defvar *fasl-directory* (default-fasl-dir) "The directory where fasl files should be placed.") (defun binary-pathname (src-pathname binary-dir) "Return the pathname where SRC-PATHNAME's binary should be compiled." (let ((cfp (compile-file-pathname src-pathname))) (merge-pathnames (make-pathname :name (pathname-name cfp) :type (pathname-type cfp)) binary-dir))) (defun handle-slynk-load-error (condition context pathname) (fresh-line *error-output*) (pprint-logical-block (*error-output* () :per-line-prefix ";; ") (format *error-output* "~%Error ~A ~A:~% ~A~%" context pathname condition))) (defun compile-files (files fasl-dir load quiet) "Compile each file in FILES if the source is newer than its corresponding binary, or the file preceding it was recompiled. If LOAD is true, load the fasl file." (let ((needs-recompile nil) (state :unknown)) (dolist (src files) (let ((dest (binary-pathname src fasl-dir))) (handler-bind ((error (lambda (c) (ecase state (:compile (handle-slynk-load-error c "compiling" src)) (:load (handle-slynk-load-error c "loading" dest)) (:unknown (handle-slynk-load-error c "???ing" src)))))) (when (or needs-recompile (not (probe-file dest)) (file-newer-p src dest)) (ensure-directories-exist dest) need to recompile SRC , so we 'll need to recompile ;; everything after this too. (setf needs-recompile t state :compile) (or (compile-file src :output-file dest :print nil :verbose (not quiet)) ;; An implementation may not necessarily signal a condition itself when COMPILE - FILE fails ( e.g. ECL ) (error "COMPILE-FILE returned NIL."))) (when load (setf state :load) (load dest :verbose (not quiet)))))))) #+cormanlisp (defun compile-files (files fasl-dir load quiet) "Corman Lisp has trouble with compiled files." (declare (ignore fasl-dir)) (when load (dolist (file files) (load file :verbose (not quiet) (force-output))))) (defun ensure-list (o) (if (listp o) o (list o))) (defun src-files (files src-dir) "Return actual pathnames for each spec in FILES." (mapcar (lambda (compound-name) (let* ((directories (butlast compound-name)) (name (car (last compound-name)))) (make-pathname :name (string-downcase name) :type "lisp" :directory (append (or (pathname-directory src-dir) '(:relative)) (mapcar #'string-downcase directories)) :defaults src-dir))) (mapcar #'ensure-list files))) (defvar *slynk-files* `(ls-backend ,@*sysdep-files* #-armedbear slynk-gray slynk-match slynk-rpc slynk slynk-completion)) (defun load-slynk (&key (src-dir *source-directory*) (fasl-dir *fasl-directory*) quiet) (compile-files (src-files *slynk-files* src-dir) fasl-dir t quiet)) (defun delete-stale-contrib-fasl-files (slynk-files contrib-files fasl-dir) (let ((newest (reduce #'max (mapcar #'file-write-date slynk-files)))) (dolist (src contrib-files) (let ((fasl (binary-pathname src fasl-dir))) (when (and (probe-file fasl) (<= (file-write-date fasl) newest)) (delete-file fasl)))))) (defun loadup () (load-slynk)) (defun setup () (funcall (q "ls-base::init"))) (defun string-starts-with (string prefix) (string-equal string prefix :end1 (min (length string) (length prefix)))) (defun list-slynk-packages () (remove-if-not (lambda (package) (let ((name (package-name package))) (and (string-not-equal name "ls-loader") (string-starts-with name "slynk")))) (list-all-packages))) (defun delete-packages (packages) (dolist (package packages) (flet ((handle-package-error (c) (let ((pkgs (set-difference (package-used-by-list package) packages))) (when pkgs (warn "deleting ~a which is used by ~{~a~^, ~}." package pkgs)) (continue c)))) (handler-bind ((package-error #'handle-package-error)) (delete-package package))))) (defun init (&key delete reload (setup t) (quiet (not *load-verbose*)) load-contribs) "Load SLYNK and initialize some global variables. If DELETE is true, delete any existing SLYNK packages. If RELOAD is true, reload SLYNK, even if the SLYNK package already exists. If SETUP is true, load user init files and initialize some global variabes in SLYNK." (if load-contribs (warn "LOAD-CONTRIBS arg to LS-LOADER:INIT is deprecated and useless")) (when (and delete (find-package :slynk)) (delete-packages (list-slynk-packages)) (mapc #'delete-package '(:ls-base :ls-io-package :ls-backend))) (cond ((or (not (find-package :ls-base)) reload) (load-slynk :quiet quiet)) (t (warn "Not reloading SLYNK. Package already exists."))) (when setup (setup))) (defun dump-image (filename) (init :setup nil) (funcall (q "ls-backend:save-image") filename)) Simple * require - module * function for asdf-loader.lisp . (defun module-binary-dir (src-file) (flet ((dir-components (path) (cdr (pathname-directory path)))) (make-pathname :directory (append (pathname-directory *fasl-directory*) (nthcdr (mismatch (dir-components *fasl-directory*) (dir-components src-file) :test #'equal) (dir-components src-file)))))) (defun require-module (module) (labels ((module () (string-upcase module)) (provided () (member (string-upcase (module)) *modules* :test #'string=))) (unless (provided) (let ((src-file (some #'(lambda (dir) (probe-file (make-pathname :name (string-downcase module) :type "lisp" :defaults dir))) *load-path*))) (assert src-file nil "Required module ~a but no source file found in ~a" module *load-path*) (compile-files (list src-file) (module-binary-dir src-file) 'load nil) (assert (provided) nil "Compiled and loaded ~a but required module ~s was not provided" src-file module)))))
null
https://raw.githubusercontent.com/snmsts/cl-langserver/3b1246a5d0bd58459e7a64708f820bf718cf7175/src/helitage/slynk-loader.lisp
lisp
-*- indent-tabs-mode: nil -*- This code has been placed in the Public Domain. All warranties are disclaimed. If you want customize the source- or fasl-directory you can set ls-loader:*source-directory* resp. ls-loader:*fasl-directory* before loading this files. E.g.: (load ".../slynk-loader.lisp") (setq ls-loader::*fasl-directory* "/tmp/fasl/") (ls-loader:init) Duplicate in slynk.lisp, who uses it to negotiate versions everything after this too. An implementation may not necessarily signal a
slynk-loader.lisp --- Compile and load the backend . Created 2003 , < > (cl:defpackage :ls-loader (:use :cl) (:export #:init #:dump-image #:*source-directory* #:*fasl-directory* #:*load-path*)) (cl:in-package :ls-loader) (defvar *source-directory* (make-pathname :name nil :type nil :defaults (or *load-pathname* *default-pathname-defaults*)) "The directory where to look for the source.") (defvar *load-path* (list *source-directory*) "A list of directories to search for modules.") (defparameter *sysdep-files* #+cmu '(slynk-source-path-parser slynk-source-file-cache (backend cmucl)) #+scl '(slynk-source-path-parser slynk-source-file-cache (backend scl)) #+sbcl '(slynk-source-path-parser slynk-source-file-cache (backend sbcl)) #+clozure '(metering (backend ccl)) #+lispworks '((backend lispworks)) #+allegro '((backend allegro)) #+clisp '(xref metering (backend clisp)) #+armedbear '((backend abcl)) #+cormanlisp '((backend corman)) #+ecl '(slynk-source-path-parser slynk-source-file-cache (backend ecl)) #+clasp '((backend clasp)) #+mkcl '((backend mkcl))) (defparameter *implementation-features* '(:allegro :lispworks :sbcl :clozure :cmu :clisp :ccl :corman :cormanlisp :armedbear :gcl :ecl :scl :mkcl :clasp)) (defparameter *os-features* '(:macosx :linux :windows :mswindows :win32 :solaris :darwin :sunos :hpux :unix)) (defparameter *architecture-features* '(:powerpc :ppc :x86 :x86-64 :x86_64 :amd64 :i686 :i586 :i486 :pc386 :iapx386 :sparc64 :sparc :hppa64 :hppa :arm :armv5l :armv6l :armv7l :arm64 :pentium3 :pentium4 :mips :mipsel :java-1.4 :java-1.5 :java-1.6 :java-1.7)) (defun q (s) (read-from-string s)) #+ecl (defun ecl-version-string () (format nil "~A~@[-~A~]" (lisp-implementation-version) (when (find-symbol "LISP-IMPLEMENTATION-VCS-ID" :ext) (let ((vcs-id (funcall (q "ext:lisp-implementation-vcs-id")))) (when (>= (length vcs-id) 8) (subseq vcs-id 0 8)))))) #+clasp (defun clasp-version-string () (format nil "~A~@[-~A~]" (lisp-implementation-version) (core:lisp-implementation-id))) (defun lisp-version-string () #+(or clozure cmu) (substitute-if #\_ (lambda (x) (find x " /")) (lisp-implementation-version)) #+(or cormanlisp scl mkcl) (lisp-implementation-version) #+sbcl (format nil "~a~:[~;-no-threads~]" (lisp-implementation-version) #+sb-thread nil #-sb-thread t) #+lispworks (lisp-implementation-version) #+allegro (format nil "~@{~a~}" excl::*common-lisp-version-number* ANSI vs MoDeRn (if (member :smp *features*) "s" "") (if (member :64bit *features*) "-64bit" "") (excl:ics-target-case (:-ics "") (:+ics "-ics"))) #+clisp (let ((s (lisp-implementation-version))) (subseq s 0 (position #\space s))) #+armedbear (lisp-implementation-version) #+ecl (ecl-version-string) ) (defun unique-dir-name () "Return a name that can be used as a directory name that is unique to a Lisp implementation, Lisp implementation version, operating system, and hardware architecture." (flet ((first-of (features) (loop for f in features when (find f *features*) return it)) (maybe-warn (value fstring &rest args) (cond (value) (t (apply #'warn fstring args) "unknown")))) (let ((lisp (maybe-warn (first-of *implementation-features*) "No implementation feature found in ~a." *implementation-features*)) (os (maybe-warn (first-of *os-features*) "No os feature found in ~a." *os-features*)) (arch (maybe-warn (first-of *architecture-features*) "No architecture feature found in ~a." *architecture-features*)) (version (maybe-warn (lisp-version-string) "Don't know how to get Lisp ~ implementation version."))) (format nil "~(~@{~a~^-~}~)" lisp version os arch)))) (defun file-newer-p (new-file old-file) "Returns true if NEW-FILE is newer than OLD-FILE." (> (file-write-date new-file) (file-write-date old-file))) (defun sly-version-string () between sly / slynk . We use it to figure out where to put . "Return a string identifying the SLY version. Return nil if nothing appropriate is available." (ignore-errors (with-open-file (s (make-pathname :name "sly" :type "el" :directory (butlast (pathname-directory this-file) 1) :defaults this-file)) (let ((seq (make-array 200 :element-type 'character :initial-element #\null))) (read-sequence seq s :end 200) (let* ((beg (search ";; Version:" seq)) (end (position #\NewLine seq :start beg)) (middle (position #\Space seq :from-end t :end end))) (subseq seq (1+ middle) end)))))) (defun default-fasl-dir () (merge-pathnames (make-pathname :directory `(:relative ".sly" "fasl" ,@(if (sly-version-string) (list (sly-version-string))) ,(unique-dir-name))) (user-homedir-pathname))) (defvar *fasl-directory* (default-fasl-dir) "The directory where fasl files should be placed.") (defun binary-pathname (src-pathname binary-dir) "Return the pathname where SRC-PATHNAME's binary should be compiled." (let ((cfp (compile-file-pathname src-pathname))) (merge-pathnames (make-pathname :name (pathname-name cfp) :type (pathname-type cfp)) binary-dir))) (defun handle-slynk-load-error (condition context pathname) (fresh-line *error-output*) (pprint-logical-block (*error-output* () :per-line-prefix ";; ") (format *error-output* "~%Error ~A ~A:~% ~A~%" context pathname condition))) (defun compile-files (files fasl-dir load quiet) "Compile each file in FILES if the source is newer than its corresponding binary, or the file preceding it was recompiled. If LOAD is true, load the fasl file." (let ((needs-recompile nil) (state :unknown)) (dolist (src files) (let ((dest (binary-pathname src fasl-dir))) (handler-bind ((error (lambda (c) (ecase state (:compile (handle-slynk-load-error c "compiling" src)) (:load (handle-slynk-load-error c "loading" dest)) (:unknown (handle-slynk-load-error c "???ing" src)))))) (when (or needs-recompile (not (probe-file dest)) (file-newer-p src dest)) (ensure-directories-exist dest) need to recompile SRC , so we 'll need to recompile (setf needs-recompile t state :compile) (or (compile-file src :output-file dest :print nil :verbose (not quiet)) condition itself when COMPILE - FILE fails ( e.g. ECL ) (error "COMPILE-FILE returned NIL."))) (when load (setf state :load) (load dest :verbose (not quiet)))))))) #+cormanlisp (defun compile-files (files fasl-dir load quiet) "Corman Lisp has trouble with compiled files." (declare (ignore fasl-dir)) (when load (dolist (file files) (load file :verbose (not quiet) (force-output))))) (defun ensure-list (o) (if (listp o) o (list o))) (defun src-files (files src-dir) "Return actual pathnames for each spec in FILES." (mapcar (lambda (compound-name) (let* ((directories (butlast compound-name)) (name (car (last compound-name)))) (make-pathname :name (string-downcase name) :type "lisp" :directory (append (or (pathname-directory src-dir) '(:relative)) (mapcar #'string-downcase directories)) :defaults src-dir))) (mapcar #'ensure-list files))) (defvar *slynk-files* `(ls-backend ,@*sysdep-files* #-armedbear slynk-gray slynk-match slynk-rpc slynk slynk-completion)) (defun load-slynk (&key (src-dir *source-directory*) (fasl-dir *fasl-directory*) quiet) (compile-files (src-files *slynk-files* src-dir) fasl-dir t quiet)) (defun delete-stale-contrib-fasl-files (slynk-files contrib-files fasl-dir) (let ((newest (reduce #'max (mapcar #'file-write-date slynk-files)))) (dolist (src contrib-files) (let ((fasl (binary-pathname src fasl-dir))) (when (and (probe-file fasl) (<= (file-write-date fasl) newest)) (delete-file fasl)))))) (defun loadup () (load-slynk)) (defun setup () (funcall (q "ls-base::init"))) (defun string-starts-with (string prefix) (string-equal string prefix :end1 (min (length string) (length prefix)))) (defun list-slynk-packages () (remove-if-not (lambda (package) (let ((name (package-name package))) (and (string-not-equal name "ls-loader") (string-starts-with name "slynk")))) (list-all-packages))) (defun delete-packages (packages) (dolist (package packages) (flet ((handle-package-error (c) (let ((pkgs (set-difference (package-used-by-list package) packages))) (when pkgs (warn "deleting ~a which is used by ~{~a~^, ~}." package pkgs)) (continue c)))) (handler-bind ((package-error #'handle-package-error)) (delete-package package))))) (defun init (&key delete reload (setup t) (quiet (not *load-verbose*)) load-contribs) "Load SLYNK and initialize some global variables. If DELETE is true, delete any existing SLYNK packages. If RELOAD is true, reload SLYNK, even if the SLYNK package already exists. If SETUP is true, load user init files and initialize some global variabes in SLYNK." (if load-contribs (warn "LOAD-CONTRIBS arg to LS-LOADER:INIT is deprecated and useless")) (when (and delete (find-package :slynk)) (delete-packages (list-slynk-packages)) (mapc #'delete-package '(:ls-base :ls-io-package :ls-backend))) (cond ((or (not (find-package :ls-base)) reload) (load-slynk :quiet quiet)) (t (warn "Not reloading SLYNK. Package already exists."))) (when setup (setup))) (defun dump-image (filename) (init :setup nil) (funcall (q "ls-backend:save-image") filename)) Simple * require - module * function for asdf-loader.lisp . (defun module-binary-dir (src-file) (flet ((dir-components (path) (cdr (pathname-directory path)))) (make-pathname :directory (append (pathname-directory *fasl-directory*) (nthcdr (mismatch (dir-components *fasl-directory*) (dir-components src-file) :test #'equal) (dir-components src-file)))))) (defun require-module (module) (labels ((module () (string-upcase module)) (provided () (member (string-upcase (module)) *modules* :test #'string=))) (unless (provided) (let ((src-file (some #'(lambda (dir) (probe-file (make-pathname :name (string-downcase module) :type "lisp" :defaults dir))) *load-path*))) (assert src-file nil "Required module ~a but no source file found in ~a" module *load-path*) (compile-files (list src-file) (module-binary-dir src-file) 'load nil) (assert (provided) nil "Compiled and loaded ~a but required module ~s was not provided" src-file module)))))
2e5e0badeb5221642d8da8afce026d952f903951973fdef3bbc0f39fec64798b
russmatney/ralphie
rofi.clj
(ns ralphie.rofi (:require [babashka.process :refer [$ check]] [clojure.string :as string] [ralphie.zsh :as zsh] [ralphie.awesome :as awm] [ralphie.doctor :as doctor])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rofi-general ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn escape-rofi-label [label] (string/escape label {\& "&amp;"})) ;; TODO Tests for this,especially that ensure the result is returned (defn rofi "Expects `xs` to be a coll of maps with a `:label` key. `msg` is displayed to the user. Upon selection, if the user-input matches a label, that `x` is selected and retuned. If a no match is found, the user input is returned. If on-select is passed, it is called with the selected input. Supports :require-match? in `opts`. " TODO move opts and xs over to : rofi / prefixed keys ([opts] (rofi opts (:xs opts))) ([{:keys [msg message on-select require-match?]} xs] (doctor/log "Rofi called with" (count xs) "xs.") ;; push any floating windows into the view (awm/awm-cli {:quiet? true} (str ;; set all ontops false "for c in awful.client.iterate(function (c) return c.ontop end) do\n" "c.ontop = false; " "c.floating = false; " "end;")) (let [maps? (-> xs first map?) labels (if maps? (->> xs (map (some-fn :label :rofi/label)) (map escape-rofi-label) ) xs) msg (or msg message) selected-label (some-> ^{:in (string/join "|" labels) :out :string} ($ rofi -i ~(if require-match? "-no-custom" "") -sep "|" -markup-rows -normal-window ;; NOTE may want this to be optional -eh 2 ; ; row height ;; -dynamic ;; -no-fixed-num-lines -dmenu -mesg ~msg -sync -p *) ((fn [proc] ;; check for type of error (let [res @proc] (cond (zero? (:exit res)) (-> res :out string/trim) TODO determine if simple nothing - selected or actual rofi error (= 1 (:exit res)) (do (doctor/log "Rofi Nothing Selected (or Error)") nil) :else (do (println res) (check proc)))))))] (when (seq selected-label) TODO use index - by , or just make a map (let [selected-x (if maps? (->> xs (filter (fn [x] (-> (or (:rofi/label x) (:label x)) escape-rofi-label (string/starts-with? selected-label)))) first) selected-label)] (if selected-x (if-let [on-select (or ((some-fn :rofi/on-select :on-select) selected-x) on-select)] (do TODO support zero - arity on - select here ;; (println "on-select found" on-select) ;; (println "argslists" (-> on-select meta :arglists)) (on-select selected-x)) selected-x) selected-label)))))) (comment TODO convert to tests (-> ^{:in "11 iiii\n22 IIIIII\n33 33333"} ($ rofi -i -dmenu -mesg "Select bookmark to open" -sync -p *) check :out slurp) (rofi {:msg "message"} [{:label "iii" :url "urlllll"} {:label "333" :url "something"} {:label "jkjkjkjkjkjkjkjkjkjkjkjkjkjkjk" :url "w/e"} {:label "xxxxxxxx" :url "--------------"}]) (rofi {:require-match? true :msg "message"} [{:label "iii" :url "urlllll"} {:label "333" :url "something"} {:label "jkjkjkjkjkjkjkjkjkjkjkjkjkjkjk" :url "w/e"} {:label "xxxxxxxx" :url "--------------"}])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Suggestion helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; TODO move to zsh namespace (defn zsh-history "Zsh history as rofi-xs. TODO cache/speed up/trim allowed entries " [] (->> (zsh/history) reverse ;; (sort-by :timestamp >) (map (fn [{:keys [line]}] {:label line :on-select :label})))) (comment (take 3 (zsh-history)))
null
https://raw.githubusercontent.com/russmatney/ralphie/b096c1c5d05154feff59975135896c0555233295/src/ralphie/rofi.clj
clojure
rofi-general TODO Tests for this,especially that ensure the result is returned push any floating windows into the view set all ontops false NOTE may want this to be optional ; row height -dynamic -no-fixed-num-lines check for type of error (println "on-select found" on-select) (println "argslists" (-> on-select meta :arglists)) Suggestion helpers (sort-by :timestamp >)
(ns ralphie.rofi (:require [babashka.process :refer [$ check]] [clojure.string :as string] [ralphie.zsh :as zsh] [ralphie.awesome :as awm] [ralphie.doctor :as doctor])) (defn escape-rofi-label [label] (string/escape label {\& "&amp;"})) (defn rofi "Expects `xs` to be a coll of maps with a `:label` key. `msg` is displayed to the user. Upon selection, if the user-input matches a label, that `x` is selected and retuned. If a no match is found, the user input is returned. If on-select is passed, it is called with the selected input. Supports :require-match? in `opts`. " TODO move opts and xs over to : rofi / prefixed keys ([opts] (rofi opts (:xs opts))) ([{:keys [msg message on-select require-match?]} xs] (doctor/log "Rofi called with" (count xs) "xs.") (awm/awm-cli {:quiet? true} (str "for c in awful.client.iterate(function (c) return c.ontop end) do\n" "c.ontop = false; " "c.floating = false; " "end;")) (let [maps? (-> xs first map?) labels (if maps? (->> xs (map (some-fn :label :rofi/label)) (map escape-rofi-label) ) xs) msg (or msg message) selected-label (some-> ^{:in (string/join "|" labels) :out :string} ($ rofi -i ~(if require-match? "-no-custom" "") -sep "|" -markup-rows -dmenu -mesg ~msg -sync -p *) ((fn [proc] (let [res @proc] (cond (zero? (:exit res)) (-> res :out string/trim) TODO determine if simple nothing - selected or actual rofi error (= 1 (:exit res)) (do (doctor/log "Rofi Nothing Selected (or Error)") nil) :else (do (println res) (check proc)))))))] (when (seq selected-label) TODO use index - by , or just make a map (let [selected-x (if maps? (->> xs (filter (fn [x] (-> (or (:rofi/label x) (:label x)) escape-rofi-label (string/starts-with? selected-label)))) first) selected-label)] (if selected-x (if-let [on-select (or ((some-fn :rofi/on-select :on-select) selected-x) on-select)] (do TODO support zero - arity on - select here (on-select selected-x)) selected-x) selected-label)))))) (comment TODO convert to tests (-> ^{:in "11 iiii\n22 IIIIII\n33 33333"} ($ rofi -i -dmenu -mesg "Select bookmark to open" -sync -p *) check :out slurp) (rofi {:msg "message"} [{:label "iii" :url "urlllll"} {:label "333" :url "something"} {:label "jkjkjkjkjkjkjkjkjkjkjkjkjkjkjk" :url "w/e"} {:label "xxxxxxxx" :url "--------------"}]) (rofi {:require-match? true :msg "message"} [{:label "iii" :url "urlllll"} {:label "333" :url "something"} {:label "jkjkjkjkjkjkjkjkjkjkjkjkjkjkjk" :url "w/e"} {:label "xxxxxxxx" :url "--------------"}])) TODO move to zsh namespace (defn zsh-history "Zsh history as rofi-xs. TODO cache/speed up/trim allowed entries " [] (->> (zsh/history) reverse (map (fn [{:keys [line]}] {:label line :on-select :label})))) (comment (take 3 (zsh-history)))
e784db5e3aa6e96298eef2905d824f1d0b8ee5253e987860c7164132db24219d
nomeata/tasty-expected-failure
ExpectedFailure.hs
# LANGUAGE CPP # # LANGUAGE DeriveDataTypeable , ScopedTypeVariables , LambdaCase # module Test.Tasty.ExpectedFailure (expectFail, expectFailBecause, ignoreTest, ignoreTestBecause, wrapTest) where import Test.Tasty.Options import Test.Tasty.Runners import Test.Tasty.Providers #if MIN_VERSION_tasty(1,3,1) import Test.Tasty.Providers.ConsoleFormat ( ResultDetailsPrinter(..) ) #endif import Test.Tasty ( Timeout(..), askOption, localOption ) import Data.Typeable import Data.Tagged import Data.Maybe import Data.Monoid import Control.Exception ( displayException, evaluate, try, SomeException ) import Control.Concurrent.Timeout ( timeout ) data WrappedTest t = WrappedTest Timeout (IO Result -> IO Result) t deriving Typeable instance forall t. IsTest t => IsTest (WrappedTest t) where run opts (WrappedTest tmout wrap t) prog = -- Re-implement timeouts and exception handling *inside* the -- wrapper. The primary location for timeout and exception handling is in ` executeTest ` in the Tasty module 's -- Test.Tasty.Run implementation, but that handling is above the -- level of this wrapper which therefore cannot absorb timeouts -- and exceptions as *expected* failures. let (pre,post) = case tmout of NoTimeout -> (fmap Just, fromJust) Timeout t s -> (timeout t, fromMaybe (timeoutResult t s)) timeoutResult t s = Result { resultOutcome = Failure $ TestTimedOut t , resultDescription = "Timed out after " <> s , resultShortDescription = "TIMEOUT" , resultTime = fromIntegral t #if MIN_VERSION_tasty(1,3,1) , resultDetailsPrinter = ResultDetailsPrinter . const . const $ return () #endif } exceptionResult e = Result { resultOutcome = Failure $ TestThrewException e , resultDescription = "Exception: " ++ displayException e , resultShortDescription = "FAIL" , resultTime = 0 #if MIN_VERSION_tasty(1,3,1) , resultDetailsPrinter = ResultDetailsPrinter . const . const $ return () #endif } forceList = foldr seq () in wrap $ try (pre (run opts t prog -- Ensure exceptions trying to show the -- failure result are caught as "expected" ( see Issue # 24 and note below ) >>= \r -> evaluate (forceList (resultDescription r) `seq` forceList (resultShortDescription r) `seq` resultOutcome r `seq` r))) >>= \case Right r -> return (post r) Left (e :: SomeException) -> return $ exceptionResult e testOptions = retag (testOptions :: Tagged t [OptionDescription]) -- Note regarding post-run evaluate above: -- -- The normal behavior of tasty-expected-failure is to run the -- test, show the failure result, but then note that the failure -- is expected and not count that against a test failure. If the -- test unexpectedly succeeds, a message to that effect is -- printed, but there is no resultDescription display of the test -- inputs. -- As of Tasty 1.4 , the core tasty code was enhanced to fix issue # 280 in tasty : essentially the test result report is forced . -- However, when used with tests expected to fail that also throw -- exceptions when attempting to show the result, the forcing in Tasty 1.4 causes an exception to be thrown after the -- tasty-expected-failure protections but still within the realm -- where tasty would count it as a failure. The fix here attempts -- to `show` the failing value here in tasty-expected-failure; if -- an exception occurs during that `show` then code here will -- report it (somewhat incorrectly) via the exceptionResult above, -- where tasty's subsequent forcing of the text of that -- exceptionResult no longer causes an exception *there*. Since -- the value is only shown if there was already a failure, the -- reason is misleading but the outcome is consistent with the -- intent of tasty-expected-failure handling. -- | 'wrapTest' allows you to modify the behaviour of the tests, e.g. by -- modifying the result or not running the test at all. It is used to implement -- 'expectFail' and 'ignoreTest'. wrapTest :: (IO Result -> IO Result) -> TestTree -> TestTree wrapTest wrap = go where go (SingleTest n t) = askOption $ \(old_timeout :: Timeout) -> disable Tasty 's timeout ; handled here instead SingleTest n (WrappedTest old_timeout wrap t) go (TestGroup name tests) = TestGroup name (map go tests) go (PlusTestOptions plus tree) = PlusTestOptions plus (go tree) go (WithResource spec gentree) = WithResource spec (go . gentree) go (AskOptions f) = AskOptions (go . f) -- | Marks all tests in the given test suite as expected failures: The tests will -- still be run, but if they succeed, it is reported as a test suite failure, -- and conversely a the failure of the test is ignored. -- -- Any output of a failing test is still printed. -- -- This is useful if, in a test driven development, tests are written and -- commited to the master branch before their implementation: It allows the -- tests to fail (as expected) without making the whole test suite fail. -- -- Similarly, regressions and bugs can be documented in the test suite this -- way, until a fix is commited, and if a fix is applied (intentionally or -- accidentially), the test suite will remind you to remove the 'expectFail' -- marker. expectFail :: TestTree -> TestTree expectFail = expectFail' Nothing -- | Like 'expectFail' but with additional comment expectFailBecause :: String -> TestTree -> TestTree expectFailBecause reason = expectFail' (Just reason) expectFail' :: Maybe String -> TestTree -> TestTree expectFail' reason = wrapTest (fmap change) where change r | resultSuccessful r = r { resultOutcome = Failure TestFailed , resultDescription = resultDescription r <> " (unexpected success" <> comment <> ")" , resultShortDescription = resultShortDescription r <> " (unexpected" <> comment <> ")" } | otherwise = r { resultOutcome = Success , resultDescription = resultDescription r <> " (expected failure)" , resultShortDescription = resultShortDescription r <> " (expected" <> comment <> ")" } "" `append` s = s t `append` s | last t == '\n' = t ++ s ++ "\n" | otherwise = t ++ "\n" ++ s comment = maybe "" (mappend ": ") reason -- | Prevents the tests from running and reports them as succeeding. -- -- This may be be desireable as an alternative to commenting out the tests. This -- way, they are still typechecked (preventing bitrot), and the test report -- lists them, which serves as a reminder that there are ignored tests. -- Note that any setup / teardown actions executed by ' Test . ' -- are still executed. You can bypass this manually as in the following example: -- -- @ -- askOption $ \\(MyFlag b) -> if b then else ignoreTest . mytest $ return junkvalue -- @ ignoreTest :: TestTree -> TestTree ignoreTest = ignoreTest' Nothing -- | Like 'ignoreTest' but with additional comment ignoreTestBecause :: String -> TestTree -> TestTree ignoreTestBecause reason = ignoreTest' (Just reason) ignoreTest' :: Maybe String -> TestTree -> TestTree ignoreTest' reason = wrapTest $ const $ return $ (testPassed $ fromMaybe "" reason) { resultShortDescription = "IGNORED" }
null
https://raw.githubusercontent.com/nomeata/tasty-expected-failure/33b71e694b954e35c05859fff3ca886d8cfe5bfe/Test/Tasty/ExpectedFailure.hs
haskell
Re-implement timeouts and exception handling *inside* the wrapper. The primary location for timeout and exception Test.Tasty.Run implementation, but that handling is above the level of this wrapper which therefore cannot absorb timeouts and exceptions as *expected* failures. Ensure exceptions trying to show the failure result are caught as "expected" Note regarding post-run evaluate above: The normal behavior of tasty-expected-failure is to run the test, show the failure result, but then note that the failure is expected and not count that against a test failure. If the test unexpectedly succeeds, a message to that effect is printed, but there is no resultDescription display of the test inputs. However, when used with tests expected to fail that also throw exceptions when attempting to show the result, the forcing in tasty-expected-failure protections but still within the realm where tasty would count it as a failure. The fix here attempts to `show` the failing value here in tasty-expected-failure; if an exception occurs during that `show` then code here will report it (somewhat incorrectly) via the exceptionResult above, where tasty's subsequent forcing of the text of that exceptionResult no longer causes an exception *there*. Since the value is only shown if there was already a failure, the reason is misleading but the outcome is consistent with the intent of tasty-expected-failure handling. | 'wrapTest' allows you to modify the behaviour of the tests, e.g. by modifying the result or not running the test at all. It is used to implement 'expectFail' and 'ignoreTest'. | Marks all tests in the given test suite as expected failures: The tests will still be run, but if they succeed, it is reported as a test suite failure, and conversely a the failure of the test is ignored. Any output of a failing test is still printed. This is useful if, in a test driven development, tests are written and commited to the master branch before their implementation: It allows the tests to fail (as expected) without making the whole test suite fail. Similarly, regressions and bugs can be documented in the test suite this way, until a fix is commited, and if a fix is applied (intentionally or accidentially), the test suite will remind you to remove the 'expectFail' marker. | Like 'expectFail' but with additional comment | Prevents the tests from running and reports them as succeeding. This may be be desireable as an alternative to commenting out the tests. This way, they are still typechecked (preventing bitrot), and the test report lists them, which serves as a reminder that there are ignored tests. are still executed. You can bypass this manually as in the following example: @ askOption $ \\(MyFlag b) -> if b @ | Like 'ignoreTest' but with additional comment
# LANGUAGE CPP # # LANGUAGE DeriveDataTypeable , ScopedTypeVariables , LambdaCase # module Test.Tasty.ExpectedFailure (expectFail, expectFailBecause, ignoreTest, ignoreTestBecause, wrapTest) where import Test.Tasty.Options import Test.Tasty.Runners import Test.Tasty.Providers #if MIN_VERSION_tasty(1,3,1) import Test.Tasty.Providers.ConsoleFormat ( ResultDetailsPrinter(..) ) #endif import Test.Tasty ( Timeout(..), askOption, localOption ) import Data.Typeable import Data.Tagged import Data.Maybe import Data.Monoid import Control.Exception ( displayException, evaluate, try, SomeException ) import Control.Concurrent.Timeout ( timeout ) data WrappedTest t = WrappedTest Timeout (IO Result -> IO Result) t deriving Typeable instance forall t. IsTest t => IsTest (WrappedTest t) where run opts (WrappedTest tmout wrap t) prog = handling is in ` executeTest ` in the Tasty module 's let (pre,post) = case tmout of NoTimeout -> (fmap Just, fromJust) Timeout t s -> (timeout t, fromMaybe (timeoutResult t s)) timeoutResult t s = Result { resultOutcome = Failure $ TestTimedOut t , resultDescription = "Timed out after " <> s , resultShortDescription = "TIMEOUT" , resultTime = fromIntegral t #if MIN_VERSION_tasty(1,3,1) , resultDetailsPrinter = ResultDetailsPrinter . const . const $ return () #endif } exceptionResult e = Result { resultOutcome = Failure $ TestThrewException e , resultDescription = "Exception: " ++ displayException e , resultShortDescription = "FAIL" , resultTime = 0 #if MIN_VERSION_tasty(1,3,1) , resultDetailsPrinter = ResultDetailsPrinter . const . const $ return () #endif } forceList = foldr seq () in wrap $ try (pre (run opts t prog ( see Issue # 24 and note below ) >>= \r -> evaluate (forceList (resultDescription r) `seq` forceList (resultShortDescription r) `seq` resultOutcome r `seq` r))) >>= \case Right r -> return (post r) Left (e :: SomeException) -> return $ exceptionResult e testOptions = retag (testOptions :: Tagged t [OptionDescription]) As of Tasty 1.4 , the core tasty code was enhanced to fix issue # 280 in tasty : essentially the test result report is forced . Tasty 1.4 causes an exception to be thrown after the wrapTest :: (IO Result -> IO Result) -> TestTree -> TestTree wrapTest wrap = go where go (SingleTest n t) = askOption $ \(old_timeout :: Timeout) -> disable Tasty 's timeout ; handled here instead SingleTest n (WrappedTest old_timeout wrap t) go (TestGroup name tests) = TestGroup name (map go tests) go (PlusTestOptions plus tree) = PlusTestOptions plus (go tree) go (WithResource spec gentree) = WithResource spec (go . gentree) go (AskOptions f) = AskOptions (go . f) expectFail :: TestTree -> TestTree expectFail = expectFail' Nothing expectFailBecause :: String -> TestTree -> TestTree expectFailBecause reason = expectFail' (Just reason) expectFail' :: Maybe String -> TestTree -> TestTree expectFail' reason = wrapTest (fmap change) where change r | resultSuccessful r = r { resultOutcome = Failure TestFailed , resultDescription = resultDescription r <> " (unexpected success" <> comment <> ")" , resultShortDescription = resultShortDescription r <> " (unexpected" <> comment <> ")" } | otherwise = r { resultOutcome = Success , resultDescription = resultDescription r <> " (expected failure)" , resultShortDescription = resultShortDescription r <> " (expected" <> comment <> ")" } "" `append` s = s t `append` s | last t == '\n' = t ++ s ++ "\n" | otherwise = t ++ "\n" ++ s comment = maybe "" (mappend ": ") reason Note that any setup / teardown actions executed by ' Test . ' then else ignoreTest . mytest $ return junkvalue ignoreTest :: TestTree -> TestTree ignoreTest = ignoreTest' Nothing ignoreTestBecause :: String -> TestTree -> TestTree ignoreTestBecause reason = ignoreTest' (Just reason) ignoreTest' :: Maybe String -> TestTree -> TestTree ignoreTest' reason = wrapTest $ const $ return $ (testPassed $ fromMaybe "" reason) { resultShortDescription = "IGNORED" }
b6be119eb93073ba0f49dd35fdc9abb4f3b97dc999fd8f2383ab1ed9b16d4fd1
bennn/dissertation
main.rkt
#lang racket ;; Run a Simulation of Interacting Automata (random-seed 7480) ;; ============================================================================= (require require-typed-check "../base/untyped.rkt" "automata.rkt" "population.rkt" "utilities.rkt") (define (payoff? x) (and (real? x) (<= 0 x))) ;; effect run timed simulation, create and display plot of average payoffs ;; effect measure time needed for the simulation (define (main) (simulation->lines (evolve (build-random-population 300) 500 100 20)) (void)) (define (simulation->lines data) (for/list ([d (in-list data)][n (in-naturals)]) (list n d))) computes the list of average payoffs over the evolution of population p for ;; c cycles of of match-ups with r rounds per match and at birth/death rate of s (define (evolve p c s r) (cond [(zero? c) '()] [else (define p2 (match-up* p r)) Note r is typed as State even though State is not exported (define pp (population-payoffs p2)) (define p3 (death-birth p2 s)) ;; Note s same as r (cons (assert (relative-average pp r) payoff?) Note evolve is assigned ( - > ... [ Probability ] ) even though it is explicitly typed ... [ ] (evolve p3 (- c 1) s r))])) ;; ----------------------------------------------------------------------------- (time (main))
null
https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/scrbl/jfp-2019/benchmarks/fsm/untyped/main.rkt
racket
Run a Simulation of Interacting Automata ============================================================================= effect run timed simulation, create and display plot of average payoffs effect measure time needed for the simulation c cycles of of match-ups with r rounds per match and at birth/death rate of s Note s same as r -----------------------------------------------------------------------------
#lang racket (random-seed 7480) (require require-typed-check "../base/untyped.rkt" "automata.rkt" "population.rkt" "utilities.rkt") (define (payoff? x) (and (real? x) (<= 0 x))) (define (main) (simulation->lines (evolve (build-random-population 300) 500 100 20)) (void)) (define (simulation->lines data) (for/list ([d (in-list data)][n (in-naturals)]) (list n d))) computes the list of average payoffs over the evolution of population p for (define (evolve p c s r) (cond [(zero? c) '()] [else (define p2 (match-up* p r)) Note r is typed as State even though State is not exported (define pp (population-payoffs p2)) (define p3 (death-birth p2 s)) (cons (assert (relative-average pp r) payoff?) Note evolve is assigned ( - > ... [ Probability ] ) even though it is explicitly typed ... [ ] (evolve p3 (- c 1) s r))])) (time (main))
bf1a4e6d80e5af07461a4cebe8ca19de9b8bf0f13fa290c1c377a476ec22810f
typelead/eta
tc190.hs
{-# LANGUAGE CPP, KindSignatures #-} The record update triggered a kind error in GHC 6.2 module Foo where data HT (ref :: * -> *) = HT { kcount :: Int } set_kcount :: Int -> HT s -> HT s set_kcount kc ht = ht{kcount=kc}
null
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc190.hs
haskell
# LANGUAGE CPP, KindSignatures #
The record update triggered a kind error in GHC 6.2 module Foo where data HT (ref :: * -> *) = HT { kcount :: Int } set_kcount :: Int -> HT s -> HT s set_kcount kc ht = ht{kcount=kc}
da0bc3515602cf22a6b5335b81837ec8373edcb699d7af7e111947cf17c38bfb
Clozure/ccl
scribe.lisp
;;; -*- Log: hemlock.log; Package: Hemlock -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; #+CMU (ext:file-comment "$Header$") ;;; ;;; ********************************************************************** ;;; (in-package :hemlock) ;;;; Variables. (defvar *scribe-para-break-table* (make-hash-table :test #'equal) "A table of the Scribe commands that should be paragraph delimiters.") ;;; (dolist (todo '("begin" "newpage" "make" "device" "caption" "tag" "end" "chapter" "section" "appendix" "subsection" "paragraph" "unnumbered" "appendixsection" "prefacesection" "heading" "majorheading" "subheading")) (setf (gethash todo *scribe-para-break-table*) t)) (defhvar "Open Paren Character" "The open bracket inserted by Scribe commands." :value #\[) (defhvar "Close Paren Character" "The close bracket inserted by Scribe commands." :value #\]) (defhvar "Escape Character" "The escape character inserted by Scribe commands." :value #\@) (defhvar "Scribe Bracket Table" "This table maps a Scribe brackets, open and close, to their opposing brackets." :value (make-array char-code-limit)) ;;; (mapc #'(lambda (x y) (setf (svref (value scribe-bracket-table) (char-code x)) y) (setf (svref (value scribe-bracket-table) (char-code y)) x)) '(#\( #\[ #\{ #\<) '(#\) #\] #\} #\>)) ;;; (defun opposing-bracket (bracket) (svref (value scribe-bracket-table) (char-code bracket))) " Scribe Syntax " Attribute . (defattribute "Scribe Syntax" "For Scribe Syntax, Possible types are: basically # \@. :OPEN-PAREN ; Characters that open a Scribe paren: #\[, #\{, #\(, #\<. :CLOSE-PAREN ; Characters that close a Scribe paren: #\], #\}, #\), #\>. end of a Scribe command . end of a Scribe command . " 'symbol nil) (setf (character-attribute :scribe-syntax #\)) :close-paren) (setf (character-attribute :scribe-syntax #\]) :close-paren) (setf (character-attribute :scribe-syntax #\}) :close-paren) (setf (character-attribute :scribe-syntax #\>) :close-paren) (setf (character-attribute :scribe-syntax #\() :open-paren) (setf (character-attribute :scribe-syntax #\[) :open-paren) (setf (character-attribute :scribe-syntax #\{) :open-paren) (setf (character-attribute :scribe-syntax #\<) :open-paren) (setf (character-attribute :scribe-syntax #\space) :space) (setf (character-attribute :scribe-syntax #\newline) :newline) (setf (character-attribute :scribe-syntax #\@) :escape) " Scribe " mode and setup . (defmode "Scribe" :major-p t) (shadow-attribute :paragraph-delimiter #\@ 1 "Scribe") (shadow-attribute :word-delimiter #\' 0 "Scribe") ;from Text Mode (shadow-attribute :word-delimiter #\backspace 0 "Scribe") ;from Text Mode (shadow-attribute :word-delimiter #\_ 0 "Scribe") ;from Text Mode (define-file-type-hook ("mss") (buffer type) (declare (ignore type)) (setf (buffer-major-mode buffer) "Scribe")) ;;;; Commands. (defcommand "Scribe Mode" (p) "Puts buffer in Scribe mode. Sets up comment variables and has delimiter matching. The definition of paragraphs is changed to know about scribe commands." "Puts buffer in Scribe mode." (declare (ignore p)) (setf (buffer-major-mode (current-buffer)) "Scribe")) (defcommand "Select Scribe Warnings" (p) "Goes to the Scribe Warnings buffer if it exists." "Goes to the Scribe Warnings buffer if it exists." (declare (ignore p)) (let ((buffer (getstring "Scribe Warnings" *buffer-names*))) (if buffer (change-to-buffer buffer) (editor-error "There is no Scribe Warnings buffer.")))) (defcommand "Add Scribe Paragraph Delimiter" (p &optional (word (prompt-for-string :prompt "Scribe command: " :help "Name of Scribe command to make delimit paragraphs." :trim t))) "Prompts for a name to add to the table of commands that delimit paragraphs in Scribe mode. If a prefix argument is supplied, then the command name is removed from the table." "Add or remove Word in the *scribe-para-break-table*, depending on P." (setf (gethash word *scribe-para-break-table*) (not p))) (defcommand "List Scribe Paragraph Delimiters" (p) "Pops up a display of the Scribe commands that delimit paragraphs." "Pops up a display of the Scribe commands that delimit paragraphs." (declare (ignore p)) (let (result) (maphash #'(lambda (k v) (declare (ignore v)) (push k result)) *scribe-para-break-table*) (setf result (sort result #'string<)) (with-pop-up-display (s :height (length result)) (dolist (ele result) (write-line ele s))))) (defcommand "Scribe Insert Bracket" (p) "Inserts a the bracket it is bound to and then shows the matching bracket." "Inserts a the bracket it is bound to and then shows the matching bracket." (declare (ignore p)) (scribe-insert-paren (current-point) (hemlock-ext:key-event-char *last-key-event-typed*))) (defhvar "Scribe Command Table" "This is a character dispatching table indicating which Scribe command or environment to use." :value (make-hash-table) :mode "Scribe") (defvar *scribe-directive-type-table* (make-string-table :initial-contents '(("Command" . :command) ("Environment" . :environment)))) (defcommand "Add Scribe Directive" (p &optional (command-name nil command-name-p) type key-event mode) "Adds a new scribe function to put into \"Scribe Command Table\"." "Adds a new scribe function to put into \"Scribe Command Table\"." (declare (ignore p)) (let ((command-name (if command-name-p command-name (or command-name (prompt-for-string :help "Directive Name" :prompt "Directive: "))))) (multiple-value-bind (ignore type) (if type (values nil type) (prompt-for-keyword (list *scribe-directive-type-table*) :help "Enter Command or Environment." :prompt "Command or Environment: ")) (declare (ignore ignore)) (let ((key-event (or key-event (prompt-for-key-event :prompt "Dispatch Character: ")))) (setf (gethash key-event (cond (mode (variable-value 'scribe-command-table :mode mode)) ((hemlock-bound-p 'scribe-command-table) (value scribe-command-table)) (t (editor-error "Could not find \"Scribe Command Table\".")))) (cons type command-name)))))) (defcommand "Insert Scribe Directive" (p) "Prompts for a character to dispatch on. Some indicate \"commands\" versus \"environments\". Commands are wrapped around the previous or current word. If there is no previous word, the command is insert, leaving point between the brackets. Environments are wrapped around the next or current paragraph, but when the region is active, this wraps the environment around the region. Each uses \"Open Paren Character\" and \"Close Paren Character\"." "Wrap some text with some stuff." (declare (ignore p)) (loop (let ((key-event (prompt-for-key-event :prompt "Dispatch Character: "))) (if (logical-key-event-p key-event :help) (directive-help) (let ((table-entry (gethash key-event (value scribe-command-table)))) (ecase (car table-entry) (:command (insert-scribe-directive (current-point) (cdr table-entry)) (return)) (:environment (enclose-with-environment (current-point) (cdr table-entry)) (return)) ((nil) (editor-error "Unknown dispatch character.")))))))) " Insert Scribe Directive " support . (defun directive-help () (let ((commands ()) (environments ())) (declare (list commands environments)) (maphash #'(lambda (k v) (if (eql (car v) :command) (push (cons k (cdr v)) commands) (push (cons k (cdr v)) environments))) (value scribe-command-table)) (setf commands (sort commands #'string< :key #'cdr)) (setf environments (sort environments #'string< :key #'cdr)) (with-pop-up-display (s :height (1+ (max (length commands) (length environments)))) (format s "~2TCommands~47TEnvironments~%") (do ((commands commands (rest commands)) (environments environments (rest environments))) ((and (endp commands) (endp environments))) (let* ((command (first commands)) (environment (first environments)) (cmd-char (first command)) (cmd-name (rest command)) (env-char (first environment)) (env-name (rest environment))) (write-string " " s) (when cmd-char (hemlock-ext:print-pretty-key-event cmd-char s) (format s "~7T") (write-string (or cmd-name "<prompts for command name>") s)) (when env-char (format s "~47T") (hemlock-ext:print-pretty-key-event env-char s) (format s "~51T") (write-string (or env-name "<prompts for command name>") s)) (terpri s)))))) ;;; ;;; Inserting and extending :command directives. ;;; (defhvar "Insert Scribe Directive Function" "\"Insert Scribe Directive\" calls this function when the directive type is :command. The function takes four arguments: a mark pointing to the word start, the formatting command string, the open-paren character to use, and a mark pointing to the word end." :value 'scribe-insert-scribe-directive-fun :mode "Scribe") (defun scribe-insert-scribe-directive-fun (word-start command-string open-paren-char word-end) (insert-character word-start (value escape-character)) (insert-string word-start command-string) (insert-character word-start open-paren-char) (insert-character word-end (value close-paren-character))) (defhvar "Extend Scribe Directive Function" "\"Insert Scribe Directive\" calls this function when the directive type is :command to extend the the commands effect. This function takes a string and three marks: the first on pointing before the open-paren character for the directive. The string is the command-string to selected by the user which this function uses to determine if it is actually extending a command or inserting a new one. The function must move the first mark before any command text for the directive and the second mark to the end of any command text. It moves the third mark to the previous word's start where the command region should be. If this returns non-nil \"Insert Scribe Directive\" moves the command region previous one word, and otherwise it inserts the directive." :value 'scribe-extend-scribe-directive-fun :mode "Scribe") (defun scribe-extend-scribe-directive-fun (command-string command-end command-start word-start) (word-offset (move-mark command-start command-end) -1) (when (string= (the simple-string (region-to-string (region command-start command-end))) command-string) (mark-before command-start) (mark-after command-end) (word-offset (move-mark word-start command-start) -1))) ;;; INSERT-SCRIBE-DIRECTIVE first looks for the current or previous word at mark . Word - p says if we found one . If mark is immediately before a word , ;;; we use that word instead of the previous. This is because if mark corresponds to the CURRENT - POINT , the Hemlock cursor is displayed on the ;;; first character of the word making users think the mark is in the word ;;; instead of before it. If we find a word, then we see if it already has ;;; the given command-string, and if it does, we extend the use of the command- ;;; string to the previous word. At the end, if we hadn't found a word, we ;;; backup the mark one character to put it between the command brackets. ;;; (defun insert-scribe-directive (mark &optional command-string) (with-mark ((word-start mark :left-inserting) (word-end mark :left-inserting)) (let ((open-paren-char (value open-paren-character)) (word-p (if (and (zerop (character-attribute :word-delimiter (next-character word-start))) (= (character-attribute :word-delimiter (previous-character word-start)) 1)) word-start (word-offset word-start -1))) (command-string (or command-string (prompt-for-string :trim t :prompt "Environment: " :help "Name of environment to enclose with.")))) (declare (simple-string command-string)) (cond (word-p (word-offset (move-mark word-end word-start) 1) (if (test-char (next-character word-end) :scribe-syntax :close-paren) (with-mark ((command-start word-start :left-inserting) (command-end word-end :left-inserting)) ;; Move command-end from word-end to open-paren of command. (balance-paren (mark-after command-end)) (if (funcall (value extend-scribe-directive-function) command-string command-end command-start word-start) (let ((region (delete-and-save-region (region command-start command-end)))) (word-offset (move-mark word-start command-start) -1) (ninsert-region word-start region)) (funcall (value insert-scribe-directive-function) word-start command-string open-paren-char word-end))) (funcall (value insert-scribe-directive-function) word-start command-string open-paren-char word-end))) (t (funcall (value insert-scribe-directive-function) word-start command-string open-paren-char word-end) (mark-before mark)))))) ;;; ;;; Inserting :environment directives. ;;; (defun enclose-with-environment (mark &optional environment) (if (region-active-p) (let ((region (current-region))) (with-mark ((top (region-start region) :left-inserting) (bottom (region-end region) :left-inserting)) (get-and-insert-environment top bottom environment))) (with-mark ((bottom-mark mark :left-inserting)) (let ((paragraphp (paragraph-offset bottom-mark 1))) (unless (or paragraphp (and (last-line-p bottom-mark) (end-line-p bottom-mark) (not (blank-line-p (mark-line bottom-mark))))) (editor-error "No paragraph to enclose.")) (with-mark ((top-mark bottom-mark :left-inserting)) (paragraph-offset top-mark -1) (cond ((not (blank-line-p (mark-line top-mark))) (insert-character top-mark #\Newline) (mark-before top-mark)) (t (insert-character top-mark #\Newline))) (cond ((and (last-line-p bottom-mark) (not (blank-line-p (mark-line bottom-mark)))) (insert-character bottom-mark #\Newline)) (t (insert-character bottom-mark #\Newline) (mark-before bottom-mark))) (get-and-insert-environment top-mark bottom-mark environment)))))) (defun get-and-insert-environment (top-mark bottom-mark environment) (let ((environment (or environment (prompt-for-string :trim t :prompt "Environment: " :help "Name of environment to enclose with.")))) (insert-environment top-mark "begin" environment) (insert-environment bottom-mark "end" environment))) (defun insert-environment (mark command environment) (let ((esc-char (value escape-character)) (open-paren (value open-paren-character)) (close-paren (value close-paren-character))) (insert-character mark esc-char) (insert-string mark command) (insert-character mark open-paren) (insert-string mark environment) (insert-character mark close-paren))) (add-scribe-directive-command nil nil :Environment #k"Control-l" "Scribe") (add-scribe-directive-command nil nil :Command #k"Control-w" "Scribe") (add-scribe-directive-command nil "Begin" :Command #k"b" "Scribe") (add-scribe-directive-command nil "End" :Command #k"e" "Scribe") (add-scribe-directive-command nil "Center" :Environment #k"c" "Scribe") (add-scribe-directive-command nil "Description" :Environment #k"d" "Scribe") (add-scribe-directive-command nil "Display" :Environment #k"Control-d" "Scribe") (add-scribe-directive-command nil "Enumerate" :Environment #k"n" "Scribe") (add-scribe-directive-command nil "Example" :Environment #k"x" "Scribe") (add-scribe-directive-command nil "FileExample" :Environment #k"y" "Scribe") (add-scribe-directive-command nil "FlushLeft" :Environment #k"l" "Scribe") (add-scribe-directive-command nil "FlushRight" :Environment #k"r" "Scribe") (add-scribe-directive-command nil "Format" :Environment #k"f" "Scribe") (add-scribe-directive-command nil "Group" :Environment #k"g" "Scribe") (add-scribe-directive-command nil "Itemize" :Environment #k"Control-i" "Scribe") (add-scribe-directive-command nil "Multiple" :Environment #k"m" "Scribe") (add-scribe-directive-command nil "ProgramExample" :Environment #k"p" "Scribe") (add-scribe-directive-command nil "Quotation" :Environment #k"q" "Scribe") (add-scribe-directive-command nil "Text" :Environment #k"t" "Scribe") (add-scribe-directive-command nil "i" :Command #k"i" "Scribe") (add-scribe-directive-command nil "b" :Command #k"Control-b" "Scribe") (add-scribe-directive-command nil "-" :Command #k"\-" "Scribe") (add-scribe-directive-command nil "+" :Command #k"+" "Scribe") (add-scribe-directive-command nil "u" :Command #k"Control-j" "Scribe") (add-scribe-directive-command nil "p" :Command #k"Control-p" "Scribe") (add-scribe-directive-command nil "r" :Command #k"Control-r" "Scribe") (add-scribe-directive-command nil "t" :Command #k"Control-t" "Scribe") (add-scribe-directive-command nil "g" :Command #k"Control-a" "Scribe") (add-scribe-directive-command nil "un" :Command #k"Control-n" "Scribe") (add-scribe-directive-command nil "ux" :Command #k"Control-x" "Scribe") (add-scribe-directive-command nil "c" :Command #k"Control-k" "Scribe") Scribe paragraph delimiter function . (defhvar "Paragraph Delimiter Function" "Scribe Mode's way of delimiting paragraphs." :mode "Scribe" :value 'scribe-delim-para-function) (defun scribe-delim-para-function (mark) "Returns whether there is a paragraph delimiting Scribe command on the current line. Add or remove commands for this purpose with the command \"Add Scribe Paragraph Delimiter\"." (let ((next-char (next-character mark))) (when (paragraph-delimiter-attribute-p next-char) (if (eq (character-attribute :scribe-syntax next-char) :escape) (with-mark ((begin mark) (end mark)) (mark-after begin) (if (scan-char end :scribe-syntax (or :space :newline :open-paren)) (gethash (nstring-downcase (region-to-string (region begin end))) *scribe-para-break-table*) (editor-error "Unable to find Scribe command ending."))) t)))) ;;;; Bracket matching. (defun scribe-insert-paren (mark bracket-char) (insert-character mark bracket-char) (with-mark ((m mark)) (if (balance-paren m) (when (value paren-pause-period) (unless (show-mark m (current-window) (value paren-pause-period)) (clear-echo-area) (message "~A" (line-string (mark-line m))))) (editor-error)))) ;;; BALANCE-PAREN moves the mark to the matching open paren character, or ;;; returns nil. The mark must be after the closing paren. ;;; (defun balance-paren (mark) (with-mark ((m mark)) (when (rev-scan-char m :scribe-syntax (or :open-paren :close-paren)) (mark-before m) (let ((paren-count 1) (first-paren (next-character m))) (loop (unless (rev-scan-char m :scribe-syntax (or :open-paren :close-paren)) (return nil)) (if (test-char (previous-character m) :scribe-syntax :open-paren) (setq paren-count (1- paren-count)) (setq paren-count (1+ paren-count))) (when (< paren-count 0) (return nil)) (when (= paren-count 0) OPPOSING - BRACKET calls VALUE ( each time around the loop ) (cond ((char= (opposing-bracket (previous-character m)) first-paren) (mark-before (move-mark mark m)) (return t)) (t (editor-error "Scribe paren mismatch.")))) (mark-before m))))))
null
https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/cocoa-ide/hemlock/unused/archive/scribe.lisp
lisp
-*- Log: hemlock.log; Package: Hemlock -*- ********************************************************************** ********************************************************************** Variables. Characters that open a Scribe paren: #\[, #\{, #\(, #\<. Characters that close a Scribe paren: #\], #\}, #\), #\>. from Text Mode from Text Mode from Text Mode Commands. Inserting and extending :command directives. INSERT-SCRIBE-DIRECTIVE first looks for the current or previous word at we use that word instead of the previous. This is because if mark first character of the word making users think the mark is in the word instead of before it. If we find a word, then we see if it already has the given command-string, and if it does, we extend the use of the command- string to the previous word. At the end, if we hadn't found a word, we backup the mark one character to put it between the command brackets. Move command-end from word-end to open-paren of command. Inserting :environment directives. Bracket matching. BALANCE-PAREN moves the mark to the matching open paren character, or returns nil. The mark must be after the closing paren.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . #+CMU (ext:file-comment "$Header$") (in-package :hemlock) (defvar *scribe-para-break-table* (make-hash-table :test #'equal) "A table of the Scribe commands that should be paragraph delimiters.") (dolist (todo '("begin" "newpage" "make" "device" "caption" "tag" "end" "chapter" "section" "appendix" "subsection" "paragraph" "unnumbered" "appendixsection" "prefacesection" "heading" "majorheading" "subheading")) (setf (gethash todo *scribe-para-break-table*) t)) (defhvar "Open Paren Character" "The open bracket inserted by Scribe commands." :value #\[) (defhvar "Close Paren Character" "The close bracket inserted by Scribe commands." :value #\]) (defhvar "Escape Character" "The escape character inserted by Scribe commands." :value #\@) (defhvar "Scribe Bracket Table" "This table maps a Scribe brackets, open and close, to their opposing brackets." :value (make-array char-code-limit)) (mapc #'(lambda (x y) (setf (svref (value scribe-bracket-table) (char-code x)) y) (setf (svref (value scribe-bracket-table) (char-code y)) x)) '(#\( #\[ #\{ #\<) '(#\) #\] #\} #\>)) (defun opposing-bracket (bracket) (svref (value scribe-bracket-table) (char-code bracket))) " Scribe Syntax " Attribute . (defattribute "Scribe Syntax" "For Scribe Syntax, Possible types are: basically # \@. end of a Scribe command . end of a Scribe command . " 'symbol nil) (setf (character-attribute :scribe-syntax #\)) :close-paren) (setf (character-attribute :scribe-syntax #\]) :close-paren) (setf (character-attribute :scribe-syntax #\}) :close-paren) (setf (character-attribute :scribe-syntax #\>) :close-paren) (setf (character-attribute :scribe-syntax #\() :open-paren) (setf (character-attribute :scribe-syntax #\[) :open-paren) (setf (character-attribute :scribe-syntax #\{) :open-paren) (setf (character-attribute :scribe-syntax #\<) :open-paren) (setf (character-attribute :scribe-syntax #\space) :space) (setf (character-attribute :scribe-syntax #\newline) :newline) (setf (character-attribute :scribe-syntax #\@) :escape) " Scribe " mode and setup . (defmode "Scribe" :major-p t) (shadow-attribute :paragraph-delimiter #\@ 1 "Scribe") (define-file-type-hook ("mss") (buffer type) (declare (ignore type)) (setf (buffer-major-mode buffer) "Scribe")) (defcommand "Scribe Mode" (p) "Puts buffer in Scribe mode. Sets up comment variables and has delimiter matching. The definition of paragraphs is changed to know about scribe commands." "Puts buffer in Scribe mode." (declare (ignore p)) (setf (buffer-major-mode (current-buffer)) "Scribe")) (defcommand "Select Scribe Warnings" (p) "Goes to the Scribe Warnings buffer if it exists." "Goes to the Scribe Warnings buffer if it exists." (declare (ignore p)) (let ((buffer (getstring "Scribe Warnings" *buffer-names*))) (if buffer (change-to-buffer buffer) (editor-error "There is no Scribe Warnings buffer.")))) (defcommand "Add Scribe Paragraph Delimiter" (p &optional (word (prompt-for-string :prompt "Scribe command: " :help "Name of Scribe command to make delimit paragraphs." :trim t))) "Prompts for a name to add to the table of commands that delimit paragraphs in Scribe mode. If a prefix argument is supplied, then the command name is removed from the table." "Add or remove Word in the *scribe-para-break-table*, depending on P." (setf (gethash word *scribe-para-break-table*) (not p))) (defcommand "List Scribe Paragraph Delimiters" (p) "Pops up a display of the Scribe commands that delimit paragraphs." "Pops up a display of the Scribe commands that delimit paragraphs." (declare (ignore p)) (let (result) (maphash #'(lambda (k v) (declare (ignore v)) (push k result)) *scribe-para-break-table*) (setf result (sort result #'string<)) (with-pop-up-display (s :height (length result)) (dolist (ele result) (write-line ele s))))) (defcommand "Scribe Insert Bracket" (p) "Inserts a the bracket it is bound to and then shows the matching bracket." "Inserts a the bracket it is bound to and then shows the matching bracket." (declare (ignore p)) (scribe-insert-paren (current-point) (hemlock-ext:key-event-char *last-key-event-typed*))) (defhvar "Scribe Command Table" "This is a character dispatching table indicating which Scribe command or environment to use." :value (make-hash-table) :mode "Scribe") (defvar *scribe-directive-type-table* (make-string-table :initial-contents '(("Command" . :command) ("Environment" . :environment)))) (defcommand "Add Scribe Directive" (p &optional (command-name nil command-name-p) type key-event mode) "Adds a new scribe function to put into \"Scribe Command Table\"." "Adds a new scribe function to put into \"Scribe Command Table\"." (declare (ignore p)) (let ((command-name (if command-name-p command-name (or command-name (prompt-for-string :help "Directive Name" :prompt "Directive: "))))) (multiple-value-bind (ignore type) (if type (values nil type) (prompt-for-keyword (list *scribe-directive-type-table*) :help "Enter Command or Environment." :prompt "Command or Environment: ")) (declare (ignore ignore)) (let ((key-event (or key-event (prompt-for-key-event :prompt "Dispatch Character: ")))) (setf (gethash key-event (cond (mode (variable-value 'scribe-command-table :mode mode)) ((hemlock-bound-p 'scribe-command-table) (value scribe-command-table)) (t (editor-error "Could not find \"Scribe Command Table\".")))) (cons type command-name)))))) (defcommand "Insert Scribe Directive" (p) "Prompts for a character to dispatch on. Some indicate \"commands\" versus \"environments\". Commands are wrapped around the previous or current word. If there is no previous word, the command is insert, leaving point between the brackets. Environments are wrapped around the next or current paragraph, but when the region is active, this wraps the environment around the region. Each uses \"Open Paren Character\" and \"Close Paren Character\"." "Wrap some text with some stuff." (declare (ignore p)) (loop (let ((key-event (prompt-for-key-event :prompt "Dispatch Character: "))) (if (logical-key-event-p key-event :help) (directive-help) (let ((table-entry (gethash key-event (value scribe-command-table)))) (ecase (car table-entry) (:command (insert-scribe-directive (current-point) (cdr table-entry)) (return)) (:environment (enclose-with-environment (current-point) (cdr table-entry)) (return)) ((nil) (editor-error "Unknown dispatch character.")))))))) " Insert Scribe Directive " support . (defun directive-help () (let ((commands ()) (environments ())) (declare (list commands environments)) (maphash #'(lambda (k v) (if (eql (car v) :command) (push (cons k (cdr v)) commands) (push (cons k (cdr v)) environments))) (value scribe-command-table)) (setf commands (sort commands #'string< :key #'cdr)) (setf environments (sort environments #'string< :key #'cdr)) (with-pop-up-display (s :height (1+ (max (length commands) (length environments)))) (format s "~2TCommands~47TEnvironments~%") (do ((commands commands (rest commands)) (environments environments (rest environments))) ((and (endp commands) (endp environments))) (let* ((command (first commands)) (environment (first environments)) (cmd-char (first command)) (cmd-name (rest command)) (env-char (first environment)) (env-name (rest environment))) (write-string " " s) (when cmd-char (hemlock-ext:print-pretty-key-event cmd-char s) (format s "~7T") (write-string (or cmd-name "<prompts for command name>") s)) (when env-char (format s "~47T") (hemlock-ext:print-pretty-key-event env-char s) (format s "~51T") (write-string (or env-name "<prompts for command name>") s)) (terpri s)))))) (defhvar "Insert Scribe Directive Function" "\"Insert Scribe Directive\" calls this function when the directive type is :command. The function takes four arguments: a mark pointing to the word start, the formatting command string, the open-paren character to use, and a mark pointing to the word end." :value 'scribe-insert-scribe-directive-fun :mode "Scribe") (defun scribe-insert-scribe-directive-fun (word-start command-string open-paren-char word-end) (insert-character word-start (value escape-character)) (insert-string word-start command-string) (insert-character word-start open-paren-char) (insert-character word-end (value close-paren-character))) (defhvar "Extend Scribe Directive Function" "\"Insert Scribe Directive\" calls this function when the directive type is :command to extend the the commands effect. This function takes a string and three marks: the first on pointing before the open-paren character for the directive. The string is the command-string to selected by the user which this function uses to determine if it is actually extending a command or inserting a new one. The function must move the first mark before any command text for the directive and the second mark to the end of any command text. It moves the third mark to the previous word's start where the command region should be. If this returns non-nil \"Insert Scribe Directive\" moves the command region previous one word, and otherwise it inserts the directive." :value 'scribe-extend-scribe-directive-fun :mode "Scribe") (defun scribe-extend-scribe-directive-fun (command-string command-end command-start word-start) (word-offset (move-mark command-start command-end) -1) (when (string= (the simple-string (region-to-string (region command-start command-end))) command-string) (mark-before command-start) (mark-after command-end) (word-offset (move-mark word-start command-start) -1))) mark . Word - p says if we found one . If mark is immediately before a word , corresponds to the CURRENT - POINT , the Hemlock cursor is displayed on the (defun insert-scribe-directive (mark &optional command-string) (with-mark ((word-start mark :left-inserting) (word-end mark :left-inserting)) (let ((open-paren-char (value open-paren-character)) (word-p (if (and (zerop (character-attribute :word-delimiter (next-character word-start))) (= (character-attribute :word-delimiter (previous-character word-start)) 1)) word-start (word-offset word-start -1))) (command-string (or command-string (prompt-for-string :trim t :prompt "Environment: " :help "Name of environment to enclose with.")))) (declare (simple-string command-string)) (cond (word-p (word-offset (move-mark word-end word-start) 1) (if (test-char (next-character word-end) :scribe-syntax :close-paren) (with-mark ((command-start word-start :left-inserting) (command-end word-end :left-inserting)) (balance-paren (mark-after command-end)) (if (funcall (value extend-scribe-directive-function) command-string command-end command-start word-start) (let ((region (delete-and-save-region (region command-start command-end)))) (word-offset (move-mark word-start command-start) -1) (ninsert-region word-start region)) (funcall (value insert-scribe-directive-function) word-start command-string open-paren-char word-end))) (funcall (value insert-scribe-directive-function) word-start command-string open-paren-char word-end))) (t (funcall (value insert-scribe-directive-function) word-start command-string open-paren-char word-end) (mark-before mark)))))) (defun enclose-with-environment (mark &optional environment) (if (region-active-p) (let ((region (current-region))) (with-mark ((top (region-start region) :left-inserting) (bottom (region-end region) :left-inserting)) (get-and-insert-environment top bottom environment))) (with-mark ((bottom-mark mark :left-inserting)) (let ((paragraphp (paragraph-offset bottom-mark 1))) (unless (or paragraphp (and (last-line-p bottom-mark) (end-line-p bottom-mark) (not (blank-line-p (mark-line bottom-mark))))) (editor-error "No paragraph to enclose.")) (with-mark ((top-mark bottom-mark :left-inserting)) (paragraph-offset top-mark -1) (cond ((not (blank-line-p (mark-line top-mark))) (insert-character top-mark #\Newline) (mark-before top-mark)) (t (insert-character top-mark #\Newline))) (cond ((and (last-line-p bottom-mark) (not (blank-line-p (mark-line bottom-mark)))) (insert-character bottom-mark #\Newline)) (t (insert-character bottom-mark #\Newline) (mark-before bottom-mark))) (get-and-insert-environment top-mark bottom-mark environment)))))) (defun get-and-insert-environment (top-mark bottom-mark environment) (let ((environment (or environment (prompt-for-string :trim t :prompt "Environment: " :help "Name of environment to enclose with.")))) (insert-environment top-mark "begin" environment) (insert-environment bottom-mark "end" environment))) (defun insert-environment (mark command environment) (let ((esc-char (value escape-character)) (open-paren (value open-paren-character)) (close-paren (value close-paren-character))) (insert-character mark esc-char) (insert-string mark command) (insert-character mark open-paren) (insert-string mark environment) (insert-character mark close-paren))) (add-scribe-directive-command nil nil :Environment #k"Control-l" "Scribe") (add-scribe-directive-command nil nil :Command #k"Control-w" "Scribe") (add-scribe-directive-command nil "Begin" :Command #k"b" "Scribe") (add-scribe-directive-command nil "End" :Command #k"e" "Scribe") (add-scribe-directive-command nil "Center" :Environment #k"c" "Scribe") (add-scribe-directive-command nil "Description" :Environment #k"d" "Scribe") (add-scribe-directive-command nil "Display" :Environment #k"Control-d" "Scribe") (add-scribe-directive-command nil "Enumerate" :Environment #k"n" "Scribe") (add-scribe-directive-command nil "Example" :Environment #k"x" "Scribe") (add-scribe-directive-command nil "FileExample" :Environment #k"y" "Scribe") (add-scribe-directive-command nil "FlushLeft" :Environment #k"l" "Scribe") (add-scribe-directive-command nil "FlushRight" :Environment #k"r" "Scribe") (add-scribe-directive-command nil "Format" :Environment #k"f" "Scribe") (add-scribe-directive-command nil "Group" :Environment #k"g" "Scribe") (add-scribe-directive-command nil "Itemize" :Environment #k"Control-i" "Scribe") (add-scribe-directive-command nil "Multiple" :Environment #k"m" "Scribe") (add-scribe-directive-command nil "ProgramExample" :Environment #k"p" "Scribe") (add-scribe-directive-command nil "Quotation" :Environment #k"q" "Scribe") (add-scribe-directive-command nil "Text" :Environment #k"t" "Scribe") (add-scribe-directive-command nil "i" :Command #k"i" "Scribe") (add-scribe-directive-command nil "b" :Command #k"Control-b" "Scribe") (add-scribe-directive-command nil "-" :Command #k"\-" "Scribe") (add-scribe-directive-command nil "+" :Command #k"+" "Scribe") (add-scribe-directive-command nil "u" :Command #k"Control-j" "Scribe") (add-scribe-directive-command nil "p" :Command #k"Control-p" "Scribe") (add-scribe-directive-command nil "r" :Command #k"Control-r" "Scribe") (add-scribe-directive-command nil "t" :Command #k"Control-t" "Scribe") (add-scribe-directive-command nil "g" :Command #k"Control-a" "Scribe") (add-scribe-directive-command nil "un" :Command #k"Control-n" "Scribe") (add-scribe-directive-command nil "ux" :Command #k"Control-x" "Scribe") (add-scribe-directive-command nil "c" :Command #k"Control-k" "Scribe") Scribe paragraph delimiter function . (defhvar "Paragraph Delimiter Function" "Scribe Mode's way of delimiting paragraphs." :mode "Scribe" :value 'scribe-delim-para-function) (defun scribe-delim-para-function (mark) "Returns whether there is a paragraph delimiting Scribe command on the current line. Add or remove commands for this purpose with the command \"Add Scribe Paragraph Delimiter\"." (let ((next-char (next-character mark))) (when (paragraph-delimiter-attribute-p next-char) (if (eq (character-attribute :scribe-syntax next-char) :escape) (with-mark ((begin mark) (end mark)) (mark-after begin) (if (scan-char end :scribe-syntax (or :space :newline :open-paren)) (gethash (nstring-downcase (region-to-string (region begin end))) *scribe-para-break-table*) (editor-error "Unable to find Scribe command ending."))) t)))) (defun scribe-insert-paren (mark bracket-char) (insert-character mark bracket-char) (with-mark ((m mark)) (if (balance-paren m) (when (value paren-pause-period) (unless (show-mark m (current-window) (value paren-pause-period)) (clear-echo-area) (message "~A" (line-string (mark-line m))))) (editor-error)))) (defun balance-paren (mark) (with-mark ((m mark)) (when (rev-scan-char m :scribe-syntax (or :open-paren :close-paren)) (mark-before m) (let ((paren-count 1) (first-paren (next-character m))) (loop (unless (rev-scan-char m :scribe-syntax (or :open-paren :close-paren)) (return nil)) (if (test-char (previous-character m) :scribe-syntax :open-paren) (setq paren-count (1- paren-count)) (setq paren-count (1+ paren-count))) (when (< paren-count 0) (return nil)) (when (= paren-count 0) OPPOSING - BRACKET calls VALUE ( each time around the loop ) (cond ((char= (opposing-bracket (previous-character m)) first-paren) (mark-before (move-mark mark m)) (return t)) (t (editor-error "Scribe paren mismatch.")))) (mark-before m))))))
bacc759edbe8e51c8fd2f670b02051ab1b38cdf07b1469cb904ff7f59fae9c82
marigold-dev/deku
message_pool.ml
open Deku_concepts type message_state = | Accepted | Pending of { queue : string list } | Unknown | Late type message_pool = | Message_pool of { current : Level.t; by_level : message_state Message_hash.Map.t Level.Map.t; } and t = message_pool let message_state_encoding = let open Data_encoding in union [ case ~title:"Accepted" (Tag 0) unit (function Accepted -> Some () | _ -> None) (fun () -> Accepted); case ~title:"Pending" (Tag 1) (list string) (function Pending { queue } -> Some queue | _ -> None) (fun queue -> Pending { queue }); case ~title:"Unknown" (Tag 2) unit (function Unknown -> Some () | _ -> None) (fun () -> Unknown); case ~title:"Late" (Tag 3) unit (function Late -> Some () | _ -> None) (fun () -> Late); ] let encoding = let open Data_encoding in conv (fun (Message_pool { current; by_level }) -> (current, by_level)) (fun (current, by_level) -> Message_pool { current; by_level }) (tup2 Level.encoding (Level.Map.encoding (Message_hash.Map.encoding message_state_encoding))) type fragment = | Fragment_encode of { content : Message.Content.t } | Fragment_decode of { expected : Message.Header.t; raw_content : string } type outcome = | Outcome_message of { message : Message.t } | Outcome_error of { expected : Message.Header.t; exn : exn } type action = | Message_pool_message of { message : Message.t } | Message_pool_fragment of { fragment : fragment } let initial = Message_pool { current = Level.zero; by_level = Level.Map.empty } (* helpers *) let rec drop ~level ~until by_level = match Level.(until > level) with | true -> let by_level = Level.Map.remove level by_level in let level = Level.next level in drop ~level ~until by_level | false -> Level.Map.remove until by_level let drop ~until by_level = match Level.Map.min_binding_opt by_level with | Some (level, _by_hash) -> drop ~level ~until by_level | None -> by_level let by_hash ~level by_level = match Level.Map.find_opt level by_level with | Some by_hash -> by_hash | None -> Message_hash.Map.empty let state ~hash ~level pool = let (Message_pool { current; by_level }) = pool in let by_hash = by_hash ~level by_level in match Level.(level > current) with | true -> ( match Message_hash.Map.find_opt hash by_hash with | Some state -> state | None -> Unknown) | false -> Late let with_state ~hash ~level state pool = let (Message_pool { current; by_level }) = pool in let by_hash = by_hash ~level by_level in let by_hash = Message_hash.Map.add hash state by_hash in let by_level = Level.Map.add level by_hash by_level in Message_pool { current; by_level } (* external *) let encode ~content = (* TODO: content hash to prevent double encoding *) Fragment_encode { content } let decode ~raw_header ~raw_content pool = let open Message.Header in try let expected = Message.Header.decode ~raw_header in let (Message_header { hash; level }) = expected in match state ~hash ~level pool with | Accepted -> (pool, None) | Pending { queue } -> let queue = raw_content :: queue in let state = Pending { queue } in let pool = with_state ~hash ~level state pool in (pool, None) | Unknown -> let queue = [] in let state = Pending { queue } in let pool = with_state ~hash ~level state pool in let fragment = Fragment_decode { expected; raw_content } in (pool, Some fragment) | Late -> (pool, None) with exn -> Logs.warn (fun m -> m "message.header: %s" (Printexc.to_string exn)); (pool, None) let compute fragment = match fragment with | Fragment_encode { content } -> let message = Message.encode ~content in Outcome_message { message } | Fragment_decode { expected; raw_content } -> ( try let message = Message.decode ~expected ~raw_content in Outcome_message { message } with exn -> Outcome_error { expected; exn }) let apply ~outcome pool = (* TODO: be resilient to double apply *) match outcome with | Outcome_message { message } -> ( let (Message { header; _ }) = message in let (Message_header { hash; level }) = header in match state ~hash ~level pool with | Pending _ | Unknown -> let pool = with_state ~hash ~level Accepted pool in let message = Message_pool_message { message } in (pool, Some message) | Accepted | Late -> (pool, None)) | Outcome_error { expected; exn } -> ( Logs.warn (fun m -> m "outcome.error: %s" (Printexc.to_string exn)); let (Message_header { hash; level }) = expected in match state ~hash ~level pool with | Pending { queue } -> ( match queue with | [] -> let pool = with_state ~hash ~level Unknown pool in (pool, None) | raw_content :: queue -> TODO : dedup logic let state = Pending { queue } in let pool = with_state ~hash ~level state pool in let fragment = Fragment_decode { expected; raw_content } in let fragment = Message_pool_fragment { fragment } in (pool, Some fragment)) | Accepted | Unknown | Late -> (pool, None)) let close ~until pool = let (Message_pool { current = _; by_level }) = pool in TODO : this allows to reopen ( close ~ until : Level.initial ) (* TODO: worst case scenario this becomes n log n, probably limit the drop until *) let by_level = drop ~until by_level in Message_pool { current = until; by_level }
null
https://raw.githubusercontent.com/marigold-dev/deku/cdf82852196b55f755f40850515580be4fd9a3fa/deku-p/src/core/gossip/message_pool.ml
ocaml
helpers external TODO: content hash to prevent double encoding TODO: be resilient to double apply TODO: worst case scenario this becomes n log n, probably limit the drop until
open Deku_concepts type message_state = | Accepted | Pending of { queue : string list } | Unknown | Late type message_pool = | Message_pool of { current : Level.t; by_level : message_state Message_hash.Map.t Level.Map.t; } and t = message_pool let message_state_encoding = let open Data_encoding in union [ case ~title:"Accepted" (Tag 0) unit (function Accepted -> Some () | _ -> None) (fun () -> Accepted); case ~title:"Pending" (Tag 1) (list string) (function Pending { queue } -> Some queue | _ -> None) (fun queue -> Pending { queue }); case ~title:"Unknown" (Tag 2) unit (function Unknown -> Some () | _ -> None) (fun () -> Unknown); case ~title:"Late" (Tag 3) unit (function Late -> Some () | _ -> None) (fun () -> Late); ] let encoding = let open Data_encoding in conv (fun (Message_pool { current; by_level }) -> (current, by_level)) (fun (current, by_level) -> Message_pool { current; by_level }) (tup2 Level.encoding (Level.Map.encoding (Message_hash.Map.encoding message_state_encoding))) type fragment = | Fragment_encode of { content : Message.Content.t } | Fragment_decode of { expected : Message.Header.t; raw_content : string } type outcome = | Outcome_message of { message : Message.t } | Outcome_error of { expected : Message.Header.t; exn : exn } type action = | Message_pool_message of { message : Message.t } | Message_pool_fragment of { fragment : fragment } let initial = Message_pool { current = Level.zero; by_level = Level.Map.empty } let rec drop ~level ~until by_level = match Level.(until > level) with | true -> let by_level = Level.Map.remove level by_level in let level = Level.next level in drop ~level ~until by_level | false -> Level.Map.remove until by_level let drop ~until by_level = match Level.Map.min_binding_opt by_level with | Some (level, _by_hash) -> drop ~level ~until by_level | None -> by_level let by_hash ~level by_level = match Level.Map.find_opt level by_level with | Some by_hash -> by_hash | None -> Message_hash.Map.empty let state ~hash ~level pool = let (Message_pool { current; by_level }) = pool in let by_hash = by_hash ~level by_level in match Level.(level > current) with | true -> ( match Message_hash.Map.find_opt hash by_hash with | Some state -> state | None -> Unknown) | false -> Late let with_state ~hash ~level state pool = let (Message_pool { current; by_level }) = pool in let by_hash = by_hash ~level by_level in let by_hash = Message_hash.Map.add hash state by_hash in let by_level = Level.Map.add level by_hash by_level in Message_pool { current; by_level } let encode ~content = Fragment_encode { content } let decode ~raw_header ~raw_content pool = let open Message.Header in try let expected = Message.Header.decode ~raw_header in let (Message_header { hash; level }) = expected in match state ~hash ~level pool with | Accepted -> (pool, None) | Pending { queue } -> let queue = raw_content :: queue in let state = Pending { queue } in let pool = with_state ~hash ~level state pool in (pool, None) | Unknown -> let queue = [] in let state = Pending { queue } in let pool = with_state ~hash ~level state pool in let fragment = Fragment_decode { expected; raw_content } in (pool, Some fragment) | Late -> (pool, None) with exn -> Logs.warn (fun m -> m "message.header: %s" (Printexc.to_string exn)); (pool, None) let compute fragment = match fragment with | Fragment_encode { content } -> let message = Message.encode ~content in Outcome_message { message } | Fragment_decode { expected; raw_content } -> ( try let message = Message.decode ~expected ~raw_content in Outcome_message { message } with exn -> Outcome_error { expected; exn }) let apply ~outcome pool = match outcome with | Outcome_message { message } -> ( let (Message { header; _ }) = message in let (Message_header { hash; level }) = header in match state ~hash ~level pool with | Pending _ | Unknown -> let pool = with_state ~hash ~level Accepted pool in let message = Message_pool_message { message } in (pool, Some message) | Accepted | Late -> (pool, None)) | Outcome_error { expected; exn } -> ( Logs.warn (fun m -> m "outcome.error: %s" (Printexc.to_string exn)); let (Message_header { hash; level }) = expected in match state ~hash ~level pool with | Pending { queue } -> ( match queue with | [] -> let pool = with_state ~hash ~level Unknown pool in (pool, None) | raw_content :: queue -> TODO : dedup logic let state = Pending { queue } in let pool = with_state ~hash ~level state pool in let fragment = Fragment_decode { expected; raw_content } in let fragment = Message_pool_fragment { fragment } in (pool, Some fragment)) | Accepted | Unknown | Late -> (pool, None)) let close ~until pool = let (Message_pool { current = _; by_level }) = pool in TODO : this allows to reopen ( close ~ until : Level.initial ) let by_level = drop ~until by_level in Message_pool { current = until; by_level }
5fa5bcab9b40c0dfc84eb19cc1f940bdc4f53526b03a7a88c168e6f7b36f9704
waymonad/waymonad
SeatMapping.hs
waymonad A wayland compositor in the spirit of xmonad Copyright ( C ) 2017 This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA Reach us at waymonad A wayland compositor in the spirit of xmonad Copyright (C) 2017 Markus Ongyerth This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Reach us at -} # LANGUAGE ScopedTypeVariables # module Waymonad.Hooks.SeatMapping ( mappingChangeEvt , outputChangeEvt , wsChangeLogHook ) where import Control.Monad (when, join, forM_) import Waymonad.Output (Output) import Waymonad.ViewSet (WSTag) import Waymonad (getState) import Waymonad.Types import Waymonad.Utility.Mapping (getOutputKeyboards, getOutputPointers, getOutputWS) import Waymonad.Utility.Log checkOutput :: WSTag a => Maybe Output -> Maybe Output -> (Maybe a -> Maybe a -> SeatWSChange a) -> Way vs a () checkOutput pre cur con = do preWS <- join <$> traverse getOutputWS pre curWS <- join <$> traverse getOutputWS cur when (preWS /= curWS) $ do hook <- wayHooksSeatWSChange . wayCoreHooks <$> getState hook $ con preWS curWS outputChangeEvt :: WSTag a => SeatOutputChange -> Way vs a () outputChangeEvt (SeatOutputChange SeatPointer _ seat pre cur) = checkOutput pre cur $ SeatWSChange SeatKeyboard SideEffect seat outputChangeEvt (SeatOutputChange SeatKeyboard _ seat pre cur) = checkOutput pre cur $ SeatWSChange SeatKeyboard SideEffect seat mappingChangeEvt :: WSTag a => OutputMappingEvent a -> Way vs a () mappingChangeEvt (OutputMappingEvent out pre cur) = do keys <- getOutputKeyboards out points <- getOutputPointers out hook <- wayHooksSeatWSChange . wayCoreHooks <$> getState forM_ points $ \point -> hook $ SeatWSChange SeatPointer SideEffect point pre cur forM_ keys $ \key -> hook $ SeatWSChange SeatKeyboard SideEffect key pre cur wsChangeLogHook :: forall ws vs. WSTag ws => SeatWSChange ws -> Way vs ws () wsChangeLogHook evt = logPrint loggerWS Debug evt
null
https://raw.githubusercontent.com/waymonad/waymonad/18ab493710dd54c330fb4d122ed35bc3a59585df/src/Waymonad/Hooks/SeatMapping.hs
haskell
waymonad A wayland compositor in the spirit of xmonad Copyright ( C ) 2017 This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA Reach us at waymonad A wayland compositor in the spirit of xmonad Copyright (C) 2017 Markus Ongyerth This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Reach us at -} # LANGUAGE ScopedTypeVariables # module Waymonad.Hooks.SeatMapping ( mappingChangeEvt , outputChangeEvt , wsChangeLogHook ) where import Control.Monad (when, join, forM_) import Waymonad.Output (Output) import Waymonad.ViewSet (WSTag) import Waymonad (getState) import Waymonad.Types import Waymonad.Utility.Mapping (getOutputKeyboards, getOutputPointers, getOutputWS) import Waymonad.Utility.Log checkOutput :: WSTag a => Maybe Output -> Maybe Output -> (Maybe a -> Maybe a -> SeatWSChange a) -> Way vs a () checkOutput pre cur con = do preWS <- join <$> traverse getOutputWS pre curWS <- join <$> traverse getOutputWS cur when (preWS /= curWS) $ do hook <- wayHooksSeatWSChange . wayCoreHooks <$> getState hook $ con preWS curWS outputChangeEvt :: WSTag a => SeatOutputChange -> Way vs a () outputChangeEvt (SeatOutputChange SeatPointer _ seat pre cur) = checkOutput pre cur $ SeatWSChange SeatKeyboard SideEffect seat outputChangeEvt (SeatOutputChange SeatKeyboard _ seat pre cur) = checkOutput pre cur $ SeatWSChange SeatKeyboard SideEffect seat mappingChangeEvt :: WSTag a => OutputMappingEvent a -> Way vs a () mappingChangeEvt (OutputMappingEvent out pre cur) = do keys <- getOutputKeyboards out points <- getOutputPointers out hook <- wayHooksSeatWSChange . wayCoreHooks <$> getState forM_ points $ \point -> hook $ SeatWSChange SeatPointer SideEffect point pre cur forM_ keys $ \key -> hook $ SeatWSChange SeatKeyboard SideEffect key pre cur wsChangeLogHook :: forall ws vs. WSTag ws => SeatWSChange ws -> Way vs ws () wsChangeLogHook evt = logPrint loggerWS Debug evt
e2529f2fcc2f122bc6bb7933ae82ed3577a7f8029eee11df899a45c52ab749f3
paurkedal/ocaml-mediawiki-api
mwapi_prereq.ml
Copyright ( C ) 2013 - -2017 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the OCaml static compilation exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this library . If not , see < / > . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the OCaml static compilation exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see </>. *) open Printf let failwith_f fmt = ksprintf failwith fmt let pair x y = x, y type params = (string * string) list let pass conv label ?default x params = if default = Some x then params else (label, conv x) :: params let pass_opt conv label xo params = match xo with | None -> params | Some x -> (label, conv x) :: params let pass_list conv label xs params = match xs with | [] -> params | _ -> (label, String.concat "|" (List.map conv xs)) :: params let pass_if label cond params = if cond then (label, "") :: params else params let mw_time_format = "%Y-%m-%dT%H:%M:%SZ" let caltime_of_string = CalendarLib.Printer.Calendar.from_fstring mw_time_format let string_of_caltime = CalendarLib.Printer.Calendar.sprint mw_time_format module K_repair = struct open Kojson_pattern let int = K.convert "int" begin function | `Int i -> i | `String s -> int_of_string s | _ -> failwith "A string or, preferably, integer expected." end end
null
https://raw.githubusercontent.com/paurkedal/ocaml-mediawiki-api/6a1c1043a8ad578ea321a314fbe0a12a8d0933cf/lib/mwapi_prereq.ml
ocaml
Copyright ( C ) 2013 - -2017 Petter A. Urkedal < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the OCaml static compilation exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this library . If not , see < / > . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the OCaml static compilation exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see </>. *) open Printf let failwith_f fmt = ksprintf failwith fmt let pair x y = x, y type params = (string * string) list let pass conv label ?default x params = if default = Some x then params else (label, conv x) :: params let pass_opt conv label xo params = match xo with | None -> params | Some x -> (label, conv x) :: params let pass_list conv label xs params = match xs with | [] -> params | _ -> (label, String.concat "|" (List.map conv xs)) :: params let pass_if label cond params = if cond then (label, "") :: params else params let mw_time_format = "%Y-%m-%dT%H:%M:%SZ" let caltime_of_string = CalendarLib.Printer.Calendar.from_fstring mw_time_format let string_of_caltime = CalendarLib.Printer.Calendar.sprint mw_time_format module K_repair = struct open Kojson_pattern let int = K.convert "int" begin function | `Int i -> i | `String s -> int_of_string s | _ -> failwith "A string or, preferably, integer expected." end end
81399c12a8c8d22877ca5fca6c3639dce8ceb560ec4b999bbf56b0bab12c0f61
lambdamikel/VISCO
draw15.lisp
-*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : GUI ; Base : 10 -*- (in-package gui) (defconstant +label-text-style+ (parse-text-style '(:sans-serif nil :very-small))) (defconstant +highlighted-label-text-style+ (parse-text-style '(:sans-serif (:bold :italic) :small))) (defconstant +at-most-label-text-style+ (parse-text-style '(:sans-serif nil :very-large))) (defconstant +at-most-highlighted-label-text-style+ (parse-text-style '(:sans-serif (:bold :italic) :huge))) (defconstant +object-without-disjoint-and-intersects-relations-ink+ (make-gray-color 0.7)) (defconstant +my-yellow+ (make-rgb-color 1 0.5 0.2)) (defconstant +overlapping-line-dashes+ '(3 5)) (defconstant +transparency-properties-dashes+ '(2 2)) (defconstant +beam-thickness+ 2) (defconstant +rubberband-thickness+ 1) (defconstant +rubberband-waveness+ 3) (defconstant +marble-size+ 5) (defconstant +nail-size+ 5) (defconstant +bullet-size+ 4) (defconstant +arrow-head-size+ 5) (defconstant +marble-gravity+ 10) (defconstant +nail-gravity+ 10) (defconstant +line-gravity+ 15) (defconstant +drawn-enclosure-gravity+ 30) (defconstant +chain-and-polygon-gravity+ 30) (defconstant +ar-1st-arrow-offset+ 12) ; ar = atomic rubberband (defconstant +ar-2nd-arrow-offset+ 17) (defconstant +two-guiding-lines-length+ 20) ; fwo = transparency without origin (defconstant +chain-and-polygon-icon-gravity+ 10) (defconstant +oc-gravity+ 10) (defconstant +bullet-gravity+ 10) (defconstant +marble-highlight+ 10) (defconstant +nail-highlight+ 10) (defconstant +line-highlight+ 6) (defconstant +transparency-highlight+ 5) (defconstant +enclosure-highlight+ 2) (defconstant +chain-and-polygon-icon-highlight+ 6) (defconstant +oc-highlight+ 3) (defconstant +bullet-highlight+ 5) (defconstant +intervall-highlight+ 2) (defconstant +arrow-head-highlight+ 10) (defconstant +label-text-style-line-height+ 10) (defconstant +transparency-arrow-length+ 15) ;;; ;;; ;;; (defgeneric draw (obj stream &key &allow-other-keys)) (defmethod draw :around ((obj gui-object) stream &key ink (top-level t) subobjects-draw-only-gravity-field (draw-component-objects t) (draw-relative-orientation-circles t) (single-box (typep obj '(or gui-enclosure gui-transparency))) (draw-label t) border-for (gravity-field t) handling-active highlight (allow-sensitive-inferiors t) (draw-chain-or-polygon-icon-p t) label-x label-y (output-recording t)) (let ((gravity-field (and (not handling-active) (not highlight) gravity-field))) (labels ((do-it () (with-visco-frame (visco) (labels ((do-it () (with-drawing-options (stream :ink (cond ((and border-for (not (eq border-for 'focus))) (ecase border-for (intersects +my-yellow+) (inside/contains (if (typep obj 'gui-enclosure) (inside-ink obj) +yellow+)) (disjoint +blue+))) ((or handling-active highlight *sceleton-view*) +flipping-ink+) ((eq (current-transparency visco) obj) (current-transparency-ink obj)) (t (if (and (typep obj '(or gui-point gui-line)) (ignore-disjoint-and-intersects-relations-p obj)) +object-without-disjoint-and-intersects-relations-ink+ (or ink (ink obj)))))) (apply #'call-next-method obj stream :ink ink :top-level top-level :subobjects-draw-only-gravity-field subobjects-draw-only-gravity-field :draw-component-objects draw-component-objects :draw-relative-orientation-circles draw-relative-orientation-circles :single-box single-box :draw-label draw-label :border-for border-for :gravity-field gravity-field :handling-active handling-active :highlight highlight :allow-sensitive-inferiors allow-sensitive-inferiors :draw-chain-or-polygon-icon-p draw-chain-or-polygon-icon-p :label-x label-x :label-y label-y :output-recording output-recording nil)))) (if (and top-level (eq border-for 'focus)) (with-border (stream :offset 5) (do-it)) (do-it)))))) (if (and output-recording (or *ignore-inactive-flag* (not (inactive obj)))) (with-output-as-presentation (stream obj (type-of obj) :single-box single-box :allow-sensitive-inferiors allow-sensitive-inferiors) (do-it)) (with-output-recording-options (stream :draw t :record nil) (do-it)))))) (defmethod draw-label ((obj gui-label) stream &key highlight label-x label-y handling-active (label-text-style +label-text-style+) (highlighted-label-text-style +highlighted-label-text-style+) (label-text-style-line-height +label-text-style-line-height+)) (multiple-value-bind (x y) (get-label-origin-for (object obj)) (let ((x (or label-x (+ x (x-off obj)))) (y (or label-y (+ y (y-off obj))))) (labels ((draw-it () (let ((line y)) (dolist (string (text obj)) (draw-text* stream string x line) (incf line label-text-style-line-height))))) (when highlight (with-drawing-options (stream :ink (when (or handling-active highlight) +flipping-ink+) :text-style (case highlight (:highlight label-text-style) (otherwise highlighted-label-text-style))) (draw-it))) (with-drawing-options (stream :ink (when (or handling-active highlight) +flipping-ink+) :text-style (case highlight (:highlight highlighted-label-text-style) (otherwise label-text-style))) (draw-it)))))) (defmethod draw-label* (text x y stream &key (label-text-style +label-text-style+) (label-text-style-line-height +label-text-style-line-height+)) (with-drawing-options (stream :text-style label-text-style) (let ((line y)) (dolist (string text) (draw-text* stream string x line) (incf line label-text-style-line-height))))) (defun draw-arrow-head (stream p dir-fac rot &rest args) (apply #'draw-arrow-head* stream (x p) (y p) dir-fac rot args)) (defun draw-arrow-head* (stream x y dir-fac rot &key (offset 0) (filled t) (arrow-head-size +arrow-head-size+)) (let ((trans (make-rotation-transformation* rot x y))) (with-drawing-options (stream :transformation trans) (let* ((x (+ x offset)) (x1 x) (y1 (+ y arrow-head-size)) (x2 (+ x (* dir-fac arrow-head-size))) (y2 y) (x3 x) (y3 (- y arrow-head-size))) (draw-polygon* stream (list x1 y1 x2 y2 x3 y3) :filled filled))))) (defmethod draw-gui-line ((obj gui-line) stream r &rest args &key (draw-component-objects t) &allow-other-keys) (unless (already-drawn obj) (draw-line* stream (x (p1 obj)) (y (p1 obj)) (x (p2 obj)) (y (p2 obj)) :line-dashes (when (1d-intersects-other-lines-p obj) +overlapping-line-dashes+) :line-thickness r)) (when draw-component-objects (apply #'draw (p1 obj) stream :top-level nil args) (apply #'draw (p2 obj) stream :top-level nil args))) (defmethod draw-gui-rubberband ((obj gui-line) stream r &rest args &key (draw-component-objects t) &allow-other-keys) (unless (already-drawn obj) (let* ((l (/ (length-of-line obj) 9)) (intersects (1d-intersects-other-lines-p obj) ) (alpha (global-orientation obj)) (alpha-orth1 (+ alpha +pi/2+)) (alpha-orth2 (- alpha +pi/2+)) (xs (x (p1 obj))) (ys (y (p1 obj))) (xe (x (p2 obj))) (ye (y (p2 obj))) (xi (* l (cos alpha))) (yi (* l (sin alpha))) (xii-orth1 (* +rubberband-waveness+ (cos alpha-orth1))) (xii-orth2 (* +rubberband-waveness+ (cos alpha-orth2))) (yii-orth1 (* +rubberband-waveness+ (sin alpha-orth1))) (yii-orth2 (* +rubberband-waveness+ (sin alpha-orth2))) (lx xs) (ly ys) (cx xs) (cy ys)) (dotimes (n 8) (incf cx xi) (incf cy yi) (let ((x (+ cx (if (evenp n) xii-orth1 xii-orth2))) (y (+ cy (if (evenp n) yii-orth1 yii-orth2)))) (draw-line* stream lx ly x y :line-thickness r :line-dashes (when intersects +overlapping-line-dashes+)) (setf lx x ly y))) (draw-line* stream lx ly xe ye :line-thickness r :line-dashes (when intersects +overlapping-line-dashes+)) (draw-line* stream xs ys xe ye :line-thickness r :line-dashes (when intersects +overlapping-line-dashes+)))) (when draw-component-objects (apply #'draw (p1 obj) stream :top-level nil args) (apply #'draw (p2 obj) stream :top-level nil args))) (defmethod draw-gravity-field ((obj geom-point) stream r) (draw-circle* stream (x obj) (y obj) r :ink +transparent-ink+ :filled t)) (defmethod draw-gravity-field ((obj geom-line) stream r) (draw-gravity-field-for-line stream (x (p1 obj)) (y (p1 obj)) (x (p2 obj)) (y (p2 obj)) r)) (defun draw-gravity-field-for-line (stream x1 y1 x2 y2 r) (draw-line* stream x1 y1 x2 y2 :line-thickness r :ink +transparent-ink+)) (defun draw-gravity-field-for-circle (stream x y radius r) (draw-circle* stream x y radius :line-thickness r :filled nil :ink +transparent-ink+)) ;;; ;;; ;;; (defun draw-epsilon-body (obj r stream &rest args) (multiple-value-bind (p1fx p1fy p1tx p1ty p2fx p2fy p2tx p2ty) (get-epsilon-enclosure-relevant-points* obj r) (apply #'draw-polygon* stream (list p1fx p1fy p2fx p2fy p2tx p2ty p1tx p1ty p1fx p1fy) args))) (defun draw-epsilon-circle (obj r stream &rest args) (apply #'draw-circle* stream (x obj) (y obj) r args)) (defun draw-epsilon-segment (obj r stream &rest args) (apply #'draw-epsilon-circle (p1 obj) r stream args) (apply #'draw-epsilon-circle (p2 obj) r stream args) (apply #'draw-epsilon-body obj r stream args)) ;;; ;;; ;;; (defgeneric highlight (obj stream state) (:method-combination progn)) (defmethod highlight progn ((obj gui-chain-or-polygon) stream state) (dolist (segment (segments obj)) (draw segment stream :draw-component-objects nil :highlight state :output-recording nil)) (dolist (point (point-list obj)) (draw point stream :highlight state :output-recording nil)) (draw (status-label obj) stream :highlight state :output-recording nil) (when (at-most-constraint obj) (draw (at-most-label obj) stream :highlight state :output-recording nil))) (defmethod highlight progn ((obj gui-object) stream state) (unless (typep obj 'gui-chain-or-polygon) (draw obj stream :highlight state :output-recording nil))) ;;; ;;; ;;; (defmethod object-selected-position-test ((obj gui-enclosure) record x y) (declare (ignore record)) (asg-inside-p* x y obj)) (define-presentation-method highlight-presentation ((obj gui-chain-or-polygon) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-label) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-point) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-line) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-transparency) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-orientation-arrow) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-relative-orientation-circle) record stream state) (highlight (presentation-object record) stream state)) ;;; ;;; ;;; (defmethod get-label-origin-for ((obj gui-point)) (values (x obj) (y obj))) (defmethod get-label-origin-for ((obj gui-transparency)) (values (x (pcenter obj)) (y (pcenter obj)))) (defmethod get-label-origin-for ((obj gui-line)) (values (x (pcenter obj)) (y (pcenter obj)))) (defmethod get-label-origin-for ((obj gui-chain-or-polygon)) (values (x (centroid obj)) (y (centroid obj)))) (defmethod get-label-origin-for ((obj gui-drawn-enclosure)) (values (x (centroid obj)) (y (centroid obj)))) (defmethod get-label-origin-for ((obj gui-derived-enclosure)) (get-label-origin-for (arg-object obj))) ;;; ;;; ;;; (defmethod draw ((obj gui-status-label) stream &key handling-active highlight label-x label-y gravity-field draw-chain-or-polygon-icon-p) (setf (text obj) (list (if (and (typep (object obj) 'possible-operator-result-mixin) (res-of-operators (object obj))) (concatenate 'string (get-status-string (status (object obj))) " (D)") (get-status-string (status (object obj)))))) (draw-label obj stream :handling-active handling-active :highlight highlight :label-x label-x :label-y label-y) (labels ((draw-it () (let ((object (object obj))) (multiple-value-bind (x y) (get-label-origin-for object) (when (typep object 'gui-chain-or-polygon) (with-translation (stream (or label-x (+ (x-off obj) x 20)) (or label-y (+ (y-off obj) y 20))) (with-scaling (stream 0.1) (with-translation (stream (- x) (- y)) (dolist (segment (segments object)) (draw-line* stream (x (p1 segment)) (y (p1 segment)) (x (p2 segment)) (y (p2 segment)) :line-thickness (when highlight +chain-and-polygon-icon-highlight+)) (when gravity-field (draw-gravity-field-for-line stream (x (p1 segment)) (y (p1 segment)) (x (p2 segment)) (y (p2 segment)) +chain-and-polygon-icon-gravity+))))))))))) (when draw-chain-or-polygon-icon-p (draw-it)))) (defmethod draw ((obj gui-semantics-label) stream &key highlight handling-active label-x label-y) (setf (text obj) (mapcar #'(lambda (s) (first (lookup-os s))) (semantics (object obj)))) (draw-label obj stream :highlight highlight :handling-active handling-active :label-x label-x :label-y label-y)) (defmethod draw ((obj gui-at-most-label) stream &key highlight handling-active label-x label-y) (setf (text obj) (list (format nil "~A" (at-most-constraint (object obj))))) (draw-label obj stream :highlight highlight :handling-active handling-active :label-x label-x :label-y label-y :label-text-style +at-most-label-text-style+ :highlighted-label-text-style +at-most-highlighted-label-text-style+)) (defmethod draw ((obj gui-orientation-arrow) stream &key highlight gravity-field) (multiple-value-bind (x y) (get-origin-for obj) (let* ((alpha (+ (alpha-off obj) (if (typep (object obj) 'geom-line) (global-orientation (object obj)) 0))) (r (r obj)) (r-offset 3)) (labels ((draw-scale-mark (mark) (let ((x (+ x (* (cos (+ alpha mark)) r))) (y (+ y (* (sin (+ alpha mark)) r)))) (draw-circle* stream x y (if highlight +bullet-highlight+ +bullet-size+))))) (let ((x1 (+ x (* (cos alpha) (- r 5)))) (y1 (+ y (* (sin alpha) (- r 5))))) (draw-line* stream x y x1 y1 :line-thickness (when highlight +oc-highlight+)) (draw-arrow-head* stream x1 y1 1.0 alpha :offset (- +arrow-head-size+) :arrow-head-size (if highlight +arrow-head-highlight+ +arrow-head-size+)) (when gravity-field (draw-gravity-field-for-line stream x y x1 y1 +oc-gravity+)) (let ((cs (orientation-constraint (object obj)))) (unless (and (null (rest cs)) (numberp (first cs)) (zerop (first cs))) (draw-circle* stream x y r :filled nil :line-thickness (when highlight +oc-highlight+)) (when gravity-field (draw-gravity-field-for-circle stream x y r +oc-gravity+)) (dolist (entry cs) (if (listp entry) (progn (draw-circle* stream x y (+ r r-offset) :end-angle (- +2pi+ (+ alpha (first entry))) :start-angle (- +2pi+ (+ alpha (second entry))) :line-thickness (when highlight +oc-highlight+) :filled nil) (draw-circle* stream x y (+ r r-offset) :end-angle (- +2pi+ (+ alpha pi (first entry))) :start-angle (- +2pi+ (+ alpha pi (second entry))) :line-thickness (when highlight +oc-highlight+) :filled nil)) (progn (draw-scale-mark (+ pi entry)) (draw-scale-mark entry))))))))))) (defmethod draw ((obj gui-relative-orientation-circle) stream &key highlight gravity-field ) (let* ((obj1 (object1 obj)) (obj2 (object2 obj)) (r (r obj)) (r-offset 3) (w (/ (allowed-derivation obj) 2)) (alpha1 (global-orientation obj1)) (alpha2 (global-orientation obj2))) (multiple-value-bind (x y) (calculate-intersection-point obj1 obj2) (when (and x y) (draw-circle* stream x y r :filled nil :line-thickness (when highlight +oc-highlight+)) (when gravity-field (draw-gravity-field-for-circle stream x y r +oc-gravity+)) (labels ((draw-it (alpha) (if (=-eps w 0) (draw-circle* stream (+ x (* (cos alpha) r)) (+ y (* (sin alpha) r)) (if highlight +bullet-highlight+ +bullet-size+)) (draw-circle* stream x y (+ r r-offset) :end-angle (- +2pi+ (- alpha w)) :start-angle (- +2pi+ (+ alpha w)) :line-thickness (when highlight +oc-highlight+) :filled nil)))) (with-drawing-options (stream :line-thickness 2) (draw-it alpha1) (incf r-offset 2) (draw-it (+ pi alpha1))) (incf r-offset 2) (draw-it alpha2) (incf r-offset 2) (draw-it (+ pi alpha2))))))) ;;; ;;; ;;; (defmethod draw :after ((obj gui-query-object) stream &rest args &key (draw-label t) (output-recording t)) (labels ((draw-it () (apply #'draw (status-label obj) stream :top-level nil args) (when (semantics obj) (apply #'draw (semantics-label obj) stream :border-for nil :ink nil :top-level nil args)))) (when (and draw-label (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) (defmethod draw :after ((obj orientation-constraint-mixin) stream &rest args &key (output-recording t)) (labels ((draw-it () (apply #'draw (orientation-arrow obj) stream :border-for nil :ink nil :top-level nil args))) (when (and (orientation-constraint obj) (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) (defmethod draw :after ((obj at-most-constraint-mixin) stream &rest args &key (draw-label t) (output-recording t)) (labels ((draw-it () (apply #'draw (at-most-label obj) stream :border-for nil :ink nil :top-level nil args))) (when (and draw-label (at-most-constraint obj) (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) (defmethod draw :after ((obj gui-atomic-rubberband) stream &rest args &key (output-recording t) (draw-relative-orientation-circles t) highlight) (labels ((draw-it () (dolist (circle (relative-orientation-circles obj)) (when (eq obj (object1 circle)) (apply #'draw circle stream :border-for nil :ink nil :top-level nil args))))) (when (and (relative-orientation-circles obj) draw-relative-orientation-circles (not highlight) (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) ;;; ;;; ;;; (defmethod draw ((obj gui-transparency) stream &key highlight) (labels ((draw-it (r) (draw-rectangle* stream (x (pmin obj)) (y (pmin obj)) (x (pmax obj)) (y (pmax obj)) :line-thickness r :filled nil) (let* ((xmin (x (pmin obj))) (ymin (y (pmin obj))) (xmax (x (pmax obj))) (ymax (y (pmax obj))) (xmiddle (/ (+ xmin xmax) 2)) (ymiddle (/ (+ ymin ymax) 2)) (sxt (sx-type obj)) (syt (sy-type obj))) (with-drawing-options (stream :line-dashes +transparency-properties-dashes+) (when (height obj) (if (or (not syt) (and (symin obj) (symax obj) (= (symin obj) (symax obj)))) (draw-text* stream (format nil "~A m." (round (height obj))) (+ xmin 4) (- ymiddle 4)) (draw-text* stream (format nil "~A ... ~A" (if (symin obj) (format nil "~A m." (round (* (symin obj) (height obj)))) "0") (if (symax obj) (format nil "~A m." (round (* (symax obj) (height obj)))) "infinity")) (+ xmin 4) (- ymiddle 4)))) (when (width obj) (if (or (not sxt) (and (sxmin obj) (sxmax obj) (= (sxmin obj) (sxmax obj)))) (draw-text* stream (format nil "~A m." (round (width obj))) (+ xmiddle 4) (- ymax 4)) (draw-text* stream (format nil "~A ... ~A" (if (sxmin obj) (format nil "~A m." (round (* (sxmin obj) (width obj)))) "0") (if (sxmax obj) (format nil "~A m." (round (* (sxmax obj) (width obj)))) "infinity")) (+ xmiddle 4) (- ymax 4)))) (when sxt (when (=> (sxmax obj) (not (= 1.0 (sxmax obj)))) (draw-arrow* stream xmin ymiddle (- xmin +transparency-arrow-length+) ymiddle) (draw-arrow* stream xmax ymiddle (+ xmax +transparency-arrow-length+) ymiddle)) (when (=> (sxmin obj) (not (= 1.0 (sxmin obj)))) (draw-arrow* stream xmin ymiddle (+ xmin +transparency-arrow-length+) ymiddle) (draw-arrow* stream xmax ymiddle (- xmax +transparency-arrow-length+) ymiddle))) (when syt (when (=> (symax obj) (not (= 1.0 (symax obj)))) (draw-arrow* stream xmiddle ymin xmiddle (- ymin +transparency-arrow-length+)) (draw-arrow* stream xmiddle ymax xmiddle (+ ymax +transparency-arrow-length+))) (when (=> (symin obj) (not (= 1.0 (symin obj)))) (draw-arrow* stream xmiddle ymin xmiddle (+ ymin +transparency-arrow-length+)) (draw-arrow* stream xmiddle ymax xmiddle (- ymax +transparency-arrow-length+)))) (when (sxsy-constraint obj) (if (origin obj) (progn (draw-line* stream (x (origin obj)) (y (origin obj)) xmin ymin) (draw-line* stream (x (origin obj)) (y (origin obj)) xmin ymax) (draw-line* stream (x (origin obj)) (y (origin obj)) xmax ymin) (draw-line* stream (x (origin obj)) (y (origin obj)) xmax ymax)) (progn (draw-line* stream xmin ymin (+ xmin +two-guiding-lines-length+) (+ ymin +two-guiding-lines-length+)) (draw-line* stream xmin ymax (+ xmin +two-guiding-lines-length+) (- ymax +two-guiding-lines-length+)) (draw-line* stream xmax ymin (- xmax +two-guiding-lines-length+) (+ ymin +two-guiding-lines-length+)) (draw-line* stream xmax ymax (- xmax +two-guiding-lines-length+) (- ymax +two-guiding-lines-length+))))))))) (if highlight (draw-it +transparency-highlight+) (draw-it 0)))) ;;; ;;; ;;; (defmethod draw ((obj gui-marble) stream &key top-level gravity-field subobjects-draw-only-gravity-field highlight) (labels ((draw-it (r) (when (or (not (already-drawn obj)) top-level (and (not top-level) (not subobjects-draw-only-gravity-field))) (draw-circle* stream (x obj) (y obj) r :filled nil)))) (if highlight (draw-it +marble-highlight+) (progn (when gravity-field (draw-gravity-field obj stream +marble-gravity+)) (draw-it +marble-size+))))) (defmethod draw ((obj gui-nail) stream &key top-level gravity-field subobjects-draw-only-gravity-field highlight) (labels ((draw-it (r) (when (or (not (already-drawn obj)) top-level (and (not top-level) (not subobjects-draw-only-gravity-field))) (draw-marker* stream (x obj) (y obj) r)))) (if highlight (draw-it +nail-highlight+) (progn (when gravity-field (draw-gravity-field obj stream +nail-gravity+)) (draw-it +nail-size+))))) (defmethod draw ((obj gui-origin) stream &key top-level gravity-field subobjects-draw-only-gravity-field highlight) (labels ((draw-it (r) (when (or (not (already-drawn obj)) top-level (and (not top-level) (not subobjects-draw-only-gravity-field))) (draw-rectangle* stream (- (x obj) r) (- (y obj) r) (+ (x obj) r) (+ (y obj) r) :filled t)))) (if highlight (draw-it +nail-highlight+) (progn (when gravity-field (draw-gravity-field obj stream +nail-gravity+)) (draw-it +nail-size+))))) ;;; ;;; ;;; (defmethod draw ((obj gui-beam) stream &rest args &key highlight gravity-field) (if highlight (apply #'draw-gui-line obj stream (+ +beam-thickness+ +line-highlight+) args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +beam-thickness+ args)))) (defmethod draw ((obj gui-atomic-rubberband) stream &rest args &key highlight gravity-field) (unless (already-drawn obj) (let ((alpha (geometry::global-orientation obj))) (draw-arrow-head stream (p1 obj) -1.0 alpha :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) -1.0 (+ pi alpha) :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p1 obj) 1 alpha :offset +ar-2nd-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) 1 (+ pi alpha) :offset +ar-2nd-arrow-offset+ :filled nil))) (if highlight (apply #'draw-gui-line obj stream +line-highlight+ args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +rubberband-thickness+ args)))) (defmethod draw ((obj gui-atomic->=-rubberband) stream &rest args &key highlight gravity-field) (unless (already-drawn obj) (let ((alpha (geometry::global-orientation obj))) (draw-arrow-head stream (p1 obj) -1 alpha :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) -1 (+ pi alpha) :offset +ar-1st-arrow-offset+ :filled nil))) (if highlight (apply #'draw-gui-line obj stream +line-highlight+ args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +rubberband-thickness+ args)))) (defmethod draw ((obj gui-atomic-<=-rubberband) stream &rest args &key highlight gravity-field) (unless (already-drawn obj) (let ((alpha (geometry::global-orientation obj))) (draw-arrow-head stream (p1 obj) 1 alpha :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) 1 (+ pi alpha) :offset +ar-1st-arrow-offset+ :filled nil))) (if highlight (apply #'draw-gui-line obj stream +line-highlight+ args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +rubberband-thickness+ args)))) (defmethod draw ((obj gui-rubberband) stream &rest args &key highlight gravity-field) (if highlight (apply #'draw-gui-line obj stream (+ +rubberband-thickness+ +line-highlight+) args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-rubberband obj stream +rubberband-thickness+ args)))) ;;; ;;; ;;; (defmethod draw ((obj gui-chain-or-polygon) stream &rest args &key gravity-field draw-component-objects) (unless (already-drawn obj) (when gravity-field (dolist (segment (segments obj)) (draw-gravity-field segment stream +chain-and-polygon-gravity+))) (dolist (segment (segments obj)) (if draw-component-objects (apply #'draw segment stream :single-box nil :top-level nil args) (draw-line* stream (x (p1 segment)) (y (p1 segment)) (x (p2 segment)) (y (p2 segment))))))) ;;; ;;; ;;; (defmethod draw ((obj gui-enclosure) stream &key) (draw-polygon* stream (drawable-pointlist obj) :closed t)) (defmethod draw ((obj gui-epsilon-enclosure) stream &key) (let ((r (radius obj)) (obj (arg-object obj))) (typecase obj (point (draw-epsilon-circle obj r stream )) (line (draw-epsilon-segment obj r stream)) (chain-or-polygon (dolist (segment (segments obj)) (draw-epsilon-body segment r stream)) (dolist (point (point-list obj)) (draw-epsilon-circle point r stream))))))
null
https://raw.githubusercontent.com/lambdamikel/VISCO/836d325b5c6037517470835c635b3063446d3d8a/src/GUI/draw15.lisp
lisp
Syntax : Ansi - Common - Lisp ; Package : GUI ; Base : 10 -*- ar = atomic rubberband fwo = transparency without origin
(in-package gui) (defconstant +label-text-style+ (parse-text-style '(:sans-serif nil :very-small))) (defconstant +highlighted-label-text-style+ (parse-text-style '(:sans-serif (:bold :italic) :small))) (defconstant +at-most-label-text-style+ (parse-text-style '(:sans-serif nil :very-large))) (defconstant +at-most-highlighted-label-text-style+ (parse-text-style '(:sans-serif (:bold :italic) :huge))) (defconstant +object-without-disjoint-and-intersects-relations-ink+ (make-gray-color 0.7)) (defconstant +my-yellow+ (make-rgb-color 1 0.5 0.2)) (defconstant +overlapping-line-dashes+ '(3 5)) (defconstant +transparency-properties-dashes+ '(2 2)) (defconstant +beam-thickness+ 2) (defconstant +rubberband-thickness+ 1) (defconstant +rubberband-waveness+ 3) (defconstant +marble-size+ 5) (defconstant +nail-size+ 5) (defconstant +bullet-size+ 4) (defconstant +arrow-head-size+ 5) (defconstant +marble-gravity+ 10) (defconstant +nail-gravity+ 10) (defconstant +line-gravity+ 15) (defconstant +drawn-enclosure-gravity+ 30) (defconstant +chain-and-polygon-gravity+ 30) (defconstant +ar-2nd-arrow-offset+ 17) (defconstant +chain-and-polygon-icon-gravity+ 10) (defconstant +oc-gravity+ 10) (defconstant +bullet-gravity+ 10) (defconstant +marble-highlight+ 10) (defconstant +nail-highlight+ 10) (defconstant +line-highlight+ 6) (defconstant +transparency-highlight+ 5) (defconstant +enclosure-highlight+ 2) (defconstant +chain-and-polygon-icon-highlight+ 6) (defconstant +oc-highlight+ 3) (defconstant +bullet-highlight+ 5) (defconstant +intervall-highlight+ 2) (defconstant +arrow-head-highlight+ 10) (defconstant +label-text-style-line-height+ 10) (defconstant +transparency-arrow-length+ 15) (defgeneric draw (obj stream &key &allow-other-keys)) (defmethod draw :around ((obj gui-object) stream &key ink (top-level t) subobjects-draw-only-gravity-field (draw-component-objects t) (draw-relative-orientation-circles t) (single-box (typep obj '(or gui-enclosure gui-transparency))) (draw-label t) border-for (gravity-field t) handling-active highlight (allow-sensitive-inferiors t) (draw-chain-or-polygon-icon-p t) label-x label-y (output-recording t)) (let ((gravity-field (and (not handling-active) (not highlight) gravity-field))) (labels ((do-it () (with-visco-frame (visco) (labels ((do-it () (with-drawing-options (stream :ink (cond ((and border-for (not (eq border-for 'focus))) (ecase border-for (intersects +my-yellow+) (inside/contains (if (typep obj 'gui-enclosure) (inside-ink obj) +yellow+)) (disjoint +blue+))) ((or handling-active highlight *sceleton-view*) +flipping-ink+) ((eq (current-transparency visco) obj) (current-transparency-ink obj)) (t (if (and (typep obj '(or gui-point gui-line)) (ignore-disjoint-and-intersects-relations-p obj)) +object-without-disjoint-and-intersects-relations-ink+ (or ink (ink obj)))))) (apply #'call-next-method obj stream :ink ink :top-level top-level :subobjects-draw-only-gravity-field subobjects-draw-only-gravity-field :draw-component-objects draw-component-objects :draw-relative-orientation-circles draw-relative-orientation-circles :single-box single-box :draw-label draw-label :border-for border-for :gravity-field gravity-field :handling-active handling-active :highlight highlight :allow-sensitive-inferiors allow-sensitive-inferiors :draw-chain-or-polygon-icon-p draw-chain-or-polygon-icon-p :label-x label-x :label-y label-y :output-recording output-recording nil)))) (if (and top-level (eq border-for 'focus)) (with-border (stream :offset 5) (do-it)) (do-it)))))) (if (and output-recording (or *ignore-inactive-flag* (not (inactive obj)))) (with-output-as-presentation (stream obj (type-of obj) :single-box single-box :allow-sensitive-inferiors allow-sensitive-inferiors) (do-it)) (with-output-recording-options (stream :draw t :record nil) (do-it)))))) (defmethod draw-label ((obj gui-label) stream &key highlight label-x label-y handling-active (label-text-style +label-text-style+) (highlighted-label-text-style +highlighted-label-text-style+) (label-text-style-line-height +label-text-style-line-height+)) (multiple-value-bind (x y) (get-label-origin-for (object obj)) (let ((x (or label-x (+ x (x-off obj)))) (y (or label-y (+ y (y-off obj))))) (labels ((draw-it () (let ((line y)) (dolist (string (text obj)) (draw-text* stream string x line) (incf line label-text-style-line-height))))) (when highlight (with-drawing-options (stream :ink (when (or handling-active highlight) +flipping-ink+) :text-style (case highlight (:highlight label-text-style) (otherwise highlighted-label-text-style))) (draw-it))) (with-drawing-options (stream :ink (when (or handling-active highlight) +flipping-ink+) :text-style (case highlight (:highlight highlighted-label-text-style) (otherwise label-text-style))) (draw-it)))))) (defmethod draw-label* (text x y stream &key (label-text-style +label-text-style+) (label-text-style-line-height +label-text-style-line-height+)) (with-drawing-options (stream :text-style label-text-style) (let ((line y)) (dolist (string text) (draw-text* stream string x line) (incf line label-text-style-line-height))))) (defun draw-arrow-head (stream p dir-fac rot &rest args) (apply #'draw-arrow-head* stream (x p) (y p) dir-fac rot args)) (defun draw-arrow-head* (stream x y dir-fac rot &key (offset 0) (filled t) (arrow-head-size +arrow-head-size+)) (let ((trans (make-rotation-transformation* rot x y))) (with-drawing-options (stream :transformation trans) (let* ((x (+ x offset)) (x1 x) (y1 (+ y arrow-head-size)) (x2 (+ x (* dir-fac arrow-head-size))) (y2 y) (x3 x) (y3 (- y arrow-head-size))) (draw-polygon* stream (list x1 y1 x2 y2 x3 y3) :filled filled))))) (defmethod draw-gui-line ((obj gui-line) stream r &rest args &key (draw-component-objects t) &allow-other-keys) (unless (already-drawn obj) (draw-line* stream (x (p1 obj)) (y (p1 obj)) (x (p2 obj)) (y (p2 obj)) :line-dashes (when (1d-intersects-other-lines-p obj) +overlapping-line-dashes+) :line-thickness r)) (when draw-component-objects (apply #'draw (p1 obj) stream :top-level nil args) (apply #'draw (p2 obj) stream :top-level nil args))) (defmethod draw-gui-rubberband ((obj gui-line) stream r &rest args &key (draw-component-objects t) &allow-other-keys) (unless (already-drawn obj) (let* ((l (/ (length-of-line obj) 9)) (intersects (1d-intersects-other-lines-p obj) ) (alpha (global-orientation obj)) (alpha-orth1 (+ alpha +pi/2+)) (alpha-orth2 (- alpha +pi/2+)) (xs (x (p1 obj))) (ys (y (p1 obj))) (xe (x (p2 obj))) (ye (y (p2 obj))) (xi (* l (cos alpha))) (yi (* l (sin alpha))) (xii-orth1 (* +rubberband-waveness+ (cos alpha-orth1))) (xii-orth2 (* +rubberband-waveness+ (cos alpha-orth2))) (yii-orth1 (* +rubberband-waveness+ (sin alpha-orth1))) (yii-orth2 (* +rubberband-waveness+ (sin alpha-orth2))) (lx xs) (ly ys) (cx xs) (cy ys)) (dotimes (n 8) (incf cx xi) (incf cy yi) (let ((x (+ cx (if (evenp n) xii-orth1 xii-orth2))) (y (+ cy (if (evenp n) yii-orth1 yii-orth2)))) (draw-line* stream lx ly x y :line-thickness r :line-dashes (when intersects +overlapping-line-dashes+)) (setf lx x ly y))) (draw-line* stream lx ly xe ye :line-thickness r :line-dashes (when intersects +overlapping-line-dashes+)) (draw-line* stream xs ys xe ye :line-thickness r :line-dashes (when intersects +overlapping-line-dashes+)))) (when draw-component-objects (apply #'draw (p1 obj) stream :top-level nil args) (apply #'draw (p2 obj) stream :top-level nil args))) (defmethod draw-gravity-field ((obj geom-point) stream r) (draw-circle* stream (x obj) (y obj) r :ink +transparent-ink+ :filled t)) (defmethod draw-gravity-field ((obj geom-line) stream r) (draw-gravity-field-for-line stream (x (p1 obj)) (y (p1 obj)) (x (p2 obj)) (y (p2 obj)) r)) (defun draw-gravity-field-for-line (stream x1 y1 x2 y2 r) (draw-line* stream x1 y1 x2 y2 :line-thickness r :ink +transparent-ink+)) (defun draw-gravity-field-for-circle (stream x y radius r) (draw-circle* stream x y radius :line-thickness r :filled nil :ink +transparent-ink+)) (defun draw-epsilon-body (obj r stream &rest args) (multiple-value-bind (p1fx p1fy p1tx p1ty p2fx p2fy p2tx p2ty) (get-epsilon-enclosure-relevant-points* obj r) (apply #'draw-polygon* stream (list p1fx p1fy p2fx p2fy p2tx p2ty p1tx p1ty p1fx p1fy) args))) (defun draw-epsilon-circle (obj r stream &rest args) (apply #'draw-circle* stream (x obj) (y obj) r args)) (defun draw-epsilon-segment (obj r stream &rest args) (apply #'draw-epsilon-circle (p1 obj) r stream args) (apply #'draw-epsilon-circle (p2 obj) r stream args) (apply #'draw-epsilon-body obj r stream args)) (defgeneric highlight (obj stream state) (:method-combination progn)) (defmethod highlight progn ((obj gui-chain-or-polygon) stream state) (dolist (segment (segments obj)) (draw segment stream :draw-component-objects nil :highlight state :output-recording nil)) (dolist (point (point-list obj)) (draw point stream :highlight state :output-recording nil)) (draw (status-label obj) stream :highlight state :output-recording nil) (when (at-most-constraint obj) (draw (at-most-label obj) stream :highlight state :output-recording nil))) (defmethod highlight progn ((obj gui-object) stream state) (unless (typep obj 'gui-chain-or-polygon) (draw obj stream :highlight state :output-recording nil))) (defmethod object-selected-position-test ((obj gui-enclosure) record x y) (declare (ignore record)) (asg-inside-p* x y obj)) (define-presentation-method highlight-presentation ((obj gui-chain-or-polygon) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-label) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-point) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-line) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-transparency) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-orientation-arrow) record stream state) (highlight (presentation-object record) stream state)) (define-presentation-method highlight-presentation ((obj gui-relative-orientation-circle) record stream state) (highlight (presentation-object record) stream state)) (defmethod get-label-origin-for ((obj gui-point)) (values (x obj) (y obj))) (defmethod get-label-origin-for ((obj gui-transparency)) (values (x (pcenter obj)) (y (pcenter obj)))) (defmethod get-label-origin-for ((obj gui-line)) (values (x (pcenter obj)) (y (pcenter obj)))) (defmethod get-label-origin-for ((obj gui-chain-or-polygon)) (values (x (centroid obj)) (y (centroid obj)))) (defmethod get-label-origin-for ((obj gui-drawn-enclosure)) (values (x (centroid obj)) (y (centroid obj)))) (defmethod get-label-origin-for ((obj gui-derived-enclosure)) (get-label-origin-for (arg-object obj))) (defmethod draw ((obj gui-status-label) stream &key handling-active highlight label-x label-y gravity-field draw-chain-or-polygon-icon-p) (setf (text obj) (list (if (and (typep (object obj) 'possible-operator-result-mixin) (res-of-operators (object obj))) (concatenate 'string (get-status-string (status (object obj))) " (D)") (get-status-string (status (object obj)))))) (draw-label obj stream :handling-active handling-active :highlight highlight :label-x label-x :label-y label-y) (labels ((draw-it () (let ((object (object obj))) (multiple-value-bind (x y) (get-label-origin-for object) (when (typep object 'gui-chain-or-polygon) (with-translation (stream (or label-x (+ (x-off obj) x 20)) (or label-y (+ (y-off obj) y 20))) (with-scaling (stream 0.1) (with-translation (stream (- x) (- y)) (dolist (segment (segments object)) (draw-line* stream (x (p1 segment)) (y (p1 segment)) (x (p2 segment)) (y (p2 segment)) :line-thickness (when highlight +chain-and-polygon-icon-highlight+)) (when gravity-field (draw-gravity-field-for-line stream (x (p1 segment)) (y (p1 segment)) (x (p2 segment)) (y (p2 segment)) +chain-and-polygon-icon-gravity+))))))))))) (when draw-chain-or-polygon-icon-p (draw-it)))) (defmethod draw ((obj gui-semantics-label) stream &key highlight handling-active label-x label-y) (setf (text obj) (mapcar #'(lambda (s) (first (lookup-os s))) (semantics (object obj)))) (draw-label obj stream :highlight highlight :handling-active handling-active :label-x label-x :label-y label-y)) (defmethod draw ((obj gui-at-most-label) stream &key highlight handling-active label-x label-y) (setf (text obj) (list (format nil "~A" (at-most-constraint (object obj))))) (draw-label obj stream :highlight highlight :handling-active handling-active :label-x label-x :label-y label-y :label-text-style +at-most-label-text-style+ :highlighted-label-text-style +at-most-highlighted-label-text-style+)) (defmethod draw ((obj gui-orientation-arrow) stream &key highlight gravity-field) (multiple-value-bind (x y) (get-origin-for obj) (let* ((alpha (+ (alpha-off obj) (if (typep (object obj) 'geom-line) (global-orientation (object obj)) 0))) (r (r obj)) (r-offset 3)) (labels ((draw-scale-mark (mark) (let ((x (+ x (* (cos (+ alpha mark)) r))) (y (+ y (* (sin (+ alpha mark)) r)))) (draw-circle* stream x y (if highlight +bullet-highlight+ +bullet-size+))))) (let ((x1 (+ x (* (cos alpha) (- r 5)))) (y1 (+ y (* (sin alpha) (- r 5))))) (draw-line* stream x y x1 y1 :line-thickness (when highlight +oc-highlight+)) (draw-arrow-head* stream x1 y1 1.0 alpha :offset (- +arrow-head-size+) :arrow-head-size (if highlight +arrow-head-highlight+ +arrow-head-size+)) (when gravity-field (draw-gravity-field-for-line stream x y x1 y1 +oc-gravity+)) (let ((cs (orientation-constraint (object obj)))) (unless (and (null (rest cs)) (numberp (first cs)) (zerop (first cs))) (draw-circle* stream x y r :filled nil :line-thickness (when highlight +oc-highlight+)) (when gravity-field (draw-gravity-field-for-circle stream x y r +oc-gravity+)) (dolist (entry cs) (if (listp entry) (progn (draw-circle* stream x y (+ r r-offset) :end-angle (- +2pi+ (+ alpha (first entry))) :start-angle (- +2pi+ (+ alpha (second entry))) :line-thickness (when highlight +oc-highlight+) :filled nil) (draw-circle* stream x y (+ r r-offset) :end-angle (- +2pi+ (+ alpha pi (first entry))) :start-angle (- +2pi+ (+ alpha pi (second entry))) :line-thickness (when highlight +oc-highlight+) :filled nil)) (progn (draw-scale-mark (+ pi entry)) (draw-scale-mark entry))))))))))) (defmethod draw ((obj gui-relative-orientation-circle) stream &key highlight gravity-field ) (let* ((obj1 (object1 obj)) (obj2 (object2 obj)) (r (r obj)) (r-offset 3) (w (/ (allowed-derivation obj) 2)) (alpha1 (global-orientation obj1)) (alpha2 (global-orientation obj2))) (multiple-value-bind (x y) (calculate-intersection-point obj1 obj2) (when (and x y) (draw-circle* stream x y r :filled nil :line-thickness (when highlight +oc-highlight+)) (when gravity-field (draw-gravity-field-for-circle stream x y r +oc-gravity+)) (labels ((draw-it (alpha) (if (=-eps w 0) (draw-circle* stream (+ x (* (cos alpha) r)) (+ y (* (sin alpha) r)) (if highlight +bullet-highlight+ +bullet-size+)) (draw-circle* stream x y (+ r r-offset) :end-angle (- +2pi+ (- alpha w)) :start-angle (- +2pi+ (+ alpha w)) :line-thickness (when highlight +oc-highlight+) :filled nil)))) (with-drawing-options (stream :line-thickness 2) (draw-it alpha1) (incf r-offset 2) (draw-it (+ pi alpha1))) (incf r-offset 2) (draw-it alpha2) (incf r-offset 2) (draw-it (+ pi alpha2))))))) (defmethod draw :after ((obj gui-query-object) stream &rest args &key (draw-label t) (output-recording t)) (labels ((draw-it () (apply #'draw (status-label obj) stream :top-level nil args) (when (semantics obj) (apply #'draw (semantics-label obj) stream :border-for nil :ink nil :top-level nil args)))) (when (and draw-label (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) (defmethod draw :after ((obj orientation-constraint-mixin) stream &rest args &key (output-recording t)) (labels ((draw-it () (apply #'draw (orientation-arrow obj) stream :border-for nil :ink nil :top-level nil args))) (when (and (orientation-constraint obj) (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) (defmethod draw :after ((obj at-most-constraint-mixin) stream &rest args &key (draw-label t) (output-recording t)) (labels ((draw-it () (apply #'draw (at-most-label obj) stream :border-for nil :ink nil :top-level nil args))) (when (and draw-label (at-most-constraint obj) (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) (defmethod draw :after ((obj gui-atomic-rubberband) stream &rest args &key (output-recording t) (draw-relative-orientation-circles t) highlight) (labels ((draw-it () (dolist (circle (relative-orientation-circles obj)) (when (eq obj (object1 circle)) (apply #'draw circle stream :border-for nil :ink nil :top-level nil args))))) (when (and (relative-orientation-circles obj) draw-relative-orientation-circles (not highlight) (not (already-drawn obj))) (if output-recording (with-output-as-presentation (stream obj (type-of obj)) (draw-it)) (draw-it))))) (defmethod draw ((obj gui-transparency) stream &key highlight) (labels ((draw-it (r) (draw-rectangle* stream (x (pmin obj)) (y (pmin obj)) (x (pmax obj)) (y (pmax obj)) :line-thickness r :filled nil) (let* ((xmin (x (pmin obj))) (ymin (y (pmin obj))) (xmax (x (pmax obj))) (ymax (y (pmax obj))) (xmiddle (/ (+ xmin xmax) 2)) (ymiddle (/ (+ ymin ymax) 2)) (sxt (sx-type obj)) (syt (sy-type obj))) (with-drawing-options (stream :line-dashes +transparency-properties-dashes+) (when (height obj) (if (or (not syt) (and (symin obj) (symax obj) (= (symin obj) (symax obj)))) (draw-text* stream (format nil "~A m." (round (height obj))) (+ xmin 4) (- ymiddle 4)) (draw-text* stream (format nil "~A ... ~A" (if (symin obj) (format nil "~A m." (round (* (symin obj) (height obj)))) "0") (if (symax obj) (format nil "~A m." (round (* (symax obj) (height obj)))) "infinity")) (+ xmin 4) (- ymiddle 4)))) (when (width obj) (if (or (not sxt) (and (sxmin obj) (sxmax obj) (= (sxmin obj) (sxmax obj)))) (draw-text* stream (format nil "~A m." (round (width obj))) (+ xmiddle 4) (- ymax 4)) (draw-text* stream (format nil "~A ... ~A" (if (sxmin obj) (format nil "~A m." (round (* (sxmin obj) (width obj)))) "0") (if (sxmax obj) (format nil "~A m." (round (* (sxmax obj) (width obj)))) "infinity")) (+ xmiddle 4) (- ymax 4)))) (when sxt (when (=> (sxmax obj) (not (= 1.0 (sxmax obj)))) (draw-arrow* stream xmin ymiddle (- xmin +transparency-arrow-length+) ymiddle) (draw-arrow* stream xmax ymiddle (+ xmax +transparency-arrow-length+) ymiddle)) (when (=> (sxmin obj) (not (= 1.0 (sxmin obj)))) (draw-arrow* stream xmin ymiddle (+ xmin +transparency-arrow-length+) ymiddle) (draw-arrow* stream xmax ymiddle (- xmax +transparency-arrow-length+) ymiddle))) (when syt (when (=> (symax obj) (not (= 1.0 (symax obj)))) (draw-arrow* stream xmiddle ymin xmiddle (- ymin +transparency-arrow-length+)) (draw-arrow* stream xmiddle ymax xmiddle (+ ymax +transparency-arrow-length+))) (when (=> (symin obj) (not (= 1.0 (symin obj)))) (draw-arrow* stream xmiddle ymin xmiddle (+ ymin +transparency-arrow-length+)) (draw-arrow* stream xmiddle ymax xmiddle (- ymax +transparency-arrow-length+)))) (when (sxsy-constraint obj) (if (origin obj) (progn (draw-line* stream (x (origin obj)) (y (origin obj)) xmin ymin) (draw-line* stream (x (origin obj)) (y (origin obj)) xmin ymax) (draw-line* stream (x (origin obj)) (y (origin obj)) xmax ymin) (draw-line* stream (x (origin obj)) (y (origin obj)) xmax ymax)) (progn (draw-line* stream xmin ymin (+ xmin +two-guiding-lines-length+) (+ ymin +two-guiding-lines-length+)) (draw-line* stream xmin ymax (+ xmin +two-guiding-lines-length+) (- ymax +two-guiding-lines-length+)) (draw-line* stream xmax ymin (- xmax +two-guiding-lines-length+) (+ ymin +two-guiding-lines-length+)) (draw-line* stream xmax ymax (- xmax +two-guiding-lines-length+) (- ymax +two-guiding-lines-length+))))))))) (if highlight (draw-it +transparency-highlight+) (draw-it 0)))) (defmethod draw ((obj gui-marble) stream &key top-level gravity-field subobjects-draw-only-gravity-field highlight) (labels ((draw-it (r) (when (or (not (already-drawn obj)) top-level (and (not top-level) (not subobjects-draw-only-gravity-field))) (draw-circle* stream (x obj) (y obj) r :filled nil)))) (if highlight (draw-it +marble-highlight+) (progn (when gravity-field (draw-gravity-field obj stream +marble-gravity+)) (draw-it +marble-size+))))) (defmethod draw ((obj gui-nail) stream &key top-level gravity-field subobjects-draw-only-gravity-field highlight) (labels ((draw-it (r) (when (or (not (already-drawn obj)) top-level (and (not top-level) (not subobjects-draw-only-gravity-field))) (draw-marker* stream (x obj) (y obj) r)))) (if highlight (draw-it +nail-highlight+) (progn (when gravity-field (draw-gravity-field obj stream +nail-gravity+)) (draw-it +nail-size+))))) (defmethod draw ((obj gui-origin) stream &key top-level gravity-field subobjects-draw-only-gravity-field highlight) (labels ((draw-it (r) (when (or (not (already-drawn obj)) top-level (and (not top-level) (not subobjects-draw-only-gravity-field))) (draw-rectangle* stream (- (x obj) r) (- (y obj) r) (+ (x obj) r) (+ (y obj) r) :filled t)))) (if highlight (draw-it +nail-highlight+) (progn (when gravity-field (draw-gravity-field obj stream +nail-gravity+)) (draw-it +nail-size+))))) (defmethod draw ((obj gui-beam) stream &rest args &key highlight gravity-field) (if highlight (apply #'draw-gui-line obj stream (+ +beam-thickness+ +line-highlight+) args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +beam-thickness+ args)))) (defmethod draw ((obj gui-atomic-rubberband) stream &rest args &key highlight gravity-field) (unless (already-drawn obj) (let ((alpha (geometry::global-orientation obj))) (draw-arrow-head stream (p1 obj) -1.0 alpha :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) -1.0 (+ pi alpha) :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p1 obj) 1 alpha :offset +ar-2nd-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) 1 (+ pi alpha) :offset +ar-2nd-arrow-offset+ :filled nil))) (if highlight (apply #'draw-gui-line obj stream +line-highlight+ args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +rubberband-thickness+ args)))) (defmethod draw ((obj gui-atomic->=-rubberband) stream &rest args &key highlight gravity-field) (unless (already-drawn obj) (let ((alpha (geometry::global-orientation obj))) (draw-arrow-head stream (p1 obj) -1 alpha :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) -1 (+ pi alpha) :offset +ar-1st-arrow-offset+ :filled nil))) (if highlight (apply #'draw-gui-line obj stream +line-highlight+ args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +rubberband-thickness+ args)))) (defmethod draw ((obj gui-atomic-<=-rubberband) stream &rest args &key highlight gravity-field) (unless (already-drawn obj) (let ((alpha (geometry::global-orientation obj))) (draw-arrow-head stream (p1 obj) 1 alpha :offset +ar-1st-arrow-offset+ :filled nil) (draw-arrow-head stream (p2 obj) 1 (+ pi alpha) :offset +ar-1st-arrow-offset+ :filled nil))) (if highlight (apply #'draw-gui-line obj stream +line-highlight+ args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-line obj stream +rubberband-thickness+ args)))) (defmethod draw ((obj gui-rubberband) stream &rest args &key highlight gravity-field) (if highlight (apply #'draw-gui-line obj stream (+ +rubberband-thickness+ +line-highlight+) args) (progn (when gravity-field (draw-gravity-field obj stream +line-gravity+)) (apply #'draw-gui-rubberband obj stream +rubberband-thickness+ args)))) (defmethod draw ((obj gui-chain-or-polygon) stream &rest args &key gravity-field draw-component-objects) (unless (already-drawn obj) (when gravity-field (dolist (segment (segments obj)) (draw-gravity-field segment stream +chain-and-polygon-gravity+))) (dolist (segment (segments obj)) (if draw-component-objects (apply #'draw segment stream :single-box nil :top-level nil args) (draw-line* stream (x (p1 segment)) (y (p1 segment)) (x (p2 segment)) (y (p2 segment))))))) (defmethod draw ((obj gui-enclosure) stream &key) (draw-polygon* stream (drawable-pointlist obj) :closed t)) (defmethod draw ((obj gui-epsilon-enclosure) stream &key) (let ((r (radius obj)) (obj (arg-object obj))) (typecase obj (point (draw-epsilon-circle obj r stream )) (line (draw-epsilon-segment obj r stream)) (chain-or-polygon (dolist (segment (segments obj)) (draw-epsilon-body segment r stream)) (dolist (point (point-list obj)) (draw-epsilon-circle point r stream))))))
38301d926cac337fef752154b16758ee53be7f1145f13530f444d4b1b25c343e
headwinds/reagent-reframe-material-ui
pprint.cljs
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns cljs.pprint (:refer-clojure :exclude [deftype print println pr prn float?]) (:require-macros [cljs.pprint :as m :refer [with-pretty-writer getf setf deftype pprint-logical-block print-length-loop defdirectives formatter-out]]) (:require [cljs.core :refer [IWriter IDeref]] [clojure.string :as string] [goog.string :as gstring]) (:import [goog.string StringBuffer])) ;;====================================================================== override print fns to use * out * ;;====================================================================== (defn- print [& more] (-write *out* (apply print-str more))) (defn- println [& more] (apply print more) (-write *out* \newline)) (defn- print-char [c] (-write *out* (condp = c \backspace "\\backspace" \tab "\\tab" \newline "\\newline" \formfeed "\\formfeed" \return "\\return" \" "\\\"" \\ "\\\\" (str "\\" c)))) (defn- ^:dynamic pr [& more] (-write *out* (apply pr-str more))) (defn- prn [& more] (apply pr more) (-write *out* \newline)) ;;====================================================================== ;; cljs specific utils ;;====================================================================== (defn ^boolean float? "Returns true if n is an float." [n] (and (number? n) (not ^boolean (js/isNaN n)) (not (identical? n js/Infinity)) (not (== (js/parseFloat n) (js/parseInt n 10))))) (defn char-code "Convert char to int" [c] (cond (number? c) c (and (string? c) (== (.-length c) 1)) (.charCodeAt c 0) :else (throw (js/Error. "Argument to char must be a character or number")))) ;;====================================================================== Utilities ;;====================================================================== (defn- map-passing-context [func initial-context lis] (loop [context initial-context lis lis acc []] (if (empty? lis) [acc context] (let [this (first lis) remainder (next lis) [result new-context] (apply func [this context])] (recur new-context remainder (conj acc result)))))) (defn- consume [func initial-context] (loop [context initial-context acc []] (let [[result new-context] (apply func [context])] (if (not result) [acc new-context] (recur new-context (conj acc result)))))) (defn- consume-while [func initial-context] (loop [context initial-context acc []] (let [[result continue new-context] (apply func [context])] (if (not continue) [acc context] (recur new-context (conj acc result)))))) (defn- unzip-map [m] "Take a map that has pairs in the value slots and produce a pair of maps, the first having all the first elements of the pairs and the second all the second elements of the pairs" [(into {} (for [[k [v1 v2]] m] [k v1])) (into {} (for [[k [v1 v2]] m] [k v2]))]) (defn- tuple-map [m v1] "For all the values, v, in the map, replace them with [v v1]" (into {} (for [[k v] m] [k [v v1]]))) (defn- rtrim [s c] "Trim all instances of c from the end of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s (dec (count s))) c)) (loop [n (dec len)] (cond (neg? n) "" (not (= (nth s n) c)) (subs s 0 (inc n)) true (recur (dec n)))) s))) (defn- ltrim [s c] "Trim all instances of c from the beginning of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s 0) c)) (loop [n 0] (if (or (= n len) (not (= (nth s n) c))) (subs s n) (recur (inc n)))) s))) (defn- prefix-count [aseq val] "Return the number of times that val occurs at the start of sequence aseq, if val is a seq itself, count the number of times any element of val occurs at the beginning of aseq" (let [test (if (coll? val) (set val) #{val})] (loop [pos 0] (if (or (= pos (count aseq)) (not (test (nth aseq pos)))) pos (recur (inc pos)))))) ;; Flush the pretty-print buffer without flushing the underlying stream (defprotocol IPrettyFlush (-ppflush [pp])) ;;====================================================================== ;; column_writer.clj ;;====================================================================== (def ^:dynamic ^{:private true} *default-page-width* 72) (defn- get-field [this sym] (sym @@this)) (defn- set-field [this sym new-val] (swap! @this assoc sym new-val)) (defn- get-column [this] (get-field this :cur)) (defn- get-line [this] (get-field this :line)) (defn- get-max-column [this] (get-field this :max)) (defn- set-max-column [this new-max] (set-field this :max new-max) nil) (defn- get-writer [this] (get-field this :base)) ;; Why is the c argument an integer? (defn- c-write-char [this c] (if (= c \newline) (do (set-field this :cur 0) (set-field this :line (inc (get-field this :line)))) (set-field this :cur (inc (get-field this :cur)))) (-write (get-field this :base) c)) (defn- column-writer ([writer] (column-writer writer *default-page-width*)) ([writer max-columns] (let [fields (atom {:max max-columns, :cur 0, :line 0 :base writer})] (reify IDeref (-deref [_] fields) IWriter (-flush [_] (-flush writer)) (-write -write is n't multi - arity , so need different way to do this #_([this ^chars cbuf ^Number off ^Number len] (let [writer (get-field this :base)] (-write writer cbuf off len))) [this x] (condp = (type x) js/String (let [s x nl (.lastIndexOf s \newline)] (if (neg? nl) (set-field this :cur (+ (get-field this :cur) (count s))) (do (set-field this :cur (- (count s) nl 1)) (set-field this :line (+ (get-field this :line) (count (filter #(= % \newline) s)))))) (-write (get-field this :base) s)) js/Number (c-write-char this x))))))) ;;====================================================================== pretty_writer.clj ;;====================================================================== ;;====================================================================== ;; Forward declarations ;;====================================================================== (declare ^{:arglists '([this])} get-miser-width) ;;====================================================================== ;; The data structures used by pretty-writer ;;====================================================================== (defrecord ^{:private true} logical-block [parent section start-col indent done-nl intra-block-nl prefix per-line-prefix suffix logical-block-callback]) (defn- ancestor? [parent child] (loop [child (:parent child)] (cond (nil? child) false (identical? parent child) true :else (recur (:parent child))))) (defn- buffer-length [l] (let [l (seq l)] (if l (- (:end-pos (last l)) (:start-pos (first l))) 0))) ;; A blob of characters (aka a string) (deftype buffer-blob :data :trailing-white-space :start-pos :end-pos) ;; A newline (deftype nl-t :type :logical-block :start-pos :end-pos) (deftype start-block-t :logical-block :start-pos :end-pos) (deftype end-block-t :logical-block :start-pos :end-pos) (deftype indent-t :logical-block :relative-to :offset :start-pos :end-pos) (def ^:private pp-newline (fn [] "\n")) (declare emit-nl) (defmulti ^{:private true} write-token #(:type-tag %2)) (defmethod write-token :start-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :start)) (let [lb (:logical-block token)] (when-let [prefix (:prefix lb)] (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col)))) (defmethod write-token :end-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :end)) (when-let [suffix (:suffix (:logical-block token))] (-write (getf :base) suffix))) (defmethod write-token :indent-t [this token] (let [lb (:logical-block token)] (reset! (:indent lb) (+ (:offset token) (condp = (:relative-to token) :block @(:start-col lb) :current (get-column (getf :base))))))) (defmethod write-token :buffer-blob [this token] (-write (getf :base) (:data token))) (defmethod write-token :nl-t [this token] (if (or (= (:type token) :mandatory) (and (not (= (:type token) :fill)) @(:done-nl (:logical-block token)))) (emit-nl this token) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (setf :trailing-white-space nil)) (defn- write-tokens [this tokens force-trailing-whitespace] (doseq [token tokens] (if-not (= (:type-tag token) :nl-t) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (write-token this token) (setf :trailing-white-space (:trailing-white-space token)) (let [tws (getf :trailing-white-space)] (when (and force-trailing-whitespace tws) (-write (getf :base) tws) (setf :trailing-white-space nil))))) ;;====================================================================== ;; emit-nl? method defs for each type of new line. This makes ;; the decision about whether to print this type of new line. ;;====================================================================== (defn- tokens-fit? [this tokens] (let [maxcol (get-max-column (getf :base))] (or (nil? maxcol) (< (+ (get-column (getf :base)) (buffer-length tokens)) maxcol)))) (defn- linear-nl? [this lb section] (or @(:done-nl lb) (not (tokens-fit? this section)))) (defn- miser-nl? [this lb section] (let [miser-width (get-miser-width this) maxcol (get-max-column (getf :base))] (and miser-width maxcol (>= @(:start-col lb) (- maxcol miser-width)) (linear-nl? this lb section)))) (defmulti ^{:private true} emit-nl? (fn [t _ _ _] (:type t))) (defmethod emit-nl? :linear [newl this section _] (let [lb (:logical-block newl)] (linear-nl? this lb section))) (defmethod emit-nl? :miser [newl this section _] (let [lb (:logical-block newl)] (miser-nl? this lb section))) (defmethod emit-nl? :fill [newl this section subsection] (let [lb (:logical-block newl)] (or @(:intra-block-nl lb) (not (tokens-fit? this subsection)) (miser-nl? this lb section)))) (defmethod emit-nl? :mandatory [_ _ _ _] true) ;;====================================================================== ;; Various support functions ;;====================================================================== (defn- get-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(not (and (nl-t? %) (ancestor? (:logical-block %) lb))) (next buffer)))] [section (seq (drop (inc (count section)) buffer))])) (defn- get-sub-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(let [nl-lb (:logical-block %)] (not (and (nl-t? %) (or (= nl-lb lb) (ancestor? nl-lb lb))))) (next buffer)))] section)) (defn- update-nl-state [lb] (reset! (:intra-block-nl lb) true) (reset! (:done-nl lb) true) (loop [lb (:parent lb)] (if lb (do (reset! (:done-nl lb) true) (reset! (:intra-block-nl lb) true) (recur (:parent lb)))))) (defn- emit-nl [this nl] (-write (getf :base) (pp-newline)) (setf :trailing-white-space nil) (let [lb (:logical-block nl) prefix (:per-line-prefix lb)] (if prefix (-write (getf :base) prefix)) (let [istr (apply str (repeat (- @(:indent lb) (count prefix)) \space))] (-write (getf :base) istr)) (update-nl-state lb))) (defn- split-at-newline [tokens] (let [pre (seq (take-while #(not (nl-t? %)) tokens))] [pre (seq (drop (count pre) tokens))])) ;; write-token-string is called when the set of tokens in the buffer ;; is long than the available space on the line (defn- write-token-string [this tokens] (let [[a b] (split-at-newline tokens)] (if a (write-tokens this a false)) (if b (let [[section remainder] (get-section b) newl (first b)] (let [do-nl (emit-nl? newl this section (get-sub-section b)) result (if do-nl (do (emit-nl this newl) (next b)) b) long-section (not (tokens-fit? this result)) result (if long-section (let [rem2 (write-token-string this section)] (if (= rem2 section) If that did n't produce any output , it has no nls ; so we'll force it (write-tokens this section false) remainder) (into [] (concat rem2 remainder)))) result)] result))))) (defn- write-line [this] (loop [buffer (getf :buffer)] (setf :buffer (into [] buffer)) (if (not (tokens-fit? this buffer)) (let [new-buffer (write-token-string this buffer)] (if-not (identical? buffer new-buffer) (recur new-buffer)))))) ;; Add a buffer token to the buffer and see if it's time to start ;; writing (defn- add-to-buffer [this token] (setf :buffer (conj (getf :buffer) token)) (if (not (tokens-fit? this (getf :buffer))) (write-line this))) ;; Write all the tokens that have been buffered (defn- write-buffered-output [this] (write-line this) (if-let [buf (getf :buffer)] (do (write-tokens this buf true) (setf :buffer [])))) (defn- write-white-space [this] (when-let [tws (getf :trailing-white-space)] (-write (getf :base) tws) (setf :trailing-white-space nil))) ;;; If there are newlines in the string, print the lines up until the last newline, ;;; making the appropriate adjustments. Return the remainder of the string (defn- write-initial-lines [^Writer this ^String s] (let [lines (string/split s "\n" -1)] (if (= (count lines) 1) s (let [^String prefix (:per-line-prefix (first (getf :logical-blocks))) ^String l (first lines)] (if (= :buffering (getf :mode)) (let [oldpos (getf :pos) newpos (+ oldpos (count l))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob l nil oldpos newpos)) (write-buffered-output this)) (do (write-white-space this) (-write (getf :base) l))) (-write (getf :base) \newline) (doseq [^String l (next (butlast lines))] (-write (getf :base) l) (-write (getf :base) (pp-newline)) (if prefix (-write (getf :base) prefix))) (setf :buffering :writing) (last lines))))) (defn- p-write-char [this c] (if (= (getf :mode) :writing) (do (write-white-space this) (-write (getf :base) c)) (if (= c \newline) (write-initial-lines this \newline) (let [oldpos (getf :pos) newpos (inc oldpos)] (setf :pos newpos) (add-to-buffer this (make-buffer-blob (char c) nil oldpos newpos)))))) ;;====================================================================== Initialize the pretty - writer instance ;;====================================================================== (defn- pretty-writer [writer max-columns miser-width] (let [lb (logical-block. nil nil (atom 0) (atom 0) (atom false) (atom false) nil nil nil nil) ; NOTE: may want to just `specify!` #js { ... fields ... } with the protocols fields (atom {:pretty-writer true :base (column-writer writer max-columns) :logical-blocks lb :sections nil :mode :writing :buffer [] :buffer-block lb :buffer-level 1 :miser-width miser-width :trailing-white-space nil :pos 0})] (reify IDeref (-deref [_] fields) IWriter (-write [this x] (condp = (type x) js/String (let [s0 (write-initial-lines this x) s (string/replace-first s0 #"\s+$" "") white-space (subs s0 (count s)) mode (getf :mode)] (if (= mode :writing) (do (write-white-space this) (-write (getf :base) s) (setf :trailing-white-space white-space)) (let [oldpos (getf :pos) newpos (+ oldpos (count s0))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob s white-space oldpos newpos))))) js/Number (p-write-char this x))) (-flush [this] (-ppflush this) (-flush (getf :base))) IPrettyFlush (-ppflush [this] (if (= (getf :mode) :buffering) (do (write-tokens this (getf :buffer) true) (setf :buffer [])) (write-white-space this))) ))) ;;====================================================================== ;; Methods for pretty-writer ;;====================================================================== (defn- start-block [this prefix per-line-prefix suffix] (let [lb (logical-block. (getf :logical-blocks) nil (atom 0) (atom 0) (atom false) (atom false) prefix per-line-prefix suffix nil)] (setf :logical-blocks lb) (if (= (getf :mode) :writing) (do (write-white-space this) (when-let [cb (getf :logical-block-callback)] (cb :start)) (if prefix (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col))) (let [oldpos (getf :pos) newpos (+ oldpos (if prefix (count prefix) 0))] (setf :pos newpos) (add-to-buffer this (make-start-block-t lb oldpos newpos)))))) (defn- end-block [this] (let [lb (getf :logical-blocks) suffix (:suffix lb)] (if (= (getf :mode) :writing) (do (write-white-space this) (if suffix (-write (getf :base) suffix)) (when-let [cb (getf :logical-block-callback)] (cb :end))) (let [oldpos (getf :pos) newpos (+ oldpos (if suffix (count suffix) 0))] (setf :pos newpos) (add-to-buffer this (make-end-block-t lb oldpos newpos)))) (setf :logical-blocks (:parent lb)))) (defn- nl [this type] (setf :mode :buffering) (let [pos (getf :pos)] (add-to-buffer this (make-nl-t type (getf :logical-blocks) pos pos)))) (defn- indent [this relative-to offset] (let [lb (getf :logical-blocks)] (if (= (getf :mode) :writing) (do (write-white-space this) (reset! (:indent lb) (+ offset (condp = relative-to :block @(:start-col lb) :current (get-column (getf :base)))))) (let [pos (getf :pos)] (add-to-buffer this (make-indent-t lb relative-to offset pos pos)))))) (defn- get-miser-width [this] (getf :miser-width)) ;;====================================================================== ;; pprint_base.clj ;;====================================================================== ;;====================================================================== ;; Variables that control the pretty printer ;;====================================================================== ;; *print-length*, *print-level*, *print-namespace-maps* and *print-dup* are defined in cljs.core (def ^:dynamic ^{:doc "Bind to true if you want write to use pretty printing"} *print-pretty* true) (defonce ^:dynamic ^{:doc "The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch to modify." :added "1.2"} *print-pprint-dispatch* nil) (def ^:dynamic ^{:doc "Pretty printing will try to avoid anything going beyond this column. Set it to nil to have pprint let the line be arbitrarily long. This will ignore all non-mandatory newlines.", :added "1.2"} *print-right-margin* 72) (def ^:dynamic ^{:doc "The column at which to enter miser style. Depending on the dispatch table, miser style add newlines in more places to try to keep lines short allowing for further levels of nesting.", :added "1.2"} *print-miser-width* 40) TODO implement output limiting (def ^:dynamic ^{:private true, :doc "Maximum number of lines to print in a pretty print instance (N.B. This is not yet used)"} *print-lines* nil) ;;; TODO: implement circle and shared (def ^:dynamic ^{:private true, :doc "Mark circular structures (N.B. This is not yet used)"} *print-circle* nil) ;;; TODO: should we just use *print-dup* here? (def ^:dynamic ^{:private true, :doc "Mark repeated structures rather than repeat them (N.B. This is not yet used)"} *print-shared* nil) (def ^:dynamic ^{:doc "Don't print namespaces with symbols. This is particularly useful when pretty printing the results of macro expansions" :added "1.2"} *print-suppress-namespaces* nil) ;;; TODO: support print-base and print-radix in cl-format ;;; TODO: support print-base and print-radix in rationals (def ^:dynamic ^{:doc "Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8, or 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the radix specifier is in the form #XXr where XX is the decimal value of *print-base* " :added "1.2"} *print-radix* nil) (def ^:dynamic ^{:doc "The base to use for printing integers and rationals." :added "1.2"} *print-base* 10) ;;====================================================================== ;; Internal variables that keep track of where we are in the ;; structure ;;====================================================================== (def ^:dynamic ^{:private true} *current-level* 0) (def ^:dynamic ^{:private true} *current-length* nil) ;;====================================================================== ;; Support for the write function ;;====================================================================== (declare ^{:arglists '([n])} format-simple-number) ;; This map causes var metadata to be included in the compiled output, even in advanced compilation . See CLJS-1853 - ;; (def ^{:private true} write-option-table ;; {;:array *print-array* ;; :base #'cljs.pprint/*print-base*, ;; ;;:case *print-case*, ;; :circle #'cljs.pprint/*print-circle*, ;; ;;:escape *print-escape*, ; ; : * print - gensym * , ;; :length #'cljs.core/*print-length*, ;; :level #'cljs.core/*print-level*, ;; :lines #'cljs.pprint/*print-lines*, ;; :miser-width #'cljs.pprint/*print-miser-width*, ;; :dispatch #'cljs.pprint/*print-pprint-dispatch*, ;; :pretty #'cljs.pprint/*print-pretty*, ;; :radix #'cljs.pprint/*print-radix*, ;; :readably #'cljs.core/*print-readably*, ;; :right-margin #'cljs.pprint/*print-right-margin*, ;; :suppress-namespaces #'cljs.pprint/*print-suppress-namespaces*}) (defn- table-ize [t m] (apply hash-map (mapcat #(when-let [v (get t (key %))] [v (val %)]) m))) (defn- pretty-writer? "Return true iff x is a PrettyWriter" [x] (and (satisfies? IDeref x) (:pretty-writer @@x))) (defn- make-pretty-writer "Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width" [base-writer right-margin miser-width] (pretty-writer base-writer right-margin miser-width)) (defn write-out "Write an object to *out* subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). *out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility of the caller. This method is primarily intended for use by pretty print dispatch functions that already know that the pretty printer will have set up their environment appropriately. Normal library clients should use the standard \"write\" interface. " [object] (let [length-reached (and *current-length* *print-length* (>= *current-length* *print-length*))] (if-not *print-pretty* (pr object) (if length-reached TODO could this ( incorrectly ) print ... on the next line ? (do (if *current-length* (set! *current-length* (inc *current-length*))) (*print-pprint-dispatch* object)))) length-reached)) (defn write "Write an object subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). Returns the string result if :stream is nil or nil otherwise. The following keyword arguments can be passed with values: Keyword Meaning Default value :stream Writer for output or nil true (indicates *out*) :base Base to use for writing rationals Current value of *print-base* :circle* If true, mark circular structures Current value of *print-circle* :length Maximum elements to show in sublists Current value of *print-length* :level Maximum depth Current value of *print-level* :lines* Maximum lines of output Current value of *print-lines* :miser-width Width to enter miser mode Current value of *print-miser-width* :dispatch The pretty print dispatch function Current value of *print-pprint-dispatch* :pretty If true, do pretty printing Current value of *print-pretty* :radix If true, prepend a radix specifier Current value of *print-radix* :readably* If true, print readably Current value of *print-readably* :right-margin The column for the right margin Current value of *print-right-margin* :suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces* * = not yet supported " [object & kw-args] (let [options (merge {:stream true} (apply hash-map kw-args))] TODO rewrite this as a macro (binding [cljs.pprint/*print-base* (:base options cljs.pprint/*print-base*) ;;:case *print-case*, cljs.pprint/*print-circle* (:circle options cljs.pprint/*print-circle*) ;;:escape *print-escape* : * print - gensym * cljs.core/*print-length* (:length options cljs.core/*print-length*) cljs.core/*print-level* (:level options cljs.core/*print-level*) cljs.pprint/*print-lines* (:lines options cljs.pprint/*print-lines*) cljs.pprint/*print-miser-width* (:miser-width options cljs.pprint/*print-miser-width*) cljs.pprint/*print-pprint-dispatch* (:dispatch options cljs.pprint/*print-pprint-dispatch*) cljs.pprint/*print-pretty* (:pretty options cljs.pprint/*print-pretty*) cljs.pprint/*print-radix* (:radix options cljs.pprint/*print-radix*) cljs.core/*print-readably* (:readably options cljs.core/*print-readably*) cljs.pprint/*print-right-margin* (:right-margin options cljs.pprint/*print-right-margin*) cljs.pprint/*print-suppress-namespaces* (:suppress-namespaces options cljs.pprint/*print-suppress-namespaces*)] TODO enable printing base #_[bindings (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})] (binding [] (let [sb (StringBuffer.) optval (if (contains? options :stream) (:stream options) true) base-writer (if (or (true? optval) (nil? optval)) (StringBufferWriter. sb) optval)] (if *print-pretty* (with-pretty-writer base-writer (write-out object)) (binding [*out* base-writer] (pr object))) (if (true? optval) (string-print (str sb))) (if (nil? optval) (str sb))))))) (defn pprint ([object] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] (pprint object *out*) (string-print (str sb))))) ([object writer] (with-pretty-writer writer (binding [*print-pretty* true] (write-out object)) (if (not (= 0 (get-column *out*))) (-write *out* \newline))))) (defn set-pprint-dispatch [function] (set! *print-pprint-dispatch* function) nil) ;;====================================================================== ;; Support for the functional interface to the pretty printer ;;====================================================================== (defn- check-enumerated-arg [arg choices] (if-not (choices arg) TODO clean up choices string (throw (js/Error. (str "Bad argument: " arg ". It must be one of " choices))))) (defn- level-exceeded [] (and *print-level* (>= *current-level* *print-level*))) (defn pprint-newline "Print a conditional newline to a pretty printing stream. kind specifies if the newline is :linear, :miser, :fill, or :mandatory. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [kind] (check-enumerated-arg kind #{:linear :miser :fill :mandatory}) (nl *out* kind)) (defn pprint-indent "Create an indent at this point in the pretty printing stream. This defines how following lines are indented. relative-to can be either :block or :current depending whether the indent should be computed relative to the start of the logical block or the current column position. n is an offset. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [relative-to n] (check-enumerated-arg relative-to #{:block :current}) (indent *out* relative-to n)) TODO a real implementation for pprint - tab (defn pprint-tab "Tab at this point in the pretty printing stream. kind specifies whether the tab is :line, :section, :line-relative, or :section-relative. Colnum and colinc specify the target column and the increment to move the target forward if the output is already past the original target. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer. THIS FUNCTION IS NOT YET IMPLEMENTED." {:added "1.2"} [kind colnum colinc] (check-enumerated-arg kind #{:line :section :line-relative :section-relative}) (throw (js/Error. "pprint-tab is not yet implemented"))) ;;====================================================================== ;; cl_format.clj ;;====================================================================== ;; Forward references (declare ^{:arglists '([format-str])} compile-format) (declare ^{:arglists '([stream format args] [format args])} execute-format) (declare ^{:arglists '([s])} init-navigator) ;; End forward references (defn cl-format "An implementation of a Common Lisp compatible format function. cl-format formats its arguments to an output stream or string based on the format control string given. It supports sophisticated formatting of structured data. Writer satisfies IWriter, true to output via *print-fn* or nil to output to a string, format-in is the format control string and the remaining arguments are the data to be formatted. The format control string is a string to be output with embedded 'format directives' describing how to format the various arguments passed in. If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format returns nil. For example: (let [results [46 38 22]] (cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\" (count results) results)) Prints via *print-fn*: There are 3 results: 46, 38, 22 Detailed documentation on format control strings is available in the \"Common Lisp the Language, 2nd edition\", Chapter 22 (available online at: -repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000) and in the Common Lisp HyperSpec at " {:see-also [["-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000" "Common Lisp the Language"] ["" "Common Lisp HyperSpec"]]} [writer format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format writer compiled-format navigator))) (def ^:dynamic ^{:private true} *format-str* nil) (defn- format-error [message offset] (let [full-message (str message \newline *format-str* \newline (apply str (repeat offset \space)) "^" \newline)] (throw (js/Error full-message)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Argument navigators manage the argument list ;; as the format statement moves through the list ;; (possibly going forwards and backwards as it does so) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord ^{:private true} arg-navigator [seq rest pos]) (defn- init-navigator "Create a new arg-navigator from the sequence with the position set to 0" {:skip-wiki true} [s] (let [s (seq s)] (arg-navigator. s s 0))) ;; TODO call format-error with offset (defn- next-arg [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] (throw (js/Error "Not enough arguments for format definition"))))) (defn- next-arg-or-nil [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] [nil navigator]))) ;; Get an argument off the arg list and compile it if it's not already compiled (defn- get-format-arg [navigator] (let [[raw-format navigator] (next-arg navigator) compiled-format (if (string? raw-format) (compile-format raw-format) raw-format)] [compiled-format navigator])) (declare relative-reposition) (defn- absolute-reposition [navigator position] (if (>= position (:pos navigator)) (relative-reposition navigator (- (:pos navigator) position)) (arg-navigator. (:seq navigator) (drop position (:seq navigator)) position))) (defn- relative-reposition [navigator position] (let [newpos (+ (:pos navigator) position)] (if (neg? position) (absolute-reposition navigator newpos) (arg-navigator. (:seq navigator) (drop position (:rest navigator)) newpos)))) (defrecord ^{:private true} compiled-directive [func def params offset]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; When looking at the parameter list, we may need to manipulate ;; the argument list as well (for 'V' and '#' parameter types). ;; We hide all of this behind a function, but clients need to ;; manage changing arg navigator ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: validate parameters when they come from arg list (defn- realize-parameter [[param [raw-val offset]] navigator] (let [[real-param new-navigator] (cond (contains? #{:at :colon} param) ;pass flags through unchanged - this really isn't necessary [raw-val navigator] (= raw-val :parameter-from-args) (next-arg navigator) (= raw-val :remaining-arg-count) [(count (:rest navigator)) navigator] true [raw-val navigator])] [[param [real-param offset]] new-navigator])) (defn- realize-parameter-list [parameter-map navigator] (let [[pairs new-navigator] (map-passing-context realize-parameter navigator parameter-map)] [(into {} pairs) new-navigator])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions that support individual directives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Common handling code for ~A and ~S ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([base val])} opt-base-str) (def ^{:private true} special-radix-markers {2 "#b" 8 "#o" 16 "#x"}) (defn- format-simple-number [n] (cond (integer? n) (if (= *print-base* 10) (str n (if *print-radix* ".")) (str (if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r"))) (opt-base-str *print-base* n))) ;;(ratio? n) ;;no ratio support :else nil)) (defn- format-ascii [print-func params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator) base-output (or (format-simple-number arg) (print-func arg)) base-width (.-length base-output) min-width (+ base-width (:minpad params)) width (if (>= min-width (:mincol params)) min-width (+ min-width (* (+ (quot (- (:mincol params) min-width 1) (:colinc params)) 1) (:colinc params)))) chars (apply str (repeat (- width base-width) (:padchar params)))] (if (:at params) (print (str chars base-output)) (print (str base-output chars))) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Support for the integer directives ~D , ~X , ~O , ~B and some of ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- integral? "returns true if a number is actually an integer (that is, has no fractional part)" [x] (cond (integer? x) true ;;(decimal? x) ;;no decimal support (float? x) (= x (Math/floor x)) ;;(ratio? x) ;;no ratio support :else false)) (defn- remainders "Return the list of remainders (essentially the 'digits') of val in the given base" [base val] (reverse (first (consume #(if (pos? %) [(rem % base) (quot % base)] [nil nil]) val)))) ;; TODO: xlated-val does not seem to be used here. NB (defn- base-str "Return val as a string in the given base" [base val] (if (zero? val) "0" (let [xlated-val (cond ;(float? val) (bigdec val) ;;No bigdec ( ratio ? ) nil ; ; No ratio :else val)] (apply str (map #(if (< % 10) (char (+ (char-code \0) %)) (char (+ (char-code \a) (- % 10)))) (remainders base val)))))) ;;Not sure if this is accurate or necessary (def ^{:private true} javascript-base-formats {8 "%o", 10 "%d", 16 "%x"}) (defn- opt-base-str "Return val as a string in the given base. No cljs format, so no improved performance." [base val] (base-str base val)) (defn- group-by* [unit lis] (reverse (first (consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis))))) (defn- format-integer [base params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator)] (if (integral? arg) (let [neg (neg? arg) pos-arg (if neg (- arg) arg) raw-str (opt-base-str base pos-arg) group-str (if (:colon params) (let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str)) commas (repeat (count groups) (:commachar params))] (apply str (next (interleave commas groups)))) raw-str) signed-str (cond neg (str "-" group-str) (:at params) (str "+" group-str) true group-str) padded-str (if (< (.-length signed-str) (:mincol params)) (str (apply str (repeat (- (:mincol params) (.-length signed-str)) (:padchar params))) signed-str) signed-str)] (print padded-str)) (format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0 :padchar (:padchar params) :at true} (init-navigator [arg]) nil)) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Support for english formats ( ~R and ~:R ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} english-cardinal-units ["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"]) (def ^{:private true} english-ordinal-units ["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth" "thirteenth" "fourteenth" "fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"]) (def ^{:private true} english-cardinal-tens ["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"]) (def ^{:private true} english-ordinal-tens ["" "" "twentieth" "thirtieth" "fortieth" "fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth"]) We use " short scale " for our units ( see ) ;; Number names from ;; We follow the rules for writing numbers from the Blue Book ;; () (def ^{:private true} english-scale-numbers ["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion" "sextillion" "septillion" "octillion" "nonillion" "decillion" "undecillion" "duodecillion" "tredecillion" "quattuordecillion" "quindecillion" "sexdecillion" "septendecillion" "octodecillion" "novemdecillion" "vigintillion"]) (defn- format-simple-cardinal "Convert a number less than 1000 to a cardinal english string" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-cardinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-cardinal-units unit-digit))))))))) (defn- add-english-scales "Take a sequence of parts, add scale numbers (e.g., million) and combine into a string offset is a factor of 10^3 to multiply by" [parts offset] (let [cnt (count parts)] (loop [acc [] pos (dec cnt) this (first parts) remainder (next parts)] (if (nil? remainder) (str (apply str (interpose ", " acc)) (if (and (not (empty? this)) (not (empty? acc))) ", ") this (if (and (not (empty? this)) (pos? (+ pos offset))) (str " " (nth english-scale-numbers (+ pos offset))))) (recur (if (empty? this) acc (conj acc (str this " " (nth english-scale-numbers (+ pos offset))))) (dec pos) (first remainder) (next remainder)))))) (defn- format-cardinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zero") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal parts) full-str (add-english-scales parts-strs 0)] (print (str (if (neg? arg) "minus ") full-str))) for numbers > 10 ^ 63 , we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})))) navigator)) (defn- format-simple-ordinal "Convert a number less than 1000 to a ordinal english string Note this should only be used for the last one in the sequence" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-ordinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (if (and (pos? ten-digit) (not (pos? unit-digit))) (nth english-ordinal-tens ten-digit) (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-ordinal-units unit-digit)))))) (if (pos? hundreds) "th"))))) (defn- format-ordinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zeroth") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal (drop-last parts)) head-str (add-english-scales parts-strs 1) tail-str (format-simple-ordinal (last parts))] (print (str (if (neg? arg) "minus ") (cond (and (not (empty? head-str)) (not (empty? tail-str))) (str head-str ", " tail-str) (not (empty? head-str)) (str head-str "th") :else tail-str)))) for numbers > 10 ^ 63 , we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0}) (let [low-two-digits (rem arg 100) not-teens (or (< 11 low-two-digits) (> 19 low-two-digits)) low-digit (rem low-two-digits 10)] (print (cond (and (== low-digit 1) not-teens) "st" (and (== low-digit 2) not-teens) "nd" (and (== low-digit 3) not-teens) "rd" :else "th"))))))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Support for roman numeral formats ( ~@R and ~@:R ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} old-roman-table [[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"] [ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"] [ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"] [ "M" "MM" "MMM"]]) (def ^{:private true} new-roman-table [[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"] [ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"] [ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"] [ "M" "MM" "MMM"]]) (defn- format-roman "Format a roman numeral using the specified look-up table" [table params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (and (number? arg) (> arg 0) (< arg 4000)) (let [digits (remainders 10 arg)] (loop [acc [] pos (dec (count digits)) digits digits] (if (empty? digits) (print (apply str acc)) (let [digit (first digits)] (recur (if (= 0 digit) acc (conj acc (nth (nth table pos) (dec digit)))) (dec pos) (next digits)))))) for anything < = 0 or > 3999 , we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})) navigator)) (defn- format-old-roman [params navigator offsets] (format-roman old-roman-table params navigator offsets)) (defn- format-new-roman [params navigator offsets] (format-roman new-roman-table params navigator offsets)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for character formats (~C) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} special-chars {8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"}) (defn- pretty-character [params navigator offsets] (let [[c navigator] (next-arg navigator) as-int (char-code c) base-char (bit-and as-int 127) meta (bit-and as-int 128) special (get special-chars base-char)] (if (> meta 0) (print "Meta-")) (print (cond special special (< base-char 32) (str "Control-" (char (+ base-char 64))) (= base-char 127) "Control-?" :else (char base-char))) navigator)) (defn- readable-character [params navigator offsets] (let [[c navigator] (next-arg navigator)] (condp = (:char-format params) \o (cl-format true "\\o~3, '0o" (char-code c)) \u (cl-format true "\\u~4, '0x" (char-code c)) nil (print-char c)) navigator)) (defn- plain-character [params navigator offsets] (let [[char navigator] (next-arg navigator)] (print char) navigator)) ;; Check to see if a result is an abort (~^) construct ;; TODO: move these funcs somewhere more appropriate (defn- abort? [context] (let [token (first context)] (or (= :up-arrow token) (= :colon-up-arrow token)))) ;; Handle the execution of "sub-clauses" in bracket constructions (defn- execute-sub-format [format args base-args] (second (map-passing-context (fn [element context] (if (abort? context) [nil context] ; just keep passing it along (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args base-args)] [nil (apply (:func element) [params args offsets])]))) args format))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for real number formats ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO - return exponent as int to eliminate double conversion (defn- float-parts-base "Produce string parts for the mantissa (normalize 1-9) and exponent" [f] (let [s (string/lower-case (str f)) exploc (.indexOf s \e) dotloc (.indexOf s \.)] (if (neg? exploc) (if (neg? dotloc) [s (str (dec (count s)))] [(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))]) (if (neg? dotloc) [(subs s 0 exploc) (subs s (inc exploc))] [(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))])))) (defn- float-parts "Take care of leading and trailing zeros in decomposed floats" [f] (let [[m e] (float-parts-base f) m1 (rtrim m \0) m2 (ltrim m1 \0) delta (- (count m1) (count m2)) e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)] (if (empty? m2) ["0" 0] [m2 (- (js/parseInt e 10) delta)]))) (defn- inc-s "Assumption: The input string consists of one or more decimal digits, and no other characters. Return a string containing one or more decimal digits containing a decimal number one larger than the input string. The output string will always be the same length as the input string, or one character longer." [s] (let [len-1 (dec (count s))] (loop [i (int len-1)] (cond (neg? i) (apply str "1" (repeat (inc len-1) "0")) (= \9 (.charAt s i)) (recur (dec i)) :else (apply str (subs s 0 i) (char (inc (char-code (.charAt s i)))) (repeat (- len-1 i) "0")))))) (defn- round-str [m e d w] (if (or d w) (let [len (count m) ;; Every formatted floating point number should include at ;; least one decimal digit and a decimal point. w (if w (max 2 w) ;;NB: if w doesn't exist, it won't ever be used because d will satisfy the cond below . gives a compilation warning if ;; we don't provide a value here. 0) round-pos (cond ;; If d was given, that forces the rounding ;; position, regardless of any width that may ;; have been specified. d (+ e d 1) ;; Otherwise w was specified, so pick round-pos ;; based upon that. If e>=0 , then abs value of number is > = 1.0 , and e+1 is number of decimal digits before the ;; decimal point when the number is written ;; without scientific notation. Never round the ;; number before the decimal point. (>= e 0) (max (inc e) (dec w)) e < 0 , so number abs value < 1.0 :else (+ w e)) [m1 e1 round-pos len] (if (= round-pos 0) [(str "0" m) (inc e) 1 (inc len)] [m e round-pos len])] (if round-pos (if (neg? round-pos) ["0" 0 false] (if (> len round-pos) (let [round-char (nth m1 round-pos) result (subs m1 0 round-pos)] (if (>= (char-code round-char) (char-code \5)) (let [round-up-result (inc-s result) expanded (> (count round-up-result) (count result))] [(if expanded (subs round-up-result 0 (dec (count round-up-result))) round-up-result) e1 expanded]) [result e1 false])) [m e false])) [m e false])) [m e false])) (defn- expand-fixed [m e d] (let [[m1 e1] (if (neg? e) [(str (apply str (repeat (dec (- e)) \0)) m) -1] [m e]) len (count m1) target-len (if d (+ e1 d 1) (inc e1))] (if (< len target-len) (str m1 (apply str (repeat (- target-len len) \0))) m1))) (defn- insert-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m e] (if (neg? e) (str "." m) (let [loc (inc e)] (str (subs m 0 loc) "." (subs m loc))))) (defn- get-fixed [m e d] (insert-decimal (expand-fixed m e d) e)) (defn- insert-scaled-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m k] (if (neg? k) (str "." m) (str (subs m 0 k) "." (subs m k)))) ;;TODO: No ratio, so not sure what to do here (defn- convert-ratio [x] x) ;; the function to render ~F directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- fixed-float [params navigator offsets] (let [w (:w params) d (:d params) [arg navigator] (next-arg navigator) [sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg]) abs (convert-ratio abs) [mantissa exp] (float-parts abs) scaled-exp (+ exp (:k params)) add-sign (or (:at params) (neg? arg)) append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp)) [rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp d (if w (- w (if add-sign 1 0)))) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) fixed-repr (if (and w d (>= d 1) (= (.charAt fixed-repr 0) \0) (= (.charAt fixed-repr 1) \.) (> (count fixed-repr) (- w (if add-sign 1 0)))) (subs fixed-repr 1) ;chop off leading 0 fixed-repr) prepend-zero (= (first fixed-repr) \.)] (if w (let [len (count fixed-repr) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (>= signed-len w))) append-zero (and append-zero (not (>= signed-len w))) full-len (if (or prepend-zero append-zero) (inc signed-len) signed-len)] (if (and (> full-len w) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len) (:padchar params))) (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0"))))) (print (str (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0")))) navigator)) ;; the function to render ~E directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases TODO : define ~E representation for Infinity (defn- exponential-float [params navigator offset] (let [[arg navigator] (next-arg navigator) arg (convert-ratio arg)] (loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))] (let [w (:w params) d (:d params) e (:e params) k (:k params) expchar (or (:exponentchar params) \E) add-sign (or (:at params) (neg? arg)) prepend-zero (<= k 0) scaled-exp (- exp (dec k)) scaled-exp-str (str (Math/abs scaled-exp)) scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+) (if e (apply str (repeat (- e (count scaled-exp-str)) \0))) scaled-exp-str) exp-width (count scaled-exp-str) base-mantissa-width (count mantissa) scaled-mantissa (str (apply str (repeat (- k) \0)) mantissa (if d (apply str (repeat (- d (dec base-mantissa-width) (if (neg? k) (- k) 0)) \0)))) w-mantissa (if w (- w exp-width)) [rounded-mantissa _ incr-exp] (round-str scaled-mantissa 0 (cond (= k 0) (dec d) (pos? k) d (neg? k) (dec d)) (if w-mantissa (- w-mantissa (if add-sign 1 0)))) full-mantissa (insert-scaled-decimal rounded-mantissa k) append-zero (and (= k (count rounded-mantissa)) (nil? d))] (if (not incr-exp) (if w (let [len (+ (count full-mantissa) exp-width) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (= signed-len w))) full-len (if prepend-zero (inc signed-len) signed-len) append-zero (and append-zero (< full-len w))] (if (and (or (> full-len w) (and e (> (- exp-width 2) e))) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len (if append-zero 1 0)) (:padchar params))) (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str)))) (print (str (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str))) (recur [rounded-mantissa (inc exp)])))) navigator)) ;; the function to render ~G directives ;; This just figures out whether to pass the request off to ~F or ~E based ;; on the algorithm in CLtL. ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases ;; TODO: refactor so that float-parts isn't called twice (defn- general-float [params navigator offsets] (let [[arg _] (next-arg navigator) arg (convert-ratio arg) [mantissa exp] (float-parts (if (neg? arg) (- arg) arg)) w (:w params) d (:d params) e (:e params) n (if (= arg 0.0) 0 (inc exp)) ee (if e (+ e 2) 4) ww (if w (- w ee)) d (if d d (max (count mantissa) (min n 7))) dd (- d n)] (if (<= 0 dd d) (let [navigator (fixed-float {:w ww, :d dd, :k 0, :overflowchar (:overflowchar params), :padchar (:padchar params), :at (:at params)} navigator offsets)] (print (apply str (repeat ee \space))) navigator) (exponential-float params navigator offsets)))) ;; the function to render ~$ directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- dollar-float [params navigator offsets] (let [[arg navigator] (next-arg navigator) [mantissa exp] (float-parts (Math/abs arg)) d (:d params) ; digits after the decimal n (:n params) ; minimum digits before the decimal w (:w params) ; minimum field width add-sign (or (:at params) (neg? arg)) [rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) full-repr (str (apply str (repeat (- n (.indexOf fixed-repr \.)) \0)) fixed-repr) full-len (+ (count full-repr) (if add-sign 1 0))] (print (str (if (and (:colon params) add-sign) (if (neg? arg) \- \+)) (apply str (repeat (- w full-len) (:padchar params))) (if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+)) full-repr)) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~[...~]' conditional construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ~[ ... ~ ] without any modifiers chooses one of the clauses based on the param or ;; next argument TODO check arg is positive int (defn- choice-conditional [params arg-navigator offsets] (let [arg (:selector params) [arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator)) clauses (:clauses params) clause (if (or (neg? arg) (>= arg (count clauses))) (first (:else params)) (nth clauses arg))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~:[...~] with the colon reads the next argument treating it as a truth value (defn- boolean-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (second clauses) (first clauses))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~@[...~] with the at sign executes the conditional if the next arg is not ;; nil/false without consuming the arg (defn- check-arg-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (first clauses))] (if arg (if clause (execute-sub-format clause arg-navigator (:base-args params)) arg-navigator) navigator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~{...~}' iteration construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ~{...~} without any modifiers uses the next argument as an argument list that ;; is consumed by all the iterations (defn- iterate-sublist [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator) args (init-navigator arg-list)] (loop [count 0 args args last-pos (int -1)] (if (and (not max-count) (= (:pos args) last-pos) (> count 1)) TODO get the offset in here and call format exception (throw (js/Error "%{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest args)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause args (:base-args params))] (if (= :up-arrow (first iter-result)) navigator (recur (inc count) iter-result (:pos args)))))))) ;; ~:{...~} with the colon treats the next argument as a list of sublists. Each of the ;; sublists is used as the arglist for a single iteration. (defn- iterate-list-of-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator)] (loop [count 0 arg-list arg-list] (if (or (and (empty? arg-list) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause (init-navigator (first arg-list)) (init-navigator (next arg-list)))] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) (next arg-list)))))))) ;; ~@{...~} with the at sign uses the main argument list as the arguments to the iterations ;; is consumed by all the iterations (defn- iterate-main-list [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator last-pos (int -1)] (if (and (not max-count) (= (:pos navigator) last-pos) (> count 1)) TODO get the offset in here and call format exception (throw (js/Error "%@{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause navigator (:base-args params))] (if (= :up-arrow (first iter-result)) (second iter-result) (recur (inc count) iter-result (:pos navigator)))))))) ~@:{ ... ~ } with both colon and at sign uses the main argument list as a set of sublists , one ;; of which is consumed with each iteration (defn- iterate-main-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator] (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [[sublist navigator] (next-arg-or-nil navigator) iter-result (execute-sub-format clause (init-navigator sublist) navigator)] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) navigator))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; The ' ~ < directive has two completely different meanings ;; in the '~<...~>' form it does justification, but with ;; ~<...~:>' it represents the logical block operation of the ;; pretty printer. ;; ;; Unfortunately, the current architecture decides what function ;; to call at form parsing time before the sub-clauses have been ;; folded, so it is left to run-time to make the decision. ;; ;; TODO: make it possible to make these decisions at compile-time. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([params navigator offsets])} format-logical-block) (declare ^{:arglists '([params navigator offsets])} justify-clauses) (defn- logical-block-or-justify [params navigator offsets] (if (:colon (:right-params params)) (format-logical-block params navigator offsets) (justify-clauses params navigator offsets))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~<...~>' justification directive ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- render-clauses [clauses navigator base-navigator] (loop [clauses clauses acc [] navigator navigator] (if (empty? clauses) [acc navigator] (let [clause (first clauses) [iter-result result-str] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] [(execute-sub-format clause navigator base-navigator) (str sb)]))] (if (= :up-arrow (first iter-result)) [acc (second iter-result)] (recur (next clauses) (conj acc result-str) iter-result)))))) TODO support for ~ : ; constructions (defn- justify-clauses [params navigator offsets] (let [[[eol-str] new-navigator] (when-let [else (:else params)] (render-clauses else navigator (:base-args params))) navigator (or new-navigator navigator) [else-params new-navigator] (when-let [p (:else-params params)] (realize-parameter-list p navigator)) navigator (or new-navigator navigator) min-remaining (or (first (:min-remaining else-params)) 0) max-columns (or (first (:max-columns else-params)) (get-max-column *out*)) clauses (:clauses params) [strs navigator] (render-clauses clauses navigator (:base-args params)) slots (max 1 (+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0))) chars (reduce + (map count strs)) mincol (:mincol params) minpad (:minpad params) colinc (:colinc params) minout (+ chars (* slots minpad)) result-columns (if (<= minout mincol) mincol (+ mincol (* colinc (+ 1 (quot (- minout mincol 1) colinc))))) total-pad (- result-columns chars) pad (max minpad (quot total-pad slots)) extra-pad (- total-pad (* pad slots)) pad-str (apply str (repeat pad (:padchar params)))] (if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns) max-columns)) (print eol-str)) (loop [slots slots extra-pad extra-pad strs strs pad-only (or (:colon params) (and (= (count strs) 1) (not (:at params))))] (if (seq strs) (do (print (str (if (not pad-only) (first strs)) (if (or pad-only (next strs) (:at params)) pad-str) (if (pos? extra-pad) (:padchar params)))) (recur (dec slots) (dec extra-pad) (if pad-only strs (next strs)) false)))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for case modification with ~(...~). ;;; We do this by wrapping the underlying writer with ;;; a special writer to do the appropriate modification. This ;;; allows us to support arbitrary-sized output and sources ;;; that may block. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- downcase-writer "Returns a proxy that wraps writer, converting all characters to lower case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/lower-case s))) js/Number (let [c x] TODO need to enforce integers only ? (-write writer (string/lower-case (char c)))))))) (defn- upcase-writer "Returns a proxy that wraps writer, converting all characters to upper case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/upper-case s))) js/Number (let [c x] TODO need to enforce integers only ? (-write writer (string/upper-case (char c)))))))) (defn- capitalize-string "Capitalizes the words in a string. If first? is false, don't capitalize the first character of the string even if it's a letter." [s first?] (let [f (first s) s (if (and first? f (gstring/isUnicodeChar f)) (str (string/upper-case f) (subs s 1)) s)] (apply str (first (consume (fn [s] (if (empty? s) [nil nil] (let [m (.exec (js/RegExp "\\W\\w" "g") s) offset (and m (inc (.-index m)))] (if offset [(str (subs s 0 offset) (string/upper-case (nth s offset))) (subs s (inc offset))] [s nil])))) s))))) (defn- capitalize-word-writer "Returns a proxy that wraps writer, capitalizing all words" [writer] (let [last-was-whitespace? (atom true)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (capitalize-string (.toLowerCase s) @last-was-whitespace?)) (when (pos? (.-length s)) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace (nth s (dec (count s))))))) js/Number (let [c (char x)] (let [mod-c (if @last-was-whitespace? (string/upper-case c) c)] (-write writer mod-c) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace c))))))))) (defn- init-cap-writer "Returns a proxy that wraps writer, capitalizing the first word" [writer] (let [capped (atom false)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s (string/lower-case x)] (if (not @capped) (let [m (.exec (js/RegExp "\\S" "g") s) offset (and m (.-index m))] (if offset (do (-write writer (str (subs s 0 offset) (string/upper-case (nth s offset)) (string/lower-case (subs s (inc offset))))) (reset! capped true)) (-write writer s))) (-write writer (string/lower-case s)))) js/Number (let [c (char x)] (if (and (not @capped) (gstring/isUnicodeChar c)) (do (reset! capped true) (-write writer (string/upper-case c))) (-write writer (string/lower-case c))))))))) (defn- modify-case [make-writer params navigator offsets] (let [clause (first (:clauses params))] (binding [*out* (make-writer *out*)] (execute-sub-format clause navigator (:base-args params))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; If necessary , wrap the writer in a PrettyWriter object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; TODO update this doc string to show correct way to print (defn get-pretty-writer "Returns the IWriter passed in wrapped in a pretty writer proxy, unless it's already a pretty writer. Generally, it is unnecessary to call this function, since pprint, write, and cl-format all call it if they need to. However if you want the state to be preserved across calls, you will want to wrap them with this. For example, when you want to generate column-aware output with multiple calls to cl-format, do it like in this example: (defn print-table [aseq column-width] (binding [*out* (get-pretty-writer *out*)] (doseq [row aseq] (doseq [col row] (cl-format true \"~4D~7,vT\" col column-width)) (prn)))) Now when you run: user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8) It prints a table of squares and cubes for the numbers from 1 to 10: 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000" [writer] (if (pretty-writer? writer) writer (pretty-writer writer *print-right-margin* *print-miser-width*))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for column-aware operations ~&, ~T ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fresh-line "Make a newline if *out* is not already at the beginning of the line. If *out* is not a pretty writer (which keeps track of columns), this function always outputs a newline." [] (if (satisfies? IDeref *out*) (if (not (= 0 (get-column (:base @@*out*)))) (prn)) (prn))) (defn- absolute-tabulation [params navigator offsets] (let [colnum (:colnum params) colinc (:colinc params) current (get-column (:base @@*out*)) space-count (cond (< current colnum) (- colnum current) (= colinc 0) 0 :else (- colinc (rem (- current colnum) colinc)))] (print (apply str (repeat space-count \space)))) navigator) (defn- relative-tabulation [params navigator offsets] (let [colrel (:colnum params) colinc (:colinc params) start-col (+ colrel (get-column (:base @@*out*))) offset (if (pos? colinc) (rem start-col colinc) 0) space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))] (print (apply str (repeat space-count \space)))) navigator) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for accessing the pretty printer from a format ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: support ~@; per-line-prefix separator ;; TODO: get the whole format wrapped so we can start the lb at any column (defn- format-logical-block [params navigator offsets] (let [clauses (:clauses params) clause-count (count clauses) prefix (cond (> clause-count 1) (:string (:params (first (first clauses)))) (:colon params) "(") body (nth clauses (if (> clause-count 1) 1 0)) suffix (cond (> clause-count 2) (:string (:params (first (nth clauses 2)))) (:colon params) ")") [arg navigator] (next-arg navigator)] (pprint-logical-block :prefix prefix :suffix suffix (execute-sub-format body (init-navigator arg) (:base-args params))) navigator)) (defn- set-indent [params navigator offsets] (let [relative-to (if (:colon params) :current :block)] (pprint-indent relative-to (:n params)) navigator)) ;;; TODO: support ~:T section options for ~T (defn- conditional-newline [params navigator offsets] (let [kind (if (:colon params) (if (:at params) :mandatory :fill) (if (:at params) :miser :linear))] (pprint-newline kind) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The table of directives we support, each with its params, ;;; properties, and the compilation function ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defdirectives (\A [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii print-str %1 %2 %3)) (\S [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii pr-str %1 %2 %3)) (\D [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 10 %1 %2 %3)) (\B [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 2 %1 %2 %3)) (\O [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 8 %1 %2 %3)) (\X [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 16 %1 %2 %3)) (\R [:base [nil js/Number] :mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} (do (cond ; ~R is overloaded with bizareness (first (:base params)) #(format-integer (:base %1) %1 %2 %3) (and (:at params) (:colon params)) #(format-old-roman %1 %2 %3) (:at params) #(format-new-roman %1 %2 %3) (:colon params) #(format-ordinal-english %1 %2 %3) true #(format-cardinal-english %1 %2 %3)))) (\P [] #{:at :colon :both} {} (fn [params navigator offsets] (let [navigator (if (:colon params) (relative-reposition navigator -1) navigator) strs (if (:at params) ["y" "ies"] ["" "s"]) [arg navigator] (next-arg navigator)] (print (if (= arg 1) (first strs) (second strs))) navigator))) (\C [:char-format [nil js/String]] #{:at :colon :both} {} (cond (:colon params) pretty-character (:at params) readable-character :else plain-character)) (\F [:w [nil js/Number] :d [nil js/Number] :k [0 js/Number] :overflowchar [nil js/String] :padchar [\space js/String]] #{:at} {} fixed-float) (\E [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} exponential-float) (\G [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} general-float) (\$ [:d [2 js/Number] :n [1 js/Number] :w [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} dollar-float) (\% [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (prn)) arg-navigator)) (\& [:count [1 js/Number]] #{:pretty} {} (fn [params arg-navigator offsets] (let [cnt (:count params)] (if (pos? cnt) (fresh-line)) (dotimes [i (dec cnt)] (prn))) arg-navigator)) (\| [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (print \formfeed)) arg-navigator)) (\~ [:n [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (let [n (:n params)] (print (apply str (repeat n \~))) arg-navigator))) Whitespace supression is handled in the compilation loop [] #{:colon :at} {} (fn [params arg-navigator offsets] (if (:at params) (prn)) arg-navigator)) (\T [:colnum [1 js/Number] :colinc [1 js/Number]] #{:at :pretty} {} (if (:at params) #(relative-tabulation %1 %2 %3) #(absolute-tabulation %1 %2 %3))) (\* [:n [1 js/Number]] #{:colon :at} {} (fn [params navigator offsets] (let [n (:n params)] (if (:at params) (absolute-reposition navigator n) (relative-reposition navigator (if (:colon params) (- n) n)))))) (\? [] #{:at} {} (if (:at params) (fn [params navigator offsets] ; args from main arg list (let [[subformat navigator] (get-format-arg navigator)] (execute-sub-format subformat navigator (:base-args params)))) (fn [params navigator offsets] ; args from sub-list (let [[subformat navigator] (get-format-arg navigator) [subargs navigator] (next-arg navigator) sub-navigator (init-navigator subargs)] (execute-sub-format subformat sub-navigator (:base-args params)) navigator)))) (\( [] #{:colon :at :both} {:right \), :allows-separator nil, :else nil} (let [mod-case-writer (cond (and (:at params) (:colon params)) upcase-writer (:colon params) capitalize-word-writer (:at params) init-cap-writer :else downcase-writer)] #(modify-case mod-case-writer %1 %2 %3))) (\) [] #{} {} nil) (\[ [:selector [nil js/Number]] #{:colon :at} {:right \], :allows-separator true, :else :last} (cond (:colon params) boolean-conditional (:at params) check-arg-conditional true choice-conditional)) (\; [:min-remaining [nil js/Number] :max-columns [nil js/Number]] #{:colon} {:separator true} nil) (\] [] #{} {} nil) (\{ [:max-iterations [nil js/Number]] #{:colon :at :both} {:right \}, :allows-separator false} (cond (and (:at params) (:colon params)) iterate-main-sublists (:colon params) iterate-list-of-sublists (:at params) iterate-main-list true iterate-sublist)) (\} [] #{:colon} {} nil) (\< [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:colon :at :both :pretty} {:right \>, :allows-separator true, :else :first} logical-block-or-justify) (\> [] #{:colon} {} nil) ;; TODO: detect errors in cases where colon not allowed (\^ [:arg1 [nil js/Number] :arg2 [nil js/Number] :arg3 [nil js/Number]] #{:colon} {} (fn [params navigator offsets] (let [arg1 (:arg1 params) arg2 (:arg2 params) arg3 (:arg3 params) exit (if (:colon params) :colon-up-arrow :up-arrow)] (cond (and arg1 arg2 arg3) (if (<= arg1 arg2 arg3) [exit navigator] navigator) (and arg1 arg2) (if (= arg1 arg2) [exit navigator] navigator) arg1 (if (= arg1 0) [exit navigator] navigator) true ; TODO: handle looking up the arglist stack for info (if (if (:colon params) (empty? (:rest (:base-args params))) (empty? (:rest navigator))) [exit navigator] navigator))))) (\W [] #{:at :colon :both :pretty} {} (if (or (:at params) (:colon params)) (let [bindings (concat (if (:at params) [:level nil :length nil] []) (if (:colon params) [:pretty true] []))] (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (apply write arg bindings) [:up-arrow navigator] navigator)))) (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (write-out arg) [:up-arrow navigator] navigator))))) (\_ [] #{:at :colon :both} {} conditional-newline) (\I [:n [0 js/Number]] #{:colon} {} set-indent) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Code to manage the parameters and flags associated with each ;; directive in the format string. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))") (def ^{:private true} special-params #{:parameter-from-args :remaining-arg-count}) (defn- extract-param [[s offset saw-comma]] (let [m (js/RegExp. (.-source param-pattern) "g") param (.exec m s)] (if param (let [token-str (first param) remainder (subs s (.-lastIndex m)) new-offset (+ offset (.-lastIndex m))] (if (not (= \, (nth remainder 0))) [[token-str offset] [remainder new-offset false]] [[token-str offset] [(subs remainder 1) (inc new-offset) true]])) (if saw-comma (format-error "Badly formed parameters in format directive" offset) [nil [s offset]])))) (defn- extract-params [s offset] (consume extract-param [s offset false])) (defn- translate-param "Translate the string representation of a param to the internalized representation" [[p offset]] [(cond (= (.-length p) 0) nil (and (= (.-length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args (and (= (.-length p) 1) (= \# (nth p 0))) :remaining-arg-count (and (= (.-length p) 2) (= \' (nth p 0))) (nth p 1) true (js/parseInt p 10)) offset]) (def ^{:private true} flag-defs {\: :colon, \@ :at}) (defn- extract-flags [s offset] (consume (fn [[s offset flags]] (if (empty? s) [nil [s offset flags]] (let [flag (get flag-defs (first s))] (if flag (if (contains? flags flag) (format-error (str "Flag \"" (first s) "\" appears more than once in a directive") offset) [true [(subs s 1) (inc offset) (assoc flags flag [true offset])]]) [nil [s offset flags]])))) [s offset {}])) (defn- check-flags [def flags] (let [allowed (:flags def)] (if (and (not (:at allowed)) (:at flags)) (format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:at flags) 1))) (if (and (not (:colon allowed)) (:colon flags)) (format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:colon flags) 1))) (if (and (not (:both allowed)) (:at flags) (:colon flags)) (format-error (str "Cannot combine \"@\" and \":\" flags for format directive \"" (:directive def) "\"") (min (nth (:colon flags) 1) (nth (:at flags) 1)))))) (defn- map-params "Takes a directive definition and the list of actual parameters and a map of flags and returns a map of the parameters and flags with defaults filled in. We check to make sure that there are the right types and number of parameters as well." [def params flags offset] (check-flags def flags) (if (> (count params) (count (:params def))) (format-error (cl-format nil "Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed" (:directive def) (count params) (count (:params def))) (second (first params)))) (doall (map #(let [val (first %1)] (if (not (or (nil? val) (contains? special-params val) (= (second (second %2)) (type val)))) (format-error (str "Parameter " (name (first %2)) " has bad type in directive \"" (:directive def) "\": " (type val)) (second %1))) ) params (:params def))) (merge ; create the result map (into (array-map) ; start with the default values, make sure the order is right (reverse (for [[name [default]] (:params def)] [name [default offset]]))) add the specified parameters , filtering out nils flags)); and finally add the flags (defn- compile-directive [s offset] (let [[raw-params [rest offset]] (extract-params s offset) [_ [rest offset flags]] (extract-flags rest offset) directive (first rest) def (get directive-table (string/upper-case directive)) params (if def (map-params def (map translate-param raw-params) flags offset))] (if (not directive) (format-error "Format string ended in the middle of a directive" offset)) (if (not def) (format-error (str "Directive \"" directive "\" is undefined") offset)) [(compiled-directive. ((:generator-fn def) params offset) def params offset) (let [remainder (subs rest 1) offset (inc offset) trim? (and (= \newline (:directive def)) (not (:colon params))) trim-count (if trim? (prefix-count remainder [\space \tab]) 0) remainder (subs remainder trim-count) offset (+ offset trim-count)] [remainder offset])])) (defn- compile-raw-string [s offset] (compiled-directive. (fn [_ a _] (print s) a) nil {:string s} offset)) (defn- right-bracket [this] (:right (:bracket-info (:def this)))) (defn- separator? [this] (:separator (:bracket-info (:def this)))) (defn- else-separator? [this] (and (:separator (:bracket-info (:def this))) (:colon (:params this)))) (declare ^{:arglists '([bracket-info offset remainder])} collect-clauses) (defn- process-bracket [this remainder] (let [[subex remainder] (collect-clauses (:bracket-info (:def this)) (:offset this) remainder)] [(compiled-directive. (:func this) (:def this) (merge (:params this) (tuple-map subex (:offset this))) (:offset this)) remainder])) (defn- process-clause [bracket-info offset remainder] (consume (fn [remainder] (if (empty? remainder) (format-error "No closing bracket found." offset) (let [this (first remainder) remainder (next remainder)] (cond (right-bracket this) (process-bracket this remainder) (= (:right bracket-info) (:directive (:def this))) [ nil [:right-bracket (:params this) nil remainder]] (else-separator? this) [nil [:else nil (:params this) remainder]] (separator? this) [nil [:separator nil nil remainder]] ;; TODO: check to make sure that there are no params on ~; true [this remainder])))) remainder)) (defn- collect-clauses [bracket-info offset remainder] (second (consume (fn [[clause-map saw-else remainder]] (let [[clause [type right-params else-params remainder]] (process-clause bracket-info offset remainder)] (cond (= type :right-bracket) [nil [(merge-with concat clause-map {(if saw-else :else :clauses) [clause] :right-params right-params}) remainder]] (= type :else) (cond (:else clause-map) \") inside bracket construction . " offset ) (not (:else bracket-info)) \") is in a bracket type that does n't support it . " offset) (and (= :first (:else bracket-info)) (seq (:clauses clause-map))) (format-error \") is only allowed in the first position for this directive . " offset) true ; if the ~:; is in the last position, the else clause ; is next, this was a regular clause (if (= :first (:else bracket-info)) [true [(merge-with concat clause-map {:else [clause] :else-params else-params}) false remainder]] [true [(merge-with concat clause-map {:clauses [clause]}) true remainder]])) (= type :separator) (cond saw-else \") follows an else clause ( \"~:;\ " ) inside bracket construction . " offset ) (not (:allows-separator bracket-info)) \") is in a bracket type that does n't support it . " offset) true [true [(merge-with concat clause-map {:clauses [clause]}) false remainder]])))) [{:clauses []} false remainder]))) (defn- process-nesting "Take a linearly compiled format and process the bracket directives to give it the appropriate tree structure" [format] (first (consume (fn [remainder] (let [this (first remainder) remainder (next remainder) bracket (:bracket-info (:def this))] (if (:right bracket) (process-bracket this remainder) [this remainder]))) format))) (defn- compile-format "Compiles format-str into a compiled format which can be used as an argument to cl-format just like a plain format string. Use this function for improved performance when you're using the same format string repeatedly" [format-str] (binding [*format-str* format-str] (process-nesting (first (consume (fn [[s offset]] (if (empty? s) [nil s] (let [tilde (.indexOf s \~)] (cond (neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.-length s))]] (zero? tilde) (compile-directive (subs s 1) (inc offset)) true [(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]])))) [format-str 0]))))) (defn- needs-pretty "determine whether a given compiled format has any directives that depend on the column number or pretty printing" [format] (loop [format format] (if (empty? format) false (if (or (:pretty (:flags (:def (first format)))) (some needs-pretty (first (:clauses (:params (first format))))) (some needs-pretty (first (:else (:params (first format)))))) true (recur (next format)))))) NB We depart from the original api . In clj , if execute - format is called multiple times with the same stream or ;; called on *out*, the results are different than if the same calls are made with different streams or printing ;; to a string. The reason is that mutating the underlying stream changes the result by changing spacing. ;; ;; clj: * stream = > " 1 2 3 " * true ( prints to * out * ) = > " 1 2 3 " ;; * nil (prints to string) => "1 2 3" ;; cljs: * stream = > " 1 2 3 " ;; * true (prints via *print-fn*) => "1 2 3" ;; * nil (prints to string) => "1 2 3" (defn- execute-format "Executes the format with the arguments." {:skip-wiki true} ([stream format args] (let [sb (StringBuffer.) real-stream (if (or (not stream) (true? stream)) (StringBufferWriter. sb) stream) wrapped-stream (if (and (needs-pretty format) (not (pretty-writer? real-stream))) (get-pretty-writer real-stream) real-stream)] (binding [*out* wrapped-stream] (try (execute-format format args) (finally (if-not (identical? real-stream wrapped-stream) (-flush wrapped-stream)))) (cond (not stream) (str sb) (true? stream) (string-print (str sb)) :else nil)))) ([format args] (map-passing-context (fn [element context] (if (abort? context) [nil context] (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args args)] [nil (apply (:func element) [params args offsets])]))) args format) nil)) ;;; This is a bad idea, but it prevents us from leaking private symbols ;;; This should all be replaced by really compiled formats anyway. (def ^{:private true} cached-compile (memoize compile-format)) ;;====================================================================== dispatch.clj ;;====================================================================== (defn- use-method "Installs a function as a new method of multimethod associated with dispatch-value. " [multifn dispatch-val func] (-add-method multifn dispatch-val func)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementations of specific dispatch table entries ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Handle forms that can be "back-translated" to reader macros ;;; Not all reader macros can be dealt with this way or at all. Macros that we ca n't deal with at all are : ;;; ; - The comment character is absorbed by the reader and never is part of the form ` - Is fully processed at read time into a lisp expression ( which will contain concats ;;; and regular quotes). ;;; ~@ - Also fully eaten by the processing of ` and can't be used outside. ;;; , - is whitespace and is lost (like all other whitespace). Formats can generate commas ;;; where they deem them useful to help readability. ;;; ^ - Adding metadata completely disappears at read time and the data appears to be ;;; completely lost. ;;; ;;; Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{}) or directly by printing the objects using Clojure 's built - in print functions ( like : keyword , \char , or " " ) . The notable exception is # ( ) which is special - cased . (def ^{:private true} reader-macros {'quote "'" 'var "#'" 'clojure.core/deref "@", 'clojure.core/unquote "~" 'cljs.core/deref "@", 'cljs.core/unquote "~"}) (defn- pprint-reader-macro [alis] (let [macro-char (reader-macros (first alis))] (when (and macro-char (= 2 (count alis))) (-write *out* macro-char) (write-out (second alis)) true))) ;;====================================================================== Dispatch for the basic data types when interpreted ;; as data (as opposed to code). ;;====================================================================== ;;; TODO: inline these formatter statements into funcs so that we ;;; are a little easier on the stack. (Or, do "real" compilation, a ;;; la Common Lisp) ( def pprint - simple - list ( formatter - out " ~:<~@{~w~^ ~_~}~ :> " ) ) (defn- pprint-simple-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) (defn- pprint-list [alis] (if-not (pprint-reader-macro alis) (pprint-simple-list alis))) ;;; (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>")) (defn- pprint-vector [avec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [aseq (seq avec)] (when aseq (write-out (first aseq)) (when (next aseq) (-write *out* " ") (pprint-newline :linear) (recur (next aseq))))))) (def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>")) ;;; (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>")) (defn- pprint-map [amap] (let [[ns lift-map] (when (not (record? amap)) (#'cljs.core/lift-ns amap)) amap (or lift-map amap) prefix (if ns (str "#:" ns "{") "{")] (pprint-logical-block :prefix prefix :suffix "}" (print-length-loop [aseq (seq amap)] (when aseq ;;compiler gets confused with nested macro if it isn't namespaced it tries to use clojure.pprint/pprint-logical-block for some reason (m/pprint-logical-block (write-out (ffirst aseq)) (-write *out* " ") (pprint-newline :linear) (set! *current-length* 0) ;always print both parts of the [k v] pair (write-out (fnext (first aseq)))) (when (next aseq) (-write *out* ", ") (pprint-newline :linear) (recur (next aseq)))))))) (defn- pprint-simple-default [obj] ;;TODO: Update to handle arrays (?) and suppressing namespaces (-write *out* (pr-str obj))) (def pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>")) (def ^{:private true} type-map {"core$future_call" "Future", "core$promise" "Promise"}) (defn- map-ref-type "Map ugly type names to something simpler" [name] (or (when-let [match (re-find #"^[^$]+\$[^$]+" name)] (type-map match)) name)) (defn- pprint-ideref [o] (let [prefix (str "#<" (map-ref-type (.-name (type o))) "@" (goog/getUid o) ": ")] (pprint-logical-block :prefix prefix :suffix ">" (pprint-indent :block (-> (count prefix) (- 2) -)) (pprint-newline :linear) (write-out (if (and (satisfies? IPending o) (not (-realized? o))) :not-delivered @o))))) (def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>")) (defn- type-dispatcher [obj] (cond (instance? PersistentQueue obj) :queue (satisfies? IDeref obj) :deref (symbol? obj) :symbol (seq? obj) :list (map? obj) :map (vector? obj) :vector (set? obj) :set (nil? obj) nil :default :default)) (defmulti simple-dispatch "The pretty print dispatch function for simple data structure format." type-dispatcher) (use-method simple-dispatch :list pprint-list) (use-method simple-dispatch :vector pprint-vector) (use-method simple-dispatch :map pprint-map) (use-method simple-dispatch :set pprint-set) (use-method simple-dispatch nil #(-write *out* (pr-str nil))) (use-method simple-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Dispatch for the code table ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([alis])} pprint-simple-code-list) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the namespace ("ns") macro. This is quite complicated because of all the ;;; different forms supported and because programmers can choose lists or vectors ;;; in various places. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- brackets "Figure out which kind of brackets to use" [form] (if (vector? form) ["[" "]"] ["(" ")"])) (defn- pprint-ns-reference "Pretty print a single reference (import, use, etc.) from a namespace decl" [reference] (if (sequential? reference) (let [[start end] (brackets reference) [keyw & args] reference] (pprint-logical-block :prefix start :suffix end ((formatter-out "~w~:i") keyw) (loop [args args] (when (seq args) ((formatter-out " ")) (let [arg (first args)] (if (sequential? arg) (let [[start end] (brackets arg)] (pprint-logical-block :prefix start :suffix end (if (and (= (count arg) 3) (keyword? (second arg))) (let [[ns kw lis] arg] ((formatter-out "~w ~w ") ns kw) (if (sequential? lis) ((formatter-out (if (vector? lis) "~<[~;~@{~w~^ ~:_~}~;]~:>" "~<(~;~@{~w~^ ~:_~}~;)~:>")) lis) (write-out lis))) (apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg))) (when (next args) ((formatter-out "~_")))) (do (write-out arg) (when (next args) ((formatter-out "~:_")))))) (recur (next args)))))) (write-out reference))) (defn- pprint-ns "The pretty print dispatch chunk for the ns macro" [alis] (if (next alis) (let [[ns-sym ns-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map references] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") ns-sym ns-name) (when (or doc-str attr-map (seq references)) ((formatter-out "~@:_"))) (when doc-str (cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references)))) (when attr-map ((formatter-out "~w~:[~;~:@_~]") attr-map (seq references))) (loop [references references] (pprint-ns-reference (first references)) (when-let [references (next references)] (pprint-newline :linear) (recur references))))) (write-out alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Format something that looks like a simple def ( sans metadata , since the reader ;;; won't give it to us now). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Format something that looks like a defn or defmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the params and body of a defn with a single arity (defn- single-defn [alis has-doc-str?] (if (seq alis) (do (if has-doc-str? ((formatter-out " ~_")) ((formatter-out " ~@_"))) ((formatter-out "~{~w~^ ~_~}") alis)))) ;;; Format the param and body sublists of a defn with multiple arities (defn- multi-defn [alis has-doc-str?] (if (seq alis) ((formatter-out " ~_~{~w~^ ~_~}") alis))) TODO : figure out how to support capturing metadata in defns ( we might need a ;;; special reader) (defn- pprint-defn [alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") defn-sym defn-name) (if doc-str ((formatter-out " ~_~w") doc-str)) (if attr-map ((formatter-out " ~_~w") attr-map)) Note : the multi - defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something with a binding form ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- pprint-binding-form [binding-vec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [binding binding-vec] (when (seq binding) (pprint-logical-block binding (write-out (first binding)) (when (next binding) (-write *out* " ") (pprint-newline :miser) (write-out (second binding)))) (when (next (rest binding)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest binding)))))))) (defn- pprint-let [alis] (let [base-sym (first alis)] (pprint-logical-block :prefix "(" :suffix ")" (if (and (next alis) (vector? (second alis))) (do ((formatter-out "~w ~1I~@_") base-sym) (pprint-binding-form (second alis)) ((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis)))) (pprint-simple-code-list alis))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like "if" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>")) (defn- pprint-cond [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (print-length-loop [alis (next alis)] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))))) (defn- pprint-condp [alis] (if (> (count alis) 3) (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (apply (formatter-out "~w ~@_~w ~@_~w ~_") alis) (print-length-loop [alis (seq (drop 3 alis))] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))) (pprint-simple-code-list alis))) ;;; The map of symbols that are defined in an enclosing #() anonymous function (def ^:dynamic ^{:private true} *symbol-map* {}) (defn- pprint-anon-func [alis] (let [args (second alis) nlis (first (rest (rest alis)))] (if (vector? args) (binding [*symbol-map* (if (= 1 (count args)) {(first args) "%"} (into {} (map #(vector %1 (str \% %2)) args (range 1 (inc (count args))))))] ((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis)) (pprint-simple-code-list alis)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The master definitions for formatting lists in code (that is, (fn args...) or ;;; special forms). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is ;;; easier on the stack. (defn- pprint-simple-code-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) ;;; Take a map with symbols as keys and add versions with no namespace. ;;; That is, if ns/sym->val is in the map, add sym->val to the result. (defn- two-forms [amap] (into {} (mapcat identity (for [x amap] [x [(symbol (name (first x))) (second x)]])))) (defn- add-core-ns [amap] (let [core "clojure.core"] (into {} (map #(let [[s f] %] (if (not (or (namespace s) (special-symbol? s))) [(symbol core (name s)) f] %)) amap)))) (def ^:dynamic ^{:private true} *code-table* (two-forms (add-core-ns {'def pprint-hold-first, 'defonce pprint-hold-first, 'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn, 'let pprint-let, 'loop pprint-let, 'binding pprint-let, 'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let, 'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let, 'when-first pprint-let, 'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if, 'cond pprint-cond, 'condp pprint-condp, 'fn* pprint-anon-func, '. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first, 'locking pprint-hold-first, 'struct pprint-hold-first, 'struct-map pprint-hold-first, 'ns pprint-ns }))) (defn- pprint-code-list [alis] (if-not (pprint-reader-macro alis) (if-let [special-form (*code-table* (first alis))] (special-form alis) (pprint-simple-code-list alis)))) (defn- pprint-code-symbol [sym] (if-let [arg-num (sym *symbol-map*)] (print arg-num) (if *print-suppress-namespaces* (print (name sym)) (pr sym)))) (defmulti code-dispatch "The pretty print dispatch function for pretty printing Clojure code." {:added "1.2" :arglists '[[object]]} type-dispatcher) (use-method code-dispatch :list pprint-code-list) (use-method code-dispatch :symbol pprint-code-symbol) ;; The following are all exact copies of simple-dispatch (use-method code-dispatch :vector pprint-vector) (use-method code-dispatch :map pprint-map) (use-method code-dispatch :set pprint-set) (use-method code-dispatch :queue pprint-pqueue) (use-method code-dispatch :deref pprint-ideref) (use-method code-dispatch nil pr) (use-method code-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;; For testing (comment (with-pprint-dispatch code-dispatch (pprint '(defn cl-format "An implementation of a Common Lisp compatible format function" [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn cl-format [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn- -write ([this x] (condp = (class x) String (let [s0 (write-initial-lines this x) s (.replaceFirst s0 "\\s+$" "") white-space (.substring s0 (count s)) mode (getf :mode)] (if (= mode :writing) (dosync (write-white-space this) (.col_write this s) (setf :trailing-white-space white-space)) (add-to-buffer this (make-buffer-blob s white-space)))) Integer (let [c ^Character x] (if (= (getf :mode) :writing) (do (write-white-space this) (.col_write this x)) (if (= c (int \newline)) (write-initial-lines this "\n") (add-to-buffer this (make-buffer-blob (str (char c)) nil)))))))))) (with-pprint-dispatch code-dispatch (pprint '(defn pprint-defn [writer alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block writer :prefix "(" :suffix ")" (cl-format true "~w ~1I~@_~w" defn-sym defn-name) (if doc-str (cl-format true " ~_~w" doc-str)) (if attr-map (cl-format true " ~_~w" attr-map)) Note : the multi - defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list writer alis))))) ) ;;====================================================================== ;; print_table.clj ;;====================================================================== (defn- add-padding [width s] (let [padding (max 0 (- width (count s)))] (apply str (clojure.string/join (repeat padding \space)) s))) (defn print-table "Prints a collection of maps in a textual table. Prints table headings ks, and then a line of output for each row, corresponding to the keys in ks. If ks are not specified, use the keys of the first item in rows." {:added "1.3"} ([ks rows] (binding [*print-newline*] (when (seq rows) (let [widths (map (fn [k] (apply max (count (str k)) (map #(count (str (get % k))) rows))) ks) spacers (map #(apply str (repeat % "-")) widths) fmt-row (fn [leader divider trailer row] (str leader (apply str (interpose divider (for [[col width] (map vector (map #(get row %) ks) widths)] (add-padding width (str col))))) trailer))] (cljs.core/println) (cljs.core/println (fmt-row "| " " | " " |" (zipmap ks ks))) (cljs.core/println (fmt-row "|-" "-+-" "-|" (zipmap ks spacers))) (doseq [row rows] (cljs.core/println (fmt-row "| " " | " " |" row))))))) ([rows] (print-table (keys (first rows)) rows)))
null
https://raw.githubusercontent.com/headwinds/reagent-reframe-material-ui/8a6fba82a026cfedca38491becac85751be9a9d4/resources/public/js/out/cljs/pprint.cljs
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. ====================================================================== ====================================================================== ====================================================================== cljs specific utils ====================================================================== ====================================================================== ====================================================================== Flush the pretty-print buffer without flushing the underlying stream ====================================================================== column_writer.clj ====================================================================== Why is the c argument an integer? ====================================================================== ====================================================================== ====================================================================== Forward declarations ====================================================================== ====================================================================== The data structures used by pretty-writer ====================================================================== A blob of characters (aka a string) A newline ====================================================================== emit-nl? method defs for each type of new line. This makes the decision about whether to print this type of new line. ====================================================================== ====================================================================== Various support functions ====================================================================== write-token-string is called when the set of tokens in the buffer is long than the available space on the line so we'll force it Add a buffer token to the buffer and see if it's time to start writing Write all the tokens that have been buffered If there are newlines in the string, print the lines up until the last newline, making the appropriate adjustments. Return the remainder of the string ====================================================================== ====================================================================== NOTE: may want to just `specify!` #js { ... fields ... } with the protocols ====================================================================== Methods for pretty-writer ====================================================================== ====================================================================== pprint_base.clj ====================================================================== ====================================================================== Variables that control the pretty printer ====================================================================== *print-length*, *print-level*, *print-namespace-maps* and *print-dup* are defined in cljs.core TODO: implement circle and shared TODO: should we just use *print-dup* here? TODO: support print-base and print-radix in cl-format TODO: support print-base and print-radix in rationals ====================================================================== Internal variables that keep track of where we are in the structure ====================================================================== ====================================================================== Support for the write function ====================================================================== This map causes var metadata to be included in the compiled output, even (def ^{:private true} write-option-table {;:array *print-array* :base #'cljs.pprint/*print-base*, ;;:case *print-case*, :circle #'cljs.pprint/*print-circle*, ;;:escape *print-escape*, ; : * print - gensym * , :length #'cljs.core/*print-length*, :level #'cljs.core/*print-level*, :lines #'cljs.pprint/*print-lines*, :miser-width #'cljs.pprint/*print-miser-width*, :dispatch #'cljs.pprint/*print-pprint-dispatch*, :pretty #'cljs.pprint/*print-pretty*, :radix #'cljs.pprint/*print-radix*, :readably #'cljs.core/*print-readably*, :right-margin #'cljs.pprint/*print-right-margin*, :suppress-namespaces #'cljs.pprint/*print-suppress-namespaces*}) :case *print-case*, :escape *print-escape* ====================================================================== Support for the functional interface to the pretty printer ====================================================================== ====================================================================== cl_format.clj ====================================================================== Forward references End forward references Argument navigators manage the argument list as the format statement moves through the list (possibly going forwards and backwards as it does so) TODO call format-error with offset Get an argument off the arg list and compile it if it's not already compiled When looking at the parameter list, we may need to manipulate the argument list as well (for 'V' and '#' parameter types). We hide all of this behind a function, but clients need to manage changing arg navigator TODO: validate parameters when they come from arg list pass flags through unchanged - this really isn't necessary Functions that support individual directives (ratio? n) ;;no ratio support (decimal? x) ;;no decimal support (ratio? x) ;;no ratio support TODO: xlated-val does not seem to be used here. (float? val) (bigdec val) ;;No bigdec ; No ratio Not sure if this is accurate or necessary Number names from We follow the rules for writing numbers from the Blue Book () some numbers are too big for Math/abs (is this true?) some numbers are too big for Math/abs (is this true?) Support for character formats (~C) Check to see if a result is an abort (~^) construct TODO: move these funcs somewhere more appropriate Handle the execution of "sub-clauses" in bracket constructions just keep passing it along Support for real number formats TODO - return exponent as int to eliminate double conversion Every formatted floating point number should include at least one decimal digit and a decimal point. NB: if w doesn't exist, it won't ever be used because d will we don't provide a value here. If d was given, that forces the rounding position, regardless of any width that may have been specified. Otherwise w was specified, so pick round-pos based upon that. decimal point when the number is written without scientific notation. Never round the number before the decimal point. TODO: No ratio, so not sure what to do here the function to render ~F directives TODO: support rationals. Back off to ~D/~A in the appropriate cases chop off leading 0 the function to render ~E directives TODO: support rationals. Back off to ~D/~A in the appropriate cases the function to render ~G directives This just figures out whether to pass the request off to ~F or ~E based on the algorithm in CLtL. TODO: support rationals. Back off to ~D/~A in the appropriate cases TODO: refactor so that float-parts isn't called twice the function to render ~$ directives TODO: support rationals. Back off to ~D/~A in the appropriate cases digits after the decimal minimum digits before the decimal minimum field width Support for the '~[...~]' conditional construct in its different flavors next argument ~:[...~] with the colon reads the next argument treating it as a truth value ~@[...~] with the at sign executes the conditional if the next arg is not nil/false without consuming the arg Support for the '~{...~}' iteration construct in its different flavors ~{...~} without any modifiers uses the next argument as an argument list that is consumed by all the iterations ~:{...~} with the colon treats the next argument as a list of sublists. Each of the sublists is used as the arglist for a single iteration. ~@{...~} with the at sign uses the main argument list as the arguments to the iterations is consumed by all the iterations of which is consumed with each iteration in the '~<...~>' form it does justification, but with ~<...~:>' it represents the logical block operation of the pretty printer. Unfortunately, the current architecture decides what function to call at form parsing time before the sub-clauses have been folded, so it is left to run-time to make the decision. TODO: make it possible to make these decisions at compile-time. Support for the '~<...~>' justification directive constructions Support for case modification with ~(...~). We do this by wrapping the underlying writer with a special writer to do the appropriate modification. This allows us to support arbitrary-sized output and sources that may block. no multi-arity, not sure of importance no multi-arity, not sure of importance no multi-arity no multi-arity Support for column-aware operations ~&, ~T Support for accessing the pretty printer from a format TODO: support ~@; per-line-prefix separator TODO: get the whole format wrapped so we can start the lb at any column TODO: support ~:T section options for ~T The table of directives we support, each with its params, properties, and the compilation function ~R is overloaded with bizareness args from main arg list args from sub-list [:min-remaining [nil js/Number] :max-columns [nil js/Number]] TODO: detect errors in cases where colon not allowed TODO: handle looking up the arglist stack for info Code to manage the parameters and flags associated with each directive in the format string. create the result map start with the default values, make sure the order is right and finally add the flags TODO: check to make sure that there are no params on ~; if the ~:; is in the last position, the else clause is next, this was a regular clause \ " ) inside bracket construction . " offset ) called on *out*, the results are different than if the same calls are made with different streams or printing to a string. The reason is that mutating the underlying stream changes the result by changing spacing. clj: * nil (prints to string) => "1 2 3" cljs: * true (prints via *print-fn*) => "1 2 3" * nil (prints to string) => "1 2 3" This is a bad idea, but it prevents us from leaking private symbols This should all be replaced by really compiled formats anyway. ====================================================================== ====================================================================== Implementations of specific dispatch table entries Handle forms that can be "back-translated" to reader macros Not all reader macros can be dealt with this way or at all. ; - The comment character is absorbed by the reader and never is part of the form and regular quotes). ~@ - Also fully eaten by the processing of ` and can't be used outside. , - is whitespace and is lost (like all other whitespace). Formats can generate commas where they deem them useful to help readability. ^ - Adding metadata completely disappears at read time and the data appears to be completely lost. Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{}) ====================================================================== as data (as opposed to code). ====================================================================== TODO: inline these formatter statements into funcs so that we are a little easier on the stack. (Or, do "real" compilation, a la Common Lisp) (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>")) (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>")) compiler gets confused with nested macro if it isn't namespaced always print both parts of the [k v] pair TODO: Update to handle arrays (?) and suppressing namespaces Format the namespace ("ns") macro. This is quite complicated because of all the different forms supported and because programmers can choose lists or vectors in various places. won't give it to us now). Format the params and body of a defn with a single arity Format the param and body sublists of a defn with multiple arities special reader) Format something with a binding form Format something that looks like "if" The map of symbols that are defined in an enclosing #() anonymous function The master definitions for formatting lists in code (that is, (fn args...) or special forms). This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is easier on the stack. Take a map with symbols as keys and add versions with no namespace. That is, if ns/sym->val is in the map, add sym->val to the result. The following are all exact copies of simple-dispatch For testing ====================================================================== print_table.clj ======================================================================
Copyright ( c ) . All rights reserved . (ns cljs.pprint (:refer-clojure :exclude [deftype print println pr prn float?]) (:require-macros [cljs.pprint :as m :refer [with-pretty-writer getf setf deftype pprint-logical-block print-length-loop defdirectives formatter-out]]) (:require [cljs.core :refer [IWriter IDeref]] [clojure.string :as string] [goog.string :as gstring]) (:import [goog.string StringBuffer])) override print fns to use * out * (defn- print [& more] (-write *out* (apply print-str more))) (defn- println [& more] (apply print more) (-write *out* \newline)) (defn- print-char [c] (-write *out* (condp = c \backspace "\\backspace" \tab "\\tab" \newline "\\newline" \formfeed "\\formfeed" \return "\\return" \" "\\\"" \\ "\\\\" (str "\\" c)))) (defn- ^:dynamic pr [& more] (-write *out* (apply pr-str more))) (defn- prn [& more] (apply pr more) (-write *out* \newline)) (defn ^boolean float? "Returns true if n is an float." [n] (and (number? n) (not ^boolean (js/isNaN n)) (not (identical? n js/Infinity)) (not (== (js/parseFloat n) (js/parseInt n 10))))) (defn char-code "Convert char to int" [c] (cond (number? c) c (and (string? c) (== (.-length c) 1)) (.charCodeAt c 0) :else (throw (js/Error. "Argument to char must be a character or number")))) Utilities (defn- map-passing-context [func initial-context lis] (loop [context initial-context lis lis acc []] (if (empty? lis) [acc context] (let [this (first lis) remainder (next lis) [result new-context] (apply func [this context])] (recur new-context remainder (conj acc result)))))) (defn- consume [func initial-context] (loop [context initial-context acc []] (let [[result new-context] (apply func [context])] (if (not result) [acc new-context] (recur new-context (conj acc result)))))) (defn- consume-while [func initial-context] (loop [context initial-context acc []] (let [[result continue new-context] (apply func [context])] (if (not continue) [acc context] (recur new-context (conj acc result)))))) (defn- unzip-map [m] "Take a map that has pairs in the value slots and produce a pair of maps, the first having all the first elements of the pairs and the second all the second elements of the pairs" [(into {} (for [[k [v1 v2]] m] [k v1])) (into {} (for [[k [v1 v2]] m] [k v2]))]) (defn- tuple-map [m v1] "For all the values, v, in the map, replace them with [v v1]" (into {} (for [[k v] m] [k [v v1]]))) (defn- rtrim [s c] "Trim all instances of c from the end of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s (dec (count s))) c)) (loop [n (dec len)] (cond (neg? n) "" (not (= (nth s n) c)) (subs s 0 (inc n)) true (recur (dec n)))) s))) (defn- ltrim [s c] "Trim all instances of c from the beginning of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s 0) c)) (loop [n 0] (if (or (= n len) (not (= (nth s n) c))) (subs s n) (recur (inc n)))) s))) (defn- prefix-count [aseq val] "Return the number of times that val occurs at the start of sequence aseq, if val is a seq itself, count the number of times any element of val occurs at the beginning of aseq" (let [test (if (coll? val) (set val) #{val})] (loop [pos 0] (if (or (= pos (count aseq)) (not (test (nth aseq pos)))) pos (recur (inc pos)))))) (defprotocol IPrettyFlush (-ppflush [pp])) (def ^:dynamic ^{:private true} *default-page-width* 72) (defn- get-field [this sym] (sym @@this)) (defn- set-field [this sym new-val] (swap! @this assoc sym new-val)) (defn- get-column [this] (get-field this :cur)) (defn- get-line [this] (get-field this :line)) (defn- get-max-column [this] (get-field this :max)) (defn- set-max-column [this new-max] (set-field this :max new-max) nil) (defn- get-writer [this] (get-field this :base)) (defn- c-write-char [this c] (if (= c \newline) (do (set-field this :cur 0) (set-field this :line (inc (get-field this :line)))) (set-field this :cur (inc (get-field this :cur)))) (-write (get-field this :base) c)) (defn- column-writer ([writer] (column-writer writer *default-page-width*)) ([writer max-columns] (let [fields (atom {:max max-columns, :cur 0, :line 0 :base writer})] (reify IDeref (-deref [_] fields) IWriter (-flush [_] (-flush writer)) (-write -write is n't multi - arity , so need different way to do this #_([this ^chars cbuf ^Number off ^Number len] (let [writer (get-field this :base)] (-write writer cbuf off len))) [this x] (condp = (type x) js/String (let [s x nl (.lastIndexOf s \newline)] (if (neg? nl) (set-field this :cur (+ (get-field this :cur) (count s))) (do (set-field this :cur (- (count s) nl 1)) (set-field this :line (+ (get-field this :line) (count (filter #(= % \newline) s)))))) (-write (get-field this :base) s)) js/Number (c-write-char this x))))))) pretty_writer.clj (declare ^{:arglists '([this])} get-miser-width) (defrecord ^{:private true} logical-block [parent section start-col indent done-nl intra-block-nl prefix per-line-prefix suffix logical-block-callback]) (defn- ancestor? [parent child] (loop [child (:parent child)] (cond (nil? child) false (identical? parent child) true :else (recur (:parent child))))) (defn- buffer-length [l] (let [l (seq l)] (if l (- (:end-pos (last l)) (:start-pos (first l))) 0))) (deftype buffer-blob :data :trailing-white-space :start-pos :end-pos) (deftype nl-t :type :logical-block :start-pos :end-pos) (deftype start-block-t :logical-block :start-pos :end-pos) (deftype end-block-t :logical-block :start-pos :end-pos) (deftype indent-t :logical-block :relative-to :offset :start-pos :end-pos) (def ^:private pp-newline (fn [] "\n")) (declare emit-nl) (defmulti ^{:private true} write-token #(:type-tag %2)) (defmethod write-token :start-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :start)) (let [lb (:logical-block token)] (when-let [prefix (:prefix lb)] (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col)))) (defmethod write-token :end-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :end)) (when-let [suffix (:suffix (:logical-block token))] (-write (getf :base) suffix))) (defmethod write-token :indent-t [this token] (let [lb (:logical-block token)] (reset! (:indent lb) (+ (:offset token) (condp = (:relative-to token) :block @(:start-col lb) :current (get-column (getf :base))))))) (defmethod write-token :buffer-blob [this token] (-write (getf :base) (:data token))) (defmethod write-token :nl-t [this token] (if (or (= (:type token) :mandatory) (and (not (= (:type token) :fill)) @(:done-nl (:logical-block token)))) (emit-nl this token) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (setf :trailing-white-space nil)) (defn- write-tokens [this tokens force-trailing-whitespace] (doseq [token tokens] (if-not (= (:type-tag token) :nl-t) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (write-token this token) (setf :trailing-white-space (:trailing-white-space token)) (let [tws (getf :trailing-white-space)] (when (and force-trailing-whitespace tws) (-write (getf :base) tws) (setf :trailing-white-space nil))))) (defn- tokens-fit? [this tokens] (let [maxcol (get-max-column (getf :base))] (or (nil? maxcol) (< (+ (get-column (getf :base)) (buffer-length tokens)) maxcol)))) (defn- linear-nl? [this lb section] (or @(:done-nl lb) (not (tokens-fit? this section)))) (defn- miser-nl? [this lb section] (let [miser-width (get-miser-width this) maxcol (get-max-column (getf :base))] (and miser-width maxcol (>= @(:start-col lb) (- maxcol miser-width)) (linear-nl? this lb section)))) (defmulti ^{:private true} emit-nl? (fn [t _ _ _] (:type t))) (defmethod emit-nl? :linear [newl this section _] (let [lb (:logical-block newl)] (linear-nl? this lb section))) (defmethod emit-nl? :miser [newl this section _] (let [lb (:logical-block newl)] (miser-nl? this lb section))) (defmethod emit-nl? :fill [newl this section subsection] (let [lb (:logical-block newl)] (or @(:intra-block-nl lb) (not (tokens-fit? this subsection)) (miser-nl? this lb section)))) (defmethod emit-nl? :mandatory [_ _ _ _] true) (defn- get-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(not (and (nl-t? %) (ancestor? (:logical-block %) lb))) (next buffer)))] [section (seq (drop (inc (count section)) buffer))])) (defn- get-sub-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(let [nl-lb (:logical-block %)] (not (and (nl-t? %) (or (= nl-lb lb) (ancestor? nl-lb lb))))) (next buffer)))] section)) (defn- update-nl-state [lb] (reset! (:intra-block-nl lb) true) (reset! (:done-nl lb) true) (loop [lb (:parent lb)] (if lb (do (reset! (:done-nl lb) true) (reset! (:intra-block-nl lb) true) (recur (:parent lb)))))) (defn- emit-nl [this nl] (-write (getf :base) (pp-newline)) (setf :trailing-white-space nil) (let [lb (:logical-block nl) prefix (:per-line-prefix lb)] (if prefix (-write (getf :base) prefix)) (let [istr (apply str (repeat (- @(:indent lb) (count prefix)) \space))] (-write (getf :base) istr)) (update-nl-state lb))) (defn- split-at-newline [tokens] (let [pre (seq (take-while #(not (nl-t? %)) tokens))] [pre (seq (drop (count pre) tokens))])) (defn- write-token-string [this tokens] (let [[a b] (split-at-newline tokens)] (if a (write-tokens this a false)) (if b (let [[section remainder] (get-section b) newl (first b)] (let [do-nl (emit-nl? newl this section (get-sub-section b)) result (if do-nl (do (emit-nl this newl) (next b)) b) long-section (not (tokens-fit? this result)) result (if long-section (let [rem2 (write-token-string this section)] (if (= rem2 section) If that did n't produce any output , it has no nls (write-tokens this section false) remainder) (into [] (concat rem2 remainder)))) result)] result))))) (defn- write-line [this] (loop [buffer (getf :buffer)] (setf :buffer (into [] buffer)) (if (not (tokens-fit? this buffer)) (let [new-buffer (write-token-string this buffer)] (if-not (identical? buffer new-buffer) (recur new-buffer)))))) (defn- add-to-buffer [this token] (setf :buffer (conj (getf :buffer) token)) (if (not (tokens-fit? this (getf :buffer))) (write-line this))) (defn- write-buffered-output [this] (write-line this) (if-let [buf (getf :buffer)] (do (write-tokens this buf true) (setf :buffer [])))) (defn- write-white-space [this] (when-let [tws (getf :trailing-white-space)] (-write (getf :base) tws) (setf :trailing-white-space nil))) (defn- write-initial-lines [^Writer this ^String s] (let [lines (string/split s "\n" -1)] (if (= (count lines) 1) s (let [^String prefix (:per-line-prefix (first (getf :logical-blocks))) ^String l (first lines)] (if (= :buffering (getf :mode)) (let [oldpos (getf :pos) newpos (+ oldpos (count l))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob l nil oldpos newpos)) (write-buffered-output this)) (do (write-white-space this) (-write (getf :base) l))) (-write (getf :base) \newline) (doseq [^String l (next (butlast lines))] (-write (getf :base) l) (-write (getf :base) (pp-newline)) (if prefix (-write (getf :base) prefix))) (setf :buffering :writing) (last lines))))) (defn- p-write-char [this c] (if (= (getf :mode) :writing) (do (write-white-space this) (-write (getf :base) c)) (if (= c \newline) (write-initial-lines this \newline) (let [oldpos (getf :pos) newpos (inc oldpos)] (setf :pos newpos) (add-to-buffer this (make-buffer-blob (char c) nil oldpos newpos)))))) Initialize the pretty - writer instance (defn- pretty-writer [writer max-columns miser-width] (let [lb (logical-block. nil nil (atom 0) (atom 0) (atom false) (atom false) nil nil nil nil) fields (atom {:pretty-writer true :base (column-writer writer max-columns) :logical-blocks lb :sections nil :mode :writing :buffer [] :buffer-block lb :buffer-level 1 :miser-width miser-width :trailing-white-space nil :pos 0})] (reify IDeref (-deref [_] fields) IWriter (-write [this x] (condp = (type x) js/String (let [s0 (write-initial-lines this x) s (string/replace-first s0 #"\s+$" "") white-space (subs s0 (count s)) mode (getf :mode)] (if (= mode :writing) (do (write-white-space this) (-write (getf :base) s) (setf :trailing-white-space white-space)) (let [oldpos (getf :pos) newpos (+ oldpos (count s0))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob s white-space oldpos newpos))))) js/Number (p-write-char this x))) (-flush [this] (-ppflush this) (-flush (getf :base))) IPrettyFlush (-ppflush [this] (if (= (getf :mode) :buffering) (do (write-tokens this (getf :buffer) true) (setf :buffer [])) (write-white-space this))) ))) (defn- start-block [this prefix per-line-prefix suffix] (let [lb (logical-block. (getf :logical-blocks) nil (atom 0) (atom 0) (atom false) (atom false) prefix per-line-prefix suffix nil)] (setf :logical-blocks lb) (if (= (getf :mode) :writing) (do (write-white-space this) (when-let [cb (getf :logical-block-callback)] (cb :start)) (if prefix (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col))) (let [oldpos (getf :pos) newpos (+ oldpos (if prefix (count prefix) 0))] (setf :pos newpos) (add-to-buffer this (make-start-block-t lb oldpos newpos)))))) (defn- end-block [this] (let [lb (getf :logical-blocks) suffix (:suffix lb)] (if (= (getf :mode) :writing) (do (write-white-space this) (if suffix (-write (getf :base) suffix)) (when-let [cb (getf :logical-block-callback)] (cb :end))) (let [oldpos (getf :pos) newpos (+ oldpos (if suffix (count suffix) 0))] (setf :pos newpos) (add-to-buffer this (make-end-block-t lb oldpos newpos)))) (setf :logical-blocks (:parent lb)))) (defn- nl [this type] (setf :mode :buffering) (let [pos (getf :pos)] (add-to-buffer this (make-nl-t type (getf :logical-blocks) pos pos)))) (defn- indent [this relative-to offset] (let [lb (getf :logical-blocks)] (if (= (getf :mode) :writing) (do (write-white-space this) (reset! (:indent lb) (+ offset (condp = relative-to :block @(:start-col lb) :current (get-column (getf :base)))))) (let [pos (getf :pos)] (add-to-buffer this (make-indent-t lb relative-to offset pos pos)))))) (defn- get-miser-width [this] (getf :miser-width)) (def ^:dynamic ^{:doc "Bind to true if you want write to use pretty printing"} *print-pretty* true) (defonce ^:dynamic ^{:doc "The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch to modify." :added "1.2"} *print-pprint-dispatch* nil) (def ^:dynamic ^{:doc "Pretty printing will try to avoid anything going beyond this column. Set it to nil to have pprint let the line be arbitrarily long. This will ignore all non-mandatory newlines.", :added "1.2"} *print-right-margin* 72) (def ^:dynamic ^{:doc "The column at which to enter miser style. Depending on the dispatch table, miser style add newlines in more places to try to keep lines short allowing for further levels of nesting.", :added "1.2"} *print-miser-width* 40) TODO implement output limiting (def ^:dynamic ^{:private true, :doc "Maximum number of lines to print in a pretty print instance (N.B. This is not yet used)"} *print-lines* nil) (def ^:dynamic ^{:private true, :doc "Mark circular structures (N.B. This is not yet used)"} *print-circle* nil) (def ^:dynamic ^{:private true, :doc "Mark repeated structures rather than repeat them (N.B. This is not yet used)"} *print-shared* nil) (def ^:dynamic ^{:doc "Don't print namespaces with symbols. This is particularly useful when pretty printing the results of macro expansions" :added "1.2"} *print-suppress-namespaces* nil) (def ^:dynamic ^{:doc "Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8, or 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the radix specifier is in the form #XXr where XX is the decimal value of *print-base* " :added "1.2"} *print-radix* nil) (def ^:dynamic ^{:doc "The base to use for printing integers and rationals." :added "1.2"} *print-base* 10) (def ^:dynamic ^{:private true} *current-level* 0) (def ^:dynamic ^{:private true} *current-length* nil) (declare ^{:arglists '([n])} format-simple-number) in advanced compilation . See CLJS-1853 - (defn- table-ize [t m] (apply hash-map (mapcat #(when-let [v (get t (key %))] [v (val %)]) m))) (defn- pretty-writer? "Return true iff x is a PrettyWriter" [x] (and (satisfies? IDeref x) (:pretty-writer @@x))) (defn- make-pretty-writer "Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width" [base-writer right-margin miser-width] (pretty-writer base-writer right-margin miser-width)) (defn write-out "Write an object to *out* subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). *out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility of the caller. This method is primarily intended for use by pretty print dispatch functions that already know that the pretty printer will have set up their environment appropriately. Normal library clients should use the standard \"write\" interface. " [object] (let [length-reached (and *current-length* *print-length* (>= *current-length* *print-length*))] (if-not *print-pretty* (pr object) (if length-reached TODO could this ( incorrectly ) print ... on the next line ? (do (if *current-length* (set! *current-length* (inc *current-length*))) (*print-pprint-dispatch* object)))) length-reached)) (defn write "Write an object subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). Returns the string result if :stream is nil or nil otherwise. The following keyword arguments can be passed with values: Keyword Meaning Default value :stream Writer for output or nil true (indicates *out*) :base Base to use for writing rationals Current value of *print-base* :circle* If true, mark circular structures Current value of *print-circle* :length Maximum elements to show in sublists Current value of *print-length* :level Maximum depth Current value of *print-level* :lines* Maximum lines of output Current value of *print-lines* :miser-width Width to enter miser mode Current value of *print-miser-width* :dispatch The pretty print dispatch function Current value of *print-pprint-dispatch* :pretty If true, do pretty printing Current value of *print-pretty* :radix If true, prepend a radix specifier Current value of *print-radix* :readably* If true, print readably Current value of *print-readably* :right-margin The column for the right margin Current value of *print-right-margin* :suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces* * = not yet supported " [object & kw-args] (let [options (merge {:stream true} (apply hash-map kw-args))] TODO rewrite this as a macro (binding [cljs.pprint/*print-base* (:base options cljs.pprint/*print-base*) cljs.pprint/*print-circle* (:circle options cljs.pprint/*print-circle*) : * print - gensym * cljs.core/*print-length* (:length options cljs.core/*print-length*) cljs.core/*print-level* (:level options cljs.core/*print-level*) cljs.pprint/*print-lines* (:lines options cljs.pprint/*print-lines*) cljs.pprint/*print-miser-width* (:miser-width options cljs.pprint/*print-miser-width*) cljs.pprint/*print-pprint-dispatch* (:dispatch options cljs.pprint/*print-pprint-dispatch*) cljs.pprint/*print-pretty* (:pretty options cljs.pprint/*print-pretty*) cljs.pprint/*print-radix* (:radix options cljs.pprint/*print-radix*) cljs.core/*print-readably* (:readably options cljs.core/*print-readably*) cljs.pprint/*print-right-margin* (:right-margin options cljs.pprint/*print-right-margin*) cljs.pprint/*print-suppress-namespaces* (:suppress-namespaces options cljs.pprint/*print-suppress-namespaces*)] TODO enable printing base #_[bindings (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})] (binding [] (let [sb (StringBuffer.) optval (if (contains? options :stream) (:stream options) true) base-writer (if (or (true? optval) (nil? optval)) (StringBufferWriter. sb) optval)] (if *print-pretty* (with-pretty-writer base-writer (write-out object)) (binding [*out* base-writer] (pr object))) (if (true? optval) (string-print (str sb))) (if (nil? optval) (str sb))))))) (defn pprint ([object] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] (pprint object *out*) (string-print (str sb))))) ([object writer] (with-pretty-writer writer (binding [*print-pretty* true] (write-out object)) (if (not (= 0 (get-column *out*))) (-write *out* \newline))))) (defn set-pprint-dispatch [function] (set! *print-pprint-dispatch* function) nil) (defn- check-enumerated-arg [arg choices] (if-not (choices arg) TODO clean up choices string (throw (js/Error. (str "Bad argument: " arg ". It must be one of " choices))))) (defn- level-exceeded [] (and *print-level* (>= *current-level* *print-level*))) (defn pprint-newline "Print a conditional newline to a pretty printing stream. kind specifies if the newline is :linear, :miser, :fill, or :mandatory. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [kind] (check-enumerated-arg kind #{:linear :miser :fill :mandatory}) (nl *out* kind)) (defn pprint-indent "Create an indent at this point in the pretty printing stream. This defines how following lines are indented. relative-to can be either :block or :current depending whether the indent should be computed relative to the start of the logical block or the current column position. n is an offset. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [relative-to n] (check-enumerated-arg relative-to #{:block :current}) (indent *out* relative-to n)) TODO a real implementation for pprint - tab (defn pprint-tab "Tab at this point in the pretty printing stream. kind specifies whether the tab is :line, :section, :line-relative, or :section-relative. Colnum and colinc specify the target column and the increment to move the target forward if the output is already past the original target. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer. THIS FUNCTION IS NOT YET IMPLEMENTED." {:added "1.2"} [kind colnum colinc] (check-enumerated-arg kind #{:line :section :line-relative :section-relative}) (throw (js/Error. "pprint-tab is not yet implemented"))) (declare ^{:arglists '([format-str])} compile-format) (declare ^{:arglists '([stream format args] [format args])} execute-format) (declare ^{:arglists '([s])} init-navigator) (defn cl-format "An implementation of a Common Lisp compatible format function. cl-format formats its arguments to an output stream or string based on the format control string given. It supports sophisticated formatting of structured data. Writer satisfies IWriter, true to output via *print-fn* or nil to output to a string, format-in is the format control string and the remaining arguments are the data to be formatted. The format control string is a string to be output with embedded 'format directives' describing how to format the various arguments passed in. If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format returns nil. For example: (let [results [46 38 22]] (cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\" (count results) results)) Prints via *print-fn*: There are 3 results: 46, 38, 22 Detailed documentation on format control strings is available in the \"Common Lisp the Language, 2nd edition\", Chapter 22 (available online at: -repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000) and in the Common Lisp HyperSpec at " {:see-also [["-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000" "Common Lisp the Language"] ["" "Common Lisp HyperSpec"]]} [writer format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format writer compiled-format navigator))) (def ^:dynamic ^{:private true} *format-str* nil) (defn- format-error [message offset] (let [full-message (str message \newline *format-str* \newline (apply str (repeat offset \space)) "^" \newline)] (throw (js/Error full-message)))) (defrecord ^{:private true} arg-navigator [seq rest pos]) (defn- init-navigator "Create a new arg-navigator from the sequence with the position set to 0" {:skip-wiki true} [s] (let [s (seq s)] (arg-navigator. s s 0))) (defn- next-arg [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] (throw (js/Error "Not enough arguments for format definition"))))) (defn- next-arg-or-nil [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] [nil navigator]))) (defn- get-format-arg [navigator] (let [[raw-format navigator] (next-arg navigator) compiled-format (if (string? raw-format) (compile-format raw-format) raw-format)] [compiled-format navigator])) (declare relative-reposition) (defn- absolute-reposition [navigator position] (if (>= position (:pos navigator)) (relative-reposition navigator (- (:pos navigator) position)) (arg-navigator. (:seq navigator) (drop position (:seq navigator)) position))) (defn- relative-reposition [navigator position] (let [newpos (+ (:pos navigator) position)] (if (neg? position) (absolute-reposition navigator newpos) (arg-navigator. (:seq navigator) (drop position (:rest navigator)) newpos)))) (defrecord ^{:private true} compiled-directive [func def params offset]) (defn- realize-parameter [[param [raw-val offset]] navigator] (let [[real-param new-navigator] (cond [raw-val navigator] (= raw-val :parameter-from-args) (next-arg navigator) (= raw-val :remaining-arg-count) [(count (:rest navigator)) navigator] true [raw-val navigator])] [[param [real-param offset]] new-navigator])) (defn- realize-parameter-list [parameter-map navigator] (let [[pairs new-navigator] (map-passing-context realize-parameter navigator parameter-map)] [(into {} pairs) new-navigator])) Common handling code for ~A and ~S (declare ^{:arglists '([base val])} opt-base-str) (def ^{:private true} special-radix-markers {2 "#b" 8 "#o" 16 "#x"}) (defn- format-simple-number [n] (cond (integer? n) (if (= *print-base* 10) (str n (if *print-radix* ".")) (str (if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r"))) (opt-base-str *print-base* n))) :else nil)) (defn- format-ascii [print-func params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator) base-output (or (format-simple-number arg) (print-func arg)) base-width (.-length base-output) min-width (+ base-width (:minpad params)) width (if (>= min-width (:mincol params)) min-width (+ min-width (* (+ (quot (- (:mincol params) min-width 1) (:colinc params)) 1) (:colinc params)))) chars (apply str (repeat (- width base-width) (:padchar params)))] (if (:at params) (print (str chars base-output)) (print (str base-output chars))) arg-navigator)) Support for the integer directives ~D , ~X , ~O , ~B and some of (defn- integral? "returns true if a number is actually an integer (that is, has no fractional part)" [x] (cond (integer? x) true (float? x) (= x (Math/floor x)) :else false)) (defn- remainders "Return the list of remainders (essentially the 'digits') of val in the given base" [base val] (reverse (first (consume #(if (pos? %) [(rem % base) (quot % base)] [nil nil]) val)))) NB (defn- base-str "Return val as a string in the given base" [base val] (if (zero? val) "0" (let [xlated-val (cond :else val)] (apply str (map #(if (< % 10) (char (+ (char-code \0) %)) (char (+ (char-code \a) (- % 10)))) (remainders base val)))))) (def ^{:private true} javascript-base-formats {8 "%o", 10 "%d", 16 "%x"}) (defn- opt-base-str "Return val as a string in the given base. No cljs format, so no improved performance." [base val] (base-str base val)) (defn- group-by* [unit lis] (reverse (first (consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis))))) (defn- format-integer [base params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator)] (if (integral? arg) (let [neg (neg? arg) pos-arg (if neg (- arg) arg) raw-str (opt-base-str base pos-arg) group-str (if (:colon params) (let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str)) commas (repeat (count groups) (:commachar params))] (apply str (next (interleave commas groups)))) raw-str) signed-str (cond neg (str "-" group-str) (:at params) (str "+" group-str) true group-str) padded-str (if (< (.-length signed-str) (:mincol params)) (str (apply str (repeat (- (:mincol params) (.-length signed-str)) (:padchar params))) signed-str) signed-str)] (print padded-str)) (format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0 :padchar (:padchar params) :at true} (init-navigator [arg]) nil)) arg-navigator)) Support for english formats ( ~R and ~:R ) (def ^{:private true} english-cardinal-units ["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"]) (def ^{:private true} english-ordinal-units ["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth" "thirteenth" "fourteenth" "fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"]) (def ^{:private true} english-cardinal-tens ["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"]) (def ^{:private true} english-ordinal-tens ["" "" "twentieth" "thirtieth" "fortieth" "fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth"]) We use " short scale " for our units ( see ) (def ^{:private true} english-scale-numbers ["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion" "sextillion" "septillion" "octillion" "nonillion" "decillion" "undecillion" "duodecillion" "tredecillion" "quattuordecillion" "quindecillion" "sexdecillion" "septendecillion" "octodecillion" "novemdecillion" "vigintillion"]) (defn- format-simple-cardinal "Convert a number less than 1000 to a cardinal english string" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-cardinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-cardinal-units unit-digit))))))))) (defn- add-english-scales "Take a sequence of parts, add scale numbers (e.g., million) and combine into a string offset is a factor of 10^3 to multiply by" [parts offset] (let [cnt (count parts)] (loop [acc [] pos (dec cnt) this (first parts) remainder (next parts)] (if (nil? remainder) (str (apply str (interpose ", " acc)) (if (and (not (empty? this)) (not (empty? acc))) ", ") this (if (and (not (empty? this)) (pos? (+ pos offset))) (str " " (nth english-scale-numbers (+ pos offset))))) (recur (if (empty? this) acc (conj acc (str this " " (nth english-scale-numbers (+ pos offset))))) (dec pos) (first remainder) (next remainder)))))) (defn- format-cardinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zero") parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal parts) full-str (add-english-scales parts-strs 0)] (print (str (if (neg? arg) "minus ") full-str))) for numbers > 10 ^ 63 , we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})))) navigator)) (defn- format-simple-ordinal "Convert a number less than 1000 to a ordinal english string Note this should only be used for the last one in the sequence" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-ordinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (if (and (pos? ten-digit) (not (pos? unit-digit))) (nth english-ordinal-tens ten-digit) (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-ordinal-units unit-digit)))))) (if (pos? hundreds) "th"))))) (defn- format-ordinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zeroth") parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal (drop-last parts)) head-str (add-english-scales parts-strs 1) tail-str (format-simple-ordinal (last parts))] (print (str (if (neg? arg) "minus ") (cond (and (not (empty? head-str)) (not (empty? tail-str))) (str head-str ", " tail-str) (not (empty? head-str)) (str head-str "th") :else tail-str)))) for numbers > 10 ^ 63 , we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0}) (let [low-two-digits (rem arg 100) not-teens (or (< 11 low-two-digits) (> 19 low-two-digits)) low-digit (rem low-two-digits 10)] (print (cond (and (== low-digit 1) not-teens) "st" (and (== low-digit 2) not-teens) "nd" (and (== low-digit 3) not-teens) "rd" :else "th"))))))) navigator)) Support for roman numeral formats ( ~@R and ~@:R ) (def ^{:private true} old-roman-table [[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"] [ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"] [ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"] [ "M" "MM" "MMM"]]) (def ^{:private true} new-roman-table [[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"] [ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"] [ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"] [ "M" "MM" "MMM"]]) (defn- format-roman "Format a roman numeral using the specified look-up table" [table params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (and (number? arg) (> arg 0) (< arg 4000)) (let [digits (remainders 10 arg)] (loop [acc [] pos (dec (count digits)) digits digits] (if (empty? digits) (print (apply str acc)) (let [digit (first digits)] (recur (if (= 0 digit) acc (conj acc (nth (nth table pos) (dec digit)))) (dec pos) (next digits)))))) for anything < = 0 or > 3999 , we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})) navigator)) (defn- format-old-roman [params navigator offsets] (format-roman old-roman-table params navigator offsets)) (defn- format-new-roman [params navigator offsets] (format-roman new-roman-table params navigator offsets)) (def ^{:private true} special-chars {8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"}) (defn- pretty-character [params navigator offsets] (let [[c navigator] (next-arg navigator) as-int (char-code c) base-char (bit-and as-int 127) meta (bit-and as-int 128) special (get special-chars base-char)] (if (> meta 0) (print "Meta-")) (print (cond special special (< base-char 32) (str "Control-" (char (+ base-char 64))) (= base-char 127) "Control-?" :else (char base-char))) navigator)) (defn- readable-character [params navigator offsets] (let [[c navigator] (next-arg navigator)] (condp = (:char-format params) \o (cl-format true "\\o~3, '0o" (char-code c)) \u (cl-format true "\\u~4, '0x" (char-code c)) nil (print-char c)) navigator)) (defn- plain-character [params navigator offsets] (let [[char navigator] (next-arg navigator)] (print char) navigator)) (defn- abort? [context] (let [token (first context)] (or (= :up-arrow token) (= :colon-up-arrow token)))) (defn- execute-sub-format [format args base-args] (second (map-passing-context (fn [element context] (if (abort? context) (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args base-args)] [nil (apply (:func element) [params args offsets])]))) args format))) (defn- float-parts-base "Produce string parts for the mantissa (normalize 1-9) and exponent" [f] (let [s (string/lower-case (str f)) exploc (.indexOf s \e) dotloc (.indexOf s \.)] (if (neg? exploc) (if (neg? dotloc) [s (str (dec (count s)))] [(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))]) (if (neg? dotloc) [(subs s 0 exploc) (subs s (inc exploc))] [(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))])))) (defn- float-parts "Take care of leading and trailing zeros in decomposed floats" [f] (let [[m e] (float-parts-base f) m1 (rtrim m \0) m2 (ltrim m1 \0) delta (- (count m1) (count m2)) e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)] (if (empty? m2) ["0" 0] [m2 (- (js/parseInt e 10) delta)]))) (defn- inc-s "Assumption: The input string consists of one or more decimal digits, and no other characters. Return a string containing one or more decimal digits containing a decimal number one larger than the input string. The output string will always be the same length as the input string, or one character longer." [s] (let [len-1 (dec (count s))] (loop [i (int len-1)] (cond (neg? i) (apply str "1" (repeat (inc len-1) "0")) (= \9 (.charAt s i)) (recur (dec i)) :else (apply str (subs s 0 i) (char (inc (char-code (.charAt s i)))) (repeat (- len-1 i) "0")))))) (defn- round-str [m e d w] (if (or d w) (let [len (count m) w (if w (max 2 w) satisfy the cond below . gives a compilation warning if 0) round-pos (cond d (+ e d 1) If e>=0 , then abs value of number is > = 1.0 , and e+1 is number of decimal digits before the (>= e 0) (max (inc e) (dec w)) e < 0 , so number abs value < 1.0 :else (+ w e)) [m1 e1 round-pos len] (if (= round-pos 0) [(str "0" m) (inc e) 1 (inc len)] [m e round-pos len])] (if round-pos (if (neg? round-pos) ["0" 0 false] (if (> len round-pos) (let [round-char (nth m1 round-pos) result (subs m1 0 round-pos)] (if (>= (char-code round-char) (char-code \5)) (let [round-up-result (inc-s result) expanded (> (count round-up-result) (count result))] [(if expanded (subs round-up-result 0 (dec (count round-up-result))) round-up-result) e1 expanded]) [result e1 false])) [m e false])) [m e false])) [m e false])) (defn- expand-fixed [m e d] (let [[m1 e1] (if (neg? e) [(str (apply str (repeat (dec (- e)) \0)) m) -1] [m e]) len (count m1) target-len (if d (+ e1 d 1) (inc e1))] (if (< len target-len) (str m1 (apply str (repeat (- target-len len) \0))) m1))) (defn- insert-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m e] (if (neg? e) (str "." m) (let [loc (inc e)] (str (subs m 0 loc) "." (subs m loc))))) (defn- get-fixed [m e d] (insert-decimal (expand-fixed m e d) e)) (defn- insert-scaled-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m k] (if (neg? k) (str "." m) (str (subs m 0 k) "." (subs m k)))) (defn- convert-ratio [x] x) (defn- fixed-float [params navigator offsets] (let [w (:w params) d (:d params) [arg navigator] (next-arg navigator) [sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg]) abs (convert-ratio abs) [mantissa exp] (float-parts abs) scaled-exp (+ exp (:k params)) add-sign (or (:at params) (neg? arg)) append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp)) [rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp d (if w (- w (if add-sign 1 0)))) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) fixed-repr (if (and w d (>= d 1) (= (.charAt fixed-repr 0) \0) (= (.charAt fixed-repr 1) \.) (> (count fixed-repr) (- w (if add-sign 1 0)))) fixed-repr) prepend-zero (= (first fixed-repr) \.)] (if w (let [len (count fixed-repr) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (>= signed-len w))) append-zero (and append-zero (not (>= signed-len w))) full-len (if (or prepend-zero append-zero) (inc signed-len) signed-len)] (if (and (> full-len w) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len) (:padchar params))) (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0"))))) (print (str (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0")))) navigator)) TODO : define ~E representation for Infinity (defn- exponential-float [params navigator offset] (let [[arg navigator] (next-arg navigator) arg (convert-ratio arg)] (loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))] (let [w (:w params) d (:d params) e (:e params) k (:k params) expchar (or (:exponentchar params) \E) add-sign (or (:at params) (neg? arg)) prepend-zero (<= k 0) scaled-exp (- exp (dec k)) scaled-exp-str (str (Math/abs scaled-exp)) scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+) (if e (apply str (repeat (- e (count scaled-exp-str)) \0))) scaled-exp-str) exp-width (count scaled-exp-str) base-mantissa-width (count mantissa) scaled-mantissa (str (apply str (repeat (- k) \0)) mantissa (if d (apply str (repeat (- d (dec base-mantissa-width) (if (neg? k) (- k) 0)) \0)))) w-mantissa (if w (- w exp-width)) [rounded-mantissa _ incr-exp] (round-str scaled-mantissa 0 (cond (= k 0) (dec d) (pos? k) d (neg? k) (dec d)) (if w-mantissa (- w-mantissa (if add-sign 1 0)))) full-mantissa (insert-scaled-decimal rounded-mantissa k) append-zero (and (= k (count rounded-mantissa)) (nil? d))] (if (not incr-exp) (if w (let [len (+ (count full-mantissa) exp-width) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (= signed-len w))) full-len (if prepend-zero (inc signed-len) signed-len) append-zero (and append-zero (< full-len w))] (if (and (or (> full-len w) (and e (> (- exp-width 2) e))) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len (if append-zero 1 0)) (:padchar params))) (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str)))) (print (str (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str))) (recur [rounded-mantissa (inc exp)])))) navigator)) (defn- general-float [params navigator offsets] (let [[arg _] (next-arg navigator) arg (convert-ratio arg) [mantissa exp] (float-parts (if (neg? arg) (- arg) arg)) w (:w params) d (:d params) e (:e params) n (if (= arg 0.0) 0 (inc exp)) ee (if e (+ e 2) 4) ww (if w (- w ee)) d (if d d (max (count mantissa) (min n 7))) dd (- d n)] (if (<= 0 dd d) (let [navigator (fixed-float {:w ww, :d dd, :k 0, :overflowchar (:overflowchar params), :padchar (:padchar params), :at (:at params)} navigator offsets)] (print (apply str (repeat ee \space))) navigator) (exponential-float params navigator offsets)))) (defn- dollar-float [params navigator offsets] (let [[arg navigator] (next-arg navigator) [mantissa exp] (float-parts (Math/abs arg)) add-sign (or (:at params) (neg? arg)) [rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) full-repr (str (apply str (repeat (- n (.indexOf fixed-repr \.)) \0)) fixed-repr) full-len (+ (count full-repr) (if add-sign 1 0))] (print (str (if (and (:colon params) add-sign) (if (neg? arg) \- \+)) (apply str (repeat (- w full-len) (:padchar params))) (if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+)) full-repr)) navigator)) ~[ ... ~ ] without any modifiers chooses one of the clauses based on the param or TODO check arg is positive int (defn- choice-conditional [params arg-navigator offsets] (let [arg (:selector params) [arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator)) clauses (:clauses params) clause (if (or (neg? arg) (>= arg (count clauses))) (first (:else params)) (nth clauses arg))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) (defn- boolean-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (second clauses) (first clauses))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) (defn- check-arg-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (first clauses))] (if arg (if clause (execute-sub-format clause arg-navigator (:base-args params)) arg-navigator) navigator))) (defn- iterate-sublist [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator) args (init-navigator arg-list)] (loop [count 0 args args last-pos (int -1)] (if (and (not max-count) (= (:pos args) last-pos) (> count 1)) TODO get the offset in here and call format exception (throw (js/Error "%{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest args)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause args (:base-args params))] (if (= :up-arrow (first iter-result)) navigator (recur (inc count) iter-result (:pos args)))))))) (defn- iterate-list-of-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator)] (loop [count 0 arg-list arg-list] (if (or (and (empty? arg-list) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause (init-navigator (first arg-list)) (init-navigator (next arg-list)))] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) (next arg-list)))))))) (defn- iterate-main-list [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator last-pos (int -1)] (if (and (not max-count) (= (:pos navigator) last-pos) (> count 1)) TODO get the offset in here and call format exception (throw (js/Error "%@{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause navigator (:base-args params))] (if (= :up-arrow (first iter-result)) (second iter-result) (recur (inc count) iter-result (:pos navigator)))))))) ~@:{ ... ~ } with both colon and at sign uses the main argument list as a set of sublists , one (defn- iterate-main-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator] (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [[sublist navigator] (next-arg-or-nil navigator) iter-result (execute-sub-format clause (init-navigator sublist) navigator)] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) navigator))))))) The ' ~ < directive has two completely different meanings (declare ^{:arglists '([params navigator offsets])} format-logical-block) (declare ^{:arglists '([params navigator offsets])} justify-clauses) (defn- logical-block-or-justify [params navigator offsets] (if (:colon (:right-params params)) (format-logical-block params navigator offsets) (justify-clauses params navigator offsets))) (defn- render-clauses [clauses navigator base-navigator] (loop [clauses clauses acc [] navigator navigator] (if (empty? clauses) [acc navigator] (let [clause (first clauses) [iter-result result-str] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] [(execute-sub-format clause navigator base-navigator) (str sb)]))] (if (= :up-arrow (first iter-result)) [acc (second iter-result)] (recur (next clauses) (conj acc result-str) iter-result)))))) (defn- justify-clauses [params navigator offsets] (let [[[eol-str] new-navigator] (when-let [else (:else params)] (render-clauses else navigator (:base-args params))) navigator (or new-navigator navigator) [else-params new-navigator] (when-let [p (:else-params params)] (realize-parameter-list p navigator)) navigator (or new-navigator navigator) min-remaining (or (first (:min-remaining else-params)) 0) max-columns (or (first (:max-columns else-params)) (get-max-column *out*)) clauses (:clauses params) [strs navigator] (render-clauses clauses navigator (:base-args params)) slots (max 1 (+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0))) chars (reduce + (map count strs)) mincol (:mincol params) minpad (:minpad params) colinc (:colinc params) minout (+ chars (* slots minpad)) result-columns (if (<= minout mincol) mincol (+ mincol (* colinc (+ 1 (quot (- minout mincol 1) colinc))))) total-pad (- result-columns chars) pad (max minpad (quot total-pad slots)) extra-pad (- total-pad (* pad slots)) pad-str (apply str (repeat pad (:padchar params)))] (if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns) max-columns)) (print eol-str)) (loop [slots slots extra-pad extra-pad strs strs pad-only (or (:colon params) (and (= (count strs) 1) (not (:at params))))] (if (seq strs) (do (print (str (if (not pad-only) (first strs)) (if (or pad-only (next strs) (:at params)) pad-str) (if (pos? extra-pad) (:padchar params)))) (recur (dec slots) (dec extra-pad) (if pad-only strs (next strs)) false)))) navigator)) (defn- downcase-writer "Returns a proxy that wraps writer, converting all characters to lower case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/lower-case s))) js/Number (let [c x] TODO need to enforce integers only ? (-write writer (string/lower-case (char c)))))))) (defn- upcase-writer "Returns a proxy that wraps writer, converting all characters to upper case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/upper-case s))) js/Number (let [c x] TODO need to enforce integers only ? (-write writer (string/upper-case (char c)))))))) (defn- capitalize-string "Capitalizes the words in a string. If first? is false, don't capitalize the first character of the string even if it's a letter." [s first?] (let [f (first s) s (if (and first? f (gstring/isUnicodeChar f)) (str (string/upper-case f) (subs s 1)) s)] (apply str (first (consume (fn [s] (if (empty? s) [nil nil] (let [m (.exec (js/RegExp "\\W\\w" "g") s) offset (and m (inc (.-index m)))] (if offset [(str (subs s 0 offset) (string/upper-case (nth s offset))) (subs s (inc offset))] [s nil])))) s))))) (defn- capitalize-word-writer "Returns a proxy that wraps writer, capitalizing all words" [writer] (let [last-was-whitespace? (atom true)] (reify IWriter (-flush [_] (-flush writer)) (-write #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (capitalize-string (.toLowerCase s) @last-was-whitespace?)) (when (pos? (.-length s)) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace (nth s (dec (count s))))))) js/Number (let [c (char x)] (let [mod-c (if @last-was-whitespace? (string/upper-case c) c)] (-write writer mod-c) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace c))))))))) (defn- init-cap-writer "Returns a proxy that wraps writer, capitalizing the first word" [writer] (let [capped (atom false)] (reify IWriter (-flush [_] (-flush writer)) (-write #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s (string/lower-case x)] (if (not @capped) (let [m (.exec (js/RegExp "\\S" "g") s) offset (and m (.-index m))] (if offset (do (-write writer (str (subs s 0 offset) (string/upper-case (nth s offset)) (string/lower-case (subs s (inc offset))))) (reset! capped true)) (-write writer s))) (-write writer (string/lower-case s)))) js/Number (let [c (char x)] (if (and (not @capped) (gstring/isUnicodeChar c)) (do (reset! capped true) (-write writer (string/upper-case c))) (-write writer (string/lower-case c))))))))) (defn- modify-case [make-writer params navigator offsets] (let [clause (first (:clauses params))] (binding [*out* (make-writer *out*)] (execute-sub-format clause navigator (:base-args params))))) If necessary , wrap the writer in a PrettyWriter object TODO update this doc string to show correct way to print (defn get-pretty-writer "Returns the IWriter passed in wrapped in a pretty writer proxy, unless it's already a pretty writer. Generally, it is unnecessary to call this function, since pprint, write, and cl-format all call it if they need to. However if you want the state to be preserved across calls, you will want to wrap them with this. For example, when you want to generate column-aware output with multiple calls to cl-format, do it like in this example: (defn print-table [aseq column-width] (binding [*out* (get-pretty-writer *out*)] (doseq [row aseq] (doseq [col row] (cl-format true \"~4D~7,vT\" col column-width)) (prn)))) Now when you run: user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8) It prints a table of squares and cubes for the numbers from 1 to 10: 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000" [writer] (if (pretty-writer? writer) writer (pretty-writer writer *print-right-margin* *print-miser-width*))) (defn fresh-line "Make a newline if *out* is not already at the beginning of the line. If *out* is not a pretty writer (which keeps track of columns), this function always outputs a newline." [] (if (satisfies? IDeref *out*) (if (not (= 0 (get-column (:base @@*out*)))) (prn)) (prn))) (defn- absolute-tabulation [params navigator offsets] (let [colnum (:colnum params) colinc (:colinc params) current (get-column (:base @@*out*)) space-count (cond (< current colnum) (- colnum current) (= colinc 0) 0 :else (- colinc (rem (- current colnum) colinc)))] (print (apply str (repeat space-count \space)))) navigator) (defn- relative-tabulation [params navigator offsets] (let [colrel (:colnum params) colinc (:colinc params) start-col (+ colrel (get-column (:base @@*out*))) offset (if (pos? colinc) (rem start-col colinc) 0) space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))] (print (apply str (repeat space-count \space)))) navigator) (defn- format-logical-block [params navigator offsets] (let [clauses (:clauses params) clause-count (count clauses) prefix (cond (> clause-count 1) (:string (:params (first (first clauses)))) (:colon params) "(") body (nth clauses (if (> clause-count 1) 1 0)) suffix (cond (> clause-count 2) (:string (:params (first (nth clauses 2)))) (:colon params) ")") [arg navigator] (next-arg navigator)] (pprint-logical-block :prefix prefix :suffix suffix (execute-sub-format body (init-navigator arg) (:base-args params))) navigator)) (defn- set-indent [params navigator offsets] (let [relative-to (if (:colon params) :current :block)] (pprint-indent relative-to (:n params)) navigator)) (defn- conditional-newline [params navigator offsets] (let [kind (if (:colon params) (if (:at params) :mandatory :fill) (if (:at params) :miser :linear))] (pprint-newline kind) navigator)) (defdirectives (\A [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii print-str %1 %2 %3)) (\S [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii pr-str %1 %2 %3)) (\D [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 10 %1 %2 %3)) (\B [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 2 %1 %2 %3)) (\O [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 8 %1 %2 %3)) (\X [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 16 %1 %2 %3)) (\R [:base [nil js/Number] :mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} (do (first (:base params)) #(format-integer (:base %1) %1 %2 %3) (and (:at params) (:colon params)) #(format-old-roman %1 %2 %3) (:at params) #(format-new-roman %1 %2 %3) (:colon params) #(format-ordinal-english %1 %2 %3) true #(format-cardinal-english %1 %2 %3)))) (\P [] #{:at :colon :both} {} (fn [params navigator offsets] (let [navigator (if (:colon params) (relative-reposition navigator -1) navigator) strs (if (:at params) ["y" "ies"] ["" "s"]) [arg navigator] (next-arg navigator)] (print (if (= arg 1) (first strs) (second strs))) navigator))) (\C [:char-format [nil js/String]] #{:at :colon :both} {} (cond (:colon params) pretty-character (:at params) readable-character :else plain-character)) (\F [:w [nil js/Number] :d [nil js/Number] :k [0 js/Number] :overflowchar [nil js/String] :padchar [\space js/String]] #{:at} {} fixed-float) (\E [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} exponential-float) (\G [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} general-float) (\$ [:d [2 js/Number] :n [1 js/Number] :w [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} dollar-float) (\% [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (prn)) arg-navigator)) (\& [:count [1 js/Number]] #{:pretty} {} (fn [params arg-navigator offsets] (let [cnt (:count params)] (if (pos? cnt) (fresh-line)) (dotimes [i (dec cnt)] (prn))) arg-navigator)) (\| [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (print \formfeed)) arg-navigator)) (\~ [:n [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (let [n (:n params)] (print (apply str (repeat n \~))) arg-navigator))) Whitespace supression is handled in the compilation loop [] #{:colon :at} {} (fn [params arg-navigator offsets] (if (:at params) (prn)) arg-navigator)) (\T [:colnum [1 js/Number] :colinc [1 js/Number]] #{:at :pretty} {} (if (:at params) #(relative-tabulation %1 %2 %3) #(absolute-tabulation %1 %2 %3))) (\* [:n [1 js/Number]] #{:colon :at} {} (fn [params navigator offsets] (let [n (:n params)] (if (:at params) (absolute-reposition navigator n) (relative-reposition navigator (if (:colon params) (- n) n)))))) (\? [] #{:at} {} (if (:at params) (let [[subformat navigator] (get-format-arg navigator)] (execute-sub-format subformat navigator (:base-args params)))) (let [[subformat navigator] (get-format-arg navigator) [subargs navigator] (next-arg navigator) sub-navigator (init-navigator subargs)] (execute-sub-format subformat sub-navigator (:base-args params)) navigator)))) (\( [] #{:colon :at :both} {:right \), :allows-separator nil, :else nil} (let [mod-case-writer (cond (and (:at params) (:colon params)) upcase-writer (:colon params) capitalize-word-writer (:at params) init-cap-writer :else downcase-writer)] #(modify-case mod-case-writer %1 %2 %3))) (\) [] #{} {} nil) (\[ [:selector [nil js/Number]] #{:colon :at} {:right \], :allows-separator true, :else :last} (cond (:colon params) boolean-conditional (:at params) check-arg-conditional true choice-conditional)) #{:colon} {:separator true} nil) (\] [] #{} {} nil) (\{ [:max-iterations [nil js/Number]] #{:colon :at :both} {:right \}, :allows-separator false} (cond (and (:at params) (:colon params)) iterate-main-sublists (:colon params) iterate-list-of-sublists (:at params) iterate-main-list true iterate-sublist)) (\} [] #{:colon} {} nil) (\< [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:colon :at :both :pretty} {:right \>, :allows-separator true, :else :first} logical-block-or-justify) (\> [] #{:colon} {} nil) (\^ [:arg1 [nil js/Number] :arg2 [nil js/Number] :arg3 [nil js/Number]] #{:colon} {} (fn [params navigator offsets] (let [arg1 (:arg1 params) arg2 (:arg2 params) arg3 (:arg3 params) exit (if (:colon params) :colon-up-arrow :up-arrow)] (cond (and arg1 arg2 arg3) (if (<= arg1 arg2 arg3) [exit navigator] navigator) (and arg1 arg2) (if (= arg1 arg2) [exit navigator] navigator) arg1 (if (= arg1 0) [exit navigator] navigator) (if (if (:colon params) (empty? (:rest (:base-args params))) (empty? (:rest navigator))) [exit navigator] navigator))))) (\W [] #{:at :colon :both :pretty} {} (if (or (:at params) (:colon params)) (let [bindings (concat (if (:at params) [:level nil :length nil] []) (if (:colon params) [:pretty true] []))] (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (apply write arg bindings) [:up-arrow navigator] navigator)))) (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (write-out arg) [:up-arrow navigator] navigator))))) (\_ [] #{:at :colon :both} {} conditional-newline) (\I [:n [0 js/Number]] #{:colon} {} set-indent) ) (def ^{:private true} param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))") (def ^{:private true} special-params #{:parameter-from-args :remaining-arg-count}) (defn- extract-param [[s offset saw-comma]] (let [m (js/RegExp. (.-source param-pattern) "g") param (.exec m s)] (if param (let [token-str (first param) remainder (subs s (.-lastIndex m)) new-offset (+ offset (.-lastIndex m))] (if (not (= \, (nth remainder 0))) [[token-str offset] [remainder new-offset false]] [[token-str offset] [(subs remainder 1) (inc new-offset) true]])) (if saw-comma (format-error "Badly formed parameters in format directive" offset) [nil [s offset]])))) (defn- extract-params [s offset] (consume extract-param [s offset false])) (defn- translate-param "Translate the string representation of a param to the internalized representation" [[p offset]] [(cond (= (.-length p) 0) nil (and (= (.-length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args (and (= (.-length p) 1) (= \# (nth p 0))) :remaining-arg-count (and (= (.-length p) 2) (= \' (nth p 0))) (nth p 1) true (js/parseInt p 10)) offset]) (def ^{:private true} flag-defs {\: :colon, \@ :at}) (defn- extract-flags [s offset] (consume (fn [[s offset flags]] (if (empty? s) [nil [s offset flags]] (let [flag (get flag-defs (first s))] (if flag (if (contains? flags flag) (format-error (str "Flag \"" (first s) "\" appears more than once in a directive") offset) [true [(subs s 1) (inc offset) (assoc flags flag [true offset])]]) [nil [s offset flags]])))) [s offset {}])) (defn- check-flags [def flags] (let [allowed (:flags def)] (if (and (not (:at allowed)) (:at flags)) (format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:at flags) 1))) (if (and (not (:colon allowed)) (:colon flags)) (format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:colon flags) 1))) (if (and (not (:both allowed)) (:at flags) (:colon flags)) (format-error (str "Cannot combine \"@\" and \":\" flags for format directive \"" (:directive def) "\"") (min (nth (:colon flags) 1) (nth (:at flags) 1)))))) (defn- map-params "Takes a directive definition and the list of actual parameters and a map of flags and returns a map of the parameters and flags with defaults filled in. We check to make sure that there are the right types and number of parameters as well." [def params flags offset] (check-flags def flags) (if (> (count params) (count (:params def))) (format-error (cl-format nil "Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed" (:directive def) (count params) (count (:params def))) (second (first params)))) (doall (map #(let [val (first %1)] (if (not (or (nil? val) (contains? special-params val) (= (second (second %2)) (type val)))) (format-error (str "Parameter " (name (first %2)) " has bad type in directive \"" (:directive def) "\": " (type val)) (second %1))) ) params (:params def))) (reverse (for [[name [default]] (:params def)] [name [default offset]]))) add the specified parameters , filtering out nils (defn- compile-directive [s offset] (let [[raw-params [rest offset]] (extract-params s offset) [_ [rest offset flags]] (extract-flags rest offset) directive (first rest) def (get directive-table (string/upper-case directive)) params (if def (map-params def (map translate-param raw-params) flags offset))] (if (not directive) (format-error "Format string ended in the middle of a directive" offset)) (if (not def) (format-error (str "Directive \"" directive "\" is undefined") offset)) [(compiled-directive. ((:generator-fn def) params offset) def params offset) (let [remainder (subs rest 1) offset (inc offset) trim? (and (= \newline (:directive def)) (not (:colon params))) trim-count (if trim? (prefix-count remainder [\space \tab]) 0) remainder (subs remainder trim-count) offset (+ offset trim-count)] [remainder offset])])) (defn- compile-raw-string [s offset] (compiled-directive. (fn [_ a _] (print s) a) nil {:string s} offset)) (defn- right-bracket [this] (:right (:bracket-info (:def this)))) (defn- separator? [this] (:separator (:bracket-info (:def this)))) (defn- else-separator? [this] (and (:separator (:bracket-info (:def this))) (:colon (:params this)))) (declare ^{:arglists '([bracket-info offset remainder])} collect-clauses) (defn- process-bracket [this remainder] (let [[subex remainder] (collect-clauses (:bracket-info (:def this)) (:offset this) remainder)] [(compiled-directive. (:func this) (:def this) (merge (:params this) (tuple-map subex (:offset this))) (:offset this)) remainder])) (defn- process-clause [bracket-info offset remainder] (consume (fn [remainder] (if (empty? remainder) (format-error "No closing bracket found." offset) (let [this (first remainder) remainder (next remainder)] (cond (right-bracket this) (process-bracket this remainder) (= (:right bracket-info) (:directive (:def this))) [ nil [:right-bracket (:params this) nil remainder]] (else-separator? this) [nil [:else nil (:params this) remainder]] (separator? this) true [this remainder])))) remainder)) (defn- collect-clauses [bracket-info offset remainder] (second (consume (fn [[clause-map saw-else remainder]] (let [[clause [type right-params else-params remainder]] (process-clause bracket-info offset remainder)] (cond (= type :right-bracket) [nil [(merge-with concat clause-map {(if saw-else :else :clauses) [clause] :right-params right-params}) remainder]] (= type :else) (cond (:else clause-map) \") inside bracket construction . " offset ) (not (:else bracket-info)) \") is in a bracket type that does n't support it . " offset) (and (= :first (:else bracket-info)) (seq (:clauses clause-map))) (format-error \") is only allowed in the first position for this directive . " offset) (if (= :first (:else bracket-info)) [true [(merge-with concat clause-map {:else [clause] :else-params else-params}) false remainder]] [true [(merge-with concat clause-map {:clauses [clause]}) true remainder]])) (= type :separator) (cond saw-else (not (:allows-separator bracket-info)) \") is in a bracket type that does n't support it . " offset) true [true [(merge-with concat clause-map {:clauses [clause]}) false remainder]])))) [{:clauses []} false remainder]))) (defn- process-nesting "Take a linearly compiled format and process the bracket directives to give it the appropriate tree structure" [format] (first (consume (fn [remainder] (let [this (first remainder) remainder (next remainder) bracket (:bracket-info (:def this))] (if (:right bracket) (process-bracket this remainder) [this remainder]))) format))) (defn- compile-format "Compiles format-str into a compiled format which can be used as an argument to cl-format just like a plain format string. Use this function for improved performance when you're using the same format string repeatedly" [format-str] (binding [*format-str* format-str] (process-nesting (first (consume (fn [[s offset]] (if (empty? s) [nil s] (let [tilde (.indexOf s \~)] (cond (neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.-length s))]] (zero? tilde) (compile-directive (subs s 1) (inc offset)) true [(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]])))) [format-str 0]))))) (defn- needs-pretty "determine whether a given compiled format has any directives that depend on the column number or pretty printing" [format] (loop [format format] (if (empty? format) false (if (or (:pretty (:flags (:def (first format)))) (some needs-pretty (first (:clauses (:params (first format))))) (some needs-pretty (first (:else (:params (first format)))))) true (recur (next format)))))) NB We depart from the original api . In clj , if execute - format is called multiple times with the same stream or * stream = > " 1 2 3 " * true ( prints to * out * ) = > " 1 2 3 " * stream = > " 1 2 3 " (defn- execute-format "Executes the format with the arguments." {:skip-wiki true} ([stream format args] (let [sb (StringBuffer.) real-stream (if (or (not stream) (true? stream)) (StringBufferWriter. sb) stream) wrapped-stream (if (and (needs-pretty format) (not (pretty-writer? real-stream))) (get-pretty-writer real-stream) real-stream)] (binding [*out* wrapped-stream] (try (execute-format format args) (finally (if-not (identical? real-stream wrapped-stream) (-flush wrapped-stream)))) (cond (not stream) (str sb) (true? stream) (string-print (str sb)) :else nil)))) ([format args] (map-passing-context (fn [element context] (if (abort? context) [nil context] (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args args)] [nil (apply (:func element) [params args offsets])]))) args format) nil)) (def ^{:private true} cached-compile (memoize compile-format)) dispatch.clj (defn- use-method "Installs a function as a new method of multimethod associated with dispatch-value. " [multifn dispatch-val func] (-add-method multifn dispatch-val func)) Macros that we ca n't deal with at all are : ` - Is fully processed at read time into a lisp expression ( which will contain concats or directly by printing the objects using Clojure 's built - in print functions ( like : keyword , \char , or " " ) . The notable exception is # ( ) which is special - cased . (def ^{:private true} reader-macros {'quote "'" 'var "#'" 'clojure.core/deref "@", 'clojure.core/unquote "~" 'cljs.core/deref "@", 'cljs.core/unquote "~"}) (defn- pprint-reader-macro [alis] (let [macro-char (reader-macros (first alis))] (when (and macro-char (= 2 (count alis))) (-write *out* macro-char) (write-out (second alis)) true))) Dispatch for the basic data types when interpreted ( def pprint - simple - list ( formatter - out " ~:<~@{~w~^ ~_~}~ :> " ) ) (defn- pprint-simple-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) (defn- pprint-list [alis] (if-not (pprint-reader-macro alis) (pprint-simple-list alis))) (defn- pprint-vector [avec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [aseq (seq avec)] (when aseq (write-out (first aseq)) (when (next aseq) (-write *out* " ") (pprint-newline :linear) (recur (next aseq))))))) (def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>")) (defn- pprint-map [amap] (let [[ns lift-map] (when (not (record? amap)) (#'cljs.core/lift-ns amap)) amap (or lift-map amap) prefix (if ns (str "#:" ns "{") "{")] (pprint-logical-block :prefix prefix :suffix "}" (print-length-loop [aseq (seq amap)] (when aseq it tries to use clojure.pprint/pprint-logical-block for some reason (m/pprint-logical-block (write-out (ffirst aseq)) (-write *out* " ") (pprint-newline :linear) (write-out (fnext (first aseq)))) (when (next aseq) (-write *out* ", ") (pprint-newline :linear) (recur (next aseq)))))))) (defn- pprint-simple-default [obj] (-write *out* (pr-str obj))) (def pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>")) (def ^{:private true} type-map {"core$future_call" "Future", "core$promise" "Promise"}) (defn- map-ref-type "Map ugly type names to something simpler" [name] (or (when-let [match (re-find #"^[^$]+\$[^$]+" name)] (type-map match)) name)) (defn- pprint-ideref [o] (let [prefix (str "#<" (map-ref-type (.-name (type o))) "@" (goog/getUid o) ": ")] (pprint-logical-block :prefix prefix :suffix ">" (pprint-indent :block (-> (count prefix) (- 2) -)) (pprint-newline :linear) (write-out (if (and (satisfies? IPending o) (not (-realized? o))) :not-delivered @o))))) (def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>")) (defn- type-dispatcher [obj] (cond (instance? PersistentQueue obj) :queue (satisfies? IDeref obj) :deref (symbol? obj) :symbol (seq? obj) :list (map? obj) :map (vector? obj) :vector (set? obj) :set (nil? obj) nil :default :default)) (defmulti simple-dispatch "The pretty print dispatch function for simple data structure format." type-dispatcher) (use-method simple-dispatch :list pprint-list) (use-method simple-dispatch :vector pprint-vector) (use-method simple-dispatch :map pprint-map) (use-method simple-dispatch :set pprint-set) (use-method simple-dispatch nil #(-write *out* (pr-str nil))) (use-method simple-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) Dispatch for the code table (declare ^{:arglists '([alis])} pprint-simple-code-list) (defn- brackets "Figure out which kind of brackets to use" [form] (if (vector? form) ["[" "]"] ["(" ")"])) (defn- pprint-ns-reference "Pretty print a single reference (import, use, etc.) from a namespace decl" [reference] (if (sequential? reference) (let [[start end] (brackets reference) [keyw & args] reference] (pprint-logical-block :prefix start :suffix end ((formatter-out "~w~:i") keyw) (loop [args args] (when (seq args) ((formatter-out " ")) (let [arg (first args)] (if (sequential? arg) (let [[start end] (brackets arg)] (pprint-logical-block :prefix start :suffix end (if (and (= (count arg) 3) (keyword? (second arg))) (let [[ns kw lis] arg] ((formatter-out "~w ~w ") ns kw) (if (sequential? lis) ((formatter-out (if (vector? lis) "~<[~;~@{~w~^ ~:_~}~;]~:>" "~<(~;~@{~w~^ ~:_~}~;)~:>")) lis) (write-out lis))) (apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg))) (when (next args) ((formatter-out "~_")))) (do (write-out arg) (when (next args) ((formatter-out "~:_")))))) (recur (next args)))))) (write-out reference))) (defn- pprint-ns "The pretty print dispatch chunk for the ns macro" [alis] (if (next alis) (let [[ns-sym ns-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map references] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") ns-sym ns-name) (when (or doc-str attr-map (seq references)) ((formatter-out "~@:_"))) (when doc-str (cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references)))) (when attr-map ((formatter-out "~w~:[~;~:@_~]") attr-map (seq references))) (loop [references references] (pprint-ns-reference (first references)) (when-let [references (next references)] (pprint-newline :linear) (recur references))))) (write-out alis))) Format something that looks like a simple def ( sans metadata , since the reader (def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>")) Format something that looks like a defn or defmacro (defn- single-defn [alis has-doc-str?] (if (seq alis) (do (if has-doc-str? ((formatter-out " ~_")) ((formatter-out " ~@_"))) ((formatter-out "~{~w~^ ~_~}") alis)))) (defn- multi-defn [alis has-doc-str?] (if (seq alis) ((formatter-out " ~_~{~w~^ ~_~}") alis))) TODO : figure out how to support capturing metadata in defns ( we might need a (defn- pprint-defn [alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") defn-sym defn-name) (if doc-str ((formatter-out " ~_~w") doc-str)) (if attr-map ((formatter-out " ~_~w") attr-map)) Note : the multi - defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list alis))) (defn- pprint-binding-form [binding-vec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [binding binding-vec] (when (seq binding) (pprint-logical-block binding (write-out (first binding)) (when (next binding) (-write *out* " ") (pprint-newline :miser) (write-out (second binding)))) (when (next (rest binding)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest binding)))))))) (defn- pprint-let [alis] (let [base-sym (first alis)] (pprint-logical-block :prefix "(" :suffix ")" (if (and (next alis) (vector? (second alis))) (do ((formatter-out "~w ~1I~@_") base-sym) (pprint-binding-form (second alis)) ((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis)))) (pprint-simple-code-list alis))))) (def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>")) (defn- pprint-cond [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (print-length-loop [alis (next alis)] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))))) (defn- pprint-condp [alis] (if (> (count alis) 3) (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (apply (formatter-out "~w ~@_~w ~@_~w ~_") alis) (print-length-loop [alis (seq (drop 3 alis))] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))) (pprint-simple-code-list alis))) (def ^:dynamic ^{:private true} *symbol-map* {}) (defn- pprint-anon-func [alis] (let [args (second alis) nlis (first (rest (rest alis)))] (if (vector? args) (binding [*symbol-map* (if (= 1 (count args)) {(first args) "%"} (into {} (map #(vector %1 (str \% %2)) args (range 1 (inc (count args))))))] ((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis)) (pprint-simple-code-list alis)))) (defn- pprint-simple-code-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) (defn- two-forms [amap] (into {} (mapcat identity (for [x amap] [x [(symbol (name (first x))) (second x)]])))) (defn- add-core-ns [amap] (let [core "clojure.core"] (into {} (map #(let [[s f] %] (if (not (or (namespace s) (special-symbol? s))) [(symbol core (name s)) f] %)) amap)))) (def ^:dynamic ^{:private true} *code-table* (two-forms (add-core-ns {'def pprint-hold-first, 'defonce pprint-hold-first, 'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn, 'let pprint-let, 'loop pprint-let, 'binding pprint-let, 'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let, 'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let, 'when-first pprint-let, 'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if, 'cond pprint-cond, 'condp pprint-condp, 'fn* pprint-anon-func, '. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first, 'locking pprint-hold-first, 'struct pprint-hold-first, 'struct-map pprint-hold-first, 'ns pprint-ns }))) (defn- pprint-code-list [alis] (if-not (pprint-reader-macro alis) (if-let [special-form (*code-table* (first alis))] (special-form alis) (pprint-simple-code-list alis)))) (defn- pprint-code-symbol [sym] (if-let [arg-num (sym *symbol-map*)] (print arg-num) (if *print-suppress-namespaces* (print (name sym)) (pr sym)))) (defmulti code-dispatch "The pretty print dispatch function for pretty printing Clojure code." {:added "1.2" :arglists '[[object]]} type-dispatcher) (use-method code-dispatch :list pprint-code-list) (use-method code-dispatch :symbol pprint-code-symbol) (use-method code-dispatch :vector pprint-vector) (use-method code-dispatch :map pprint-map) (use-method code-dispatch :set pprint-set) (use-method code-dispatch :queue pprint-pqueue) (use-method code-dispatch :deref pprint-ideref) (use-method code-dispatch nil pr) (use-method code-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) (comment (with-pprint-dispatch code-dispatch (pprint '(defn cl-format "An implementation of a Common Lisp compatible format function" [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn cl-format [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn- -write ([this x] (condp = (class x) String (let [s0 (write-initial-lines this x) s (.replaceFirst s0 "\\s+$" "") white-space (.substring s0 (count s)) mode (getf :mode)] (if (= mode :writing) (dosync (write-white-space this) (.col_write this s) (setf :trailing-white-space white-space)) (add-to-buffer this (make-buffer-blob s white-space)))) Integer (let [c ^Character x] (if (= (getf :mode) :writing) (do (write-white-space this) (.col_write this x)) (if (= c (int \newline)) (write-initial-lines this "\n") (add-to-buffer this (make-buffer-blob (str (char c)) nil)))))))))) (with-pprint-dispatch code-dispatch (pprint '(defn pprint-defn [writer alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block writer :prefix "(" :suffix ")" (cl-format true "~w ~1I~@_~w" defn-sym defn-name) (if doc-str (cl-format true " ~_~w" doc-str)) (if attr-map (cl-format true " ~_~w" attr-map)) Note : the multi - defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list writer alis))))) ) (defn- add-padding [width s] (let [padding (max 0 (- width (count s)))] (apply str (clojure.string/join (repeat padding \space)) s))) (defn print-table "Prints a collection of maps in a textual table. Prints table headings ks, and then a line of output for each row, corresponding to the keys in ks. If ks are not specified, use the keys of the first item in rows." {:added "1.3"} ([ks rows] (binding [*print-newline*] (when (seq rows) (let [widths (map (fn [k] (apply max (count (str k)) (map #(count (str (get % k))) rows))) ks) spacers (map #(apply str (repeat % "-")) widths) fmt-row (fn [leader divider trailer row] (str leader (apply str (interpose divider (for [[col width] (map vector (map #(get row %) ks) widths)] (add-padding width (str col))))) trailer))] (cljs.core/println) (cljs.core/println (fmt-row "| " " | " " |" (zipmap ks ks))) (cljs.core/println (fmt-row "|-" "-+-" "-|" (zipmap ks spacers))) (doseq [row rows] (cljs.core/println (fmt-row "| " " | " " |" row))))))) ([rows] (print-table (keys (first rows)) rows)))
1bc0c382e76c88766dd1a8eee581e0dc5d40efce0fa440b2dc858380354fc93a
RedBrainLabs/system-graph
utils_test.clj
(ns com.redbrainlabs.system-graph.utils-test (:require [midje.sweet :refer :all] [plumbing.core :refer [fnk]] [plumbing.graph :as graph] [schema.core :as s] [com.redbrainlabs.system-graph.utils :refer :all])) (facts "#'topo-sort" sanity / characteristic test since we are relying on 's impl .. (topo-sort {:a (fnk [x] (inc x)) :b (fnk [a] (inc a)) :c (fnk [b] (inc b))}) => [:a :b :c]) (facts "#'comp-fnk" (let [square-fnk (fnk [x] (* x x)) with-inc (comp-fnk inc square-fnk)] (fact "composes the regular fn with the fnk" (with-inc {:x 5}) => 26) (fact "composes the positional fn in the metadata as well" ((-> with-inc meta :plumbing.fnk.impl/positional-info first) 5) => 26) (fact "preserves the original fnk's schema" (s/fn-schema with-inc) => (s/fn-schema square-fnk)))) (facts "#'fnk-deps" (fnk-deps (fnk [a b c])) => (just [:a :b :c] :in-any-order) (fact "works on compiled graphs" (-> {:a (fnk [x] x) :b (fnk [y] y)} graph/eager-compile fnk-deps) => (just [:x :y] :in-any-order)))
null
https://raw.githubusercontent.com/RedBrainLabs/system-graph/928d5d7de34047e54b0f05d33cf5104d0d9be53a/test/com/redbrainlabs/system_graph/utils_test.clj
clojure
(ns com.redbrainlabs.system-graph.utils-test (:require [midje.sweet :refer :all] [plumbing.core :refer [fnk]] [plumbing.graph :as graph] [schema.core :as s] [com.redbrainlabs.system-graph.utils :refer :all])) (facts "#'topo-sort" sanity / characteristic test since we are relying on 's impl .. (topo-sort {:a (fnk [x] (inc x)) :b (fnk [a] (inc a)) :c (fnk [b] (inc b))}) => [:a :b :c]) (facts "#'comp-fnk" (let [square-fnk (fnk [x] (* x x)) with-inc (comp-fnk inc square-fnk)] (fact "composes the regular fn with the fnk" (with-inc {:x 5}) => 26) (fact "composes the positional fn in the metadata as well" ((-> with-inc meta :plumbing.fnk.impl/positional-info first) 5) => 26) (fact "preserves the original fnk's schema" (s/fn-schema with-inc) => (s/fn-schema square-fnk)))) (facts "#'fnk-deps" (fnk-deps (fnk [a b c])) => (just [:a :b :c] :in-any-order) (fact "works on compiled graphs" (-> {:a (fnk [x] x) :b (fnk [y] y)} graph/eager-compile fnk-deps) => (just [:x :y] :in-any-order)))
3f7483209e875e1ac7a2a26e7acffa9b934aa1dc90fb62f1f4f025741f59acf0
verystable/warframe-autobuilder
MagazineMods.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} -- | Module : Builder . Mods . ShotgunMods . MagazineMods -- Maintainer : -- Stability : experimental -- -- Contains function that modify magazine size, applicable on primary (shotguns) weapons. module Builder.Mods.ShotgunMods.MagazineMods where import ClassyPrelude import Control.Lens ( (^.) ) import GenericFunctions.GenericFunctions import Types.GenericWeapon burdenedMagazine1 :: GenericWeapon -> GenericWeapon -> GenericWeapon burdenedMagazine1 baseWeapon targetWeapon = modifyGeneralProperty gwMagazineSize (baseWeapon ^. gwMagazineSize) (Just 0.6) (+) targetWeapon # INLINE burdenedMagazine1 # burdenedMagazine2 :: GenericWeapon -> GenericWeapon -> GenericWeapon burdenedMagazine2 baseWeapon targetWeapon = modifyGeneralProperty gwReloadTime (baseWeapon ^. gwReloadTime) (Just 0.18) (+) targetWeapon # INLINE burdenedMagazine2 # -- | Burdened Magazine [+90% Magazine, -18% Reload Speed (+18% Reload Time)] burdenedMagazine :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) burdenedMagazine baseWeapon (targetWeapon, mods) = ( burdenedMagazine1 baseWeapon $ burdenedMagazine2 baseWeapon targetWeapon , "Burdened Magazine [+90% Magazine, -18% Reload Speed (+18% Reload Time)]" : mods ) # INLINE burdenedMagazine #
null
https://raw.githubusercontent.com/verystable/warframe-autobuilder/015e0bb6812711ea27071816d054cbaa1c65770b/src/Builder/Mods/ShotgunMods/MagazineMods.hs
haskell
# LANGUAGE OverloadedStrings # | Maintainer : Stability : experimental Contains function that modify magazine size, applicable on primary (shotguns) weapons. | Burdened Magazine [+90% Magazine, -18% Reload Speed (+18% Reload Time)]
# LANGUAGE NoImplicitPrelude # Module : Builder . Mods . ShotgunMods . MagazineMods module Builder.Mods.ShotgunMods.MagazineMods where import ClassyPrelude import Control.Lens ( (^.) ) import GenericFunctions.GenericFunctions import Types.GenericWeapon burdenedMagazine1 :: GenericWeapon -> GenericWeapon -> GenericWeapon burdenedMagazine1 baseWeapon targetWeapon = modifyGeneralProperty gwMagazineSize (baseWeapon ^. gwMagazineSize) (Just 0.6) (+) targetWeapon # INLINE burdenedMagazine1 # burdenedMagazine2 :: GenericWeapon -> GenericWeapon -> GenericWeapon burdenedMagazine2 baseWeapon targetWeapon = modifyGeneralProperty gwReloadTime (baseWeapon ^. gwReloadTime) (Just 0.18) (+) targetWeapon # INLINE burdenedMagazine2 # burdenedMagazine :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) burdenedMagazine baseWeapon (targetWeapon, mods) = ( burdenedMagazine1 baseWeapon $ burdenedMagazine2 baseWeapon targetWeapon , "Burdened Magazine [+90% Magazine, -18% Reload Speed (+18% Reload Time)]" : mods ) # INLINE burdenedMagazine #
60a71ba1fee41b8a64c22af0d0814e261b5e984be6e25a60e1db906240371aad
okuoku/nausicaa
test-all.scm
#!/usr/local/bin/csi -script ;; just run this file as "csi -script test-all.scm" to run the full ;; test suite (use test extras utils irregex) (test-begin) (load "test-irregex.scm") (load "test-irregex-gauche.scm") (load "test-irregex-scsh.scm") (load "test-irregex-pcre.scm") (load "test-irregex-utf8.scm") (test-end) (test-exit)
null
https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/src/foreign/irregex-0.8.1/test-all.scm
scheme
just run this file as "csi -script test-all.scm" to run the full test suite
#!/usr/local/bin/csi -script (use test extras utils irregex) (test-begin) (load "test-irregex.scm") (load "test-irregex-gauche.scm") (load "test-irregex-scsh.scm") (load "test-irregex-pcre.scm") (load "test-irregex-utf8.scm") (test-end) (test-exit)
4eccba320f08e87ffaade6145f54706effbd81c1d02e0c5e82f4bd3de8f6fa9c
CorticalComputer/Book_NeuroevolutionThroughErlang
substrate.erl
This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM %% Copyright ( C ) 2012 by , DXNN Research Group , %All rights reserved. % This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use . -module(substrate). -compile(export_all). -include("records.hrl"). -define(SAT_LIMIT,math:pi()). -record(state,{ type, plasticity=none, morphology, specie_id, sensors, actuators, spids=[], apids=[], cpp_pids=[], cep_pids=[], densities, substrate_state_flag, old_substrate, cur_substrate, link_form }). gen(ExoSelf_PId,Node)-> spawn(Node,?MODULE,prep,[ExoSelf_PId]). prep(ExoSelf)-> random:seed(now()), receive {ExoSelf,init,InitState}-> {Sensors,Actuators,SPIds,APIds,CPP_PIds,CEP_PIds,Densities,Plasticity,LinkForm}=InitState, %io:format("InitState:~p~n",[InitState]), S = #state{ sensors=Sensors, actuators=Actuators, spids=SPIds, apids=APIds, cpp_pids=CPP_PIds, cep_pids=CEP_PIds, densities = Densities, substrate_state_flag=reset, old_substrate=void, cur_substrate=init, plasticity=Plasticity, link_form = LinkForm }, substrate:loop(ExoSelf,S,SPIds,[]) end. loop(ExoSelf,S,[SPId|SPIds],SAcc)-> receive {SPId,forward,Sensory_Signal}-> loop(ExoSelf,S,SPIds,[Sensory_Signal|SAcc]); {ExoSelf,reset_substrate}-> U_S = S#state{ old_substrate=S#state.cur_substrate, substrate_state_flag=reset }, ExoSelf ! {self(),ready}, loop(ExoSelf,U_S,[SPId|SPIds],SAcc); {ExoSelf,backup_substrate} -> % io:format("reseting:~n"), U_S = S#state{ old_substrate=S#state.cur_substrate, substrate_state_flag=reset }, ExoSelf ! {self(),ready}, loop(ExoSelf,U_S,[SPId|SPIds],SAcc); {ExoSelf,revert_substrate} -> % io:format("reverting:~n"), U_S = S#state{ cur_substrate = S#state.old_substrate, substrate_state_flag=reset }, ExoSelf ! {self(),ready}, loop(ExoSelf,U_S,[SPId|SPIds],SAcc); {ExoSelf,terminate}-> io : format("Resulting ~ n",[Substrate ] ) , void after 20000 - > % io:format("********ERROR: Substrate Crashed:~p~n",[S]) end; loop(ExoSelf,S,[],SAcc)->%All sensory signals received {U_Substrate,U_SMode,OAcc} = reason(SAcc,S), advanced_fanout(OAcc,S#state.actuators,S#state.apids), U_S = S#state{ cur_substrate=U_Substrate, substrate_state_flag=U_SMode }, loop(ExoSelf,U_S,S#state.spids,[]). reason(Input,S)-> Densities = S#state.densities, Substrate = S#state.cur_substrate, SMode = S#state.substrate_state_flag, case SMode of reset ->%io:format("reset~n"), Sensors=S#state.sensors, Actuators=S#state.actuators, CPP_PIds = S#state.cpp_pids, CEP_PIds = S#state.cep_pids, Plasticity = S#state.plasticity, New_Substrate = create_substrate(Sensors,Densities,Actuators,S#state.link_form), io : format("New_Substrate:~p ~ n",[New_Substrate ] ) , {Output,Populated_Substrate} = calculate_ResetOutput(Densities,New_Substrate,Input,CPP_PIds,CEP_PIds,Plasticity,S#state.link_form), io : format("New_Substrate:~p ~ n Output:~p ~ n Populated_Substrate:~p ~ n",[New_Substrate , Output , Populated_Substrate ] ) , U_SMode=case Plasticity of iterative -> iterative; none -> hold; abcn -> hold; modular_none -> hold end, {Populated_Substrate,U_SMode,Output}; iterative ->%io:format("Iterative~n"), CPP_PIds = S#state.cpp_pids, CEP_PIds = S#state.cep_pids, {Output,U_Substrate} = calculate_IterativeOutput(Densities,Substrate,Input,CPP_PIds,CEP_PIds), io : ~ n Densities:~p ~ n Substrate:~p ~ n U_Substrate:~p ~ n CT:~p ~ n CF:~p ~ n",[Output , Densities , Substrate , U_Substrate , CT , CF ] ) , {U_Substrate,SMode,Output}; hold ->%io:format("hold~n"), {Output,U_Substrate} = calculate_HoldOutput(Densities,Substrate,Input,S#state.link_form,S#state.plasticity), io : ~ n",[Output , Output ] ) , {U_Substrate,SMode,Output} end. advanced_fanout(OAcc,[Actuator|Actuators],[APId|APIds])-> {Output,OAccRem}=lists:split(Actuator#actuator.vl,OAcc), APId ! {self(),forward,Output}, advanced_fanout(OAccRem,Actuators,APIds); advanced_fanout([],[],[])-> ok. %%==================================================================== Internal Functions fanout([Pid|Pids],Msg)-> Pid ! Msg, fanout(Pids,Msg); fanout([],_Msg)-> true. flush_buffer()-> receive ANY -> %io:format("ANY:~p~n",[ANY]), flush_buffer() after 0 -> done end. % no_geo % {symetric,[R1,R2...Rk],[Val1...Valn]} where n == R1*R2*...Dk and k = dimension { asymetric,[[R1 .. Rp],[R1 .. Rt]],[Val1 ... Valn ] } where lists : sum(lists : flatten([[R1 ... .. Rt ] ] ) ) = = n , and depth = Dimension . % coorded, every val comes with its own coord tuple: {Coord,Val}. The coord is a list, thus specifying the dimensionality. test_cs()-> Sensors = [ #sensor{format=no_geo,vl=3}, #sensor{format={symetric,lists:reverse([2,3])},vl=6} ], Actuators = [ #actuator{format=no_geo,vl=2}, #actuator{format={symetric,lists:reverse([3,2])},vl=6} ], create_substrate(Sensors,[3,2,3,2],Actuators,l2l_feedforward). test_IS(SubstrateDimension)-> Sensors = [ #sensor{format=no_geo,vl=10}, #sensor{format={symetric,lists:reverse([3,4])},vl=[ 1,-1,-1,-1, 1,-1,-1,-1, 1,1,1,1]} ], compose_ISubstrate(Sensors,SubstrateDimension). test_OS(SubstrateDimension)-> Actuators = [ #actuator{format=no_geo,vl=10}, #actuator{format={symetric,lists:reverse([3,4])},vl=[ 1,-1,-1,-1, 1,-1,-1,-1, 1,1,1,1]} ], compose_OSubstrate(Actuators,SubstrateDimension,[w1,w2,w3]). create_substrate(Sensors,Densities,Actuators,LinkForm)-> [Depth|SubDensities] = Densities, Substrate_I = compose_ISubstrate(Sensors,length(Densities)), I_VL = length(Substrate_I), % io:format("I_VL:~p~n",[I_VL]), case LinkForm of l2l_feedforward -> Weight = 0, H = mult(SubDensities), IWeights = lists:duplicate(I_VL,Weight), HWeights = lists:duplicate(H,Weight); fully_interconnected -> Output_Neurodes = tot_ONeurodes(Actuators,0), Weight = 0, Tot_HiddenNeurodes = mult([Depth-1|SubDensities]), Tot_Weights = Tot_HiddenNeurodes + I_VL + Output_Neurodes, IWeights = lists:duplicate(Tot_Weights,Weight), HWeights = lists:duplicate(Tot_Weights,Weight); jordan_recurrent -> Output_Neurodes = tot_ONeurodes(Actuators,0), Weight = 0, H = mult(SubDensities), IWeights = lists:duplicate(I_VL+Output_Neurodes,Weight), HWeights = lists:duplicate(H,Weight); neuronself_recurrent -> Weight = 0, H = mult(SubDensities), IWeights = lists:duplicate(I_VL+1,Weight), HWeights = lists:duplicate(H+1,Weight) end, case Depth of 0 -> Substrate_O=compose_OSubstrate(Actuators,length(Densities),IWeights), [Substrate_I,Substrate_O]; 1 -> Substrate_R = cs(SubDensities,IWeights), Substrate_O=compose_OSubstrate(Actuators,length(Densities),HWeights), % io:format("Substrate_I:~n~p~n Substrate_R:~n~p~n Substrate_O:~n~p~n",[Substrate_I,Substrate_R,Substrate_O]), [Substrate_I,extrude(0,Substrate_R),Substrate_O]; _ -> Substrate_R = cs(SubDensities,IWeights), Substrate_H = cs(SubDensities,HWeights), Substrate_O=compose_OSubstrate(Actuators,length(Densities),HWeights), %io:format("OResolutions:~p Substrate_O:~p~n",[OResolutions,Substrate_O]), [_,RCoord|C1] = build_CoordList(Depth+1), [_|C2] = lists:reverse(C1), HCoords = lists:reverse(C2), io : , HCoords ] ) , ESubstrate_R = extrude(RCoord,Substrate_R), ESubstrates_H = [extrude(HCoord,Substrate_H) || HCoord<-HCoords], io : format("ESubstrate_R:~p ESubstrates_H:~p ~ n",[ESubstrate_R , ESubstrates_H ] ) , lists:append([[Substrate_I,ESubstrate_R],ESubstrates_H,[Substrate_O]]) end. compose_ISubstrate(Sensors,SubstrateDimension)-> compose_ISubstrate(Sensors,[],1,SubstrateDimension-2). compose_ISubstrate([S|Sensors],Acc,Max_Dim,Required_Dim)-> case S#sensor.format of undefined -> Dim=1, CoordLists = create_CoordLists([S#sensor.vl]), ISubstrate_Part=[{Coord,0,void}|| Coord<-CoordLists], {Dim,ISubstrate_Part}; no_geo -> Dim=1, CoordLists = create_CoordLists([S#sensor.vl]), ISubstrate_Part=[{Coord,0,void}|| Coord<-CoordLists], {Dim,ISubstrate_Part}; {symetric,Resolutions}-> Dim = length(Resolutions), Signal_Length = mult(Resolutions), CoordLists = create_CoordLists(Resolutions), ISubstrate_Part=[{Coord,0,void}|| Coord<-CoordLists], {Dim,ISubstrate_Part}; {coorded,Dim,Resolutions,ISubstrate_Part} -> {Dim,ISubstrate_Part} end, U_Dim = case Max_Dim > Dim of true -> Max_Dim; false -> Dim end, compose_ISubstrate(Sensors,[ISubstrate_Part|Acc],U_Dim,Required_Dim); compose_ISubstrate([],Acc,ISubstratePart_MaxDim,Required_Dim)-> case Required_Dim >= ISubstratePart_MaxDim of true -> ISubstrate_Depth = length(Acc), ISubstrate_DepthCoords = build_CoordList(ISubstrate_Depth), Passed in inverted , reversed inside , same for depth coords . false -> exit("Error in adv_extrude, Required_Depth < ISubstratePart_MaxDepth~n") end. adv_extrude([ISubstrate_Part|ISubstrate],Required_Dim,[IDepthCoord|ISubstrate_DepthCoords],LeadCoord,Acc)-> Extruded_ISP = [{[LeadCoord,IDepthCoord|lists:append(lists:duplicate(Required_Dim - length(Coord),0),Coord)],O,W} || {Coord,O,W}<-ISubstrate_Part], extrude(ISubstrate_Part,Required_Dim,IDepthCoord,[]), adv_extrude(ISubstrate,Required_Dim,ISubstrate_DepthCoords,LeadCoord,lists:append(Extruded_ISP,Acc)); adv_extrude([],_Required_Dim,[],_LeadCoord,Acc)-> Acc. extrude([{Coord,O,W}|ISubstrate_Part],Required_Dim,DepthCoord,Acc)-> Dim_Dif = Required_Dim - length(Coord), U_Coord= [1,DepthCoord|lists:append(lists:duplicate(Dim_Dif,0),Coord)], extrude(ISubstrate_Part,Required_Dim,DepthCoord,[{U_Coord,O,W}|Acc]); extrude([],_Required_Dim,_DepthCoord,Acc)-> Acc. compose_OSubstrate(Actuators,SubstrateDimension,Weights)-> compose_OSubstrate(Actuators,[],1,SubstrateDimension-2,Weights). compose_OSubstrate([A|Actuators],Acc,Max_Dim,Required_Dim,Weights)-> case A#actuator.format of undefined ->%Dim=void,OSubstrate_Part=void, Dim=1, CoordLists = create_CoordLists([A#actuator.vl]), OSubstrate_Part=[{Coord,0,Weights}|| Coord<-CoordLists], {Dim,OSubstrate_Part}; no_geo ->%Dim=void,OSubstrate_Part=void, Dim=1, CoordLists = create_CoordLists([A#actuator.vl]), OSubstrate_Part=[{Coord,0,Weights}|| Coord<-CoordLists], {Dim,OSubstrate_Part}; {symetric,Resolutions}->%Dim=void,OSubstrate_Part=void, Dim = length(Resolutions), Signal_Length = mult(Resolutions), CoordLists = create_CoordLists(Resolutions), OSubstrate_Part=[{Coord,0,Weights}|| Coord<-CoordLists], {Dim,OSubstrate_Part}; {coorded,Dim,Resolutions,Unadjusted_OSubstrate_Part} -> OSubstrate_Part=[{Coord,O,Weights}|| {Coord,O,_}<-Unadjusted_OSubstrate_Part], {Dim,OSubstrate_Part} end, U_Dim = case Max_Dim > Dim of true -> Max_Dim; false -> Dim end, compose_OSubstrate(Actuators,[OSubstrate_Part|Acc],U_Dim,Required_Dim,Weights); compose_OSubstrate([],Acc,OSubstratePart_MaxDim,Required_Dim,_Weights)-> case Required_Dim >= OSubstratePart_MaxDim of true ->%done; ISubstrate_Depth = length(Acc), ISubstrate_DepthCoords = build_CoordList(ISubstrate_Depth), Passed in inverted , reversed inside , same for depth coord false -> exit("Error in adv_extrude, Required_Depth < OSubstratePart_MaxDepth~n") end. find_depth(Resolutions)->find_depth(Resolutions,0). find_depth(Resolutions,Acc)-> case is_list(Resolutions) of true -> [_Head|Tail] = Resolutions, find_depth(Tail,Acc+1); false -> Acc end. %Substrate encoding: X density = n, Y density = k, Z density = p, T density = l Weights = [ W1,W2 ... WI ] , [ [ { [ , ... Wn]} ... {[Z1,Yn , Xk],o,[W1 ... Wn]}] ... [{[Zs , Y , X],o,[W1 ... Wn ] } ... ] ] , build_CoordList(Density)-> case Density == 1 of true -> [0.0]; false -> DensityDividers = Density - 1, Resolution = 2/DensityDividers, build_CoordList(Resolution,DensityDividers,1,[]) end. extend(I,DI,D,Substrate)-> void. mult(List)-> mult(List,1). mult([Val|List],Acc)-> mult(List,Val*Acc); mult([],Acc)-> Acc. tot_ONeurodes([A|Actuators],Acc)-> Tot_ANeurodes=case A#actuator.format of undefined -> A#actuator.vl; no_geo -> A#actuator.vl; {symetric,Resolutions}-> mult(Resolutions); {coorded,Dim,Resolutions,Unadjusted_OSubstrate_Part} -> length(Unadjusted_OSubstrate_Part) end, tot_ONeurodes(Actuators,Tot_ANeurodes+Acc); tot_ONeurodes([],Acc)-> Acc. %[{[D3,D2,D1],o,[W1,W2,W3...]}...] cs(Densities,Weights)-> RDensities = lists:reverse(Densities), Substrate = create_CoordLists(RDensities,[]), attach(Substrate,0,Weights). create_CoordLists(Densities)-> create_CoordLists(Densities,[]). create_CoordLists([Density|RDensities],[])-> CoordList = build_CoordList(Density), XtendedCoordList = [[Coord]||Coord <- CoordList], create_CoordLists(RDensities,XtendedCoordList); create_CoordLists([Density|RDensities],Acc)-> CoordList = build_CoordList(Density), XtendedCoordList = [[Coord|Sub_Coord]||Coord <- CoordList,Sub_Coord <- Acc], create_CoordLists(RDensities,XtendedCoordList); create_CoordLists([],Acc)-> Acc. build_CoordList(Resolution,0,Coord,Acc)-> [-1|Acc]; build_CoordList(Resolution,DensityDividers,Coord,Acc)-> build_CoordList(Resolution,DensityDividers-1,Coord-Resolution,[Coord|Acc]). attach(List,E1,E2)-> attach(List,E1,E2,[]). attach([Val|List],E1,E2,Acc)-> attach(List,E1,E2,[{Val,E1,E2}|Acc]); attach([],_E1,_E2,Acc)-> lists:reverse(Acc). extrude(NewDimension_Coord,Substrate)-> extrude(NewDimension_Coord,Substrate,[]). extrude(NewDimension_Coord,[{Coord,O,W}|Substrate],Acc)-> extrude(NewDimension_Coord,Substrate,[{[NewDimension_Coord|Coord],O,W}|Acc]); extrude(_Coord,[],Acc)-> lists:reverse(Acc). { VL,{actuator , Actuator , Id , Parameters } } %{VL,{sensor,System,Id,Parameters}} %CF: % neural: [{Actuator1,[N_Id1...N_Idn]},{Actuator2,[N_Id1...N_Idn]}...] % hypercube: [{CFTag1,[N_Id1...N_Idn]},{CFTag2,[N_Id2...N_Idn]}...] CFTag:[{weight,1}...] %CT: % neural: [{Sensor1,[{N_Id1,FilterTag1},{N_Id2,FilterTag2}...]}...] FilterTag:{single,Index} | {block,VL} hypercube : [ { CTTag1,[{N_Id1,FilterTag1},{N_Id2,FilterTag2 } ... ] } ... ] CTTag:[{cartesian , VL } ... ] , FilterTag:{single , Index } | { block , VL } calculate_IterativeOutput(Densities,Substrate,Input,CPP_PIds,CEP_PIds)-> [IHyperlayer|PHyperlayers] = Substrate, Populated_IHyperlayer = populate_InputHyperlayer(IHyperlayer,lists:flatten(Input),[]), {Output,U_PHyperlayers} = update_PHyperlayers(Populated_IHyperlayer,PHyperlayers,CPP_PIds,CEP_PIds), {Output,[Populated_IHyperlayer|U_PHyperlayers]}. update_PHyperlayers(Populated_IHyperlayer,U_PHyperlayers,CPP_PIds,CEP_PIds)-> [CurPHyperlayer|RemPHyperlayers] = U_PHyperlayers, update_PHyperlayers(Populated_IHyperlayer,CurPHyperlayer,RemPHyperlayers,CPP_PIds,CEP_PIds,[],[]). update_PHyperlayers(PrevHyperlayer,[{Coord,PrevO,PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> U_O=calculate_output(PrevHyperlayer,{Coord,PrevO,PrevWeights},0), U_Weights = get_weights(PrevHyperlayer,Coord,CPP_PIds,CEP_PIds,[],PrevWeights,U_O), update_PHyperlayers(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,U_O,U_Weights}|Acc1],Acc2); update_PHyperlayers(_PrevHyperlayer,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> PrevHyperlayer = lists:reverse(Acc1), update_PHyperlayers(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[PrevHyperlayer|Acc2]); update_PHyperlayers(_PrevHyperlayer,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> OutputHyperlayer = lists:reverse(Acc1), {[O||{_Coord,O,_Weights}<-OutputHyperlayer],lists:reverse([OutputHyperlayer|Acc2])}. get_weights([{I_Coord,I,_I_Weights}|PrevHypercube],Coord,CPP_PIds,CEP_PIds,Acc,[W|Weights],O)-> plasticity_fanout(CPP_PIds,I_Coord,Coord,[I,O,W]), U_W=fanin(CEP_PIds,[]), get_weights(PrevHypercube,Coord,CPP_PIds,CEP_PIds,[functions:sat(U_W,3.1415,-3.1415)|Acc],Weights,O); get_weights([],_Coord,CPP_PIds,CEP_PIds,Acc,[],_O)-> lists:reverse(Acc). plasticity_fanout([CPP_PId|CPP_PIds],I_Coord,Coord,IOW)-> CPP_PId ! {self(),I_Coord,Coord,IOW}, plasticity_fanout(CPP_PIds,I_Coord,Coord,IOW); plasticity_fanout([],_I_Coord,_Coord,_IOW)-> done. fanin([CEP_PId|CEP_PIds],W)-> receive {CEP_PId,Command,Signal}-> U_W=substrate:Command(Signal,W) end, fanin(CEP_PIds,U_W); fanin([],W)-> W. set_weight(Signal,_WP)-> Threshold = 0.33 , Processed_Weight = if % Weight > Threshold -> ( functions : ; % Weight < -Threshold -> ( functions : scale(Weight,-Threshold,-1)-1)/2 ; % true -> 0 %end [U_W] = Signal, U_W. weight_expression(Signal,_WP) -> [U_W,Expression]=Signal, case Expression > 0 of true -> U_W; false -> 0 end. set_abcn(Signal,_WP)-> [U_W,A,B,C,N] = Signal, %Delta_Weight = N*(A*Input*Output + B*Input + C*Output), {U_W,abcn,[A,B,C,N]}. iterative(Signal,{W,none})-> [Delta_Weight] = Signal, W + Delta_Weight. calculate_HoldOutput(Densities,Substrate,Input,LinkForm,Plasticity)-> [IHyperlayer|Populated_PHyperlayers] = Substrate, Populated_IHyperlayer = populate_InputHyperlayer(IHyperlayer,lists:flatten(Input),[]), {Output,U_PHyperlayers}=calculate_substrate_output(Populated_IHyperlayer,Populated_PHyperlayers,LinkForm,Plasticity), {Output,[IHyperlayer|U_PHyperlayers]}. calculate_ResetOutput(Densities,Substrate,Input,CPP_PIds,CEP_PIds,Plasticity,LinkForm)-> [IHyperlayer|PHyperlayers] = Substrate, %io:format("IHyperlayer:~p~n PHyperlayers:~p~n",[IHyperlayer,PHyperlayers]), Populated_IHyperlayer = populate_InputHyperlayer(IHyperlayer,lists:flatten(Input),[]), case Plasticity of iterative -> %Populated_Substrate = [Populated_IHyperlayer|PHyperlayers], {Output,U_PHyperlayers}=calculate_substrate_output(Populated_IHyperlayer,PHyperlayers,LinkForm,Plasticity), {Output,[IHyperlayer|U_PHyperlayers]}; _ ->%none, modular_none Populated_PHyperlayers = populate_PHyperlayers(Substrate,CPP_PIds,CEP_PIds,LinkForm), %Populated_Substrate = lists:append([Populated_IHyperlayer],Populated_PHyperlayers), {Output,U_PHyperlayers}=calculate_substrate_output(Populated_IHyperlayer,Populated_PHyperlayers,LinkForm,Plasticity), {Output,[IHyperlayer|U_PHyperlayers]} end. populate_InputHyperlayer([{Coord,PrevO,void}|Substrate],[I|Input],Acc)-> populate_InputHyperlayer(Substrate,Input,[{Coord,I,void}|Acc]); populate_InputHyperlayer([],[],Acc)-> lists:reverse(Acc). populate_PHyperlayers(Substrate,CPP_PIds,CEP_PIds,LinkForm)-> case LinkForm of l2l_feedforward -> [PrevHypercube,CurHypercube|RemSubstrate] = Substrate, populate_PHyperlayers_l2l(PrevHypercube,CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]); fully_interconnected -> [_InputHypercube,CurHypercube|RemSubstrate] = Substrate, populate_PHyperlayers_fi(lists:flatten(Substrate),CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]); jordan_recurrent -> [IHypercube,CurHypercube|RemSubstrate] = Substrate, [OSubstrate|_]=lists:reverse(Substrate), populate_PHyperlayers_l2l(lists:flatten([IHypercube,OSubstrate]),CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]); neuronself_recurrent -> [PrevHypercube,CurHypercube|RemSubstrate] = Substrate, populate_PHyperlayers_nsr(PrevHypercube,CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]) end. populate_PHyperlayers_l2l(PrevHyperlayer,[{Coord,PrevO,PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> NewWeights = get_weights(PrevHyperlayer,Coord,CPP_PIds,CEP_PIds,[]), populate_PHyperlayers_l2l(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,PrevO,NewWeights}|Acc1],Acc2); populate_PHyperlayers_l2l(_PrevHyperlayer,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> PrevHyperlayer = lists:reverse(Acc1), populate_PHyperlayers_l2l(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[PrevHyperlayer|Acc2]); populate_PHyperlayers_l2l(_PrevHyperlayer,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> lists:reverse([lists:reverse(Acc1)|Acc2]). populate_PHyperlayers_fi(FlatSubstrate,[{Coord,PrevO,_PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> NewWeights = get_weights(FlatSubstrate,Coord,CPP_PIds,CEP_PIds,[]), populate_PHyperlayers_fi(FlatSubstrate,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,PrevO,NewWeights}|Acc1],Acc2); populate_PHyperlayers_fi(FlatSubstrate,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> populate_PHyperlayers_fi(FlatSubstrate,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[lists:reverse(Acc1)|Acc2]); populate_PHyperlayers_fi(_FlatSubstrate,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> lists:reverse([lists:reverse(Acc1)|Acc2]). populate_PHyperlayers_nsr(PrevHyperlayer,[{Coord,PrevO,_PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> NewWeights = get_weights([{Coord,PrevO,_PrevWeights}|PrevHyperlayer],Coord,CPP_PIds,CEP_PIds,[]), populate_PHyperlayers_nsr(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,PrevO,NewWeights}|Acc1],Acc2); populate_PHyperlayers_nsr(_PrevHyperlayer,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> PrevHyperlayer = lists:reverse(Acc1), populate_PHyperlayers_nsr(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[PrevHyperlayer|Acc2]); populate_PHyperlayers_nsr(_PrevHyperlayer,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> lists:reverse([lists:reverse(Acc1)|Acc2]). get_weights([{I_Coord,I,_I_Weights}|PrevHypercube],Coord,CPP_PIds,CEP_PIds,Acc)-> static_fanout(CPP_PIds,I_Coord,Coord), U_W=fanin(CEP_PIds,[]), get_weights(PrevHypercube,Coord,CPP_PIds,CEP_PIds,[functions:sat(U_W,3.1415,-3.1415)|Acc]); get_weights([],_Coord,_CPP_PIds,_CEP_PIds,Acc)-> lists:reverse(Acc). static_fanout([CPP_PId|CPP_PIds],I_Coord,Coord)-> %io:format("CPP_PId:~p~n",[CPP_PId]), CPP_PId ! {self(),I_Coord,Coord}, static_fanout(CPP_PIds,I_Coord,Coord); static_fanout([],_I_Coord,_Coord)-> done. calculate_substrate_output(ISubstrate,Substrate,LinkForm,Plasticity)-> case LinkForm of l2l_feedforward -> calculate_output_std(ISubstrate,Substrate,Plasticity,[]); fully_interconnected -> calculate_output_fi(ISubstrate,Substrate,Plasticity,[]); jordan_recurrent -> [OSubstrate|_] = lists:reverse(Substrate,Plasticity), calculate_output_std(lists:flatten([ISubstrate|OSubstrate]),Substrate,Plasticity,[]); neuronself_recurrent -> calculate_output_nsr(ISubstrate,Substrate,Plasticity,[]) end. calculate_output_std(Prev_Hyperlayer,[Cur_Hyperlayer|Substrate],Plasticity,Acc)-> Updated_CurHyperlayer = [{Coord,calculate_output(Prev_Hyperlayer,{Coord,Prev_O,Weights},Plasticity),Weights} || {Coord,Prev_O,Weights} <- Cur_Hyperlayer], io : ~ n",[Updated_CurHypercube ] ) , calculate_output_std(Updated_CurHyperlayer,Substrate,Plasticity,[Updated_CurHyperlayer|Acc]); calculate_output_std(Output_Hyperlayer,[],_Plasticity,Acc)-> {[Output || {_Coord,Output,_Weights} <- Output_Hyperlayer],lists:reverse(Acc)}. calculate_output(I_Neurodes,Neurode,Plasticity)-> case Plasticity of abcn -> calculate_neurode_output_plast(I_Neurodes,Neurode,0), update_neurode(I_Neurodes,Neurode); _ -> calculate_neurode_output_noplast(I_Neurodes,Neurode,0) end. calculate_neurode_output_noplast([{_I_Coord,O,_I_Weights}|I_Neurodes],{Coord,Prev_O,[Weight|Weights]},Acc)-> calculate_neurode_output_noplast(I_Neurodes,{Coord,Prev_O,Weights},O*Weight+Acc); calculate_neurode_output_noplast([],{Coord,Prev_O,[]},Acc)-> functions:tanh(Acc). calculate_neurode_output_plast([{_I_Coord,O,_I_Weights}|I_Neurodes],{Coord,Prev_O,[{W,_LF,_Parameters}|WPs]},Acc)-> calculate_neurode_output_plast(I_Neurodes,{Coord,Prev_O,WPs},O*W+Acc); calculate_neurode_output_plast([],{Coord,Prev_O,[]},Acc)-> functions:tanh(Acc). update_neurode(I_Neurodes,Neurode)-> ok. calculate_output_fi(Input_Substrate,[Cur_Hypercube|Substrate],Plasticity,Acc)-> Updated_CurHypercube = [{Coord,calculate_output(lists:flatten([Input_Substrate,Cur_Hypercube|Substrate]),{Coord,Prev_O,Weights},Plasticity),Weights} || {Coord,Prev_O,Weights} <- Cur_Hypercube], calculate_output_fi([Input_Substrate|Updated_CurHypercube],Substrate,Plasticity,Acc); calculate_output_fi(Output_Hyperlayer,[],_Plasticity,Acc)-> {[Output || {_Coord,Output,_Weights} <- Output_Hyperlayer],lists:reverse(Acc)}. calculate_output_nsr(Prev_Hypercube,[Cur_Hypercube|Substrate],Plasticity,Acc)-> Updated_CurHypercube = [{Coord,calculate_output([{Coord,Prev_O,Weights}|Prev_Hypercube],{Coord,Prev_O,Weights},Plasticity),Weights} || {Coord,Prev_O,Weights} <- Cur_Hypercube], calculate_output_nsr(Updated_CurHypercube,Substrate,Plasticity,Acc); calculate_output_nsr(Output_Hyperlayer,[],_Plasticity,Acc)-> {[Output || {_Coord,Output,_Weights} <- Output_Hyperlayer],lists:reverse(Acc)}.
null
https://raw.githubusercontent.com/CorticalComputer/Book_NeuroevolutionThroughErlang/81b96e3d7985624a6183cb313a7f9bff0a7e14c5/Ch_16/substrate.erl
erlang
All rights reserved. io:format("InitState:~p~n",[InitState]), io:format("reseting:~n"), io:format("reverting:~n"), io:format("********ERROR: Substrate Crashed:~p~n",[S]) All sensory signals received io:format("reset~n"), io:format("Iterative~n"), io:format("hold~n"), ==================================================================== Internal Functions io:format("ANY:~p~n",[ANY]), no_geo {symetric,[R1,R2...Rk],[Val1...Valn]} where n == R1*R2*...Dk and k = dimension coorded, every val comes with its own coord tuple: {Coord,Val}. The coord is a list, thus specifying the dimensionality. io:format("I_VL:~p~n",[I_VL]), io:format("Substrate_I:~n~p~n Substrate_R:~n~p~n Substrate_O:~n~p~n",[Substrate_I,Substrate_R,Substrate_O]), io:format("OResolutions:~p Substrate_O:~p~n",[OResolutions,Substrate_O]), Dim=void,OSubstrate_Part=void, Dim=void,OSubstrate_Part=void, Dim=void,OSubstrate_Part=void, done; Substrate encoding: X density = n, Y density = k, Z density = p, T density = l [{[D3,D2,D1],o,[W1,W2,W3...]}...] {VL,{sensor,System,Id,Parameters}} CF: neural: [{Actuator1,[N_Id1...N_Idn]},{Actuator2,[N_Id1...N_Idn]}...] hypercube: [{CFTag1,[N_Id1...N_Idn]},{CFTag2,[N_Id2...N_Idn]}...] CFTag:[{weight,1}...] CT: neural: [{Sensor1,[{N_Id1,FilterTag1},{N_Id2,FilterTag2}...]}...] FilterTag:{single,Index} | {block,VL} Weight > Threshold -> Weight < -Threshold -> true -> end Delta_Weight = N*(A*Input*Output + B*Input + C*Output), io:format("IHyperlayer:~p~n PHyperlayers:~p~n",[IHyperlayer,PHyperlayers]), Populated_Substrate = [Populated_IHyperlayer|PHyperlayers], none, modular_none Populated_Substrate = lists:append([Populated_IHyperlayer],Populated_PHyperlayers), io:format("CPP_PId:~p~n",[CPP_PId]),
This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM Copyright ( C ) 2012 by , DXNN Research Group , This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use . -module(substrate). -compile(export_all). -include("records.hrl"). -define(SAT_LIMIT,math:pi()). -record(state,{ type, plasticity=none, morphology, specie_id, sensors, actuators, spids=[], apids=[], cpp_pids=[], cep_pids=[], densities, substrate_state_flag, old_substrate, cur_substrate, link_form }). gen(ExoSelf_PId,Node)-> spawn(Node,?MODULE,prep,[ExoSelf_PId]). prep(ExoSelf)-> random:seed(now()), receive {ExoSelf,init,InitState}-> {Sensors,Actuators,SPIds,APIds,CPP_PIds,CEP_PIds,Densities,Plasticity,LinkForm}=InitState, S = #state{ sensors=Sensors, actuators=Actuators, spids=SPIds, apids=APIds, cpp_pids=CPP_PIds, cep_pids=CEP_PIds, densities = Densities, substrate_state_flag=reset, old_substrate=void, cur_substrate=init, plasticity=Plasticity, link_form = LinkForm }, substrate:loop(ExoSelf,S,SPIds,[]) end. loop(ExoSelf,S,[SPId|SPIds],SAcc)-> receive {SPId,forward,Sensory_Signal}-> loop(ExoSelf,S,SPIds,[Sensory_Signal|SAcc]); {ExoSelf,reset_substrate}-> U_S = S#state{ old_substrate=S#state.cur_substrate, substrate_state_flag=reset }, ExoSelf ! {self(),ready}, loop(ExoSelf,U_S,[SPId|SPIds],SAcc); {ExoSelf,backup_substrate} -> U_S = S#state{ old_substrate=S#state.cur_substrate, substrate_state_flag=reset }, ExoSelf ! {self(),ready}, loop(ExoSelf,U_S,[SPId|SPIds],SAcc); {ExoSelf,revert_substrate} -> U_S = S#state{ cur_substrate = S#state.old_substrate, substrate_state_flag=reset }, ExoSelf ! {self(),ready}, loop(ExoSelf,U_S,[SPId|SPIds],SAcc); {ExoSelf,terminate}-> io : format("Resulting ~ n",[Substrate ] ) , void after 20000 - > end; {U_Substrate,U_SMode,OAcc} = reason(SAcc,S), advanced_fanout(OAcc,S#state.actuators,S#state.apids), U_S = S#state{ cur_substrate=U_Substrate, substrate_state_flag=U_SMode }, loop(ExoSelf,U_S,S#state.spids,[]). reason(Input,S)-> Densities = S#state.densities, Substrate = S#state.cur_substrate, SMode = S#state.substrate_state_flag, case SMode of Sensors=S#state.sensors, Actuators=S#state.actuators, CPP_PIds = S#state.cpp_pids, CEP_PIds = S#state.cep_pids, Plasticity = S#state.plasticity, New_Substrate = create_substrate(Sensors,Densities,Actuators,S#state.link_form), io : format("New_Substrate:~p ~ n",[New_Substrate ] ) , {Output,Populated_Substrate} = calculate_ResetOutput(Densities,New_Substrate,Input,CPP_PIds,CEP_PIds,Plasticity,S#state.link_form), io : format("New_Substrate:~p ~ n Output:~p ~ n Populated_Substrate:~p ~ n",[New_Substrate , Output , Populated_Substrate ] ) , U_SMode=case Plasticity of iterative -> iterative; none -> hold; abcn -> hold; modular_none -> hold end, {Populated_Substrate,U_SMode,Output}; CPP_PIds = S#state.cpp_pids, CEP_PIds = S#state.cep_pids, {Output,U_Substrate} = calculate_IterativeOutput(Densities,Substrate,Input,CPP_PIds,CEP_PIds), io : ~ n Densities:~p ~ n Substrate:~p ~ n U_Substrate:~p ~ n CT:~p ~ n CF:~p ~ n",[Output , Densities , Substrate , U_Substrate , CT , CF ] ) , {U_Substrate,SMode,Output}; {Output,U_Substrate} = calculate_HoldOutput(Densities,Substrate,Input,S#state.link_form,S#state.plasticity), io : ~ n",[Output , Output ] ) , {U_Substrate,SMode,Output} end. advanced_fanout(OAcc,[Actuator|Actuators],[APId|APIds])-> {Output,OAccRem}=lists:split(Actuator#actuator.vl,OAcc), APId ! {self(),forward,Output}, advanced_fanout(OAccRem,Actuators,APIds); advanced_fanout([],[],[])-> ok. fanout([Pid|Pids],Msg)-> Pid ! Msg, fanout(Pids,Msg); fanout([],_Msg)-> true. flush_buffer()-> receive flush_buffer() after 0 -> done end. { asymetric,[[R1 .. Rp],[R1 .. Rt]],[Val1 ... Valn ] } where lists : sum(lists : flatten([[R1 ... .. Rt ] ] ) ) = = n , and depth = Dimension . test_cs()-> Sensors = [ #sensor{format=no_geo,vl=3}, #sensor{format={symetric,lists:reverse([2,3])},vl=6} ], Actuators = [ #actuator{format=no_geo,vl=2}, #actuator{format={symetric,lists:reverse([3,2])},vl=6} ], create_substrate(Sensors,[3,2,3,2],Actuators,l2l_feedforward). test_IS(SubstrateDimension)-> Sensors = [ #sensor{format=no_geo,vl=10}, #sensor{format={symetric,lists:reverse([3,4])},vl=[ 1,-1,-1,-1, 1,-1,-1,-1, 1,1,1,1]} ], compose_ISubstrate(Sensors,SubstrateDimension). test_OS(SubstrateDimension)-> Actuators = [ #actuator{format=no_geo,vl=10}, #actuator{format={symetric,lists:reverse([3,4])},vl=[ 1,-1,-1,-1, 1,-1,-1,-1, 1,1,1,1]} ], compose_OSubstrate(Actuators,SubstrateDimension,[w1,w2,w3]). create_substrate(Sensors,Densities,Actuators,LinkForm)-> [Depth|SubDensities] = Densities, Substrate_I = compose_ISubstrate(Sensors,length(Densities)), I_VL = length(Substrate_I), case LinkForm of l2l_feedforward -> Weight = 0, H = mult(SubDensities), IWeights = lists:duplicate(I_VL,Weight), HWeights = lists:duplicate(H,Weight); fully_interconnected -> Output_Neurodes = tot_ONeurodes(Actuators,0), Weight = 0, Tot_HiddenNeurodes = mult([Depth-1|SubDensities]), Tot_Weights = Tot_HiddenNeurodes + I_VL + Output_Neurodes, IWeights = lists:duplicate(Tot_Weights,Weight), HWeights = lists:duplicate(Tot_Weights,Weight); jordan_recurrent -> Output_Neurodes = tot_ONeurodes(Actuators,0), Weight = 0, H = mult(SubDensities), IWeights = lists:duplicate(I_VL+Output_Neurodes,Weight), HWeights = lists:duplicate(H,Weight); neuronself_recurrent -> Weight = 0, H = mult(SubDensities), IWeights = lists:duplicate(I_VL+1,Weight), HWeights = lists:duplicate(H+1,Weight) end, case Depth of 0 -> Substrate_O=compose_OSubstrate(Actuators,length(Densities),IWeights), [Substrate_I,Substrate_O]; 1 -> Substrate_R = cs(SubDensities,IWeights), Substrate_O=compose_OSubstrate(Actuators,length(Densities),HWeights), [Substrate_I,extrude(0,Substrate_R),Substrate_O]; _ -> Substrate_R = cs(SubDensities,IWeights), Substrate_H = cs(SubDensities,HWeights), Substrate_O=compose_OSubstrate(Actuators,length(Densities),HWeights), [_,RCoord|C1] = build_CoordList(Depth+1), [_|C2] = lists:reverse(C1), HCoords = lists:reverse(C2), io : , HCoords ] ) , ESubstrate_R = extrude(RCoord,Substrate_R), ESubstrates_H = [extrude(HCoord,Substrate_H) || HCoord<-HCoords], io : format("ESubstrate_R:~p ESubstrates_H:~p ~ n",[ESubstrate_R , ESubstrates_H ] ) , lists:append([[Substrate_I,ESubstrate_R],ESubstrates_H,[Substrate_O]]) end. compose_ISubstrate(Sensors,SubstrateDimension)-> compose_ISubstrate(Sensors,[],1,SubstrateDimension-2). compose_ISubstrate([S|Sensors],Acc,Max_Dim,Required_Dim)-> case S#sensor.format of undefined -> Dim=1, CoordLists = create_CoordLists([S#sensor.vl]), ISubstrate_Part=[{Coord,0,void}|| Coord<-CoordLists], {Dim,ISubstrate_Part}; no_geo -> Dim=1, CoordLists = create_CoordLists([S#sensor.vl]), ISubstrate_Part=[{Coord,0,void}|| Coord<-CoordLists], {Dim,ISubstrate_Part}; {symetric,Resolutions}-> Dim = length(Resolutions), Signal_Length = mult(Resolutions), CoordLists = create_CoordLists(Resolutions), ISubstrate_Part=[{Coord,0,void}|| Coord<-CoordLists], {Dim,ISubstrate_Part}; {coorded,Dim,Resolutions,ISubstrate_Part} -> {Dim,ISubstrate_Part} end, U_Dim = case Max_Dim > Dim of true -> Max_Dim; false -> Dim end, compose_ISubstrate(Sensors,[ISubstrate_Part|Acc],U_Dim,Required_Dim); compose_ISubstrate([],Acc,ISubstratePart_MaxDim,Required_Dim)-> case Required_Dim >= ISubstratePart_MaxDim of true -> ISubstrate_Depth = length(Acc), ISubstrate_DepthCoords = build_CoordList(ISubstrate_Depth), Passed in inverted , reversed inside , same for depth coords . false -> exit("Error in adv_extrude, Required_Depth < ISubstratePart_MaxDepth~n") end. adv_extrude([ISubstrate_Part|ISubstrate],Required_Dim,[IDepthCoord|ISubstrate_DepthCoords],LeadCoord,Acc)-> Extruded_ISP = [{[LeadCoord,IDepthCoord|lists:append(lists:duplicate(Required_Dim - length(Coord),0),Coord)],O,W} || {Coord,O,W}<-ISubstrate_Part], extrude(ISubstrate_Part,Required_Dim,IDepthCoord,[]), adv_extrude(ISubstrate,Required_Dim,ISubstrate_DepthCoords,LeadCoord,lists:append(Extruded_ISP,Acc)); adv_extrude([],_Required_Dim,[],_LeadCoord,Acc)-> Acc. extrude([{Coord,O,W}|ISubstrate_Part],Required_Dim,DepthCoord,Acc)-> Dim_Dif = Required_Dim - length(Coord), U_Coord= [1,DepthCoord|lists:append(lists:duplicate(Dim_Dif,0),Coord)], extrude(ISubstrate_Part,Required_Dim,DepthCoord,[{U_Coord,O,W}|Acc]); extrude([],_Required_Dim,_DepthCoord,Acc)-> Acc. compose_OSubstrate(Actuators,SubstrateDimension,Weights)-> compose_OSubstrate(Actuators,[],1,SubstrateDimension-2,Weights). compose_OSubstrate([A|Actuators],Acc,Max_Dim,Required_Dim,Weights)-> case A#actuator.format of Dim=1, CoordLists = create_CoordLists([A#actuator.vl]), OSubstrate_Part=[{Coord,0,Weights}|| Coord<-CoordLists], {Dim,OSubstrate_Part}; Dim=1, CoordLists = create_CoordLists([A#actuator.vl]), OSubstrate_Part=[{Coord,0,Weights}|| Coord<-CoordLists], {Dim,OSubstrate_Part}; Dim = length(Resolutions), Signal_Length = mult(Resolutions), CoordLists = create_CoordLists(Resolutions), OSubstrate_Part=[{Coord,0,Weights}|| Coord<-CoordLists], {Dim,OSubstrate_Part}; {coorded,Dim,Resolutions,Unadjusted_OSubstrate_Part} -> OSubstrate_Part=[{Coord,O,Weights}|| {Coord,O,_}<-Unadjusted_OSubstrate_Part], {Dim,OSubstrate_Part} end, U_Dim = case Max_Dim > Dim of true -> Max_Dim; false -> Dim end, compose_OSubstrate(Actuators,[OSubstrate_Part|Acc],U_Dim,Required_Dim,Weights); compose_OSubstrate([],Acc,OSubstratePart_MaxDim,Required_Dim,_Weights)-> case Required_Dim >= OSubstratePart_MaxDim of ISubstrate_Depth = length(Acc), ISubstrate_DepthCoords = build_CoordList(ISubstrate_Depth), Passed in inverted , reversed inside , same for depth coord false -> exit("Error in adv_extrude, Required_Depth < OSubstratePart_MaxDepth~n") end. find_depth(Resolutions)->find_depth(Resolutions,0). find_depth(Resolutions,Acc)-> case is_list(Resolutions) of true -> [_Head|Tail] = Resolutions, find_depth(Tail,Acc+1); false -> Acc end. Weights = [ W1,W2 ... WI ] , [ [ { [ , ... Wn]} ... {[Z1,Yn , Xk],o,[W1 ... Wn]}] ... [{[Zs , Y , X],o,[W1 ... Wn ] } ... ] ] , build_CoordList(Density)-> case Density == 1 of true -> [0.0]; false -> DensityDividers = Density - 1, Resolution = 2/DensityDividers, build_CoordList(Resolution,DensityDividers,1,[]) end. extend(I,DI,D,Substrate)-> void. mult(List)-> mult(List,1). mult([Val|List],Acc)-> mult(List,Val*Acc); mult([],Acc)-> Acc. tot_ONeurodes([A|Actuators],Acc)-> Tot_ANeurodes=case A#actuator.format of undefined -> A#actuator.vl; no_geo -> A#actuator.vl; {symetric,Resolutions}-> mult(Resolutions); {coorded,Dim,Resolutions,Unadjusted_OSubstrate_Part} -> length(Unadjusted_OSubstrate_Part) end, tot_ONeurodes(Actuators,Tot_ANeurodes+Acc); tot_ONeurodes([],Acc)-> Acc. cs(Densities,Weights)-> RDensities = lists:reverse(Densities), Substrate = create_CoordLists(RDensities,[]), attach(Substrate,0,Weights). create_CoordLists(Densities)-> create_CoordLists(Densities,[]). create_CoordLists([Density|RDensities],[])-> CoordList = build_CoordList(Density), XtendedCoordList = [[Coord]||Coord <- CoordList], create_CoordLists(RDensities,XtendedCoordList); create_CoordLists([Density|RDensities],Acc)-> CoordList = build_CoordList(Density), XtendedCoordList = [[Coord|Sub_Coord]||Coord <- CoordList,Sub_Coord <- Acc], create_CoordLists(RDensities,XtendedCoordList); create_CoordLists([],Acc)-> Acc. build_CoordList(Resolution,0,Coord,Acc)-> [-1|Acc]; build_CoordList(Resolution,DensityDividers,Coord,Acc)-> build_CoordList(Resolution,DensityDividers-1,Coord-Resolution,[Coord|Acc]). attach(List,E1,E2)-> attach(List,E1,E2,[]). attach([Val|List],E1,E2,Acc)-> attach(List,E1,E2,[{Val,E1,E2}|Acc]); attach([],_E1,_E2,Acc)-> lists:reverse(Acc). extrude(NewDimension_Coord,Substrate)-> extrude(NewDimension_Coord,Substrate,[]). extrude(NewDimension_Coord,[{Coord,O,W}|Substrate],Acc)-> extrude(NewDimension_Coord,Substrate,[{[NewDimension_Coord|Coord],O,W}|Acc]); extrude(_Coord,[],Acc)-> lists:reverse(Acc). { VL,{actuator , Actuator , Id , Parameters } } hypercube : [ { CTTag1,[{N_Id1,FilterTag1},{N_Id2,FilterTag2 } ... ] } ... ] CTTag:[{cartesian , VL } ... ] , FilterTag:{single , Index } | { block , VL } calculate_IterativeOutput(Densities,Substrate,Input,CPP_PIds,CEP_PIds)-> [IHyperlayer|PHyperlayers] = Substrate, Populated_IHyperlayer = populate_InputHyperlayer(IHyperlayer,lists:flatten(Input),[]), {Output,U_PHyperlayers} = update_PHyperlayers(Populated_IHyperlayer,PHyperlayers,CPP_PIds,CEP_PIds), {Output,[Populated_IHyperlayer|U_PHyperlayers]}. update_PHyperlayers(Populated_IHyperlayer,U_PHyperlayers,CPP_PIds,CEP_PIds)-> [CurPHyperlayer|RemPHyperlayers] = U_PHyperlayers, update_PHyperlayers(Populated_IHyperlayer,CurPHyperlayer,RemPHyperlayers,CPP_PIds,CEP_PIds,[],[]). update_PHyperlayers(PrevHyperlayer,[{Coord,PrevO,PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> U_O=calculate_output(PrevHyperlayer,{Coord,PrevO,PrevWeights},0), U_Weights = get_weights(PrevHyperlayer,Coord,CPP_PIds,CEP_PIds,[],PrevWeights,U_O), update_PHyperlayers(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,U_O,U_Weights}|Acc1],Acc2); update_PHyperlayers(_PrevHyperlayer,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> PrevHyperlayer = lists:reverse(Acc1), update_PHyperlayers(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[PrevHyperlayer|Acc2]); update_PHyperlayers(_PrevHyperlayer,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> OutputHyperlayer = lists:reverse(Acc1), {[O||{_Coord,O,_Weights}<-OutputHyperlayer],lists:reverse([OutputHyperlayer|Acc2])}. get_weights([{I_Coord,I,_I_Weights}|PrevHypercube],Coord,CPP_PIds,CEP_PIds,Acc,[W|Weights],O)-> plasticity_fanout(CPP_PIds,I_Coord,Coord,[I,O,W]), U_W=fanin(CEP_PIds,[]), get_weights(PrevHypercube,Coord,CPP_PIds,CEP_PIds,[functions:sat(U_W,3.1415,-3.1415)|Acc],Weights,O); get_weights([],_Coord,CPP_PIds,CEP_PIds,Acc,[],_O)-> lists:reverse(Acc). plasticity_fanout([CPP_PId|CPP_PIds],I_Coord,Coord,IOW)-> CPP_PId ! {self(),I_Coord,Coord,IOW}, plasticity_fanout(CPP_PIds,I_Coord,Coord,IOW); plasticity_fanout([],_I_Coord,_Coord,_IOW)-> done. fanin([CEP_PId|CEP_PIds],W)-> receive {CEP_PId,Command,Signal}-> U_W=substrate:Command(Signal,W) end, fanin(CEP_PIds,U_W); fanin([],W)-> W. set_weight(Signal,_WP)-> Threshold = 0.33 , Processed_Weight = if ( functions : ; ( functions : scale(Weight,-Threshold,-1)-1)/2 ; 0 [U_W] = Signal, U_W. weight_expression(Signal,_WP) -> [U_W,Expression]=Signal, case Expression > 0 of true -> U_W; false -> 0 end. set_abcn(Signal,_WP)-> [U_W,A,B,C,N] = Signal, {U_W,abcn,[A,B,C,N]}. iterative(Signal,{W,none})-> [Delta_Weight] = Signal, W + Delta_Weight. calculate_HoldOutput(Densities,Substrate,Input,LinkForm,Plasticity)-> [IHyperlayer|Populated_PHyperlayers] = Substrate, Populated_IHyperlayer = populate_InputHyperlayer(IHyperlayer,lists:flatten(Input),[]), {Output,U_PHyperlayers}=calculate_substrate_output(Populated_IHyperlayer,Populated_PHyperlayers,LinkForm,Plasticity), {Output,[IHyperlayer|U_PHyperlayers]}. calculate_ResetOutput(Densities,Substrate,Input,CPP_PIds,CEP_PIds,Plasticity,LinkForm)-> [IHyperlayer|PHyperlayers] = Substrate, Populated_IHyperlayer = populate_InputHyperlayer(IHyperlayer,lists:flatten(Input),[]), case Plasticity of iterative -> {Output,U_PHyperlayers}=calculate_substrate_output(Populated_IHyperlayer,PHyperlayers,LinkForm,Plasticity), {Output,[IHyperlayer|U_PHyperlayers]}; Populated_PHyperlayers = populate_PHyperlayers(Substrate,CPP_PIds,CEP_PIds,LinkForm), {Output,U_PHyperlayers}=calculate_substrate_output(Populated_IHyperlayer,Populated_PHyperlayers,LinkForm,Plasticity), {Output,[IHyperlayer|U_PHyperlayers]} end. populate_InputHyperlayer([{Coord,PrevO,void}|Substrate],[I|Input],Acc)-> populate_InputHyperlayer(Substrate,Input,[{Coord,I,void}|Acc]); populate_InputHyperlayer([],[],Acc)-> lists:reverse(Acc). populate_PHyperlayers(Substrate,CPP_PIds,CEP_PIds,LinkForm)-> case LinkForm of l2l_feedforward -> [PrevHypercube,CurHypercube|RemSubstrate] = Substrate, populate_PHyperlayers_l2l(PrevHypercube,CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]); fully_interconnected -> [_InputHypercube,CurHypercube|RemSubstrate] = Substrate, populate_PHyperlayers_fi(lists:flatten(Substrate),CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]); jordan_recurrent -> [IHypercube,CurHypercube|RemSubstrate] = Substrate, [OSubstrate|_]=lists:reverse(Substrate), populate_PHyperlayers_l2l(lists:flatten([IHypercube,OSubstrate]),CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]); neuronself_recurrent -> [PrevHypercube,CurHypercube|RemSubstrate] = Substrate, populate_PHyperlayers_nsr(PrevHypercube,CurHypercube,RemSubstrate,CPP_PIds,CEP_PIds,[],[]) end. populate_PHyperlayers_l2l(PrevHyperlayer,[{Coord,PrevO,PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> NewWeights = get_weights(PrevHyperlayer,Coord,CPP_PIds,CEP_PIds,[]), populate_PHyperlayers_l2l(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,PrevO,NewWeights}|Acc1],Acc2); populate_PHyperlayers_l2l(_PrevHyperlayer,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> PrevHyperlayer = lists:reverse(Acc1), populate_PHyperlayers_l2l(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[PrevHyperlayer|Acc2]); populate_PHyperlayers_l2l(_PrevHyperlayer,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> lists:reverse([lists:reverse(Acc1)|Acc2]). populate_PHyperlayers_fi(FlatSubstrate,[{Coord,PrevO,_PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> NewWeights = get_weights(FlatSubstrate,Coord,CPP_PIds,CEP_PIds,[]), populate_PHyperlayers_fi(FlatSubstrate,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,PrevO,NewWeights}|Acc1],Acc2); populate_PHyperlayers_fi(FlatSubstrate,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> populate_PHyperlayers_fi(FlatSubstrate,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[lists:reverse(Acc1)|Acc2]); populate_PHyperlayers_fi(_FlatSubstrate,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> lists:reverse([lists:reverse(Acc1)|Acc2]). populate_PHyperlayers_nsr(PrevHyperlayer,[{Coord,PrevO,_PrevWeights}|CurHyperlayer],Substrate,CPP_PIds,CEP_PIds,Acc1,Acc2)-> NewWeights = get_weights([{Coord,PrevO,_PrevWeights}|PrevHyperlayer],Coord,CPP_PIds,CEP_PIds,[]), populate_PHyperlayers_nsr(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[{Coord,PrevO,NewWeights}|Acc1],Acc2); populate_PHyperlayers_nsr(_PrevHyperlayer,[],[CurHyperlayer|Substrate],CPP_PIds,CEP_PIds,Acc1,Acc2)-> PrevHyperlayer = lists:reverse(Acc1), populate_PHyperlayers_nsr(PrevHyperlayer,CurHyperlayer,Substrate,CPP_PIds,CEP_PIds,[],[PrevHyperlayer|Acc2]); populate_PHyperlayers_nsr(_PrevHyperlayer,[],[],CPP_PIds,CEP_PIds,Acc1,Acc2)-> lists:reverse([lists:reverse(Acc1)|Acc2]). get_weights([{I_Coord,I,_I_Weights}|PrevHypercube],Coord,CPP_PIds,CEP_PIds,Acc)-> static_fanout(CPP_PIds,I_Coord,Coord), U_W=fanin(CEP_PIds,[]), get_weights(PrevHypercube,Coord,CPP_PIds,CEP_PIds,[functions:sat(U_W,3.1415,-3.1415)|Acc]); get_weights([],_Coord,_CPP_PIds,_CEP_PIds,Acc)-> lists:reverse(Acc). static_fanout([CPP_PId|CPP_PIds],I_Coord,Coord)-> CPP_PId ! {self(),I_Coord,Coord}, static_fanout(CPP_PIds,I_Coord,Coord); static_fanout([],_I_Coord,_Coord)-> done. calculate_substrate_output(ISubstrate,Substrate,LinkForm,Plasticity)-> case LinkForm of l2l_feedforward -> calculate_output_std(ISubstrate,Substrate,Plasticity,[]); fully_interconnected -> calculate_output_fi(ISubstrate,Substrate,Plasticity,[]); jordan_recurrent -> [OSubstrate|_] = lists:reverse(Substrate,Plasticity), calculate_output_std(lists:flatten([ISubstrate|OSubstrate]),Substrate,Plasticity,[]); neuronself_recurrent -> calculate_output_nsr(ISubstrate,Substrate,Plasticity,[]) end. calculate_output_std(Prev_Hyperlayer,[Cur_Hyperlayer|Substrate],Plasticity,Acc)-> Updated_CurHyperlayer = [{Coord,calculate_output(Prev_Hyperlayer,{Coord,Prev_O,Weights},Plasticity),Weights} || {Coord,Prev_O,Weights} <- Cur_Hyperlayer], io : ~ n",[Updated_CurHypercube ] ) , calculate_output_std(Updated_CurHyperlayer,Substrate,Plasticity,[Updated_CurHyperlayer|Acc]); calculate_output_std(Output_Hyperlayer,[],_Plasticity,Acc)-> {[Output || {_Coord,Output,_Weights} <- Output_Hyperlayer],lists:reverse(Acc)}. calculate_output(I_Neurodes,Neurode,Plasticity)-> case Plasticity of abcn -> calculate_neurode_output_plast(I_Neurodes,Neurode,0), update_neurode(I_Neurodes,Neurode); _ -> calculate_neurode_output_noplast(I_Neurodes,Neurode,0) end. calculate_neurode_output_noplast([{_I_Coord,O,_I_Weights}|I_Neurodes],{Coord,Prev_O,[Weight|Weights]},Acc)-> calculate_neurode_output_noplast(I_Neurodes,{Coord,Prev_O,Weights},O*Weight+Acc); calculate_neurode_output_noplast([],{Coord,Prev_O,[]},Acc)-> functions:tanh(Acc). calculate_neurode_output_plast([{_I_Coord,O,_I_Weights}|I_Neurodes],{Coord,Prev_O,[{W,_LF,_Parameters}|WPs]},Acc)-> calculate_neurode_output_plast(I_Neurodes,{Coord,Prev_O,WPs},O*W+Acc); calculate_neurode_output_plast([],{Coord,Prev_O,[]},Acc)-> functions:tanh(Acc). update_neurode(I_Neurodes,Neurode)-> ok. calculate_output_fi(Input_Substrate,[Cur_Hypercube|Substrate],Plasticity,Acc)-> Updated_CurHypercube = [{Coord,calculate_output(lists:flatten([Input_Substrate,Cur_Hypercube|Substrate]),{Coord,Prev_O,Weights},Plasticity),Weights} || {Coord,Prev_O,Weights} <- Cur_Hypercube], calculate_output_fi([Input_Substrate|Updated_CurHypercube],Substrate,Plasticity,Acc); calculate_output_fi(Output_Hyperlayer,[],_Plasticity,Acc)-> {[Output || {_Coord,Output,_Weights} <- Output_Hyperlayer],lists:reverse(Acc)}. calculate_output_nsr(Prev_Hypercube,[Cur_Hypercube|Substrate],Plasticity,Acc)-> Updated_CurHypercube = [{Coord,calculate_output([{Coord,Prev_O,Weights}|Prev_Hypercube],{Coord,Prev_O,Weights},Plasticity),Weights} || {Coord,Prev_O,Weights} <- Cur_Hypercube], calculate_output_nsr(Updated_CurHypercube,Substrate,Plasticity,Acc); calculate_output_nsr(Output_Hyperlayer,[],_Plasticity,Acc)-> {[Output || {_Coord,Output,_Weights} <- Output_Hyperlayer],lists:reverse(Acc)}.
5857b8cd4f205c544f072f594e3c44f81e939dff8943d8d2dd74ca7dfbbab517
ml-in-barcelona/ppxlib-simple-example
ppx.ml
open Ppxlib let expander ~loc ~path:_ = Ast_builder.Default.estring ~loc "r3p14ccd 70 r4nd0m 5tr1n9" let pattern = let open Ast_pattern in pstr nil let extension = Context_free.Rule.extension (Extension.declare "yay" Expression pattern expander) let () = Driver.register_transformation ~rules:[ extension ] "simple-ppx"
null
https://raw.githubusercontent.com/ml-in-barcelona/ppxlib-simple-example/14ce34f859f9ba5125584cf4bd28518cbaa3939c/src/ppx.ml
ocaml
open Ppxlib let expander ~loc ~path:_ = Ast_builder.Default.estring ~loc "r3p14ccd 70 r4nd0m 5tr1n9" let pattern = let open Ast_pattern in pstr nil let extension = Context_free.Rule.extension (Extension.declare "yay" Expression pattern expander) let () = Driver.register_transformation ~rules:[ extension ] "simple-ppx"
2c094db2d2bea58a5c0a815948c5f6e3b8e39f1f1ee4b00bd73071e21ffb661f
TrustInSoft/tis-interpreter
cabs_debug.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Cabs open Format let pp_cabsloc fmt (pos1 , _pos2) = fprintf fmt "%d,%s" pos1.Lexing.pos_lnum (Filename.basename (pos1.Lexing.pos_fname)) let pp_storage fmt = function | NO_STORAGE -> fprintf fmt "NO_STORAGE" | AUTO -> fprintf fmt "AUTO" | STATIC -> fprintf fmt "STATIC" | EXTERN -> fprintf fmt "EXTERN" | REGISTER -> fprintf fmt "REGISTER" let pp_fun_spec fmt = function | INLINE -> fprintf fmt "INLINE" | VIRTUAL -> fprintf fmt "VIRTUAL" | EXPLICIT -> fprintf fmt "EXPLICIT" let pp_cvspec fmt = function | CV_CONST -> fprintf fmt "CV_CONST" | CV_VOLATILE -> fprintf fmt "CV_VOLATILE" | CV_RESTRICT -> fprintf fmt "CV_RESTRICT" | CV_ATTRIBUTE_ANNOT s -> fprintf fmt "CV_ATTRIBUTE_ANNOT %s" s let pp_const fmt = function | CONST_INT s -> fprintf fmt "CONST_INT %s" s | CONST_FLOAT s -> fprintf fmt "CONST_FLOAT %s" s | CONST_CHAR l -> fprintf fmt "CONST_CHAR{"; List.iter (fun i -> fprintf fmt ",@ %s" (Int64.to_string i)) l; fprintf fmt "}" | CONST_WCHAR l -> fprintf fmt "CONST_WCHAR{"; List.iter (fun i -> fprintf fmt ",@ %s" (Int64.to_string i)) l; fprintf fmt "}" | CONST_STRING s -> fprintf fmt "CONST_STRING %s" s | CONST_WSTRING l -> fprintf fmt "CONST_WSTRING{"; List.iter (fun i -> fprintf fmt ",@ %s" (Int64.to_string i)) l; fprintf fmt "}" let pp_labels fmt lbls = fprintf fmt "%s" (String.concat " " lbls) let rec pp_typeSpecifier fmt = function | Tvoid -> fprintf fmt "Tvoid" | Tchar -> fprintf fmt "Tchar" | Tbool -> fprintf fmt "Tbool" | Tshort -> fprintf fmt "Tshort" | Tint -> fprintf fmt "Tint" | Tlong -> fprintf fmt "Tlong" | Tint64 -> fprintf fmt "Tint64" | Tfloat -> fprintf fmt "Tfloat" | Tdouble -> fprintf fmt "Tdouble" | Tsigned -> fprintf fmt "Tsigned" | Tunsigned -> fprintf fmt "Tunsigned" | Tnamed s -> fprintf fmt "%s" s | Tstruct (sname, None, alist) -> fprintf fmt "struct@ %s {} %a" sname pp_attrs alist | Tstruct (sname, Some fd_gp_list, alist) -> fprintf fmt "struct@ %s {%a}@ attrs=(%a)" sname pp_field_groups fd_gp_list pp_attrs alist | Tunion (uname, None, alist) -> fprintf fmt "union@ %s {} %a" uname pp_attrs alist | Tunion (uname, Some fd_gp_list, alist) -> fprintf fmt "union@ %s {%a}@ attrs=(%a)" uname pp_field_groups fd_gp_list pp_attrs alist | Tenum (ename, None, alist) -> fprintf fmt "enum@ %s {} %a" ename pp_attrs alist | Tenum (ename, Some e_item_list, alist) -> fprintf fmt "enum@ %s {" ename; List.iter (fun e -> fprintf fmt ",@ %a" pp_enum_item e) e_item_list; fprintf fmt "}@ %a" pp_attrs alist; | TtypeofE exp -> fprintf fmt "typeOfE %a" pp_exp exp | TtypeofT (spec, d_type) -> fprintf fmt "typeOfT(%a,%a)" pp_spec spec pp_decl_type d_type and pp_spec_elem fmt = function | SpecTypedef -> fprintf fmt "SpecTypedef" | SpecCV cvspec -> fprintf fmt "SpecCV %a" pp_cvspec cvspec | SpecAttr attr -> fprintf fmt "SpecAttr %a" pp_attr attr | SpecStorage storage -> fprintf fmt "SpecStorage %a" pp_storage storage | SpecInline -> fprintf fmt "SpecInline" | SpecType typeSpec -> fprintf fmt "SpecType %a" pp_typeSpecifier typeSpec | SpecPattern s -> fprintf fmt "SpecPattern %s" s and pp_spec fmt spec_elems = fprintf fmt "@[<hv 2>{" ; List.iter (fun s -> fprintf fmt "@ %a" pp_spec_elem s) spec_elems ; fprintf fmt "} @]" and pp_decl_type fmt = function | JUSTBASE -> fprintf fmt "@[<hov 2>JUSTBASE@]" | PARENTYPE (attrs1, decl_type, attrs2) -> fprintf fmt "@[<hov 2>PARENTYPE(%a, %a, %a)@]" pp_attrs attrs1 pp_decl_type decl_type pp_attrs attrs2 | ARRAY (decl_type, attrs, exp) -> fprintf fmt "@[<hov 2>ARRAY[%a, %a, %a]@]" pp_decl_type decl_type pp_attrs attrs pp_exp exp | PTR (attrs, decl_type) -> fprintf fmt "@[<hov 2>PTR(%a, %a)@]" pp_attrs attrs pp_decl_type decl_type | PROTO (decl_type, single_names, b) -> fprintf fmt "@[<hov 2>PROTO decl_type(%a), single_names(" pp_decl_type decl_type; List.iter (fun sn -> fprintf fmt ",@ %a" pp_single_name sn) single_names; fprintf fmt "),@ %b@]" b and pp_name_group fmt (spec, names) = fprintf fmt "@[<hov 2>name_group@ spec(%a), names{" pp_spec spec; List.iter (fun n -> fprintf fmt "@ %a" pp_name n) names; fprintf fmt "}@]" Warning : printing for is not complete and pp_field_group fmt = function | FIELD (spec, l) -> fprintf fmt "@[<hov 2>FIELD spec(%a), {" pp_spec spec; List.iter (fun (n,e_opt) -> fprintf fmt "@ %a" pp_name n; match e_opt with Some exp -> fprintf fmt "@ %a" pp_exp exp | _ -> ()) l; fprintf fmt "}@]" | TYPE_ANNOT _ -> fprintf fmt "TYPE_ANNOT" and pp_field_groups fmt l = fprintf fmt "{"; List.iter (fun a -> fprintf fmt ",@ %a" pp_field_group a) l; fprintf fmt "}" and pp_init_name_group fmt (spec,init_names) = fprintf fmt "@[<hov 2>init_name_group spec(%a), {" pp_spec spec; List.iter ( fun i -> fprintf fmt "@ %a" pp_init_name i) init_names; fprintf fmt "}@]" and pp_name fmt (s,decl_type,attrs,loc) = fprintf fmt "name %s, decl_type(%a), attrs(%a), loc(%a)" s pp_decl_type decl_type pp_attrs attrs pp_cabsloc loc and pp_init_name fmt (name,init_exp) = fprintf fmt "init_name name(%a), init_exp(%a)" pp_name name pp_init_exp init_exp and pp_single_name fmt (spec,name) = fprintf fmt "@[<hov 2>single_name{spec(%a), name(%a)}@]" pp_spec spec pp_name name and pp_enum_item fmt (s,exp,loc) = fprintf fmt "@[<hov 2>enum_item %s, exp(%a, loc(%a))@]" s pp_exp exp pp_cabsloc loc Warning : printing for GLOBANNOT and CUSTOM is not complete and pp_def fmt = function | FUNDEF (_, single_name, bl, loc1, loc2) -> fprintf fmt "@[<hov 2>FUNDEF (%a), loc1(%a), loc2(%a) {%a} @]" pp_single_name single_name pp_cabsloc loc1 pp_cabsloc loc2 pp_block bl | DECDEF (_, init_name_group, loc) -> fprintf fmt "@[<hov 2>DECDEF (%a, loc(%a))@]" pp_init_name_group init_name_group pp_cabsloc loc | TYPEDEF (name_group, loc) -> (* typedef normal *) fprintf fmt "@[<hov 2>TYPEDEF (%a), loc(%a)@]" pp_name_group name_group pp_cabsloc loc | ONLYTYPEDEF (spec, loc) -> (* ex : struct s{...}; *) fprintf fmt "@[<hov 2>ONLYTYPEDEF (%a), loc(%a)@]" pp_spec spec pp_cabsloc loc | GLOBASM (s, loc) -> fprintf fmt "@[<hov 2>GLOBASM %s, loc(%a)@]" s pp_cabsloc loc | PRAGMA (exp, loc) -> fprintf fmt "@[<hov 2>PRAGMA exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | LINKAGE (s, loc, defs) -> fprintf fmt "@[<hov 2>LINKAGE %s, loc(%a), defs(" s pp_cabsloc loc; List.iter (fun def -> fprintf fmt ",@ def(%a)" pp_def def) defs; fprintf fmt ")@]" | GLOBANNOT _ -> fprintf fmt "GLOBANNOT" | CUSTOM _ -> fprintf fmt "CUSTOM" and pp_file fmt (s,l) = fprintf fmt "@[FILE %s, {" s; List.iter (fun (b,def) -> fprintf fmt "@ %b, def(%a)" b pp_def def) l; fprintf fmt "@] }" and pp_block fmt bl = fprintf fmt "@[<hv 2>labels(%a), attrs(%a), {" pp_labels bl.blabels pp_attrs bl.battrs; List.iter (fun s -> fprintf fmt "@ %a" pp_stmt s) bl.bstmts ; fprintf fmt "}@]" Warning : printing for ASM , and CODE_SPEC is not complete and pp_raw_stmt fmt = function | NOP loc -> fprintf fmt "@[<hov 2>NOP loc(%a)@]" pp_cabsloc loc | COMPUTATION (exp, loc) -> fprintf fmt "@[<hov 2>COMPUTATION exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | BLOCK (bl, loc1, loc2) -> fprintf fmt "@[<hov 2>BLOCK loc1(%a), loc2(%a) {%a} @]" pp_cabsloc loc1 pp_cabsloc loc2 pp_block bl | SEQUENCE (stmt1, stmt2, loc) -> fprintf fmt "@[<hov 2>SEQUENCE stmt(%a), stmt(%a), loc(%a)@]" pp_stmt stmt1 pp_stmt stmt2 pp_cabsloc loc | IF (exp, stmt1, stmt2, loc) -> fprintf fmt "@[<hov 2>IF cond(%a), stmt(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt1 pp_stmt stmt2 pp_cabsloc loc | WHILE (_loop_inv, exp, stmt, loc) -> (* Warning : no printing for loop_invariant *) fprintf fmt "@[<hov 2>WHILE cond(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc | DOWHILE (_loop_inv, exp, stmt, loc) -> (* Warning : no printing for loop_invariant *) fprintf fmt "@[<hov 2>DOWHILE cond(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc | FOR (_loop_inv, for_clause, exp1, exp2, stmt, loc) -> (* Warning : no printing for loop_invariant *) fprintf fmt "@[<hov 2>FOR for_clause(%a), exp1(%a), exp2(%a), stmt(%a), loc(%a)@]" pp_for_clause for_clause pp_exp exp1 pp_exp exp2 pp_stmt stmt pp_cabsloc loc | BREAK loc -> fprintf fmt "@[<hov 2>BREAK loc(%a)@]" pp_cabsloc loc | CONTINUE loc -> fprintf fmt "@[<hov 2>CONTINUE loc(%a)@]" pp_cabsloc loc | RETURN (exp, loc) -> fprintf fmt "@[<hov 2>RETURN exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | SWITCH (exp, stmt, loc) -> fprintf fmt "@[<hov 2>SWITH exp(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc | CASE (exp, stmt, loc) -> fprintf fmt "@[<hov 2>CASE exp(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc | CASERANGE (exp1, exp2, stmt, loc) -> fprintf fmt "@[<hov 2>CASE exp(%a), exp(%a), stmt(%a), loc(%a)@]" pp_exp exp1 pp_exp exp2 pp_stmt stmt pp_cabsloc loc | DEFAULT (stmt, loc) -> fprintf fmt "@[<hov 2>DEFAULT stmt(%a), loc(%a)@]" pp_stmt stmt pp_cabsloc loc | LABEL (s, stmt, loc) -> fprintf fmt "@[<hov 2>LABEL %s stmt(%a), loc(%a)@]" s pp_stmt stmt pp_cabsloc loc | GOTO (s, loc) -> fprintf fmt "@[<hov 2>GOTO %s, loc(%a)@]" s pp_cabsloc loc | COMPGOTO (exp, loc) -> fprintf fmt "@[<hov 2>COMPGOTO exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | DEFINITION def -> fprintf fmt "@[<hov 2>DEFINITION %a@]" pp_def def | ASM (_,_,_,_) -> fprintf fmt "ASM" | TRY_EXCEPT (bl1, exp, bl2, loc) -> fprintf fmt "@[<hov 2>TRY_EXCEPT block(%a) exp(%a) block(%a) loc(%a)@]" pp_block bl1 pp_exp exp pp_block bl2 pp_cabsloc loc | TRY_FINALLY (bl1, bl2, loc) -> fprintf fmt "@[<hov 2>TRY_EXCEPT block(%a) block(%a) loc(%a)@]" pp_block bl1 pp_block bl2 pp_cabsloc loc | THROW(e,loc) -> fprintf fmt "@[<hov 2>THROW %a, loc(%a)@]" (Pretty_utils.pp_opt pp_exp) e pp_cabsloc loc | TRY_CATCH(s,l,loc) -> let print_one_catch fmt (v,s) = fprintf fmt "@[<v 2>@[CATCH %a {@]@;%a@]@;}" (Pretty_utils.pp_opt pp_single_name) v pp_stmt s in fprintf fmt "@[<v 2>@[TRY %a (loc %a) {@]@;%a@]@;}" pp_stmt s pp_cabsloc loc (Pretty_utils.pp_list ~sep:"@;" print_one_catch) l | CODE_ANNOT (_,_) -> fprintf fmt "CODE_ANNOT" | CODE_SPEC _ -> fprintf fmt "CODE_SPEC" and pp_stmt fmt stmt = fprintf fmt "@[<hov 2>ghost(%b), stmt(%a)@]" stmt.stmt_ghost pp_raw_stmt stmt.stmt_node (*and loop_invariant = Logic_ptree.code_annot list *) and pp_for_clause fmt = function | FC_EXP exp -> fprintf fmt "@[<hov 2>FC_EXP %a@]" pp_exp exp | FC_DECL def -> fprintf fmt "@[<hov 2>FC_DECL %a@]" pp_def def and pp_bin_op fmt = function | ADD -> fprintf fmt "ADD" | SUB -> fprintf fmt "SUB" | MUL -> fprintf fmt "MUL" | DIV -> fprintf fmt "DIV" | MOD -> fprintf fmt "MOD" | AND -> fprintf fmt "AND" | OR -> fprintf fmt "OR" | BAND -> fprintf fmt "BAND" | BOR -> fprintf fmt "BOR" | XOR -> fprintf fmt "XOR" | SHL -> fprintf fmt "SHL" | SHR -> fprintf fmt "SHR" | EQ -> fprintf fmt "EQ" | NE -> fprintf fmt "NE" | LT -> fprintf fmt "LT" | GT -> fprintf fmt "GT" | LE -> fprintf fmt "LE" | GE -> fprintf fmt "GE" | ASSIGN -> fprintf fmt "ASSIGN" | ADD_ASSIGN -> fprintf fmt "ADD_ASSIGN" | SUB_ASSIGN -> fprintf fmt "SUB_ASSIGN" | MUL_ASSIGN -> fprintf fmt "MUL_ASSIGN" | DIV_ASSIGN -> fprintf fmt "DIV_ASSIGN" | MOD_ASSIGN -> fprintf fmt "MOD_ASSIGN" | BAND_ASSIGN -> fprintf fmt "BAND_ASSIGN" | BOR_ASSIGN -> fprintf fmt "BOR_ASSIGN" | XOR_ASSIGN -> fprintf fmt "XOR_ASSIGN" | SHL_ASSIGN -> fprintf fmt "SHL_ASSIGN" | SHR_ASSIGN -> fprintf fmt "SHR_ASSIGN" and pp_un_op fmt = function | MINUS -> fprintf fmt "MINUS" | PLUS -> fprintf fmt "PLUS" | NOT -> fprintf fmt "NOT" | BNOT -> fprintf fmt "BNOT" | MEMOF -> fprintf fmt "MEMOF" | ADDROF -> fprintf fmt "ADDROF" | PREINCR -> fprintf fmt "PREINCR" | PREDECR -> fprintf fmt "PREDECR" | POSINCR -> fprintf fmt "POSINCR" | POSDECR -> fprintf fmt "POSDECR" and pp_exp fmt exp = fprintf fmt "exp(%a)" pp_exp_node exp.expr_node and pp_exp_node fmt = function | NOTHING -> fprintf fmt "NOTHING" | UNARY (un_op, exp) -> fprintf fmt "@[<hov 2>%a(%a)@]" pp_un_op un_op pp_exp exp | LABELADDR s -> fprintf fmt "@[<hov 2>LABELADDR %s@]" s | BINARY (bin_op, exp1, exp2) -> fprintf fmt "@[<hov 2>%a %a %a@]" pp_exp exp1 pp_bin_op bin_op pp_exp exp2 | QUESTION (exp1, exp2, exp3) -> fprintf fmt "@[<hov 2>QUESTION(%a, %a, %a)@]" pp_exp exp1 pp_exp exp2 pp_exp exp3 | CAST ((spec, decl_type), init_exp) -> fprintf fmt "@[<hov 2>CAST (%a, %a) %a@]" pp_spec spec pp_decl_type decl_type pp_init_exp init_exp | CALL (exp1, exps) -> fprintf fmt "@[<hov 2>CALL %a {" pp_exp exp1; List.iter (fun e -> fprintf fmt ",@ %a" pp_exp e) exps; fprintf fmt "}@]" | COMMA exps -> fprintf fmt "@[<hov 2>COMMA {"; List.iter (fun e -> fprintf fmt ",@ %a" pp_exp e) exps; fprintf fmt "}@]" | CONSTANT c -> fprintf fmt "%a" pp_const c | PAREN exp -> fprintf fmt "PAREN(%a)" pp_exp exp | VARIABLE s -> fprintf fmt "VAR %s" s | EXPR_SIZEOF exp -> fprintf fmt "EXPR_SIZEOF(%a)" pp_exp exp | TYPE_SIZEOF (spec, decl_type) -> fprintf fmt "TYP_SIZEOF(%a,%a)" pp_spec spec pp_decl_type decl_type | EXPR_ALIGNOF exp -> fprintf fmt "EXPR_ALIGNOF(%a)" pp_exp exp | TYPE_ALIGNOF (spec, decl_type) -> fprintf fmt "TYP_ALIGNEOF(%a,%a)" pp_spec spec pp_decl_type decl_type | INDEX (exp1, exp2) -> fprintf fmt "INDEX(%a, %a)" pp_exp exp1 pp_exp exp2 | MEMBEROF (exp, s) -> fprintf fmt "MEMBEROF(%a,%s)" pp_exp exp s | MEMBEROFPTR (exp, s) -> fprintf fmt "MEMBEROFPTR(%a,%s)" pp_exp exp s | GNU_BODY bl -> fprintf fmt "GNU_BODY %a" pp_block bl | EXPR_PATTERN s -> fprintf fmt "EXPR_PATTERN %s" s and pp_init_exp fmt = function | NO_INIT -> fprintf fmt "NO_INIT" | SINGLE_INIT exp -> fprintf fmt "SINGLE_INIT %a" pp_exp exp | COMPOUND_INIT l -> fprintf fmt "@[<hov 2>COMPOUND_INIT {"; match l with | [] -> fprintf fmt "}@]" | (iw, ie)::rest -> fprintf fmt ",@ (%a, %a)" pp_initwhat iw pp_init_exp ie; List.iter (fun (iw, ie) -> fprintf fmt ",@ (%a, %a)" pp_initwhat iw pp_init_exp ie) rest; fprintf fmt "}@]" and pp_initwhat fmt = function | NEXT_INIT -> fprintf fmt "NEXT_INIT" | INFIELD_INIT (s,iw) -> fprintf fmt "@[<hov 2>INFIELD_INIT (%s, %a)@]" s pp_initwhat iw | ATINDEX_INIT (exp,iw) -> fprintf fmt "@[<hov 2>ATINDEX_INIT (%a, %a)@]" pp_exp exp pp_initwhat iw | ATINDEXRANGE_INIT (exp1, exp2) -> fprintf fmt "@[<hov 2>ATINDEXRANGE_INIT (%a, %a)@]" pp_exp exp1 pp_exp exp2 and pp_attr fmt (s,el) = fprintf fmt "ATTR (%s, {" s; match el with | [] -> fprintf fmt "})" | e :: es -> fprintf fmt ",@ %a" pp_exp e; List.iter (fun e -> fprintf fmt ",@ %a" pp_exp e) es; fprintf fmt "})" and pp_attrs fmt l = fprintf fmt "{"; match l with | [] -> fprintf fmt "}" | a :: attrs -> fprintf fmt ",@ %a" pp_attr a; List.iter (fun a -> fprintf fmt ",@ %a" pp_attr a) attrs; fprintf fmt "}"
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/kernel_services/ast_printing/cabs_debug.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ typedef normal ex : struct s{...}; Warning : no printing for loop_invariant Warning : no printing for loop_invariant Warning : no printing for loop_invariant and loop_invariant = Logic_ptree.code_annot list
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cabs open Format let pp_cabsloc fmt (pos1 , _pos2) = fprintf fmt "%d,%s" pos1.Lexing.pos_lnum (Filename.basename (pos1.Lexing.pos_fname)) let pp_storage fmt = function | NO_STORAGE -> fprintf fmt "NO_STORAGE" | AUTO -> fprintf fmt "AUTO" | STATIC -> fprintf fmt "STATIC" | EXTERN -> fprintf fmt "EXTERN" | REGISTER -> fprintf fmt "REGISTER" let pp_fun_spec fmt = function | INLINE -> fprintf fmt "INLINE" | VIRTUAL -> fprintf fmt "VIRTUAL" | EXPLICIT -> fprintf fmt "EXPLICIT" let pp_cvspec fmt = function | CV_CONST -> fprintf fmt "CV_CONST" | CV_VOLATILE -> fprintf fmt "CV_VOLATILE" | CV_RESTRICT -> fprintf fmt "CV_RESTRICT" | CV_ATTRIBUTE_ANNOT s -> fprintf fmt "CV_ATTRIBUTE_ANNOT %s" s let pp_const fmt = function | CONST_INT s -> fprintf fmt "CONST_INT %s" s | CONST_FLOAT s -> fprintf fmt "CONST_FLOAT %s" s | CONST_CHAR l -> fprintf fmt "CONST_CHAR{"; List.iter (fun i -> fprintf fmt ",@ %s" (Int64.to_string i)) l; fprintf fmt "}" | CONST_WCHAR l -> fprintf fmt "CONST_WCHAR{"; List.iter (fun i -> fprintf fmt ",@ %s" (Int64.to_string i)) l; fprintf fmt "}" | CONST_STRING s -> fprintf fmt "CONST_STRING %s" s | CONST_WSTRING l -> fprintf fmt "CONST_WSTRING{"; List.iter (fun i -> fprintf fmt ",@ %s" (Int64.to_string i)) l; fprintf fmt "}" let pp_labels fmt lbls = fprintf fmt "%s" (String.concat " " lbls) let rec pp_typeSpecifier fmt = function | Tvoid -> fprintf fmt "Tvoid" | Tchar -> fprintf fmt "Tchar" | Tbool -> fprintf fmt "Tbool" | Tshort -> fprintf fmt "Tshort" | Tint -> fprintf fmt "Tint" | Tlong -> fprintf fmt "Tlong" | Tint64 -> fprintf fmt "Tint64" | Tfloat -> fprintf fmt "Tfloat" | Tdouble -> fprintf fmt "Tdouble" | Tsigned -> fprintf fmt "Tsigned" | Tunsigned -> fprintf fmt "Tunsigned" | Tnamed s -> fprintf fmt "%s" s | Tstruct (sname, None, alist) -> fprintf fmt "struct@ %s {} %a" sname pp_attrs alist | Tstruct (sname, Some fd_gp_list, alist) -> fprintf fmt "struct@ %s {%a}@ attrs=(%a)" sname pp_field_groups fd_gp_list pp_attrs alist | Tunion (uname, None, alist) -> fprintf fmt "union@ %s {} %a" uname pp_attrs alist | Tunion (uname, Some fd_gp_list, alist) -> fprintf fmt "union@ %s {%a}@ attrs=(%a)" uname pp_field_groups fd_gp_list pp_attrs alist | Tenum (ename, None, alist) -> fprintf fmt "enum@ %s {} %a" ename pp_attrs alist | Tenum (ename, Some e_item_list, alist) -> fprintf fmt "enum@ %s {" ename; List.iter (fun e -> fprintf fmt ",@ %a" pp_enum_item e) e_item_list; fprintf fmt "}@ %a" pp_attrs alist; | TtypeofE exp -> fprintf fmt "typeOfE %a" pp_exp exp | TtypeofT (spec, d_type) -> fprintf fmt "typeOfT(%a,%a)" pp_spec spec pp_decl_type d_type and pp_spec_elem fmt = function | SpecTypedef -> fprintf fmt "SpecTypedef" | SpecCV cvspec -> fprintf fmt "SpecCV %a" pp_cvspec cvspec | SpecAttr attr -> fprintf fmt "SpecAttr %a" pp_attr attr | SpecStorage storage -> fprintf fmt "SpecStorage %a" pp_storage storage | SpecInline -> fprintf fmt "SpecInline" | SpecType typeSpec -> fprintf fmt "SpecType %a" pp_typeSpecifier typeSpec | SpecPattern s -> fprintf fmt "SpecPattern %s" s and pp_spec fmt spec_elems = fprintf fmt "@[<hv 2>{" ; List.iter (fun s -> fprintf fmt "@ %a" pp_spec_elem s) spec_elems ; fprintf fmt "} @]" and pp_decl_type fmt = function | JUSTBASE -> fprintf fmt "@[<hov 2>JUSTBASE@]" | PARENTYPE (attrs1, decl_type, attrs2) -> fprintf fmt "@[<hov 2>PARENTYPE(%a, %a, %a)@]" pp_attrs attrs1 pp_decl_type decl_type pp_attrs attrs2 | ARRAY (decl_type, attrs, exp) -> fprintf fmt "@[<hov 2>ARRAY[%a, %a, %a]@]" pp_decl_type decl_type pp_attrs attrs pp_exp exp | PTR (attrs, decl_type) -> fprintf fmt "@[<hov 2>PTR(%a, %a)@]" pp_attrs attrs pp_decl_type decl_type | PROTO (decl_type, single_names, b) -> fprintf fmt "@[<hov 2>PROTO decl_type(%a), single_names(" pp_decl_type decl_type; List.iter (fun sn -> fprintf fmt ",@ %a" pp_single_name sn) single_names; fprintf fmt "),@ %b@]" b and pp_name_group fmt (spec, names) = fprintf fmt "@[<hov 2>name_group@ spec(%a), names{" pp_spec spec; List.iter (fun n -> fprintf fmt "@ %a" pp_name n) names; fprintf fmt "}@]" Warning : printing for is not complete and pp_field_group fmt = function | FIELD (spec, l) -> fprintf fmt "@[<hov 2>FIELD spec(%a), {" pp_spec spec; List.iter (fun (n,e_opt) -> fprintf fmt "@ %a" pp_name n; match e_opt with Some exp -> fprintf fmt "@ %a" pp_exp exp | _ -> ()) l; fprintf fmt "}@]" | TYPE_ANNOT _ -> fprintf fmt "TYPE_ANNOT" and pp_field_groups fmt l = fprintf fmt "{"; List.iter (fun a -> fprintf fmt ",@ %a" pp_field_group a) l; fprintf fmt "}" and pp_init_name_group fmt (spec,init_names) = fprintf fmt "@[<hov 2>init_name_group spec(%a), {" pp_spec spec; List.iter ( fun i -> fprintf fmt "@ %a" pp_init_name i) init_names; fprintf fmt "}@]" and pp_name fmt (s,decl_type,attrs,loc) = fprintf fmt "name %s, decl_type(%a), attrs(%a), loc(%a)" s pp_decl_type decl_type pp_attrs attrs pp_cabsloc loc and pp_init_name fmt (name,init_exp) = fprintf fmt "init_name name(%a), init_exp(%a)" pp_name name pp_init_exp init_exp and pp_single_name fmt (spec,name) = fprintf fmt "@[<hov 2>single_name{spec(%a), name(%a)}@]" pp_spec spec pp_name name and pp_enum_item fmt (s,exp,loc) = fprintf fmt "@[<hov 2>enum_item %s, exp(%a, loc(%a))@]" s pp_exp exp pp_cabsloc loc Warning : printing for GLOBANNOT and CUSTOM is not complete and pp_def fmt = function | FUNDEF (_, single_name, bl, loc1, loc2) -> fprintf fmt "@[<hov 2>FUNDEF (%a), loc1(%a), loc2(%a) {%a} @]" pp_single_name single_name pp_cabsloc loc1 pp_cabsloc loc2 pp_block bl | DECDEF (_, init_name_group, loc) -> fprintf fmt "@[<hov 2>DECDEF (%a, loc(%a))@]" pp_init_name_group init_name_group pp_cabsloc loc fprintf fmt "@[<hov 2>TYPEDEF (%a), loc(%a)@]" pp_name_group name_group pp_cabsloc loc fprintf fmt "@[<hov 2>ONLYTYPEDEF (%a), loc(%a)@]" pp_spec spec pp_cabsloc loc | GLOBASM (s, loc) -> fprintf fmt "@[<hov 2>GLOBASM %s, loc(%a)@]" s pp_cabsloc loc | PRAGMA (exp, loc) -> fprintf fmt "@[<hov 2>PRAGMA exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | LINKAGE (s, loc, defs) -> fprintf fmt "@[<hov 2>LINKAGE %s, loc(%a), defs(" s pp_cabsloc loc; List.iter (fun def -> fprintf fmt ",@ def(%a)" pp_def def) defs; fprintf fmt ")@]" | GLOBANNOT _ -> fprintf fmt "GLOBANNOT" | CUSTOM _ -> fprintf fmt "CUSTOM" and pp_file fmt (s,l) = fprintf fmt "@[FILE %s, {" s; List.iter (fun (b,def) -> fprintf fmt "@ %b, def(%a)" b pp_def def) l; fprintf fmt "@] }" and pp_block fmt bl = fprintf fmt "@[<hv 2>labels(%a), attrs(%a), {" pp_labels bl.blabels pp_attrs bl.battrs; List.iter (fun s -> fprintf fmt "@ %a" pp_stmt s) bl.bstmts ; fprintf fmt "}@]" Warning : printing for ASM , and CODE_SPEC is not complete and pp_raw_stmt fmt = function | NOP loc -> fprintf fmt "@[<hov 2>NOP loc(%a)@]" pp_cabsloc loc | COMPUTATION (exp, loc) -> fprintf fmt "@[<hov 2>COMPUTATION exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | BLOCK (bl, loc1, loc2) -> fprintf fmt "@[<hov 2>BLOCK loc1(%a), loc2(%a) {%a} @]" pp_cabsloc loc1 pp_cabsloc loc2 pp_block bl | SEQUENCE (stmt1, stmt2, loc) -> fprintf fmt "@[<hov 2>SEQUENCE stmt(%a), stmt(%a), loc(%a)@]" pp_stmt stmt1 pp_stmt stmt2 pp_cabsloc loc | IF (exp, stmt1, stmt2, loc) -> fprintf fmt "@[<hov 2>IF cond(%a), stmt(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt1 pp_stmt stmt2 pp_cabsloc loc fprintf fmt "@[<hov 2>WHILE cond(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc fprintf fmt "@[<hov 2>DOWHILE cond(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc fprintf fmt "@[<hov 2>FOR for_clause(%a), exp1(%a), exp2(%a), stmt(%a), loc(%a)@]" pp_for_clause for_clause pp_exp exp1 pp_exp exp2 pp_stmt stmt pp_cabsloc loc | BREAK loc -> fprintf fmt "@[<hov 2>BREAK loc(%a)@]" pp_cabsloc loc | CONTINUE loc -> fprintf fmt "@[<hov 2>CONTINUE loc(%a)@]" pp_cabsloc loc | RETURN (exp, loc) -> fprintf fmt "@[<hov 2>RETURN exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | SWITCH (exp, stmt, loc) -> fprintf fmt "@[<hov 2>SWITH exp(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc | CASE (exp, stmt, loc) -> fprintf fmt "@[<hov 2>CASE exp(%a), stmt(%a), loc(%a)@]" pp_exp exp pp_stmt stmt pp_cabsloc loc | CASERANGE (exp1, exp2, stmt, loc) -> fprintf fmt "@[<hov 2>CASE exp(%a), exp(%a), stmt(%a), loc(%a)@]" pp_exp exp1 pp_exp exp2 pp_stmt stmt pp_cabsloc loc | DEFAULT (stmt, loc) -> fprintf fmt "@[<hov 2>DEFAULT stmt(%a), loc(%a)@]" pp_stmt stmt pp_cabsloc loc | LABEL (s, stmt, loc) -> fprintf fmt "@[<hov 2>LABEL %s stmt(%a), loc(%a)@]" s pp_stmt stmt pp_cabsloc loc | GOTO (s, loc) -> fprintf fmt "@[<hov 2>GOTO %s, loc(%a)@]" s pp_cabsloc loc | COMPGOTO (exp, loc) -> fprintf fmt "@[<hov 2>COMPGOTO exp(%a, loc(%a))@]" pp_exp exp pp_cabsloc loc | DEFINITION def -> fprintf fmt "@[<hov 2>DEFINITION %a@]" pp_def def | ASM (_,_,_,_) -> fprintf fmt "ASM" | TRY_EXCEPT (bl1, exp, bl2, loc) -> fprintf fmt "@[<hov 2>TRY_EXCEPT block(%a) exp(%a) block(%a) loc(%a)@]" pp_block bl1 pp_exp exp pp_block bl2 pp_cabsloc loc | TRY_FINALLY (bl1, bl2, loc) -> fprintf fmt "@[<hov 2>TRY_EXCEPT block(%a) block(%a) loc(%a)@]" pp_block bl1 pp_block bl2 pp_cabsloc loc | THROW(e,loc) -> fprintf fmt "@[<hov 2>THROW %a, loc(%a)@]" (Pretty_utils.pp_opt pp_exp) e pp_cabsloc loc | TRY_CATCH(s,l,loc) -> let print_one_catch fmt (v,s) = fprintf fmt "@[<v 2>@[CATCH %a {@]@;%a@]@;}" (Pretty_utils.pp_opt pp_single_name) v pp_stmt s in fprintf fmt "@[<v 2>@[TRY %a (loc %a) {@]@;%a@]@;}" pp_stmt s pp_cabsloc loc (Pretty_utils.pp_list ~sep:"@;" print_one_catch) l | CODE_ANNOT (_,_) -> fprintf fmt "CODE_ANNOT" | CODE_SPEC _ -> fprintf fmt "CODE_SPEC" and pp_stmt fmt stmt = fprintf fmt "@[<hov 2>ghost(%b), stmt(%a)@]" stmt.stmt_ghost pp_raw_stmt stmt.stmt_node and pp_for_clause fmt = function | FC_EXP exp -> fprintf fmt "@[<hov 2>FC_EXP %a@]" pp_exp exp | FC_DECL def -> fprintf fmt "@[<hov 2>FC_DECL %a@]" pp_def def and pp_bin_op fmt = function | ADD -> fprintf fmt "ADD" | SUB -> fprintf fmt "SUB" | MUL -> fprintf fmt "MUL" | DIV -> fprintf fmt "DIV" | MOD -> fprintf fmt "MOD" | AND -> fprintf fmt "AND" | OR -> fprintf fmt "OR" | BAND -> fprintf fmt "BAND" | BOR -> fprintf fmt "BOR" | XOR -> fprintf fmt "XOR" | SHL -> fprintf fmt "SHL" | SHR -> fprintf fmt "SHR" | EQ -> fprintf fmt "EQ" | NE -> fprintf fmt "NE" | LT -> fprintf fmt "LT" | GT -> fprintf fmt "GT" | LE -> fprintf fmt "LE" | GE -> fprintf fmt "GE" | ASSIGN -> fprintf fmt "ASSIGN" | ADD_ASSIGN -> fprintf fmt "ADD_ASSIGN" | SUB_ASSIGN -> fprintf fmt "SUB_ASSIGN" | MUL_ASSIGN -> fprintf fmt "MUL_ASSIGN" | DIV_ASSIGN -> fprintf fmt "DIV_ASSIGN" | MOD_ASSIGN -> fprintf fmt "MOD_ASSIGN" | BAND_ASSIGN -> fprintf fmt "BAND_ASSIGN" | BOR_ASSIGN -> fprintf fmt "BOR_ASSIGN" | XOR_ASSIGN -> fprintf fmt "XOR_ASSIGN" | SHL_ASSIGN -> fprintf fmt "SHL_ASSIGN" | SHR_ASSIGN -> fprintf fmt "SHR_ASSIGN" and pp_un_op fmt = function | MINUS -> fprintf fmt "MINUS" | PLUS -> fprintf fmt "PLUS" | NOT -> fprintf fmt "NOT" | BNOT -> fprintf fmt "BNOT" | MEMOF -> fprintf fmt "MEMOF" | ADDROF -> fprintf fmt "ADDROF" | PREINCR -> fprintf fmt "PREINCR" | PREDECR -> fprintf fmt "PREDECR" | POSINCR -> fprintf fmt "POSINCR" | POSDECR -> fprintf fmt "POSDECR" and pp_exp fmt exp = fprintf fmt "exp(%a)" pp_exp_node exp.expr_node and pp_exp_node fmt = function | NOTHING -> fprintf fmt "NOTHING" | UNARY (un_op, exp) -> fprintf fmt "@[<hov 2>%a(%a)@]" pp_un_op un_op pp_exp exp | LABELADDR s -> fprintf fmt "@[<hov 2>LABELADDR %s@]" s | BINARY (bin_op, exp1, exp2) -> fprintf fmt "@[<hov 2>%a %a %a@]" pp_exp exp1 pp_bin_op bin_op pp_exp exp2 | QUESTION (exp1, exp2, exp3) -> fprintf fmt "@[<hov 2>QUESTION(%a, %a, %a)@]" pp_exp exp1 pp_exp exp2 pp_exp exp3 | CAST ((spec, decl_type), init_exp) -> fprintf fmt "@[<hov 2>CAST (%a, %a) %a@]" pp_spec spec pp_decl_type decl_type pp_init_exp init_exp | CALL (exp1, exps) -> fprintf fmt "@[<hov 2>CALL %a {" pp_exp exp1; List.iter (fun e -> fprintf fmt ",@ %a" pp_exp e) exps; fprintf fmt "}@]" | COMMA exps -> fprintf fmt "@[<hov 2>COMMA {"; List.iter (fun e -> fprintf fmt ",@ %a" pp_exp e) exps; fprintf fmt "}@]" | CONSTANT c -> fprintf fmt "%a" pp_const c | PAREN exp -> fprintf fmt "PAREN(%a)" pp_exp exp | VARIABLE s -> fprintf fmt "VAR %s" s | EXPR_SIZEOF exp -> fprintf fmt "EXPR_SIZEOF(%a)" pp_exp exp | TYPE_SIZEOF (spec, decl_type) -> fprintf fmt "TYP_SIZEOF(%a,%a)" pp_spec spec pp_decl_type decl_type | EXPR_ALIGNOF exp -> fprintf fmt "EXPR_ALIGNOF(%a)" pp_exp exp | TYPE_ALIGNOF (spec, decl_type) -> fprintf fmt "TYP_ALIGNEOF(%a,%a)" pp_spec spec pp_decl_type decl_type | INDEX (exp1, exp2) -> fprintf fmt "INDEX(%a, %a)" pp_exp exp1 pp_exp exp2 | MEMBEROF (exp, s) -> fprintf fmt "MEMBEROF(%a,%s)" pp_exp exp s | MEMBEROFPTR (exp, s) -> fprintf fmt "MEMBEROFPTR(%a,%s)" pp_exp exp s | GNU_BODY bl -> fprintf fmt "GNU_BODY %a" pp_block bl | EXPR_PATTERN s -> fprintf fmt "EXPR_PATTERN %s" s and pp_init_exp fmt = function | NO_INIT -> fprintf fmt "NO_INIT" | SINGLE_INIT exp -> fprintf fmt "SINGLE_INIT %a" pp_exp exp | COMPOUND_INIT l -> fprintf fmt "@[<hov 2>COMPOUND_INIT {"; match l with | [] -> fprintf fmt "}@]" | (iw, ie)::rest -> fprintf fmt ",@ (%a, %a)" pp_initwhat iw pp_init_exp ie; List.iter (fun (iw, ie) -> fprintf fmt ",@ (%a, %a)" pp_initwhat iw pp_init_exp ie) rest; fprintf fmt "}@]" and pp_initwhat fmt = function | NEXT_INIT -> fprintf fmt "NEXT_INIT" | INFIELD_INIT (s,iw) -> fprintf fmt "@[<hov 2>INFIELD_INIT (%s, %a)@]" s pp_initwhat iw | ATINDEX_INIT (exp,iw) -> fprintf fmt "@[<hov 2>ATINDEX_INIT (%a, %a)@]" pp_exp exp pp_initwhat iw | ATINDEXRANGE_INIT (exp1, exp2) -> fprintf fmt "@[<hov 2>ATINDEXRANGE_INIT (%a, %a)@]" pp_exp exp1 pp_exp exp2 and pp_attr fmt (s,el) = fprintf fmt "ATTR (%s, {" s; match el with | [] -> fprintf fmt "})" | e :: es -> fprintf fmt ",@ %a" pp_exp e; List.iter (fun e -> fprintf fmt ",@ %a" pp_exp e) es; fprintf fmt "})" and pp_attrs fmt l = fprintf fmt "{"; match l with | [] -> fprintf fmt "}" | a :: attrs -> fprintf fmt ",@ %a" pp_attr a; List.iter (fun a -> fprintf fmt ",@ %a" pp_attr a) attrs; fprintf fmt "}"
2ee35d68c020dcab47b1b58c39c7366a59539cc450812e3f5e031b90668a915f
c-cube/trustee
env.ml
open Common_ module TA = Type_ast type expr = TA.expr type ty = TA.ty type const = TA.const type 'a meta_var = 'a TA.Meta_var.t type t = { consts: const Str_map.t; (* const -> ty *) } let empty = { consts= Str_map.empty |> Str_map.add "bool" TA.Const.bool; } let add_const (c:const) self : t = { consts=Str_map.add c.name c self.consts; } let find_const n self = Str_map.find_opt n self.consts let all_consts self = Str_map.values self.consts let pp out (self:t) : unit = Fmt.fprintf out "(@[env"; all_consts self (fun c -> Fmt.fprintf out "@ %a" TA.Const.pp c); Fmt.fprintf out "@])" let completions (self:t) (str:string) : _ Iter.t = (* cut a range of the map that has chances of completing [str] *) let consts = self.consts in let consts = let small_enough n = String.compare n str < 0 in match Str_map.find_first_opt small_enough consts with | None -> consts | Some (n,_) -> let _, _, rhs = Str_map.split n consts in rhs in let consts = let too_big n = String.compare str n < 0 && not (CCString.prefix ~pre:str n) in match Str_map.find_last_opt too_big consts with | None -> consts | Some (n,_) -> let lhs,_,_ = Str_map.split n consts in lhs in begin (* iterate and check *) Str_map.to_iter consts |> Iter.filter_map (fun (n, c) -> if CCString.prefix ~pre:str n then Some c else None) end
null
https://raw.githubusercontent.com/c-cube/trustee/8ae3d777f55ef2b499b43c0b26e5fde1f2ea7761/src/syntax/env.ml
ocaml
const -> ty cut a range of the map that has chances of completing [str] iterate and check
open Common_ module TA = Type_ast type expr = TA.expr type ty = TA.ty type const = TA.const type 'a meta_var = 'a TA.Meta_var.t type t = { } let empty = { consts= Str_map.empty |> Str_map.add "bool" TA.Const.bool; } let add_const (c:const) self : t = { consts=Str_map.add c.name c self.consts; } let find_const n self = Str_map.find_opt n self.consts let all_consts self = Str_map.values self.consts let pp out (self:t) : unit = Fmt.fprintf out "(@[env"; all_consts self (fun c -> Fmt.fprintf out "@ %a" TA.Const.pp c); Fmt.fprintf out "@])" let completions (self:t) (str:string) : _ Iter.t = let consts = self.consts in let consts = let small_enough n = String.compare n str < 0 in match Str_map.find_first_opt small_enough consts with | None -> consts | Some (n,_) -> let _, _, rhs = Str_map.split n consts in rhs in let consts = let too_big n = String.compare str n < 0 && not (CCString.prefix ~pre:str n) in match Str_map.find_last_opt too_big consts with | None -> consts | Some (n,_) -> let lhs,_,_ = Str_map.split n consts in lhs in begin Str_map.to_iter consts |> Iter.filter_map (fun (n, c) -> if CCString.prefix ~pre:str n then Some c else None) end
842e760c0b24294ff3a7fa46f001d91284dd2b5444cf64a5c6d890b27048f723
ucsd-progsys/dsolve
typedtree.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : typedtree.mli , v 1.35 2006/04/05 02:28:13 garrigue Exp $ (* Abstract syntax tree after typing *) open Asttypes open Types (* Value expressions for the core language *) type pattern = { pat_desc: pattern_desc; pat_loc: Location.t; pat_type: type_expr; pat_env: Env.t } and pattern_desc = Tpat_any | Tpat_var of Ident.t | Tpat_alias of pattern * Ident.t | Tpat_constant of constant | Tpat_tuple of pattern list | Tpat_construct of constructor_description * pattern list | Tpat_variant of label * pattern option * row_desc | Tpat_record of (label_description * pattern) list | Tpat_array of pattern list | Tpat_or of pattern * pattern * Path.t option type partial = Partial | Total type optional = Required | Optional type expression = { exp_desc: expression_desc; exp_loc: Location.t; exp_type: type_expr; exp_env: Env.t } and expression_desc = Texp_ident of Path.t * value_description | Texp_constant of constant | Texp_let of rec_flag * (pattern * expression) list * expression | Texp_function of (pattern * expression) list * partial | Texp_apply of expression * (expression option * optional) list | Texp_match of expression * (pattern * expression) list * partial | Texp_try of expression * (pattern * expression) list | Texp_tuple of expression list | Texp_construct of constructor_description * expression list | Texp_variant of label * expression option | Texp_record of (label_description * expression) list * expression option | Texp_field of expression * label_description | Texp_setfield of expression * label_description * expression | Texp_array of expression list | Texp_ifthenelse of expression * expression * expression option | Texp_sequence of expression * expression | Texp_while of expression * expression | Texp_for of Ident.t * expression * expression * direction_flag * expression | Texp_when of expression * expression | Texp_send of expression * meth | Texp_new of Path.t * class_declaration | Texp_instvar of Path.t * Path.t | Texp_setinstvar of Path.t * Path.t * expression | Texp_override of Path.t * (Path.t * expression) list | Texp_letmodule of Ident.t * module_expr * expression | Texp_assert of expression | Texp_assertfalse | Texp_assume of expression | Texp_lazy of expression | Texp_object of class_structure * class_signature * string list and meth = Tmeth_name of string | Tmeth_val of Ident.t (* Value expressions for the class language *) and class_expr = { cl_desc: class_expr_desc; cl_loc: Location.t; cl_type: class_type; cl_env: Env.t } and class_expr_desc = Tclass_ident of Path.t | Tclass_structure of class_structure | Tclass_fun of pattern * (Ident.t * expression) list * class_expr * partial | Tclass_apply of class_expr * (expression option * optional) list | Tclass_let of rec_flag * (pattern * expression) list * (Ident.t * expression) list * class_expr | Tclass_constraint of class_expr * string list * string list * Concr.t (* Visible instance variables, methods and concretes methods *) and class_structure = { cl_field: class_field list; cl_meths: Ident.t Meths.t } and class_field = Cf_inher of class_expr * (string * Ident.t) list * (string * Ident.t) list (* Inherited instance variables and concrete methods *) | Cf_val of string * Ident.t * expression option * bool (* None = virtual, true = override *) | Cf_meth of string * expression | Cf_let of rec_flag * (pattern * expression) list * (Ident.t * expression) list | Cf_init of expression (* Value expressions for the module language *) and module_expr = { mod_desc: module_expr_desc; mod_loc: Location.t; mod_type: module_type; mod_env: Env.t } and module_expr_desc = Tmod_ident of Path.t | Tmod_structure of structure | Tmod_functor of Ident.t * module_type * module_expr | Tmod_apply of module_expr * module_expr * module_coercion | Tmod_constraint of module_expr * module_type * module_coercion and structure = structure_item list and structure_item = Tstr_eval of expression | Tstr_value of rec_flag * (pattern * expression) list | Tstr_primitive of Ident.t * value_description | Tstr_type of (Ident.t * type_declaration) list | Tstr_exception of Ident.t * exception_declaration | Tstr_exn_rebind of Ident.t * Path.t | Tstr_module of Ident.t * module_expr | Tstr_recmodule of (Ident.t * module_expr) list | Tstr_modtype of Ident.t * module_type | Tstr_open of Path.t | Tstr_class of (Ident.t * int * string list * class_expr * virtual_flag) list | Tstr_cltype of (Ident.t * cltype_declaration) list | Tstr_include of module_expr * Ident.t list and module_coercion = Tcoerce_none | Tcoerce_structure of (int * module_coercion) list | Tcoerce_functor of module_coercion * module_coercion | Tcoerce_primitive of Primitive.description (* Auxiliary functions over the a.s.t. *) val iter_pattern_desc : (pattern -> unit) -> pattern_desc -> unit val map_pattern_desc : (pattern -> pattern) -> pattern_desc -> pattern_desc val pat_bound_idents: pattern -> Ident.t list val pat_desc_bound_idents: pattern_desc -> Ident.t list val let_bound_idents: (pattern * expression) list -> Ident.t list val rev_let_bound_idents: (pattern * expression) list -> Ident.t list (* Alpha conversion of patterns *) val alpha_pat : (Ident.t * Ident.t) list -> pattern -> pattern
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/typing/typedtree.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* Abstract syntax tree after typing Value expressions for the core language Value expressions for the class language Visible instance variables, methods and concretes methods Inherited instance variables and concrete methods None = virtual, true = override Value expressions for the module language Auxiliary functions over the a.s.t. Alpha conversion of patterns
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : typedtree.mli , v 1.35 2006/04/05 02:28:13 garrigue Exp $ open Asttypes open Types type pattern = { pat_desc: pattern_desc; pat_loc: Location.t; pat_type: type_expr; pat_env: Env.t } and pattern_desc = Tpat_any | Tpat_var of Ident.t | Tpat_alias of pattern * Ident.t | Tpat_constant of constant | Tpat_tuple of pattern list | Tpat_construct of constructor_description * pattern list | Tpat_variant of label * pattern option * row_desc | Tpat_record of (label_description * pattern) list | Tpat_array of pattern list | Tpat_or of pattern * pattern * Path.t option type partial = Partial | Total type optional = Required | Optional type expression = { exp_desc: expression_desc; exp_loc: Location.t; exp_type: type_expr; exp_env: Env.t } and expression_desc = Texp_ident of Path.t * value_description | Texp_constant of constant | Texp_let of rec_flag * (pattern * expression) list * expression | Texp_function of (pattern * expression) list * partial | Texp_apply of expression * (expression option * optional) list | Texp_match of expression * (pattern * expression) list * partial | Texp_try of expression * (pattern * expression) list | Texp_tuple of expression list | Texp_construct of constructor_description * expression list | Texp_variant of label * expression option | Texp_record of (label_description * expression) list * expression option | Texp_field of expression * label_description | Texp_setfield of expression * label_description * expression | Texp_array of expression list | Texp_ifthenelse of expression * expression * expression option | Texp_sequence of expression * expression | Texp_while of expression * expression | Texp_for of Ident.t * expression * expression * direction_flag * expression | Texp_when of expression * expression | Texp_send of expression * meth | Texp_new of Path.t * class_declaration | Texp_instvar of Path.t * Path.t | Texp_setinstvar of Path.t * Path.t * expression | Texp_override of Path.t * (Path.t * expression) list | Texp_letmodule of Ident.t * module_expr * expression | Texp_assert of expression | Texp_assertfalse | Texp_assume of expression | Texp_lazy of expression | Texp_object of class_structure * class_signature * string list and meth = Tmeth_name of string | Tmeth_val of Ident.t and class_expr = { cl_desc: class_expr_desc; cl_loc: Location.t; cl_type: class_type; cl_env: Env.t } and class_expr_desc = Tclass_ident of Path.t | Tclass_structure of class_structure | Tclass_fun of pattern * (Ident.t * expression) list * class_expr * partial | Tclass_apply of class_expr * (expression option * optional) list | Tclass_let of rec_flag * (pattern * expression) list * (Ident.t * expression) list * class_expr | Tclass_constraint of class_expr * string list * string list * Concr.t and class_structure = { cl_field: class_field list; cl_meths: Ident.t Meths.t } and class_field = Cf_inher of class_expr * (string * Ident.t) list * (string * Ident.t) list | Cf_val of string * Ident.t * expression option * bool | Cf_meth of string * expression | Cf_let of rec_flag * (pattern * expression) list * (Ident.t * expression) list | Cf_init of expression and module_expr = { mod_desc: module_expr_desc; mod_loc: Location.t; mod_type: module_type; mod_env: Env.t } and module_expr_desc = Tmod_ident of Path.t | Tmod_structure of structure | Tmod_functor of Ident.t * module_type * module_expr | Tmod_apply of module_expr * module_expr * module_coercion | Tmod_constraint of module_expr * module_type * module_coercion and structure = structure_item list and structure_item = Tstr_eval of expression | Tstr_value of rec_flag * (pattern * expression) list | Tstr_primitive of Ident.t * value_description | Tstr_type of (Ident.t * type_declaration) list | Tstr_exception of Ident.t * exception_declaration | Tstr_exn_rebind of Ident.t * Path.t | Tstr_module of Ident.t * module_expr | Tstr_recmodule of (Ident.t * module_expr) list | Tstr_modtype of Ident.t * module_type | Tstr_open of Path.t | Tstr_class of (Ident.t * int * string list * class_expr * virtual_flag) list | Tstr_cltype of (Ident.t * cltype_declaration) list | Tstr_include of module_expr * Ident.t list and module_coercion = Tcoerce_none | Tcoerce_structure of (int * module_coercion) list | Tcoerce_functor of module_coercion * module_coercion | Tcoerce_primitive of Primitive.description val iter_pattern_desc : (pattern -> unit) -> pattern_desc -> unit val map_pattern_desc : (pattern -> pattern) -> pattern_desc -> pattern_desc val pat_bound_idents: pattern -> Ident.t list val pat_desc_bound_idents: pattern_desc -> Ident.t list val let_bound_idents: (pattern * expression) list -> Ident.t list val rev_let_bound_idents: (pattern * expression) list -> Ident.t list val alpha_pat : (Ident.t * Ident.t) list -> pattern -> pattern
dd8e136aa8098120aecbb0240e9cd3ce2b1a0565e830eeee0a345aadec3771c7
IronScheme/IronScheme
run.sps
#!r6rs (import (tests r6rs run) (tests r6rs test) (rnrs io simple)) (display "Running tests for (rnrs run)\n") (run-run-tests) (report-test-results)
null
https://raw.githubusercontent.com/IronScheme/IronScheme/687cde5d4e463a119e4ba28296f2af42a5c4a9df/IronScheme/IronScheme.Console/tests/r6rs/run/run.sps
scheme
#!r6rs (import (tests r6rs run) (tests r6rs test) (rnrs io simple)) (display "Running tests for (rnrs run)\n") (run-run-tests) (report-test-results)
cb56bfd8ed2cbc6c72e8b49c1f52c94e641196074a3a0927ab8efe5f66bf0539
OCamlPro/ocaml-solidity
solidity_common.ml
(**************************************************************************) (* *) Copyright ( c ) 2021 OCamlPro & Origin Labs (* *) (* 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 LICENSE.md file in the root directory. *) (* *) (* *) (**************************************************************************) open Ez_file.V1 type pos = string * (int * int) * (int * int) let dummy_pos = "", (-1, -1), (-1, -1) exception GenericError of string let error fmt = Format.kasprintf (fun s -> raise (GenericError s)) fmt type relative = [`Relative] type absolute = [`Absolute] module ExtMap = struct module type OrderedType = sig type t val compare : t -> t -> int val to_string : t -> string end module type S = sig include Map.S val of_bindings : (key * 'a) list -> 'a t val map_fold : ('a -> 'b -> 'a * 'c) -> 'a -> 'b t -> 'a * 'c t val add_uniq_opt : key -> 'a -> 'a t -> 'a t option val add_uniq : key -> 'a -> 'a t -> 'a t end module Make (Ord : OrderedType) : S with type key = Ord.t = struct include Map.Make (Ord) let of_bindings list = List.fold_left (fun map (key, v) -> add key v map) empty list let map_fold f a m = fold (fun k b (a, m) -> let a, c = f a b in a, add k c m ) m (a, empty) let add_uniq_opt key v map = if mem key map then None else Some (add key v map) let add_uniq key v map = match add_uniq_opt key v map with | None -> error "ExtMap.add_uniq %S: not uniq" (Ord.to_string key) | Some map -> map end end module ZMap = ExtMap.Make (Z) module ZSet = Set.Make (Z) module IntMap = ExtMap.Make (struct type t = int let compare = Stdlib.compare let to_string = string_of_int end) module StringMap = ExtMap.Make (struct type t = string let compare = String.compare let to_string s = s end) module StringSet = Set.Make (String) module Ident = struct type t = string let compare = String.compare let equal = String.equal let root i = Format.sprintf "@%d" i let to_string id = id let of_string id = id let printf fmt id = Format.fprintf fmt "%s" id let constructor = ":constructor" let onBounce = ":onBounce" let receive = ":receive" let fallback = ":fallback" end module LongIdent = struct type 'kind t = Ident.t list let rec compare lid1 lid2 = match lid1, lid2 with | [], [] -> 0 | [], _ :: _ -> -1 | _ :: _, [] -> 1 | id1 :: lid1, id2 :: lid2 -> let res = Ident.compare id1 id2 in if res <> 0 then res else compare lid1 lid2 let equal lid1 lid2 = compare lid1 lid2 = 0 let empty = [] let root i = [Ident.root i] let to_string lid = String.concat "." lid let of_string_rel lid = String.split_on_char '.' lid let of_string_abs lid = String.split_on_char '.' lid let of_ident_rel id = [id] let of_ident_abs id = [id] let to_ident_list idl = idl let of_ident_list_rel idl = idl let of_ident_list_abs idl = idl let append lid id = lid @ [id] let prepend id lid = id :: lid let is_empty lid = match lid with | [] -> true | _ -> false let first lid = match lid with | id :: _ -> id | _ -> error "LongIdent.first: invalid long identifier" let last lid = match List.rev lid with | id :: _ -> id | _ -> error "LongIdent.last: invalid long identifier" let split_first lid = match lid with | id :: lid -> id, lid | _ -> error "LongIdent.split_first: invalid long identifier" let split_last lid = match List.rev lid with | id :: rlid -> List.rev rlid, id | _ -> error "LongIdent.split_last: invalid long identifier" let printf fmt lid = Format.fprintf fmt "%s" (to_string lid) end module IdentMap = ExtMap.Make (Ident) module IdentAList = struct type 'a t = (Ident.t * 'a) list let length = List.length let rev = List.rev let mem = List.mem_assoc let find_opt = List.assoc_opt let map f list = List.map (fun (key, v) -> (key, f v)) list let fold_left f acc list = List.fold_left (fun acc (key, v) -> f acc key v) acc list let add_uniq key v list = if mem key list then error "Identifier %s already declared" key; (key, v) :: list end module IdentSet = Set.Make (Ident) module AbsLongIdentMap = ExtMap.Make (struct type t = absolute LongIdent.t let compare = LongIdent.compare let to_string = LongIdent.to_string end) module RelLongIdentMap = ExtMap.Make (struct type t = relative LongIdent.t let compare = LongIdent.compare let to_string = LongIdent.to_string end) module AbsLongIdentSet = Set.Make (struct type t = absolute LongIdent.t let compare = LongIdent.compare end) module RelLongIdentSet = Set.Make (struct type t = relative LongIdent.t let compare = LongIdent.compare end) module ExtList = struct include List let is_empty = function | [] -> true | _ -> false let same_lengths l1 l2 = List.compare_lengths l1 l2 = 0 let for_all2 f l1 l2 = same_lengths l1 l2 && List.for_all2 f l1 l2 let rec iter3 f l1 l2 l3 = match (l1, l2, l3) with | ([], [], []) -> () | (a1::l1, a2::l2, a3::l3) -> f a1 a2 a3; iter3 f l1 l2 l3 | (_, _, _) -> invalid_arg "ExtList.iter3" let rec fold_left3 f a l1 l2 l3 = match (l1, l2, l3) with | ([], [], []) -> a | (a1::l1, a2::l2, a3::l3) -> fold_left3 f (f a a1 a2 a3) l1 l2 l3 | (_, _, _) -> invalid_arg "ExtList.fold_left3" let opt_fold_left f a l = List.fold_left (fun a b_opt -> match b_opt with | None -> a | Some b -> f a b ) a l let map_fold f a l = let a, l = List.fold_left (fun (a, l) b -> let a, c = f a b in a, c :: l ) (a, []) l in a, List.rev l let map_fold2 f a l1 l2 = let a, l = List.fold_left2 (fun (a, l) b c -> let a, d = f a b c in a, d :: l ) (a, []) l1 l2 in a, List.rev l let rec compare cmp l1 l2 = match l1, l2 with | [], [] -> 0 | hd1 :: tl1, hd2 :: tl2 -> let hd_cmp = cmp hd1 hd2 in if hd_cmp = 0 then compare cmp tl1 tl2 else hd_cmp | [], _ -> -1 | _, [] -> 1 let find (type a) f f_err l : a = let exception Found of a in try List.iter (fun e -> match f e with | Some res -> raise (Found res) | None -> () ) l; f_err () with Found res -> res let pos f l = let exception Found of int in try let _ = List.fold_left (fun i e -> if f e then raise (Found i) else i + 1 ) 0 l in None with Found res -> Some res end module ExtInt = struct let rec fold f s e a = if s <= e then fold f (s+1) e (f s a) else a end module ExtZ = struct let _2 = Z.of_int 2 let _5 = Z.of_int 5 let _7 = Z.of_int 7 let _8 = Z.of_int 8 let _10 = Z.of_int 10 let _60 = Z.of_int 60 let _255 = Z.of_int 255 let _3600 = Z.of_int 3600 let _24x3600 = Z.of_int (24 * 3600) let _7x24x3600 = Z.of_int (7 * 24 * 3600) let _365x24x3600 = Z.of_int (365 * 24 * 3600) let _10_3 = Z.pow _10 3 let _10_6 = Z.pow _10 6 let _10_9 = Z.pow _10 9 let _10_12 = Z.pow _10 12 let _10_15 = Z.pow _10 15 let _10_18 = Z.pow _10 18 let is_neg z = Z.sign z < 0 let is_pos z = Z.sign z >= 0 let rec fold f s e a = if s <= e then fold f (Z.succ s) e (f s a) else a let numbits_mod8 z = let nb = Z.min Z.one (Z.of_int (Z.numbits z)) in Z.to_int (Z.mul (Z.div (Z.add nb _7) _8) _8) let num_zeros z = let n = ref 0 in let r = ref (snd (Z.ediv_rem z _10)) in while not (Z.equal !r Z.zero) do n := !n + 1; r := snd (Z.ediv_rem z _10) done; !n let of_binary b = let res = ref Z.zero in let l = String.length b in for i = 0 to (l-1) do let v = Z.of_int (Char.code (b.[i])) in res := Z.add (Z.shift_left !res 8) v done; !res let print_hex z = if z = Z.zero then "0" else let b = Buffer.create 100 in let rec iter z = if z = Z.zero then Buffer.add_string b "0x" else let modulo = Z.logand z _255 in let z = Z.shift_right z 8 in iter z; Printf.bprintf b "%02x" (Z.to_int modulo) in iter z; Buffer.contents b include Z end module ExtQ = struct let is_int q = Z.equal Z.one (Q.den q) let is_neg q = Q.sign q < 0 let is_pos q = Q.sign q >= 0 let to_fixed_with_dec dec q = let n = Q.num q in let d = Q.den q in let z, r = Z.ediv_rem (Z.mul n (Z.pow ExtZ._10 dec)) d in (* properly handle rounding *) if (Z.mul r ExtZ._2 < d) then z else Z.succ z let to_fixed q = let z = to_fixed_with_dec 80 q in if Z.equal Z.zero z then z, 0 else let nz = ExtZ.num_zeros z in Z.mul z (Z.pow ExtZ._10 nz), (80 - nz) include Q end type annot = .. type annot += ANone type 'a node = { contents : 'a; mutable annot : annot; pos : pos; } let annot contents annot pos = { contents; annot; pos } let strip n = n.contents let get_annot n = n.annot let string_of_pos (file, pos1, pos2) = let source = try let line1 = fst pos1 in let line2 = fst pos2 in let lines = EzFile.read_lines file in let b = Buffer.create 1000 in Array.iteri (fun l line -> let l = l+1 in if l >= line1 - 3 && l < line2 + 3 then Printf.bprintf b "%4d %c %s\n" l (if l>=line1 && l<=line2 then '>' else ' ') line ) lines; Buffer.contents b with _ -> "" in Printf.sprintf "%s:%d.%d-%d.%d" file (fst pos1) (snd pos1+1) (fst pos2) (snd pos2+1), source let set_annot n annot = match n.annot with | ANone -> n.annot <- annot | _ -> let loc, source = string_of_pos n.pos in error "%sNode annotation already set at %s" source loc let replace_annot n annot = match n.annot with | ANone -> let loc, source = string_of_pos n.pos in error "%sNode annotation not set at %s" source loc | _ -> n.annot <- annot let make_absolute_path base path = FilePath.reduce ~no_symlink:true @@ if FilePath.is_relative path then FilePath.make_absolute base path else path let is_some = function | Some _ -> true | None -> false let is_none = function | None -> true | Some _ -> false type primitive_kind = | PrimFunction | PrimMemberFunction | PrimVariable | PrimMemberVariable type primitive = { prim_name : string; prim_kind : primitive_kind; } let max_primitives = 256 let max_prim_id = ref 0 let prim_by_id = Array.make (max_primitives + 1) None let prim_by_name = ref StringMap.empty let prim_of_id id : primitive option = prim_by_id.(id) let prim_of_ident prim : (int * primitive) option = StringMap.find_opt (Ident.to_string prim) !prim_by_name let add_primitive id p = if id < 0 then error "Negative primitive id"; if id > max_primitives then error "Primitive id above limit"; begin match prim_by_id.(id) with | None -> prim_by_id.(id) <- Some p; | Some _ -> error "Primitive id %d already defined" id end; begin match prim_of_ident (Ident.of_string p.prim_name) with | None -> prim_by_name := StringMap.add p.prim_name (id, p) !prim_by_name | Some _ -> error "Primitive name already defined" end; if id > !max_prim_id then max_prim_id := id let for_freeton = ref false let to_pos pos = let open Lexing in let ({ pos_lnum = l1; pos_bol = b1; pos_cnum = c1; pos_fname; _ }, { pos_lnum = l2; pos_bol = b2; pos_cnum = c2; _ }) = pos in let c1 = c1 - b1 in let c2 = c2 - b2 in let l1 = min l1 65535 in let l2 = min l2 65535 in let c1 = min c1 255 in let c2 = min c2 255 in pos_fname, (l1, c1), (l2, c2)
null
https://raw.githubusercontent.com/OCamlPro/ocaml-solidity/9c03ceb24ad42a16dd3678849ba7eefbe27c347e/src/solidity-common/solidity_common.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the GNU Lesser General described in the LICENSE.md file in the root directory. ************************************************************************ properly handle rounding
Copyright ( c ) 2021 OCamlPro & Origin Labs Public License version 2.1 , with the special exception on linking open Ez_file.V1 type pos = string * (int * int) * (int * int) let dummy_pos = "", (-1, -1), (-1, -1) exception GenericError of string let error fmt = Format.kasprintf (fun s -> raise (GenericError s)) fmt type relative = [`Relative] type absolute = [`Absolute] module ExtMap = struct module type OrderedType = sig type t val compare : t -> t -> int val to_string : t -> string end module type S = sig include Map.S val of_bindings : (key * 'a) list -> 'a t val map_fold : ('a -> 'b -> 'a * 'c) -> 'a -> 'b t -> 'a * 'c t val add_uniq_opt : key -> 'a -> 'a t -> 'a t option val add_uniq : key -> 'a -> 'a t -> 'a t end module Make (Ord : OrderedType) : S with type key = Ord.t = struct include Map.Make (Ord) let of_bindings list = List.fold_left (fun map (key, v) -> add key v map) empty list let map_fold f a m = fold (fun k b (a, m) -> let a, c = f a b in a, add k c m ) m (a, empty) let add_uniq_opt key v map = if mem key map then None else Some (add key v map) let add_uniq key v map = match add_uniq_opt key v map with | None -> error "ExtMap.add_uniq %S: not uniq" (Ord.to_string key) | Some map -> map end end module ZMap = ExtMap.Make (Z) module ZSet = Set.Make (Z) module IntMap = ExtMap.Make (struct type t = int let compare = Stdlib.compare let to_string = string_of_int end) module StringMap = ExtMap.Make (struct type t = string let compare = String.compare let to_string s = s end) module StringSet = Set.Make (String) module Ident = struct type t = string let compare = String.compare let equal = String.equal let root i = Format.sprintf "@%d" i let to_string id = id let of_string id = id let printf fmt id = Format.fprintf fmt "%s" id let constructor = ":constructor" let onBounce = ":onBounce" let receive = ":receive" let fallback = ":fallback" end module LongIdent = struct type 'kind t = Ident.t list let rec compare lid1 lid2 = match lid1, lid2 with | [], [] -> 0 | [], _ :: _ -> -1 | _ :: _, [] -> 1 | id1 :: lid1, id2 :: lid2 -> let res = Ident.compare id1 id2 in if res <> 0 then res else compare lid1 lid2 let equal lid1 lid2 = compare lid1 lid2 = 0 let empty = [] let root i = [Ident.root i] let to_string lid = String.concat "." lid let of_string_rel lid = String.split_on_char '.' lid let of_string_abs lid = String.split_on_char '.' lid let of_ident_rel id = [id] let of_ident_abs id = [id] let to_ident_list idl = idl let of_ident_list_rel idl = idl let of_ident_list_abs idl = idl let append lid id = lid @ [id] let prepend id lid = id :: lid let is_empty lid = match lid with | [] -> true | _ -> false let first lid = match lid with | id :: _ -> id | _ -> error "LongIdent.first: invalid long identifier" let last lid = match List.rev lid with | id :: _ -> id | _ -> error "LongIdent.last: invalid long identifier" let split_first lid = match lid with | id :: lid -> id, lid | _ -> error "LongIdent.split_first: invalid long identifier" let split_last lid = match List.rev lid with | id :: rlid -> List.rev rlid, id | _ -> error "LongIdent.split_last: invalid long identifier" let printf fmt lid = Format.fprintf fmt "%s" (to_string lid) end module IdentMap = ExtMap.Make (Ident) module IdentAList = struct type 'a t = (Ident.t * 'a) list let length = List.length let rev = List.rev let mem = List.mem_assoc let find_opt = List.assoc_opt let map f list = List.map (fun (key, v) -> (key, f v)) list let fold_left f acc list = List.fold_left (fun acc (key, v) -> f acc key v) acc list let add_uniq key v list = if mem key list then error "Identifier %s already declared" key; (key, v) :: list end module IdentSet = Set.Make (Ident) module AbsLongIdentMap = ExtMap.Make (struct type t = absolute LongIdent.t let compare = LongIdent.compare let to_string = LongIdent.to_string end) module RelLongIdentMap = ExtMap.Make (struct type t = relative LongIdent.t let compare = LongIdent.compare let to_string = LongIdent.to_string end) module AbsLongIdentSet = Set.Make (struct type t = absolute LongIdent.t let compare = LongIdent.compare end) module RelLongIdentSet = Set.Make (struct type t = relative LongIdent.t let compare = LongIdent.compare end) module ExtList = struct include List let is_empty = function | [] -> true | _ -> false let same_lengths l1 l2 = List.compare_lengths l1 l2 = 0 let for_all2 f l1 l2 = same_lengths l1 l2 && List.for_all2 f l1 l2 let rec iter3 f l1 l2 l3 = match (l1, l2, l3) with | ([], [], []) -> () | (a1::l1, a2::l2, a3::l3) -> f a1 a2 a3; iter3 f l1 l2 l3 | (_, _, _) -> invalid_arg "ExtList.iter3" let rec fold_left3 f a l1 l2 l3 = match (l1, l2, l3) with | ([], [], []) -> a | (a1::l1, a2::l2, a3::l3) -> fold_left3 f (f a a1 a2 a3) l1 l2 l3 | (_, _, _) -> invalid_arg "ExtList.fold_left3" let opt_fold_left f a l = List.fold_left (fun a b_opt -> match b_opt with | None -> a | Some b -> f a b ) a l let map_fold f a l = let a, l = List.fold_left (fun (a, l) b -> let a, c = f a b in a, c :: l ) (a, []) l in a, List.rev l let map_fold2 f a l1 l2 = let a, l = List.fold_left2 (fun (a, l) b c -> let a, d = f a b c in a, d :: l ) (a, []) l1 l2 in a, List.rev l let rec compare cmp l1 l2 = match l1, l2 with | [], [] -> 0 | hd1 :: tl1, hd2 :: tl2 -> let hd_cmp = cmp hd1 hd2 in if hd_cmp = 0 then compare cmp tl1 tl2 else hd_cmp | [], _ -> -1 | _, [] -> 1 let find (type a) f f_err l : a = let exception Found of a in try List.iter (fun e -> match f e with | Some res -> raise (Found res) | None -> () ) l; f_err () with Found res -> res let pos f l = let exception Found of int in try let _ = List.fold_left (fun i e -> if f e then raise (Found i) else i + 1 ) 0 l in None with Found res -> Some res end module ExtInt = struct let rec fold f s e a = if s <= e then fold f (s+1) e (f s a) else a end module ExtZ = struct let _2 = Z.of_int 2 let _5 = Z.of_int 5 let _7 = Z.of_int 7 let _8 = Z.of_int 8 let _10 = Z.of_int 10 let _60 = Z.of_int 60 let _255 = Z.of_int 255 let _3600 = Z.of_int 3600 let _24x3600 = Z.of_int (24 * 3600) let _7x24x3600 = Z.of_int (7 * 24 * 3600) let _365x24x3600 = Z.of_int (365 * 24 * 3600) let _10_3 = Z.pow _10 3 let _10_6 = Z.pow _10 6 let _10_9 = Z.pow _10 9 let _10_12 = Z.pow _10 12 let _10_15 = Z.pow _10 15 let _10_18 = Z.pow _10 18 let is_neg z = Z.sign z < 0 let is_pos z = Z.sign z >= 0 let rec fold f s e a = if s <= e then fold f (Z.succ s) e (f s a) else a let numbits_mod8 z = let nb = Z.min Z.one (Z.of_int (Z.numbits z)) in Z.to_int (Z.mul (Z.div (Z.add nb _7) _8) _8) let num_zeros z = let n = ref 0 in let r = ref (snd (Z.ediv_rem z _10)) in while not (Z.equal !r Z.zero) do n := !n + 1; r := snd (Z.ediv_rem z _10) done; !n let of_binary b = let res = ref Z.zero in let l = String.length b in for i = 0 to (l-1) do let v = Z.of_int (Char.code (b.[i])) in res := Z.add (Z.shift_left !res 8) v done; !res let print_hex z = if z = Z.zero then "0" else let b = Buffer.create 100 in let rec iter z = if z = Z.zero then Buffer.add_string b "0x" else let modulo = Z.logand z _255 in let z = Z.shift_right z 8 in iter z; Printf.bprintf b "%02x" (Z.to_int modulo) in iter z; Buffer.contents b include Z end module ExtQ = struct let is_int q = Z.equal Z.one (Q.den q) let is_neg q = Q.sign q < 0 let is_pos q = Q.sign q >= 0 let to_fixed_with_dec dec q = let n = Q.num q in let d = Q.den q in let z, r = Z.ediv_rem (Z.mul n (Z.pow ExtZ._10 dec)) d in if (Z.mul r ExtZ._2 < d) then z else Z.succ z let to_fixed q = let z = to_fixed_with_dec 80 q in if Z.equal Z.zero z then z, 0 else let nz = ExtZ.num_zeros z in Z.mul z (Z.pow ExtZ._10 nz), (80 - nz) include Q end type annot = .. type annot += ANone type 'a node = { contents : 'a; mutable annot : annot; pos : pos; } let annot contents annot pos = { contents; annot; pos } let strip n = n.contents let get_annot n = n.annot let string_of_pos (file, pos1, pos2) = let source = try let line1 = fst pos1 in let line2 = fst pos2 in let lines = EzFile.read_lines file in let b = Buffer.create 1000 in Array.iteri (fun l line -> let l = l+1 in if l >= line1 - 3 && l < line2 + 3 then Printf.bprintf b "%4d %c %s\n" l (if l>=line1 && l<=line2 then '>' else ' ') line ) lines; Buffer.contents b with _ -> "" in Printf.sprintf "%s:%d.%d-%d.%d" file (fst pos1) (snd pos1+1) (fst pos2) (snd pos2+1), source let set_annot n annot = match n.annot with | ANone -> n.annot <- annot | _ -> let loc, source = string_of_pos n.pos in error "%sNode annotation already set at %s" source loc let replace_annot n annot = match n.annot with | ANone -> let loc, source = string_of_pos n.pos in error "%sNode annotation not set at %s" source loc | _ -> n.annot <- annot let make_absolute_path base path = FilePath.reduce ~no_symlink:true @@ if FilePath.is_relative path then FilePath.make_absolute base path else path let is_some = function | Some _ -> true | None -> false let is_none = function | None -> true | Some _ -> false type primitive_kind = | PrimFunction | PrimMemberFunction | PrimVariable | PrimMemberVariable type primitive = { prim_name : string; prim_kind : primitive_kind; } let max_primitives = 256 let max_prim_id = ref 0 let prim_by_id = Array.make (max_primitives + 1) None let prim_by_name = ref StringMap.empty let prim_of_id id : primitive option = prim_by_id.(id) let prim_of_ident prim : (int * primitive) option = StringMap.find_opt (Ident.to_string prim) !prim_by_name let add_primitive id p = if id < 0 then error "Negative primitive id"; if id > max_primitives then error "Primitive id above limit"; begin match prim_by_id.(id) with | None -> prim_by_id.(id) <- Some p; | Some _ -> error "Primitive id %d already defined" id end; begin match prim_of_ident (Ident.of_string p.prim_name) with | None -> prim_by_name := StringMap.add p.prim_name (id, p) !prim_by_name | Some _ -> error "Primitive name already defined" end; if id > !max_prim_id then max_prim_id := id let for_freeton = ref false let to_pos pos = let open Lexing in let ({ pos_lnum = l1; pos_bol = b1; pos_cnum = c1; pos_fname; _ }, { pos_lnum = l2; pos_bol = b2; pos_cnum = c2; _ }) = pos in let c1 = c1 - b1 in let c2 = c2 - b2 in let l1 = min l1 65535 in let l2 = min l2 65535 in let c1 = min c1 255 in let c2 = min c2 255 in pos_fname, (l1, c1), (l2, c2)
b9d906ab6f09b74d201ec39fc199be3ef773ba20fceefc3231489993fe99e121
plumatic/grab-bag
queue.clj
(ns plumbing.queue (:refer-clojure :exclude [peek]) (:import [java.util.concurrent BlockingQueue LinkedBlockingQueue PriorityBlockingQueue])) (set! *warn-on-reflection* true) (defn poll [^java.util.Queue q] (.poll q)) (defn peek [^java.util.Queue q] (.peek q)) (defn offer [^java.util.Queue q x] (.offer q x)) (defn put [^BlockingQueue q x] (.put q x)) (defn ^BlockingQueue local-queue "return LinkedBlockingQueue implementation of Queue protocol." ([] (LinkedBlockingQueue.)) ([^java.util.Collection xs] (LinkedBlockingQueue. xs))) (defn ^BlockingQueue blocking-queue [capicity] (LinkedBlockingQueue. (int capicity))) (defn drain "return seq of drained elements from Blocking Queue" [^BlockingQueue q & [max-elems]] (let [c (java.util.ArrayList.)] (if max-elems (.drainTo q c (int max-elems)) (.drainTo q c)) (seq c))) (defn priority-queue ([] (PriorityBlockingQueue.)) ([^java.util.Collection xs] (PriorityBlockingQueue. xs)) ([init-size ordering] (PriorityBlockingQueue. init-size (comparator ordering)))) (defn clear-priority-queue [^PriorityBlockingQueue q] (.clear q)) (defn offer-all [q vs] (doseq [v vs] (offer q v)))
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/plumbing/src/plumbing/queue.clj
clojure
(ns plumbing.queue (:refer-clojure :exclude [peek]) (:import [java.util.concurrent BlockingQueue LinkedBlockingQueue PriorityBlockingQueue])) (set! *warn-on-reflection* true) (defn poll [^java.util.Queue q] (.poll q)) (defn peek [^java.util.Queue q] (.peek q)) (defn offer [^java.util.Queue q x] (.offer q x)) (defn put [^BlockingQueue q x] (.put q x)) (defn ^BlockingQueue local-queue "return LinkedBlockingQueue implementation of Queue protocol." ([] (LinkedBlockingQueue.)) ([^java.util.Collection xs] (LinkedBlockingQueue. xs))) (defn ^BlockingQueue blocking-queue [capicity] (LinkedBlockingQueue. (int capicity))) (defn drain "return seq of drained elements from Blocking Queue" [^BlockingQueue q & [max-elems]] (let [c (java.util.ArrayList.)] (if max-elems (.drainTo q c (int max-elems)) (.drainTo q c)) (seq c))) (defn priority-queue ([] (PriorityBlockingQueue.)) ([^java.util.Collection xs] (PriorityBlockingQueue. xs)) ([init-size ordering] (PriorityBlockingQueue. init-size (comparator ordering)))) (defn clear-priority-queue [^PriorityBlockingQueue q] (.clear q)) (defn offer-all [q vs] (doseq [v vs] (offer q v)))
8b0795ea37dfd5938809a5c96a2cf1ae664f2ed9e6fc48cd72df90e07da2d334
borkdude/advent-of-cljc
borkdude.cljc
(ns aoc.y2018.d04.borkdude (:refer-clojure :exclude [read-string format]) (:require [aoc.utils :as u :refer [deftest read-string format]] [aoc.y2018.d04.data :refer [input answer-1 answer-2]] ;; :reload [clojure.test :refer [is testing]] [clojure.string :as str])) (def re #"\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})\] (Guard #\d+ )?(.*)") (defn parse-line [s] (let [[year month day hour minute guard? action] (rest (re-find re s))] {:year (u/parse-int year) :month (u/parse-int month) :day (u/parse-int day) :hour (u/parse-int hour) :minute (u/parse-int minute) :guard (when guard? (u/parse-int (re-find #"\d+" guard?))) :action action})) (def data (memoize #(map parse-line (str/split-lines input)))) (defn complete-line [{:keys [action] :as m} guard] (assoc m :guard guard :sleeping? (= "falls asleep" action))) (defn copy-lines [record from until] (map #(assoc record :minute %) (range from until))) (def process-data (memoize #(let [sorted (sort-by (juxt :year :month :day :hour :minute) (data))] (first (reduce (fn [[acc prev-guard prev-record] {:keys [:action :guard] :as n}] (let [guard (or guard prev-guard) record (complete-line n guard) copies (if (= "wakes up" action) (copy-lines prev-record (inc (:minute prev-record)) (:minute record)) []) new (conj (into acc copies) record)] [new guard record])) [[] nil nil] sorted))))) (defn max-frequency [vals] (first (apply max-key val (frequencies vals)))) (def sleeping (memoize #(keep (fn [m] (when (:sleeping? m) (select-keys m [:guard :minute]))) (process-data)))) (defn solve-1 [] (let [guards (map :guard (sleeping)) most-sleeping-guard (max-frequency guards) only-most-sleeping-guard (filter #(= most-sleeping-guard (:guard %)) (sleeping)) most-frequent-minute (:minute (max-frequency only-most-sleeping-guard))] (* most-sleeping-guard most-frequent-minute))) (defn solve-2 [] (let [{:keys [:guard :minute]} (max-frequency (sleeping))] (* guard minute))) (deftest part-1 (is (= (str answer-1) (str (solve-1))))) (deftest part-2 (is (= (str answer-2) (str (solve-2))))) What I ( re-)learned today : ;; max-key takes a comparison function. a more appropriate name might be max-by ( sort - by ( comp - val ) { : a 1 : b 2 } ) can be written as ( sort - by val > { : a 1 : b 2 } )
null
https://raw.githubusercontent.com/borkdude/advent-of-cljc/17c8abb876b95ab01eee418f1da2e402e845c596/src/aoc/y2018/d04/borkdude.cljc
clojure
:reload max-key takes a comparison function. a more appropriate name might be max-by
(ns aoc.y2018.d04.borkdude (:refer-clojure :exclude [read-string format]) (:require [aoc.utils :as u :refer [deftest read-string format]] [clojure.test :refer [is testing]] [clojure.string :as str])) (def re #"\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})\] (Guard #\d+ )?(.*)") (defn parse-line [s] (let [[year month day hour minute guard? action] (rest (re-find re s))] {:year (u/parse-int year) :month (u/parse-int month) :day (u/parse-int day) :hour (u/parse-int hour) :minute (u/parse-int minute) :guard (when guard? (u/parse-int (re-find #"\d+" guard?))) :action action})) (def data (memoize #(map parse-line (str/split-lines input)))) (defn complete-line [{:keys [action] :as m} guard] (assoc m :guard guard :sleeping? (= "falls asleep" action))) (defn copy-lines [record from until] (map #(assoc record :minute %) (range from until))) (def process-data (memoize #(let [sorted (sort-by (juxt :year :month :day :hour :minute) (data))] (first (reduce (fn [[acc prev-guard prev-record] {:keys [:action :guard] :as n}] (let [guard (or guard prev-guard) record (complete-line n guard) copies (if (= "wakes up" action) (copy-lines prev-record (inc (:minute prev-record)) (:minute record)) []) new (conj (into acc copies) record)] [new guard record])) [[] nil nil] sorted))))) (defn max-frequency [vals] (first (apply max-key val (frequencies vals)))) (def sleeping (memoize #(keep (fn [m] (when (:sleeping? m) (select-keys m [:guard :minute]))) (process-data)))) (defn solve-1 [] (let [guards (map :guard (sleeping)) most-sleeping-guard (max-frequency guards) only-most-sleeping-guard (filter #(= most-sleeping-guard (:guard %)) (sleeping)) most-frequent-minute (:minute (max-frequency only-most-sleeping-guard))] (* most-sleeping-guard most-frequent-minute))) (defn solve-2 [] (let [{:keys [:guard :minute]} (max-frequency (sleeping))] (* guard minute))) (deftest part-1 (is (= (str answer-1) (str (solve-1))))) (deftest part-2 (is (= (str answer-2) (str (solve-2))))) What I ( re-)learned today : ( sort - by ( comp - val ) { : a 1 : b 2 } ) can be written as ( sort - by val > { : a 1 : b 2 } )
64dab68f33483987ad2bdc6b0ff132bb284a58d8ce9ddb78f771d7f05d7bd0a7
tfidfwastaken/loosie
model.rkt
#lang racket/base (require db database-url deta threading racket/string) (provide init-db port app-url upload-file get-file-data (schema-out loosie)) ; A loosie is a text-based file we want to share (define-schema loosie ([id id/f #:primary-key #:auto-increment] [name string/f #:contract non-empty-string?] [mime-type binary/f] [content binary/f] [access-code string/f #:contract non-empty-string? #:unique] [passphrase string/f] [pass-protected? boolean/f] [wrap binary/f])) (define (init-db) ; make-pg-connection : (-> connection) (define make-pg-connection (let ([db-url (getenv "DATABASE_URL")]) (database-url-connector db-url))) ; pgc : connection (define pgc (virtual-connection (connection-pool (λ () (make-pg-connection))))) ; creates table if not present (create-table! pgc 'loosie) pgc) (define port (if (getenv "PORT") (string->number (getenv "PORT")) 8080)) (define app-url (if (getenv "APP_URL") (getenv "APP_URL") ":8080")) (define (upload-file db a-loosie) (insert-one! db a-loosie)) (define (get-file-data db access-code) (define query-vec (query-maybe-row db (~> (from loosie #:as l) (where (= l.access-code ,access-code))))) (if (equal? query-vec #f) #f (make-loosie #:name (vector-ref query-vec 1) #:mime-type (vector-ref query-vec 2) #:content (vector-ref query-vec 3) #:access-code access-code #:passphrase (vector-ref query-vec 5) #:pass-protected? (vector-ref query-vec 6) #:wrap (vector-ref query-vec 7))))
null
https://raw.githubusercontent.com/tfidfwastaken/loosie/5209731fca52d1b6df1a26919464f564b382b3e4/loosie/model.rkt
racket
A loosie is a text-based file we want to share make-pg-connection : (-> connection) pgc : connection creates table if not present
#lang racket/base (require db database-url deta threading racket/string) (provide init-db port app-url upload-file get-file-data (schema-out loosie)) (define-schema loosie ([id id/f #:primary-key #:auto-increment] [name string/f #:contract non-empty-string?] [mime-type binary/f] [content binary/f] [access-code string/f #:contract non-empty-string? #:unique] [passphrase string/f] [pass-protected? boolean/f] [wrap binary/f])) (define (init-db) (define make-pg-connection (let ([db-url (getenv "DATABASE_URL")]) (database-url-connector db-url))) (define pgc (virtual-connection (connection-pool (λ () (make-pg-connection))))) (create-table! pgc 'loosie) pgc) (define port (if (getenv "PORT") (string->number (getenv "PORT")) 8080)) (define app-url (if (getenv "APP_URL") (getenv "APP_URL") ":8080")) (define (upload-file db a-loosie) (insert-one! db a-loosie)) (define (get-file-data db access-code) (define query-vec (query-maybe-row db (~> (from loosie #:as l) (where (= l.access-code ,access-code))))) (if (equal? query-vec #f) #f (make-loosie #:name (vector-ref query-vec 1) #:mime-type (vector-ref query-vec 2) #:content (vector-ref query-vec 3) #:access-code access-code #:passphrase (vector-ref query-vec 5) #:pass-protected? (vector-ref query-vec 6) #:wrap (vector-ref query-vec 7))))
02f05ac2dc7bd6fa2c42032a751941efd8af067889c2aabb72630261aee744e8
richcarl/erlguten
eg_font_server.erl
%%========================================================================== Copyright ( C ) 2003 %% %% Permission is hereby granted, free of charge, to any person obtaining a %% copy of this software and associated documentation files (the " Software " ) , to deal in the Software without restriction , including %% without limitation the rights to use, copy, modify, merge, publish, distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the %% following conditions: %% %% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS %% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF %% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN %% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR %% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE %% USE OR OTHER DEALINGS IN THE SOFTWARE. %% Authors : < > %%========================================================================== -module(eg_font_server). -include("eg.hrl"). -export([start/0, stop/0, char_width/2, data/1, info/1, kern/2]). %% ============================================================================ start() -> case lists:member(fonts, ets:all()) of true -> true; false -> fonts = ets:new(fonts, [named_table,set,public]), true end. stop() -> ets:delete(fonts). %% available_fonts() -> %% eg_afm:available_fonts(). %% ensure_loaded(Font, Index) -> %% %% io:format("Ensure_loaded font number=~p = ~s~n", [Index, Font]), %% case ets:lookup(fonts, {info, Index}) of %% [_] -> %% true; %% [] -> case eg_afm : ) of { ok , { afm_qdh1,Font , , , All } } - > %% ets:insert(fonts, {{info, Index}, Font}), %% ets:insert(fonts, {{allData, Font}, All}), lists : foreach(fun({Char , W } ) - > %% ets:insert(fonts, { { width , Index , , W } ) end , ) , %% lists:foreach(fun({KP,W}) -> %% ets:insert(fonts, { , Index , KP } , W } ) end , ) , %% true; %% {error, Why} -> %% exit({cannot_load_font, Why}) %% end %% end. info(Index) -> case ets:lookup(fonts, {info, Index}) of [{_,I}] -> I; [] -> exit({font_server_info,Index}) end. data(Fontname) -> case ets:lookup(fonts, {allData, Fontname}) of [{_,I}] -> {ok, I}; [] -> error end. char_width(N, Char) -> case ets:lookup(fonts, {width,N,Char}) of [{_,W}] -> W; [] -> io:format("Cannot figure out width of:~p ~p~n",[N, Char]), io:format("Possible \n in code etc~n"), 1000 end. kern(N, KP) -> case ets:lookup(fonts, {kern,N,KP}) of [{_,W}] -> W; [] -> 0 end.
null
https://raw.githubusercontent.com/richcarl/erlguten/debd6120907e5e18b4bca5fbd5bdd9cb653f282d/src/eg_font_server.erl
erlang
========================================================================== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, following conditions: The above copyright notice and this permission notice shall be included OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================================================== ============================================================================ available_fonts() -> eg_afm:available_fonts(). ensure_loaded(Font, Index) -> %% io:format("Ensure_loaded font number=~p = ~s~n", [Index, Font]), case ets:lookup(fonts, {info, Index}) of [_] -> true; [] -> ets:insert(fonts, {{info, Index}, Font}), ets:insert(fonts, {{allData, Font}, All}), ets:insert(fonts, lists:foreach(fun({KP,W}) -> ets:insert(fonts, true; {error, Why} -> exit({cannot_load_font, Why}) end end.
Copyright ( C ) 2003 " Software " ) , to deal in the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR Authors : < > -module(eg_font_server). -include("eg.hrl"). -export([start/0, stop/0, char_width/2, data/1, info/1, kern/2]). start() -> case lists:member(fonts, ets:all()) of true -> true; false -> fonts = ets:new(fonts, [named_table,set,public]), true end. stop() -> ets:delete(fonts). case eg_afm : ) of { ok , { afm_qdh1,Font , , , All } } - > lists : foreach(fun({Char , W } ) - > { { width , Index , , W } ) end , ) , { , Index , KP } , W } ) end , ) , info(Index) -> case ets:lookup(fonts, {info, Index}) of [{_,I}] -> I; [] -> exit({font_server_info,Index}) end. data(Fontname) -> case ets:lookup(fonts, {allData, Fontname}) of [{_,I}] -> {ok, I}; [] -> error end. char_width(N, Char) -> case ets:lookup(fonts, {width,N,Char}) of [{_,W}] -> W; [] -> io:format("Cannot figure out width of:~p ~p~n",[N, Char]), io:format("Possible \n in code etc~n"), 1000 end. kern(N, KP) -> case ets:lookup(fonts, {kern,N,KP}) of [{_,W}] -> W; [] -> 0 end.
642159abbbed8740b8e0b901d0b9edd7cebdda1bf08d4a5be8b6f41f4376fcc1
semerdzhiev/fp-2020-21
exam-prep.rkt
#lang racket (define empty-tree '()) (define (make-tree root left right) (list root left right)) (define (make-leaf root) (make-tree root empty-tree empty-tree)) ;getters (define root-tree car) (define left-tree cadr) (define right-tree caddr) ; validation (define (tree? t) (or (null? t) (and (list? t) (= (length t) 3) (tree? (cadr t)) (tree? (caddr t))))) (define empty-tree? null?) (define example (make-tree 1 (make-tree 3 (make-leaf 8) empty-tree) (make-tree 7 empty-tree (make-tree 9 (make-leaf 10) (make-leaf 11))))) ; (invert tree) 4 4 ; / \ invert / \ 2 5 = = = = = = = = > 5 2 ; / \ / \ 1 3 3 1 (define (invert tree) (void) ) прави пълно дърво с дадена височина и всичко стойности във върховете са дадената стойност (define (full-tree level value) (void) ) ; поток от всички пълни дървета с дадена стойност (define (full-trees value) (void) ) Да се напише функция extremum , от , което е минимално във всеки от списъците , ако има такова , или 0 иначе ( extremum ' ( ( 1 2 3 2 ) ( 3 5 ) ( 3 3 ) ( 1 1 3 3 ) ) ) → 3 (define (extremum xs) (void) )
null
https://raw.githubusercontent.com/semerdzhiev/fp-2020-21/64fa00c4f940f75a28cc5980275b124ca21244bc/group-b/class/exam-prep.rkt
racket
getters validation (invert tree) / \ invert / \ / \ / \ поток от всички пълни дървета с дадена стойност
#lang racket (define empty-tree '()) (define (make-tree root left right) (list root left right)) (define (make-leaf root) (make-tree root empty-tree empty-tree)) (define root-tree car) (define left-tree cadr) (define right-tree caddr) (define (tree? t) (or (null? t) (and (list? t) (= (length t) 3) (tree? (cadr t)) (tree? (caddr t))))) (define empty-tree? null?) (define example (make-tree 1 (make-tree 3 (make-leaf 8) empty-tree) (make-tree 7 empty-tree (make-tree 9 (make-leaf 10) (make-leaf 11))))) 4 4 2 5 = = = = = = = = > 5 2 1 3 3 1 (define (invert tree) (void) ) прави пълно дърво с дадена височина и всичко стойности във върховете са дадената стойност (define (full-tree level value) (void) ) (define (full-trees value) (void) ) Да се напише функция extremum , от , което е минимално във всеки от списъците , ако има такова , или 0 иначе ( extremum ' ( ( 1 2 3 2 ) ( 3 5 ) ( 3 3 ) ( 1 1 3 3 ) ) ) → 3 (define (extremum xs) (void) )
6381a60db3f390f196f0e3479bed0d5813604c60141febc5ba4f5ea1fcb987d1
rlepigre/subml
subml.ml
(****************************************************************************) * { 3 Main file } (****************************************************************************) let quit = ref false let spec = Arg.align [ ( "--verbose" , Arg.Set Ast.verbose , " Display the defined types and values" ) ; ( "--quit" , Arg.Set quit , " Quit after evaluating the files" ) ; ( "--gml-file" , Arg.String Io.set_gml_file , "fn Choose the GraphMl output file" ) ; ( "--tex-file" , Arg.String Io.set_tex_file , "fn Choose the TeX output file" ) ; ( "--out-file" , Arg.String Io.(fun s -> fmts.out <- fmt_of_file s) , "fn Choose the standard output file" ) ; ( "--err-file" , Arg.String Io.(fun s -> fmts.err <- fmt_of_file s) , "fn Choose the error output file" ) ; ( "--log-file" , Arg.String Io.(fun s -> fmts.log <- fmt_of_file s) , "fn Choose the log output file" ) ; ( "--no-inline" , Arg.Clear Sct.do_inline , " Do not optimize the SCP call graph by inlining" ) ; ( "--no-contr" , Arg.Clear Ast.contract_mu , " Do not contract the fixpoints" ) ; ( "--fix-depth" , Arg.Set_int Raw.fixpoint_depth , "i Set the maximal unrolling depth for fixpoints" ) ; ( "--debug" , Arg.String Io.set_debug , "s Display the debugging informations 't': typing 's': subtyping 'u': unification 'y': size change principle 'm': sct matrix coefficient" ) ; ( "--debug-parser" , Arg.Set_int Earley_core.Earley.debug_lvl , "i Set the debug lvl of earley" ) ; ( "-I" , Arg.String (fun s -> Io.path := s :: !Io.path) , "s Add the given directory to the path") ] let _ = Sys.catch_break true; (* Reading the command lien arguments and gathering the files. *) let usage = Printf.sprintf "Usage: %s [ARGS] [FILES]" Sys.argv.(0) in let files = let files = ref [] in Arg.parse spec (fun fn -> files := !files @ [fn]) usage; !files in (* Handle the files given on the command line. *) let eval = Parser.handle_exception Parser.eval_file in let ok = List.for_all eval files in (* Run the toplevel. *) let handle_line () = let line = read_line () in if String.trim line <> "" then Parser.(execute (toplevel_of_string line)) in if not !quit && ok then begin Ast.verbose := true; try while true do Printf.printf ">> %!"; ignore (Parser.handle_exception handle_line ()) done with End_of_file -> () end; (* Close opened file and exit. *) Io.close_files (); if not ok then exit 1
null
https://raw.githubusercontent.com/rlepigre/subml/d410898910399b3286e80b129656bd7b3bc208c5/src/subml.ml
ocaml
************************************************************************** ************************************************************************** Reading the command lien arguments and gathering the files. Handle the files given on the command line. Run the toplevel. Close opened file and exit.
* { 3 Main file } let quit = ref false let spec = Arg.align [ ( "--verbose" , Arg.Set Ast.verbose , " Display the defined types and values" ) ; ( "--quit" , Arg.Set quit , " Quit after evaluating the files" ) ; ( "--gml-file" , Arg.String Io.set_gml_file , "fn Choose the GraphMl output file" ) ; ( "--tex-file" , Arg.String Io.set_tex_file , "fn Choose the TeX output file" ) ; ( "--out-file" , Arg.String Io.(fun s -> fmts.out <- fmt_of_file s) , "fn Choose the standard output file" ) ; ( "--err-file" , Arg.String Io.(fun s -> fmts.err <- fmt_of_file s) , "fn Choose the error output file" ) ; ( "--log-file" , Arg.String Io.(fun s -> fmts.log <- fmt_of_file s) , "fn Choose the log output file" ) ; ( "--no-inline" , Arg.Clear Sct.do_inline , " Do not optimize the SCP call graph by inlining" ) ; ( "--no-contr" , Arg.Clear Ast.contract_mu , " Do not contract the fixpoints" ) ; ( "--fix-depth" , Arg.Set_int Raw.fixpoint_depth , "i Set the maximal unrolling depth for fixpoints" ) ; ( "--debug" , Arg.String Io.set_debug , "s Display the debugging informations 't': typing 's': subtyping 'u': unification 'y': size change principle 'm': sct matrix coefficient" ) ; ( "--debug-parser" , Arg.Set_int Earley_core.Earley.debug_lvl , "i Set the debug lvl of earley" ) ; ( "-I" , Arg.String (fun s -> Io.path := s :: !Io.path) , "s Add the given directory to the path") ] let _ = Sys.catch_break true; let usage = Printf.sprintf "Usage: %s [ARGS] [FILES]" Sys.argv.(0) in let files = let files = ref [] in Arg.parse spec (fun fn -> files := !files @ [fn]) usage; !files in let eval = Parser.handle_exception Parser.eval_file in let ok = List.for_all eval files in let handle_line () = let line = read_line () in if String.trim line <> "" then Parser.(execute (toplevel_of_string line)) in if not !quit && ok then begin Ast.verbose := true; try while true do Printf.printf ">> %!"; ignore (Parser.handle_exception handle_line ()) done with End_of_file -> () end; Io.close_files (); if not ok then exit 1
6df76916aa89679c42a027b747f98e3f428ae60e7a2caaca10efb508d2fa8159
clj-commons/claypoole
test_helpers.clj
(ns com.climate.claypoole.test-helpers) (defn eval+ex-unwrap "Test helper. Clojure 1.10 throws CompilerException from eval. We unwrap that exception to get the original." [code] (try (eval code) (catch clojure.lang.Compiler$CompilerException e (let [cause (.getCause e)] ;; Update the stack trace to include e (.setStackTrace cause (into-array StackTraceElement (concat (.getStackTrace cause) (.getStackTrace e)))) (throw cause)))))
null
https://raw.githubusercontent.com/clj-commons/claypoole/a4bd33f3dd50d04a72d4eb81807ed2d050e7e002/test/com/climate/claypoole/test_helpers.clj
clojure
Update the stack trace to include e
(ns com.climate.claypoole.test-helpers) (defn eval+ex-unwrap "Test helper. Clojure 1.10 throws CompilerException from eval. We unwrap that exception to get the original." [code] (try (eval code) (catch clojure.lang.Compiler$CompilerException e (let [cause (.getCause e)] (.setStackTrace cause (into-array StackTraceElement (concat (.getStackTrace cause) (.getStackTrace e)))) (throw cause)))))
56a70c60a1159f0169199a0119cb804f1e3c05bbec964026b8d89a4ce7f827ae
clojure-lsp/lsp4clj
errors_test.clj
(ns lsp4clj.lsp.errors-test (:require [clojure.test :refer [deftest is]] [lsp4clj.lsp.errors :as lsp.errors])) (deftest body-should-look-up-error-by-code ;; Uses known code and message (is (= {:code -32001 :message "Unknown error"} (lsp.errors/body :unknown-error-code nil nil))) ;; Prefers custom message with known code (is (= {:code -32001 :message "Custom message"} (lsp.errors/body :unknown-error-code "Custom message" nil))) ;; Uses custom code (is (= {:code -1} (lsp.errors/body -1 nil nil))) ;; Uses custom code and message (is (= {:code -1 :message "Custom message"} (lsp.errors/body -1 "Custom message" nil))) ;; Uses custom code, message, and data (is (= {:code -1 :message "Custom message" :data {:details "error"}} (lsp.errors/body -1 "Custom message" {:details "error"}))))
null
https://raw.githubusercontent.com/clojure-lsp/lsp4clj/1edff25befa7cef6911436644abbabe195221267/test/lsp4clj/lsp/errors_test.clj
clojure
Uses known code and message Prefers custom message with known code Uses custom code Uses custom code and message Uses custom code, message, and data
(ns lsp4clj.lsp.errors-test (:require [clojure.test :refer [deftest is]] [lsp4clj.lsp.errors :as lsp.errors])) (deftest body-should-look-up-error-by-code (is (= {:code -32001 :message "Unknown error"} (lsp.errors/body :unknown-error-code nil nil))) (is (= {:code -32001 :message "Custom message"} (lsp.errors/body :unknown-error-code "Custom message" nil))) (is (= {:code -1} (lsp.errors/body -1 nil nil))) (is (= {:code -1 :message "Custom message"} (lsp.errors/body -1 "Custom message" nil))) (is (= {:code -1 :message "Custom message" :data {:details "error"}} (lsp.errors/body -1 "Custom message" {:details "error"}))))
14957f303678b00ffa4b0dbd27a3d7e3c6588a8c58e8dc7d8a5f40910eeaa3cf
bytekid/mkbtt
choose.ml
Copyright 2010 * GNU Lesser General Public License * * This file is part of MKBtt . * * is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 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 Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with MKBtt . If not , see < / > . * GNU Lesser General Public License * * This file is part of MKBtt. * * MKBtt is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * MKBtt is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with MKBtt. If not, see </>. *) * Control for node choice ( first implementation ) . @author @since 2007/04/30 @author Sarah Winkler @since 2007/04/30 *) (* Module provides functions to control the choice of a process/node from the current node set. Corresponds to strategy mkbtt1 used in old implementation. *) (*** SUBMODULES **********************************************************) module Pos = Position;; module T = Term;; module Fun = FunctionSymbol;; module Var = Variable;; module Sub = Substitution;; module NodeSet = SomeSet.Make(Node);; module CProcess = CompletionProcess;; module St = Statistics;; (*** TYPES ***************************************************************) (*** EXCEPTIONS **********************************************************) (*** GLOBALS *************************************************************) (*** FUNCTIONS ***********************************************************) (* selects node with minimal termsize *) let fold_min_termsize n (min, set) = let s = Node.terms_size n in if s < min then (s, NodeSet.singleton n) else if s == min then (min, NodeSet.add n set) else (min, set) ;; (* selects node with minimal termsize or oneway orientation *) let fold_min_termsize_or_oneway n (min, b, set) = let s1 = Node.is_oneway n in let s = Node.terms_size n in if (not s1) && b then (min, true, set) else if s1 && (not b) then (s, true, NodeSet.singleton n) else if s < min then (s, b, NodeSet.singleton n) else if s == min then (min, b, NodeSet.add n set) else (min, b, set) ;; let fold_min_termsize_tolerance t n (min, set) = let s = Node.terms_size n in if s < min then (s, NodeSet.singleton n) else let thresh = min + (truncate ((float_of_int min) *. t)) in if s <= thresh then (min, NodeSet.add n set) else (min, set) ;; let fold_max_age n (min, node) = let s = Node.stamp n in if s < min then (s, n) else (min, node) ;; let fold_deterministic n node = if (Node.compare n node) < 0 then n else node ;; let fold_max_processes n (max, set) = let m = CProcess.cardinal (Node.open_labels n) in if m > max then (m, NodeSet.singleton n) else if m == max then (max, NodeSet.add n set) else (max, set) ;; let fewest_rules no nc = let r = Setx.choose !CProcess.all_processes in let (pmin, _ ) = Setx.fold (fun p (pm, m) -> let c = NodeSetAux.count nc p in if c < m then (p, c) else (pm, m) ) !CProcess.all_processes (r, NodeSetAux.count nc r) in CProcess.singleton pmin ;; let fewest_rules no nc = let r = Setx.choose !CProcess.all_processes in let (pmin, _ ) = Setx.fold (fun p (pm, m) -> let c = NodeSetAux.count nc p in if c < m then (p, c) else (pm, m) ) !CProcess.all_processes (r, NodeSetAux.count nc r) in CProcess.singleton pmin ;; let heuristic1 ns nsc = let e = NodeSet.empty in let _, ns2 = NodeSet.fold (fold_min_termsize_tolerance 0.0) ns (100, e) in let _, ns3 = NodeSet.fold fold_max_processes ns2 (0, e) in let n = NodeSet.choose ns3 in (* new *) let _, n' = NodeSet.fold fold_max_age ns3 (!(Statistics.node_count), n) in (* just for debugging, to obtain deterministic choice *) (*NodeSet.fold fold_deterministic ns3 *) n' ;; let possibly_isomorphic options n = let rule = Node.true_rule n in match Completion.check_isomorphism options with | Completion.NoChecks -> false | Completion.Renamings -> begin match Node.is_symmetric n with | None -> let i = TrsRenaming.rule_symmetric rule in ignore (Node.update_symmetric n i); (* if i then Format.printf "Node %s is symmetric\n" (Node.to_string n);*) i | Some b -> b end | Completion.Permutations -> begin match Node.is_symmetric n with | None -> let i = TermPermutation.rule_symmetric rule in ignore (Node.update_symmetric n i); i | Some b -> b end ;; let heuristic2 ns nsc options = let e = NodeSet.empty in let ns' = NodeSet.filter (possibly_isomorphic options) ns in let ns = if NodeSet.is_empty ns' then ns else ns' in let _, ns2 = NodeSet.fold fold_min_termsize ns (100, e) in let ns2 ' = ns2 in let ns2 = if NodeSet.is_empty ns2 ' then ns2 else ' in let ns2 ' = NodeSet.filter ( possibly_isomorphic options ) ns2 in let ns2 = if NodeSet.is_empty ns2 ' then ns2 else ' in let ns2 = if NodeSet.is_empty ns2' then ns2 else ns2' in let ns2' = NodeSet.filter (possibly_isomorphic options) ns2 in let ns2 = if NodeSet.is_empty ns2' then ns2 else ns2' in*) let _, ns3 = NodeSet.fold fold_max_processes ns2 (0, e) in NodeSet.choose ns3 ;; let heuristic3 ns nsc options = let e = NodeSet.empty in let agetosize = 0.05 in let r = Random.float 1.0 in if r < agetosize then let n = NodeSet.choose ns in snd (NodeSet.fold (fold_max_age) ns (Node.stamp n, n)) else ( let ns2 = snd (NodeSet.fold (fold_min_termsize_tolerance 0.0) ns (100, e)) in let _, ns3 = NodeSet.fold fold_max_processes ns2 (0, e) in NodeSet.choose ns3) ;; let delete_processes ps ns nsc = let gamma = Hashtbl.create 5 in CProcess.iter (fun p -> CProcess.delete p; Hashtbl.replace gamma p (CProcess.empty ()); ) ps; let nso' = NodeSet.apply_split ns gamma in let nsc' = NodeSet.apply_split nsc gamma in (nso', nsc') ;; (* choose from open nodes ns. ns is assumed non-empty! *) let rec best_m ns nsc options = let ps = CProcess.fewest_rules () in CProcess.inc_choice_counts ps; (* this line is pure magic *) let ns' = NodeSet.filter (Node.contains_processes_open ps) ns in if NodeSet.is_empty ns' then let nso', nsc' = delete_processes ps ns nsc in best_m nso' nsc' options else heuristic1 ns' nsc (*options*) ;; choice function for / oKBtt let fold_min_cost s (cmin, smin) = if (State.cost_value s < cmin) then (State.cost_value s, s) else (cmin, smin) ;; let best_s pset = let _, min = Setx.fold fold_min_cost pset (100000, Setx.choose pset) in min ;;
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mkbtt/choose.ml
ocaml
Module provides functions to control the choice of a process/node from the current node set. Corresponds to strategy mkbtt1 used in old implementation. ** SUBMODULES ********************************************************* ** TYPES ************************************************************** ** EXCEPTIONS ********************************************************* ** GLOBALS ************************************************************ ** FUNCTIONS ********************************************************** selects node with minimal termsize selects node with minimal termsize or oneway orientation new just for debugging, to obtain deterministic choice NodeSet.fold fold_deterministic ns3 if i then Format.printf "Node %s is symmetric\n" (Node.to_string n); choose from open nodes ns. ns is assumed non-empty! this line is pure magic options
Copyright 2010 * GNU Lesser General Public License * * This file is part of MKBtt . * * is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 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 Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with MKBtt . If not , see < / > . * GNU Lesser General Public License * * This file is part of MKBtt. * * MKBtt is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * MKBtt is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with MKBtt. If not, see </>. *) * Control for node choice ( first implementation ) . @author @since 2007/04/30 @author Sarah Winkler @since 2007/04/30 *) module Pos = Position;; module T = Term;; module Fun = FunctionSymbol;; module Var = Variable;; module Sub = Substitution;; module NodeSet = SomeSet.Make(Node);; module CProcess = CompletionProcess;; module St = Statistics;; let fold_min_termsize n (min, set) = let s = Node.terms_size n in if s < min then (s, NodeSet.singleton n) else if s == min then (min, NodeSet.add n set) else (min, set) ;; let fold_min_termsize_or_oneway n (min, b, set) = let s1 = Node.is_oneway n in let s = Node.terms_size n in if (not s1) && b then (min, true, set) else if s1 && (not b) then (s, true, NodeSet.singleton n) else if s < min then (s, b, NodeSet.singleton n) else if s == min then (min, b, NodeSet.add n set) else (min, b, set) ;; let fold_min_termsize_tolerance t n (min, set) = let s = Node.terms_size n in if s < min then (s, NodeSet.singleton n) else let thresh = min + (truncate ((float_of_int min) *. t)) in if s <= thresh then (min, NodeSet.add n set) else (min, set) ;; let fold_max_age n (min, node) = let s = Node.stamp n in if s < min then (s, n) else (min, node) ;; let fold_deterministic n node = if (Node.compare n node) < 0 then n else node ;; let fold_max_processes n (max, set) = let m = CProcess.cardinal (Node.open_labels n) in if m > max then (m, NodeSet.singleton n) else if m == max then (max, NodeSet.add n set) else (max, set) ;; let fewest_rules no nc = let r = Setx.choose !CProcess.all_processes in let (pmin, _ ) = Setx.fold (fun p (pm, m) -> let c = NodeSetAux.count nc p in if c < m then (p, c) else (pm, m) ) !CProcess.all_processes (r, NodeSetAux.count nc r) in CProcess.singleton pmin ;; let fewest_rules no nc = let r = Setx.choose !CProcess.all_processes in let (pmin, _ ) = Setx.fold (fun p (pm, m) -> let c = NodeSetAux.count nc p in if c < m then (p, c) else (pm, m) ) !CProcess.all_processes (r, NodeSetAux.count nc r) in CProcess.singleton pmin ;; let heuristic1 ns nsc = let e = NodeSet.empty in let _, ns2 = NodeSet.fold (fold_min_termsize_tolerance 0.0) ns (100, e) in let _, ns3 = NodeSet.fold fold_max_processes ns2 (0, e) in let n = NodeSet.choose ns3 in let _, n' = NodeSet.fold fold_max_age ns3 (!(Statistics.node_count), n) in n' ;; let possibly_isomorphic options n = let rule = Node.true_rule n in match Completion.check_isomorphism options with | Completion.NoChecks -> false | Completion.Renamings -> begin match Node.is_symmetric n with | None -> let i = TrsRenaming.rule_symmetric rule in ignore (Node.update_symmetric n i); i | Some b -> b end | Completion.Permutations -> begin match Node.is_symmetric n with | None -> let i = TermPermutation.rule_symmetric rule in ignore (Node.update_symmetric n i); i | Some b -> b end ;; let heuristic2 ns nsc options = let e = NodeSet.empty in let ns' = NodeSet.filter (possibly_isomorphic options) ns in let ns = if NodeSet.is_empty ns' then ns else ns' in let _, ns2 = NodeSet.fold fold_min_termsize ns (100, e) in let ns2 ' = ns2 in let ns2 = if NodeSet.is_empty ns2 ' then ns2 else ' in let ns2 ' = NodeSet.filter ( possibly_isomorphic options ) ns2 in let ns2 = if NodeSet.is_empty ns2 ' then ns2 else ' in let ns2 = if NodeSet.is_empty ns2' then ns2 else ns2' in let ns2' = NodeSet.filter (possibly_isomorphic options) ns2 in let ns2 = if NodeSet.is_empty ns2' then ns2 else ns2' in*) let _, ns3 = NodeSet.fold fold_max_processes ns2 (0, e) in NodeSet.choose ns3 ;; let heuristic3 ns nsc options = let e = NodeSet.empty in let agetosize = 0.05 in let r = Random.float 1.0 in if r < agetosize then let n = NodeSet.choose ns in snd (NodeSet.fold (fold_max_age) ns (Node.stamp n, n)) else ( let ns2 = snd (NodeSet.fold (fold_min_termsize_tolerance 0.0) ns (100, e)) in let _, ns3 = NodeSet.fold fold_max_processes ns2 (0, e) in NodeSet.choose ns3) ;; let delete_processes ps ns nsc = let gamma = Hashtbl.create 5 in CProcess.iter (fun p -> CProcess.delete p; Hashtbl.replace gamma p (CProcess.empty ()); ) ps; let nso' = NodeSet.apply_split ns gamma in let nsc' = NodeSet.apply_split nsc gamma in (nso', nsc') ;; let rec best_m ns nsc options = let ps = CProcess.fewest_rules () in let ns' = NodeSet.filter (Node.contains_processes_open ps) ns in if NodeSet.is_empty ns' then let nso', nsc' = delete_processes ps ns nsc in best_m nso' nsc' options else ;; choice function for / oKBtt let fold_min_cost s (cmin, smin) = if (State.cost_value s < cmin) then (State.cost_value s, s) else (cmin, smin) ;; let best_s pset = let _, min = Setx.fold fold_min_cost pset (100000, Setx.choose pset) in min ;;
27058e437c0c0dc443bdf32de4838f75c7511d5e45f264dcae213bd4d199a688
brandonchinn178/advent-of-code
Day3.hs
{- stack script --resolver lts-14.12 -} # OPTIONS_GHC -Wall # # LANGUAGE LambdaCase # # LANGUAGE TypeApplications # import Data.List.Split (splitOn) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map main :: IO () main = do input <- readFile "Day3.txt" let (cmds1, cmds2) = splitCommands input pointsMap1 = toPointsMap cmds1 pointsMap2 = toPointsMap cmds2 print $ part1 pointsMap1 pointsMap2 print $ part2 pointsMap1 pointsMap2 part1 :: PointsMap -> PointsMap -> Int part1 pointsMap1 pointsMap2 = minimum $ Map.intersectionWithKey manhattanDist pointsMap1 pointsMap2 where manhattanDist (x, y) _ _ = abs x + abs y part2 :: PointsMap -> PointsMap -> Int part2 pointsMap1 pointsMap2 = minimum $ Map.intersectionWithKey addSteps pointsMap1 pointsMap2 where addSteps _ steps1 steps2 = steps1 + steps2 -- ((dx, dy), number of steps) type Command = ((Int, Int), Int) -- A list of visited points, mapped to the number of steps it took to get there. -- If a point was visited multiple times, keep the lowest number of steps type PointsMap = Map (Int, Int) Int splitCommands :: String -> ([Command], [Command]) splitCommands = toPair . map (map toCommand . splitOn ",") . lines where toPair = \case [x, y] -> (x, y) l -> error $ "Not a pair: " ++ show l toCommand :: String -> Command toCommand cmd = (dirSteps, read @Int $ tail cmd) where dirSteps = case head cmd of 'R' -> (1, 0) 'L' -> (-1, 0) 'U' -> (0, 1) 'D' -> (0, -1) dir -> error $ "Bad direction: " ++ [dir] toPointsMap :: [Command] -> PointsMap toPointsMap = Map.fromListWith const . getPoints ((0, 0), 0) where getPoints _ [] = [] getPoints ((currX, currY), currSteps) (cmd:cmds) = let ((dx, dy), steps) = cmd points = flip map [1..steps] $ \step -> let stepX = currX + dx * step stepY = currY + dy * step in ((stepX, stepY), currSteps + step) in points ++ getPoints (last points) cmds
null
https://raw.githubusercontent.com/brandonchinn178/advent-of-code/a4b0616f8764620e28759276c333fe37d6685d57/2019/Day3.hs
haskell
stack script --resolver lts-14.12 ((dx, dy), number of steps) A list of visited points, mapped to the number of steps it took to get there. If a point was visited multiple times, keep the lowest number of steps
# OPTIONS_GHC -Wall # # LANGUAGE LambdaCase # # LANGUAGE TypeApplications # import Data.List.Split (splitOn) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map main :: IO () main = do input <- readFile "Day3.txt" let (cmds1, cmds2) = splitCommands input pointsMap1 = toPointsMap cmds1 pointsMap2 = toPointsMap cmds2 print $ part1 pointsMap1 pointsMap2 print $ part2 pointsMap1 pointsMap2 part1 :: PointsMap -> PointsMap -> Int part1 pointsMap1 pointsMap2 = minimum $ Map.intersectionWithKey manhattanDist pointsMap1 pointsMap2 where manhattanDist (x, y) _ _ = abs x + abs y part2 :: PointsMap -> PointsMap -> Int part2 pointsMap1 pointsMap2 = minimum $ Map.intersectionWithKey addSteps pointsMap1 pointsMap2 where addSteps _ steps1 steps2 = steps1 + steps2 type Command = ((Int, Int), Int) type PointsMap = Map (Int, Int) Int splitCommands :: String -> ([Command], [Command]) splitCommands = toPair . map (map toCommand . splitOn ",") . lines where toPair = \case [x, y] -> (x, y) l -> error $ "Not a pair: " ++ show l toCommand :: String -> Command toCommand cmd = (dirSteps, read @Int $ tail cmd) where dirSteps = case head cmd of 'R' -> (1, 0) 'L' -> (-1, 0) 'U' -> (0, 1) 'D' -> (0, -1) dir -> error $ "Bad direction: " ++ [dir] toPointsMap :: [Command] -> PointsMap toPointsMap = Map.fromListWith const . getPoints ((0, 0), 0) where getPoints _ [] = [] getPoints ((currX, currY), currSteps) (cmd:cmds) = let ((dx, dy), steps) = cmd points = flip map [1..steps] $ \step -> let stepX = currX + dx * step stepY = currY + dy * step in ((stepX, stepY), currSteps + step) in points ++ getPoints (last points) cmds
f54e3cb6d0173f35bad72bceb972c6783d52642b5bc92265d2208f28b1cabfb9
taiki45/hs-vm
Parser.hs
module Parser ( parse , instructionsParser ) where import Control.Applicative ((<$>), (<$)) import Data.Maybe (catMaybes) import Text.ParserCombinators.Parsec hiding (label) import VM.Instruction instructionsParser :: Parser [Instruction] instructionsParser = catMaybes <$> (comment <|> instruction <|> blank) `sepBy` many1 newline where blank = Nothing <$ eof instruction :: Parser (Maybe Instruction) instruction = Just <$> choice (try <$> [ add , sub , lt , le , gt , ge , eq , not' , store , load , pushl , popl , push , pop , dup , label , jumpIf , jump , call , ret ]) add :: Parser Instruction add = Add <$ string "Add" sub :: Parser Instruction sub = Sub <$ string "Sub" lt :: Parser Instruction lt = Lt <$ string "Lt" le :: Parser Instruction le = Le <$ string "Le" gt :: Parser Instruction gt = Gt <$ string "Gt" ge :: Parser Instruction ge = Ge <$ string "Ge" eq :: Parser Instruction eq = Eq <$ string "Eq" not' :: Parser Instruction not' = Not <$ string "Not" store :: Parser Instruction store = Store <$> instWithNumber "Store" load :: Parser Instruction load = Load <$> instWithNumber "Load" push :: Parser Instruction push = Push <$> instWithNumber "Push" pop :: Parser Instruction pop = Pop <$ string "Pop" dup :: Parser Instruction dup = Dup <$ string "Dup" pushl :: Parser Instruction pushl = PushLocal <$ string "PushLocal" popl :: Parser Instruction popl = PopLocal <$ string "PopLocal" label :: Parser Instruction label = Label <$> instWithString "Label" jump :: Parser Instruction jump = Jump <$> instWithString "Jump" jumpIf :: Parser Instruction jumpIf = JumpIf <$> instWithString "JumpIf" call :: Parser Instruction call = Call <$> instWithString "Call" ret :: Parser Instruction ret = Ret <$ string "Ret" instWithNumber :: String -> Parser Integer instWithNumber s = read <$> (string s >> spaces >> many1 digit) instWithString :: String -> Parser String instWithString s = string s >> spaces >> many1 (noneOf "\n") comment :: Parser (Maybe Instruction) comment = char '#' >> many (noneOf "\n") >> return Nothing
null
https://raw.githubusercontent.com/taiki45/hs-vm/c979d594e957179c64b42ffa82e3022167cc8ad6/src/Parser.hs
haskell
module Parser ( parse , instructionsParser ) where import Control.Applicative ((<$>), (<$)) import Data.Maybe (catMaybes) import Text.ParserCombinators.Parsec hiding (label) import VM.Instruction instructionsParser :: Parser [Instruction] instructionsParser = catMaybes <$> (comment <|> instruction <|> blank) `sepBy` many1 newline where blank = Nothing <$ eof instruction :: Parser (Maybe Instruction) instruction = Just <$> choice (try <$> [ add , sub , lt , le , gt , ge , eq , not' , store , load , pushl , popl , push , pop , dup , label , jumpIf , jump , call , ret ]) add :: Parser Instruction add = Add <$ string "Add" sub :: Parser Instruction sub = Sub <$ string "Sub" lt :: Parser Instruction lt = Lt <$ string "Lt" le :: Parser Instruction le = Le <$ string "Le" gt :: Parser Instruction gt = Gt <$ string "Gt" ge :: Parser Instruction ge = Ge <$ string "Ge" eq :: Parser Instruction eq = Eq <$ string "Eq" not' :: Parser Instruction not' = Not <$ string "Not" store :: Parser Instruction store = Store <$> instWithNumber "Store" load :: Parser Instruction load = Load <$> instWithNumber "Load" push :: Parser Instruction push = Push <$> instWithNumber "Push" pop :: Parser Instruction pop = Pop <$ string "Pop" dup :: Parser Instruction dup = Dup <$ string "Dup" pushl :: Parser Instruction pushl = PushLocal <$ string "PushLocal" popl :: Parser Instruction popl = PopLocal <$ string "PopLocal" label :: Parser Instruction label = Label <$> instWithString "Label" jump :: Parser Instruction jump = Jump <$> instWithString "Jump" jumpIf :: Parser Instruction jumpIf = JumpIf <$> instWithString "JumpIf" call :: Parser Instruction call = Call <$> instWithString "Call" ret :: Parser Instruction ret = Ret <$ string "Ret" instWithNumber :: String -> Parser Integer instWithNumber s = read <$> (string s >> spaces >> many1 digit) instWithString :: String -> Parser String instWithString s = string s >> spaces >> many1 (noneOf "\n") comment :: Parser (Maybe Instruction) comment = char '#' >> many (noneOf "\n") >> return Nothing
8d4ebc467d710b856655535dfd2eacb7bf19d871373c8703477d31508e528362
callum-oakley/advent-of-code
23.clj
(ns aoc.2015.23 (:require [clojure.string :as str])) (defn parse [s] (mapv #(map read-string (re-seq #"\S+" %)) (str/split-lines s))) (defn run [m head registers] (if-let [[op x y] (get m head)] (case op hlf (recur m (inc head) (update registers x quot 2)) tpl (recur m (inc head) (update registers x * 3)) inc (recur m (inc head) (update registers x inc)) jmp (recur m (+ x head) registers) jie (recur m (if (even? (registers x)) (+ y head) (inc head)) registers) jio (recur m (if (= 1 (registers x)) (+ y head) (inc head)) registers)) (registers 'b))) (defn part-1 [m] (run m 0 '{a 0 b 0})) (defn part-2 [m] (run m 0 '{a 1 b 0}))
null
https://raw.githubusercontent.com/callum-oakley/advent-of-code/fa79f6483157e3aeeb43dd8661ca5d308d203933/src/aoc/2015/23.clj
clojure
(ns aoc.2015.23 (:require [clojure.string :as str])) (defn parse [s] (mapv #(map read-string (re-seq #"\S+" %)) (str/split-lines s))) (defn run [m head registers] (if-let [[op x y] (get m head)] (case op hlf (recur m (inc head) (update registers x quot 2)) tpl (recur m (inc head) (update registers x * 3)) inc (recur m (inc head) (update registers x inc)) jmp (recur m (+ x head) registers) jie (recur m (if (even? (registers x)) (+ y head) (inc head)) registers) jio (recur m (if (= 1 (registers x)) (+ y head) (inc head)) registers)) (registers 'b))) (defn part-1 [m] (run m 0 '{a 0 b 0})) (defn part-2 [m] (run m 0 '{a 1 b 0}))
24317d1a418af55dd3b6e40dd195a538ed5922501fa120b2edec2f48513765fb
winny-/aoc
lib.rkt
#lang racket (provide (all-defined-out)) (define (rassoc v alist [eq equal?]) (for/first ([a (in-list alist)] #:when (eq (cdr a) v)) a)) (define ORTHOGINAL-OFFSETS '((-1 0) (1 0) (0 -1) (0 1))) (define DIAGONAL-OFFSETS '((-1 -1) (-1 1) (1 -1) (1 1))) (define ALL-OFFSETS (append ORTHOGINAL-OFFSETS DIAGONAL-OFFSETS)) (define/match (lookup grid loc) [(_ (list x y)) (list-ref (list-ref grid y) x)]) (define/match (neighbors grid loc #:direction [direction 'all] #:lookup [do-lookup #f]) [((list a _ ...) (list x y) _ _) (filter identity (for/list ([offset (match direction [(list _ ...) direction] ['all ALL-OFFSETS] ['orthoginal ORTHOGINAL-OFFSETS] ['diagonal DIAGONAL-OFFSETS])]) (match-define (and neigh (list nx ny)) (map + loc offset)) (and (not (equal? loc neigh)) (<= 0 nx) (> (length a) nx) (<= 0 ny) (> (length grid) ny) (if do-lookup (list nx ny (lookup grid neigh)) neigh))))]) ;; todo does not work (define-syntax-rule (read-line/match cases ...) [(match (read-line) [(? eof-object?) eof] @,cases ... [_ eof])])
null
https://raw.githubusercontent.com/winny-/aoc/9882fd358d8c30f09c7a390bf806f06dc0da3f23/lib.rkt
racket
todo does not work
#lang racket (provide (all-defined-out)) (define (rassoc v alist [eq equal?]) (for/first ([a (in-list alist)] #:when (eq (cdr a) v)) a)) (define ORTHOGINAL-OFFSETS '((-1 0) (1 0) (0 -1) (0 1))) (define DIAGONAL-OFFSETS '((-1 -1) (-1 1) (1 -1) (1 1))) (define ALL-OFFSETS (append ORTHOGINAL-OFFSETS DIAGONAL-OFFSETS)) (define/match (lookup grid loc) [(_ (list x y)) (list-ref (list-ref grid y) x)]) (define/match (neighbors grid loc #:direction [direction 'all] #:lookup [do-lookup #f]) [((list a _ ...) (list x y) _ _) (filter identity (for/list ([offset (match direction [(list _ ...) direction] ['all ALL-OFFSETS] ['orthoginal ORTHOGINAL-OFFSETS] ['diagonal DIAGONAL-OFFSETS])]) (match-define (and neigh (list nx ny)) (map + loc offset)) (and (not (equal? loc neigh)) (<= 0 nx) (> (length a) nx) (<= 0 ny) (> (length grid) ny) (if do-lookup (list nx ny (lookup grid neigh)) neigh))))]) (define-syntax-rule (read-line/match cases ...) [(match (read-line) [(? eof-object?) eof] @,cases ... [_ eof])])
fa018b0c149c5bfa0afc1b3accd3899962980dbbfa4f1ae1e65b40a0d361ce5d
hopv/MoCHi
fdef.ml
open Util open Combinator (** Function definitions *) (** @require a.name = b.name => length a.args = length b.args *) type t = { name: string; @require length length > 0 guard: Formula.t; (* a boolean expression that does not involve side-effects and function calls *) body: Term.t } let make name args guard body = { name = name; args = args; guard = guard; body = body } let name_of f = f.name let args_of f = f.args let guard_of f = f.guard let body_of f = f.body let pr ppf fdef = if Formula.is_true fdef.guard then Format.fprintf ppf "@[<hov2>%a =@ %a@]" (List.pr_app Pattern.pr "@ ") (Pattern.V (Idnt.make fdef.name) :: fdef.args) Term.pr fdef.body else Format.fprintf ppf "@[<hov2>@[<hov2>%a@ | %a@] =@ %a@]" (List.pr_app Pattern.pr "@ ") (Pattern.V (Idnt.make fdef.name) :: fdef.args) Formula.pr fdef.guard Term.pr fdef.body let coeffs fdef = Formula.coeffs fdef.guard @ Term.coeffs fdef.body let arity_of fdef = fdef.args |> List.length
null
https://raw.githubusercontent.com/hopv/MoCHi/b0ac0d626d64b1e3c779d8e98cb232121cc3196a/fpat/fdef.ml
ocaml
* Function definitions * @require a.name = b.name => length a.args = length b.args a boolean expression that does not involve side-effects and function calls
open Util open Combinator type t = { name: string; @require length length > 0 body: Term.t } let make name args guard body = { name = name; args = args; guard = guard; body = body } let name_of f = f.name let args_of f = f.args let guard_of f = f.guard let body_of f = f.body let pr ppf fdef = if Formula.is_true fdef.guard then Format.fprintf ppf "@[<hov2>%a =@ %a@]" (List.pr_app Pattern.pr "@ ") (Pattern.V (Idnt.make fdef.name) :: fdef.args) Term.pr fdef.body else Format.fprintf ppf "@[<hov2>@[<hov2>%a@ | %a@] =@ %a@]" (List.pr_app Pattern.pr "@ ") (Pattern.V (Idnt.make fdef.name) :: fdef.args) Formula.pr fdef.guard Term.pr fdef.body let coeffs fdef = Formula.coeffs fdef.guard @ Term.coeffs fdef.body let arity_of fdef = fdef.args |> List.length
a7d14f6dbef6ca7020b7b35757f3f916cc308ffa60a12d6c0b25cebc37071b6c
mbj/stratosphere
InputFileLocationProperty.hs
module Stratosphere.Transfer.Workflow.InputFileLocationProperty ( module Exports, InputFileLocationProperty(..), mkInputFileLocationProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import {-# SOURCE #-} Stratosphere.Transfer.Workflow.EfsInputFileLocationProperty as Exports import {-# SOURCE #-} Stratosphere.Transfer.Workflow.S3InputFileLocationProperty as Exports import Stratosphere.ResourceProperties data InputFileLocationProperty = InputFileLocationProperty {efsFileLocation :: (Prelude.Maybe EfsInputFileLocationProperty), s3FileLocation :: (Prelude.Maybe S3InputFileLocationProperty)} mkInputFileLocationProperty :: InputFileLocationProperty mkInputFileLocationProperty = InputFileLocationProperty {efsFileLocation = Prelude.Nothing, s3FileLocation = Prelude.Nothing} instance ToResourceProperties InputFileLocationProperty where toResourceProperties InputFileLocationProperty {..} = ResourceProperties {awsType = "AWS::Transfer::Workflow.InputFileLocation", supportsTags = Prelude.False, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "EfsFileLocation" Prelude.<$> efsFileLocation, (JSON..=) "S3FileLocation" Prelude.<$> s3FileLocation])} instance JSON.ToJSON InputFileLocationProperty where toJSON InputFileLocationProperty {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "EfsFileLocation" Prelude.<$> efsFileLocation, (JSON..=) "S3FileLocation" Prelude.<$> s3FileLocation])) instance Property "EfsFileLocation" InputFileLocationProperty where type PropertyType "EfsFileLocation" InputFileLocationProperty = EfsInputFileLocationProperty set newValue InputFileLocationProperty {..} = InputFileLocationProperty {efsFileLocation = Prelude.pure newValue, ..} instance Property "S3FileLocation" InputFileLocationProperty where type PropertyType "S3FileLocation" InputFileLocationProperty = S3InputFileLocationProperty set newValue InputFileLocationProperty {..} = InputFileLocationProperty {s3FileLocation = Prelude.pure newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/transfer/gen/Stratosphere/Transfer/Workflow/InputFileLocationProperty.hs
haskell
# SOURCE # # SOURCE #
module Stratosphere.Transfer.Workflow.InputFileLocationProperty ( module Exports, InputFileLocationProperty(..), mkInputFileLocationProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties data InputFileLocationProperty = InputFileLocationProperty {efsFileLocation :: (Prelude.Maybe EfsInputFileLocationProperty), s3FileLocation :: (Prelude.Maybe S3InputFileLocationProperty)} mkInputFileLocationProperty :: InputFileLocationProperty mkInputFileLocationProperty = InputFileLocationProperty {efsFileLocation = Prelude.Nothing, s3FileLocation = Prelude.Nothing} instance ToResourceProperties InputFileLocationProperty where toResourceProperties InputFileLocationProperty {..} = ResourceProperties {awsType = "AWS::Transfer::Workflow.InputFileLocation", supportsTags = Prelude.False, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "EfsFileLocation" Prelude.<$> efsFileLocation, (JSON..=) "S3FileLocation" Prelude.<$> s3FileLocation])} instance JSON.ToJSON InputFileLocationProperty where toJSON InputFileLocationProperty {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "EfsFileLocation" Prelude.<$> efsFileLocation, (JSON..=) "S3FileLocation" Prelude.<$> s3FileLocation])) instance Property "EfsFileLocation" InputFileLocationProperty where type PropertyType "EfsFileLocation" InputFileLocationProperty = EfsInputFileLocationProperty set newValue InputFileLocationProperty {..} = InputFileLocationProperty {efsFileLocation = Prelude.pure newValue, ..} instance Property "S3FileLocation" InputFileLocationProperty where type PropertyType "S3FileLocation" InputFileLocationProperty = S3InputFileLocationProperty set newValue InputFileLocationProperty {..} = InputFileLocationProperty {s3FileLocation = Prelude.pure newValue, ..}
3adecfe007f42032d6c765f49aa02d68a84a28fe173919542acf6458d0f886f1
jesperes/aoc_erlang
aoc2019_day02.erl
-module(aoc2019_day02). -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2019, day = 2, name = "1202 Program Alarm", expected = {3654868, 7014}, has_input_file = true}. -type input_type() :: intcode:intcode_program(). -type result_type() :: integer(). -spec parse(Input :: binary()) -> input_type(). parse(Input) -> intcode:parse(Input). -spec solve1(Input :: input_type()) -> result_type(). solve1(Input) -> run_intcode(Input, 12, 2). -spec solve2(Input :: input_type()) -> result_type(). solve2(Input) -> [Result] = [100 * A + B || A <- lists:seq(0, 99), B <- lists:seq(0, 99), run_intcode(Input, A, B) =:= 19690720], Result. run_intcode(Prog, A, B) -> {ProgOut, _} = intcode:execute( maps:merge(Prog, #{1 => A, 2 => B})), maps:get(0, ProgOut).
null
https://raw.githubusercontent.com/jesperes/aoc_erlang/ec0786088fb9ab886ee57e17ea0149ba3e91810a/src/2019/aoc2019_day02.erl
erlang
-module(aoc2019_day02). -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2019, day = 2, name = "1202 Program Alarm", expected = {3654868, 7014}, has_input_file = true}. -type input_type() :: intcode:intcode_program(). -type result_type() :: integer(). -spec parse(Input :: binary()) -> input_type(). parse(Input) -> intcode:parse(Input). -spec solve1(Input :: input_type()) -> result_type(). solve1(Input) -> run_intcode(Input, 12, 2). -spec solve2(Input :: input_type()) -> result_type(). solve2(Input) -> [Result] = [100 * A + B || A <- lists:seq(0, 99), B <- lists:seq(0, 99), run_intcode(Input, A, B) =:= 19690720], Result. run_intcode(Prog, A, B) -> {ProgOut, _} = intcode:execute( maps:merge(Prog, #{1 => A, 2 => B})), maps:get(0, ProgOut).
7b1d995111147758c5e06d190e76f7f5214baca94f398e91261e1ec5ad8eba07
facebookarchive/duckling_old
numbers.clj
(; Context map {} "1" "um" "uma" (number 1) "2" "dois" "duas" (number 2) "3" "três" "tres" (number 3) "6" "seis" (number 6) "11" "onze" (number 11) "12" "doze" "uma dúzia" "uma duzia" (number 12) "14" "catorze" "quatorze" (number 14) "16" "dezesseis" "dezasseis" (number 16) "17" "dezessete" "dezassete" (number 17) "18" "dezoito" (number 18) "19" "dezenove" "dezanove" (number 19) "21" "vinte e um" (number 21) "23" "vinte e tres" "vinte e três" (number 23) "24" "vinte e quatro" "duas dúzias" "duas duzias" (number 24) "50" "cinquenta" "cinqüenta" "cincoenta" (number 50) "setenta" (number 70) "setenta e oito" (number 78) "oitenta" (number 80) "33" "trinta e três" "trinta e tres" (number 33) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "100" "cem" (number 100) "243" (number 243) "trezentos" (number 300) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "menos 1.200.000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "1 ponto cinco" "um ponto cinco" "1,5" (number 1.5) )
null
https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/pt/corpus/numbers.clj
clojure
Context map
{} "1" "um" "uma" (number 1) "2" "dois" "duas" (number 2) "3" "três" "tres" (number 3) "6" "seis" (number 6) "11" "onze" (number 11) "12" "doze" "uma dúzia" "uma duzia" (number 12) "14" "catorze" "quatorze" (number 14) "16" "dezesseis" "dezasseis" (number 16) "17" "dezessete" "dezassete" (number 17) "18" "dezoito" (number 18) "19" "dezenove" "dezanove" (number 19) "21" "vinte e um" (number 21) "23" "vinte e tres" "vinte e três" (number 23) "24" "vinte e quatro" "duas dúzias" "duas duzias" (number 24) "50" "cinquenta" "cinqüenta" "cincoenta" (number 50) "setenta" (number 70) "setenta e oito" (number 78) "oitenta" (number 80) "33" "trinta e três" "trinta e tres" (number 33) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "100" "cem" (number 100) "243" (number 243) "trezentos" (number 300) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "menos 1.200.000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "1 ponto cinco" "um ponto cinco" "1,5" (number 1.5) )
9ed9de34a9001468245b3219fd539a4ec6a0745431591da3dbf44a190ffe3a4e
AccelerateHS/accelerate-cuda
Paths_accelerate_cuda.hs
-- Helper script to shadow that automatically generated by cabal, but pointing -- to our local development directory. -- module Paths_accelerate_cuda where import Data.Version import System.Directory version :: Version version = Version {versionBranch = [2,0,0,0], versionTags = ["dev"]} getDataDir :: IO FilePath getDataDir = getCurrentDirectory
null
https://raw.githubusercontent.com/AccelerateHS/accelerate-cuda/6285f87859788628ce68d1ff76ce7b348f585f9e/utils/Paths_accelerate_cuda.hs
haskell
Helper script to shadow that automatically generated by cabal, but pointing to our local development directory.
module Paths_accelerate_cuda where import Data.Version import System.Directory version :: Version version = Version {versionBranch = [2,0,0,0], versionTags = ["dev"]} getDataDir :: IO FilePath getDataDir = getCurrentDirectory
69e474e77c25ded9215c61b1109be4bb811a54cf57a188c87c37521bdea078ac
Ptival/language-ocaml
ParseTree.hs
# LANGUAGE DeriveGeneric # module Language.OCaml.Definitions.Parsing.ParseTree ( Attribute, Attributes, Case (..), ClassDeclaration, ClassExpr (..), ClassField (..), ClassInfos (..), ClassSignature (..), ClassStructure (..), ClassType (..), ClassTypeDeclaration, ClassTypeField (..), Constant (..), ConstructorArguments (..), ConstructorDeclaration (..), CoreType (..), CoreTypeDesc (..), Expression (..), ExpressionDesc (..), Extension, ExtensionConstructor (..), ExtensionConstructorKind (..), IncludeDeclaration, IncludeInfos (..), LabelDeclaration (..), Longident (..), ModuleBinding (..), ModuleExpr (..), ModuleExprDesc (..), ModuleType (..), ModuleTypeDeclaration (..), ModuleTypeDesc (..), MutableFlag (..), ObjectField (..), OpenDescription (..), PackageType, Pattern (..), PatternDesc (..), Payload (..), PrivateFlag (..), RowField (..), Signature, SignatureItem (..), SignatureItemDesc (..), Structure, StructureItem (..), StructureItemDesc (..), TypeDeclaration (..), TypeException (..), TypeExtension (..), TypeKind (..), ValueBinding (..), ValueDescription (..), WithConstraint (..), none, ) where import GHC.Generics (Generic) import Language.OCaml.Definitions.Parsing.ASTTypes ( ArgLabel, ClosedFlag, DirectionFlag, Label, Loc, OverrideFlag, RecFlag, Variance, VirtualFlag, ) import Language.OCaml.Definitions.Parsing.Location ( Location, none, ) import Language.OCaml.Definitions.Parsing.Longident ( Longident (..), ) data Constant = PconstInteger String (Maybe Char) | PconstChar Char | PconstString String (Maybe String) | PconstFloat String (Maybe Char) deriving (Eq, Generic, Show) type Attribute = (Loc String, Payload) type Extension = (Loc String, Payload) type Attributes = [Attribute] data Payload = PStr Structure | PSig Signature | PTyp CoreType | PPat Pattern (Maybe Expression) deriving (Eq, Generic, Show) data CoreType = CoreType { ptypDesc :: CoreTypeDesc, ptypLoc :: Location, ptypAttributes :: Attributes } deriving (Eq, Generic, Show) data CoreTypeDesc = PtypAny | PtypVar String | PtypArrow ArgLabel CoreType CoreType | PtypTuple [CoreType] | PtypConstr (Loc Longident) [CoreType] | PtypObject [ObjectField] ClosedFlag | PtypClass (Loc Longident) [CoreType] | PtypAlias CoreType String | PtypVariant [RowField] ClosedFlag (Maybe [Label]) | PtypPoly [Loc String] CoreType | PtypPackage PackageType | PtypExtension Extension deriving (Eq, Generic, Show) data ConstructorArguments = PcstrTuple [CoreType] | PcstrRecord [LabelDeclaration] deriving (Eq, Generic, Show) data PrivateFlag = Private | Public deriving (Eq, Generic, Show) data TypeDeclaration = TypeDeclaration { ptypeName :: Loc String, ptypeParams :: [(CoreType, Variance)], ptypeCstrs :: [(CoreType, CoreType, Location)], ptypeKind :: TypeKind, ptypePrivate :: PrivateFlag, ptypeManifest :: Maybe CoreType, ptypeAttributes :: Attributes, ptypeLoc :: Location } deriving (Eq, Generic, Show) data TypeKind = PtypeAbstract | PtypeVariant [ConstructorDeclaration] | PtypeRecord [LabelDeclaration] | PtypeOpen deriving (Eq, Generic, Show) data LabelDeclaration = LabelDeclaration { pldName :: Loc String, pldMutable :: MutableFlag, pldType :: CoreType, pldLoc :: Location, pldAttributes :: Attributes } deriving (Eq, Generic, Show) data ConstructorDeclaration = ConstructorDeclaration { pcdName :: Loc String, pcdArgs :: ConstructorArguments, pcdRes :: Maybe CoreType, pcdLoc :: Location, pcdAttributes :: Attributes } deriving (Eq, Generic, Show) data MutableFlag = Immutable | Mutable deriving (Eq, Generic, Show) type Structure = [StructureItem] data StructureItem = StructureItem { pstrDesc :: StructureItemDesc, pstrLoc :: Location } deriving (Eq, Generic, Show) data StructureItemDesc = PstrEval Expression Attributes | PstrValue RecFlag [ValueBinding] | PstrPrimitive ValueDescription | PstrType RecFlag [TypeDeclaration] | PstrTypExt TypeExtension | PstrException ExtensionConstructor | PstrModule ModuleBinding | PstrRecModule [ModuleBinding] | PstrModType ModuleTypeDeclaration | PstrOpen OpenDescription | PstrClass [ClassDeclaration] | PstrClassType [ClassTypeDeclaration] | PstrInclude IncludeDeclaration | PstrAttribute Attribute | PstrExtension Extension Attributes deriving (Eq, Generic, Show) data Expression = Expression { pexpDesc :: ExpressionDesc, pexpLoc :: Location, pexpAttributes :: Attributes } deriving (Eq, Generic, Show) data ExpressionDesc = PexpIdent (Loc Longident) | PexpConstant Constant | PexpLet RecFlag [ValueBinding] Expression | PexpFunction [Case] | PexpFun ArgLabel (Maybe Expression) Pattern Expression | PexpApply Expression [(ArgLabel, Expression)] | PexpMatch Expression [Case] | PexpTry Expression [Case] | PexpTuple [Expression] | PexpConstruct (Loc Longident) (Maybe Expression) | PexpVariant Label (Maybe Expression) | PexpRecord [(Loc Longident, Expression)] (Maybe Expression) | PexpField Expression (Loc Longident) | PexpSetField Expression (Loc Longident) Expression | PexpArray [Expression] | PexpIfThenElse Expression Expression (Maybe Expression) | PexpSequence Expression Expression | PexpWhile Expression Expression | PexpFor Pattern Expression Expression DirectionFlag Expression | PexpConstraint Expression CoreType | PexpCoerce Expression (Maybe CoreType) CoreType | PexpSend Expression (Loc Label) | PexpNew (Loc Longident) | PexpSetInstVar (Loc Label) Expression | PexpOverride [(Loc Label, Expression)] | PexpLetModule (Loc String) ModuleExpr Expression | PexpLetException ExtensionConstructor Expression | PexpAssert Expression | PexpLazy Expression | PexpPoly Expression (Maybe CoreType) | PexpObject ClassStructure | PexpNewType (Loc String) Expression | PexpPack ModuleExpr | PexpOpen OverrideFlag (Loc Longident) Expression | PexpExtension Extension | PexpUnreachable deriving (Eq, Generic, Show) type Signature = [SignatureItem] data SignatureItem = SignatureItem { psigDesc :: SignatureItemDesc, psigLoc :: Location } deriving (Eq, Generic, Show) data SignatureItemDesc = PsigValue ValueDescription | -- | PsigType Asttypes.recFlag * typeDeclaration list -- | PsigTypext type_extension -- | Psig_exception extensionConstructor | PsigModule moduleDeclaration | PsigRecmodule moduleDeclaration list | PsigModtype moduleTypeDeclaration | -- | PsigInclude includeDescription | PsigClass classDescription list -- | PsigClassType classTypeDeclaration list PsigAttribute Attribute | PsigExtension Extension Attributes deriving (Eq, Generic, Show) data ValueDescription = ValueDescription { pvalName :: Loc String, pvalType :: CoreType, pvalPrim :: [String], pvalAttributes :: Attributes, pvalLoc :: Location } deriving (Eq, Generic, Show) data Pattern = Pattern { ppatDesc :: PatternDesc, ppatLoc :: Location, ppatAttributes :: Attributes } deriving (Eq, Generic, Show) data PatternDesc = PpatAny | PpatVar (Loc String) | PpatAlias Pattern (Loc String) | PpatConstant Constant | PpatInterval Constant Constant | PpatTuple [Pattern] | PpatConstruct (Loc Longident) (Maybe Pattern) | PpatVariant Label (Maybe Pattern) | PpatRecord [(Loc Longident, Pattern)] ClosedFlag | PpatArray [Pattern] | PpatOr Pattern Pattern | PpatConstraint Pattern CoreType | PpatType (Loc Longident) | PpatLazy Pattern | PpatUnpack (Loc String) | PpatException Pattern | PpatExtension Extension | PpatOpen (Loc Longident) Pattern deriving (Eq, Generic, Show) data OpenDescription = OpenDescription { popenLid :: Loc Longident, popenOverride :: OverrideFlag, popenLoc :: Location, popenAttributes :: Attributes } deriving (Eq, Generic, Show) data ModuleExpr = ModuleExpr { pmodDesc :: ModuleExprDesc, pmodLoc :: Location, pmodAttributes :: Attributes } deriving (Eq, Generic, Show) data ModuleExprDesc = PmodIdent (Loc Longident) | PmodStructure Structure | PmodFunctor (Loc String) (Maybe ModuleType) ModuleExpr | PmodApply ModuleExpr ModuleExpr | PmodConstraint ModuleExpr ModuleType | PmodUnpack Expression | PmodExtension Extension deriving (Eq, Generic, Show) data ModuleBinding = ModuleBinding { pmbName :: Loc String, pmbExpr :: ModuleExpr, pmbAttributes :: Attributes, pmbLoc :: Location } deriving (Eq, Generic, Show) data ValueBinding = ValueBinding { pvbPat :: Pattern, pvbExpr :: Expression, pvbAttributes :: Attributes, pvbLoc :: Location } deriving (Eq, Generic, Show) data Case = Case { pcLHS :: Pattern, pcGuard :: Maybe Expression, pcRHS :: Expression } deriving (Eq, Generic, Show) data ExtensionConstructor = ExtensionConstructor { pextName :: Loc String, pextKind :: ExtensionConstructorKind, pextLoc :: Location, pextAttributes :: Attributes -- C of ... [@id1] [@id2] } deriving (Eq, Generic, Show) data ExtensionConstructorKind = PextDecl ConstructorArguments (Maybe CoreType) | PextRebind (Loc Longident) deriving (Eq, Generic, Show) data TypeExtension = TypeExtension { ptyextPath :: Loc Longident, ptyextParams :: [(CoreType, Variance)], ptyextConstructors :: [ExtensionConstructor], ptyextPrivate :: PrivateFlag, ptyextAttributes :: Attributes } deriving (Eq, Generic, Show) data TypeException = TypeException { ptyexnConstructor :: ExtensionConstructor, ptyexnAttributes :: Attributes } deriving (Eq, Generic, Show) data RowField = Rtag (Loc Label) Attributes Bool [CoreType] | Rinherit CoreType deriving (Eq, Generic, Show) data ClassStructure = ClassStructure { pcstrSelf :: Pattern, pcstrFields :: [ClassField] } deriving (Eq, Generic, Show) data ClassField = ClassField { pcfDesc :: ClassFieldDesc, pcfLoc :: Location, pcfAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassFieldDesc = PcfInherit OverrideFlag ClassExpr (Maybe (Loc String)) | PcfVal (Loc Label) MutableFlag ClassFieldKind | PcfMethod (Loc Label) PrivateFlag ClassFieldKind | PcfConstraint CoreType CoreType | PcfInitializer Expression | PcfAttribute Attribute | PcfExtension Extension deriving (Eq, Generic, Show) data ClassExpr = ClassExpr { pclDesc :: ClassExprDesc, pclLoc :: Location, pclAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassExprDesc = PclConstr (Loc Longident) [CoreType] | PclStructure ClassStructure | PclFun ArgLabel (Maybe Expression) Pattern ClassExpr | PclApply ClassExpr [(ArgLabel, Expression)] | PclLet RecFlag [ValueBinding] ClassExpr | PclConstraint ClassExpr ClassType | PclExtension Extension | PclOpen OverrideFlag (Loc Longident) ClassExpr deriving (Eq, Generic, Show) data ClassType = ClassType { pctyDesc :: ClassTypeDesc, pctyLoc :: Location, pctyAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassTypeDesc = PctyConstr (Loc Longident) [CoreType] | PctySignature ClassSignature | PctyArrow ArgLabel CoreType ClassType | PctyExtension Extension | PctyOpen OverrideFlag (Loc Longident) ClassType deriving (Eq, Generic, Show) data ClassSignature = ClassSignature { pcsigSelf :: CoreType, pcsigFields :: [ClassTypeField] } deriving (Eq, Generic, Show) data ClassTypeField = ClassTypeField { pctfDesc :: ClassTypeFieldDesc, pctfLoc :: Location, pctfAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassTypeFieldDesc = PctfInherit ClassType | PctfVal (Loc Label) MutableFlag VirtualFlag CoreType | PtfMethod (Loc Label) PrivateFlag VirtualFlag CoreType | PctfConstraint CoreType CoreType | PctfAttribute Attribute | PctfExtension Extension deriving (Eq, Generic, Show) data ClassFieldKind = CfkVirtual CoreType | CfkConcrete OverrideFlag Expression deriving (Eq, Generic, Show) data ObjectField = Otag (Loc Label) Attributes CoreType | Oinherit CoreType deriving (Eq, Generic, Show) data ModuleType = ModuleType { pmtyDesc :: ModuleTypeDesc, pmtyLoc :: Location, pmtyAttributes :: Attributes } deriving (Eq, Generic, Show) data ModuleTypeDesc = PmtyIdent (Loc Longident) | PmtySignature Signature | PmtyFunctor (Loc String) (Maybe ModuleType) ModuleType | PmtyWith ModuleType [WithConstraint] | PmtyTypeOf ModuleExpr | PmtyExtension Extension | PmtyAlias (Loc Longident) deriving (Eq, Generic, Show) data ModuleTypeDeclaration = ModuleTypeDeclaration { pmtdName :: Loc String, pmtdType :: Maybe ModuleType, pmtdAttributes :: Attributes, pmtdLoc :: Location } deriving (Eq, Generic, Show) data WithConstraint = PwithType (Loc Longident) TypeDeclaration | PwithModule (Loc Longident) (Loc Longident) | PwithTypeSubst (Loc Longident) TypeDeclaration | PwithModSubst (Loc Longident) (Loc Longident) deriving (Eq, Generic, Show) type PackageType = (Loc Longident, [(Loc Longident, CoreType)]) data ClassInfos a = ClassInfos { pciVirt :: VirtualFlag, pciParams :: [(CoreType, Variance)], pciName :: Loc String, pciExpr :: a, pciLoc :: Location } deriving (Eq, Generic, Show) type ClassDeclaration = ClassInfos ClassExpr type ClassTypeDeclaration = ClassInfos ClassType data IncludeInfos a = IncludeInfos { pinclMod :: a, pinclLoc :: Location, pinclAttributes :: Attributes } deriving (Eq, Generic, Show) type IncludeDeclaration = IncludeInfos ModuleExpr
null
https://raw.githubusercontent.com/Ptival/language-ocaml/7b07fd3cc466bb2ad2cac4bfe3099505cb63a4f4/lib/Language/OCaml/Definitions/Parsing/ParseTree.hs
haskell
| PsigType Asttypes.recFlag * typeDeclaration list | PsigTypext type_extension | Psig_exception extensionConstructor | PsigInclude includeDescription | PsigClassType classTypeDeclaration list C of ... [@id1] [@id2]
# LANGUAGE DeriveGeneric # module Language.OCaml.Definitions.Parsing.ParseTree ( Attribute, Attributes, Case (..), ClassDeclaration, ClassExpr (..), ClassField (..), ClassInfos (..), ClassSignature (..), ClassStructure (..), ClassType (..), ClassTypeDeclaration, ClassTypeField (..), Constant (..), ConstructorArguments (..), ConstructorDeclaration (..), CoreType (..), CoreTypeDesc (..), Expression (..), ExpressionDesc (..), Extension, ExtensionConstructor (..), ExtensionConstructorKind (..), IncludeDeclaration, IncludeInfos (..), LabelDeclaration (..), Longident (..), ModuleBinding (..), ModuleExpr (..), ModuleExprDesc (..), ModuleType (..), ModuleTypeDeclaration (..), ModuleTypeDesc (..), MutableFlag (..), ObjectField (..), OpenDescription (..), PackageType, Pattern (..), PatternDesc (..), Payload (..), PrivateFlag (..), RowField (..), Signature, SignatureItem (..), SignatureItemDesc (..), Structure, StructureItem (..), StructureItemDesc (..), TypeDeclaration (..), TypeException (..), TypeExtension (..), TypeKind (..), ValueBinding (..), ValueDescription (..), WithConstraint (..), none, ) where import GHC.Generics (Generic) import Language.OCaml.Definitions.Parsing.ASTTypes ( ArgLabel, ClosedFlag, DirectionFlag, Label, Loc, OverrideFlag, RecFlag, Variance, VirtualFlag, ) import Language.OCaml.Definitions.Parsing.Location ( Location, none, ) import Language.OCaml.Definitions.Parsing.Longident ( Longident (..), ) data Constant = PconstInteger String (Maybe Char) | PconstChar Char | PconstString String (Maybe String) | PconstFloat String (Maybe Char) deriving (Eq, Generic, Show) type Attribute = (Loc String, Payload) type Extension = (Loc String, Payload) type Attributes = [Attribute] data Payload = PStr Structure | PSig Signature | PTyp CoreType | PPat Pattern (Maybe Expression) deriving (Eq, Generic, Show) data CoreType = CoreType { ptypDesc :: CoreTypeDesc, ptypLoc :: Location, ptypAttributes :: Attributes } deriving (Eq, Generic, Show) data CoreTypeDesc = PtypAny | PtypVar String | PtypArrow ArgLabel CoreType CoreType | PtypTuple [CoreType] | PtypConstr (Loc Longident) [CoreType] | PtypObject [ObjectField] ClosedFlag | PtypClass (Loc Longident) [CoreType] | PtypAlias CoreType String | PtypVariant [RowField] ClosedFlag (Maybe [Label]) | PtypPoly [Loc String] CoreType | PtypPackage PackageType | PtypExtension Extension deriving (Eq, Generic, Show) data ConstructorArguments = PcstrTuple [CoreType] | PcstrRecord [LabelDeclaration] deriving (Eq, Generic, Show) data PrivateFlag = Private | Public deriving (Eq, Generic, Show) data TypeDeclaration = TypeDeclaration { ptypeName :: Loc String, ptypeParams :: [(CoreType, Variance)], ptypeCstrs :: [(CoreType, CoreType, Location)], ptypeKind :: TypeKind, ptypePrivate :: PrivateFlag, ptypeManifest :: Maybe CoreType, ptypeAttributes :: Attributes, ptypeLoc :: Location } deriving (Eq, Generic, Show) data TypeKind = PtypeAbstract | PtypeVariant [ConstructorDeclaration] | PtypeRecord [LabelDeclaration] | PtypeOpen deriving (Eq, Generic, Show) data LabelDeclaration = LabelDeclaration { pldName :: Loc String, pldMutable :: MutableFlag, pldType :: CoreType, pldLoc :: Location, pldAttributes :: Attributes } deriving (Eq, Generic, Show) data ConstructorDeclaration = ConstructorDeclaration { pcdName :: Loc String, pcdArgs :: ConstructorArguments, pcdRes :: Maybe CoreType, pcdLoc :: Location, pcdAttributes :: Attributes } deriving (Eq, Generic, Show) data MutableFlag = Immutable | Mutable deriving (Eq, Generic, Show) type Structure = [StructureItem] data StructureItem = StructureItem { pstrDesc :: StructureItemDesc, pstrLoc :: Location } deriving (Eq, Generic, Show) data StructureItemDesc = PstrEval Expression Attributes | PstrValue RecFlag [ValueBinding] | PstrPrimitive ValueDescription | PstrType RecFlag [TypeDeclaration] | PstrTypExt TypeExtension | PstrException ExtensionConstructor | PstrModule ModuleBinding | PstrRecModule [ModuleBinding] | PstrModType ModuleTypeDeclaration | PstrOpen OpenDescription | PstrClass [ClassDeclaration] | PstrClassType [ClassTypeDeclaration] | PstrInclude IncludeDeclaration | PstrAttribute Attribute | PstrExtension Extension Attributes deriving (Eq, Generic, Show) data Expression = Expression { pexpDesc :: ExpressionDesc, pexpLoc :: Location, pexpAttributes :: Attributes } deriving (Eq, Generic, Show) data ExpressionDesc = PexpIdent (Loc Longident) | PexpConstant Constant | PexpLet RecFlag [ValueBinding] Expression | PexpFunction [Case] | PexpFun ArgLabel (Maybe Expression) Pattern Expression | PexpApply Expression [(ArgLabel, Expression)] | PexpMatch Expression [Case] | PexpTry Expression [Case] | PexpTuple [Expression] | PexpConstruct (Loc Longident) (Maybe Expression) | PexpVariant Label (Maybe Expression) | PexpRecord [(Loc Longident, Expression)] (Maybe Expression) | PexpField Expression (Loc Longident) | PexpSetField Expression (Loc Longident) Expression | PexpArray [Expression] | PexpIfThenElse Expression Expression (Maybe Expression) | PexpSequence Expression Expression | PexpWhile Expression Expression | PexpFor Pattern Expression Expression DirectionFlag Expression | PexpConstraint Expression CoreType | PexpCoerce Expression (Maybe CoreType) CoreType | PexpSend Expression (Loc Label) | PexpNew (Loc Longident) | PexpSetInstVar (Loc Label) Expression | PexpOverride [(Loc Label, Expression)] | PexpLetModule (Loc String) ModuleExpr Expression | PexpLetException ExtensionConstructor Expression | PexpAssert Expression | PexpLazy Expression | PexpPoly Expression (Maybe CoreType) | PexpObject ClassStructure | PexpNewType (Loc String) Expression | PexpPack ModuleExpr | PexpOpen OverrideFlag (Loc Longident) Expression | PexpExtension Extension | PexpUnreachable deriving (Eq, Generic, Show) type Signature = [SignatureItem] data SignatureItem = SignatureItem { psigDesc :: SignatureItemDesc, psigLoc :: Location } deriving (Eq, Generic, Show) data SignatureItemDesc = PsigValue ValueDescription | PsigModule moduleDeclaration | PsigRecmodule moduleDeclaration list | PsigModtype moduleTypeDeclaration | | PsigClass classDescription list PsigAttribute Attribute | PsigExtension Extension Attributes deriving (Eq, Generic, Show) data ValueDescription = ValueDescription { pvalName :: Loc String, pvalType :: CoreType, pvalPrim :: [String], pvalAttributes :: Attributes, pvalLoc :: Location } deriving (Eq, Generic, Show) data Pattern = Pattern { ppatDesc :: PatternDesc, ppatLoc :: Location, ppatAttributes :: Attributes } deriving (Eq, Generic, Show) data PatternDesc = PpatAny | PpatVar (Loc String) | PpatAlias Pattern (Loc String) | PpatConstant Constant | PpatInterval Constant Constant | PpatTuple [Pattern] | PpatConstruct (Loc Longident) (Maybe Pattern) | PpatVariant Label (Maybe Pattern) | PpatRecord [(Loc Longident, Pattern)] ClosedFlag | PpatArray [Pattern] | PpatOr Pattern Pattern | PpatConstraint Pattern CoreType | PpatType (Loc Longident) | PpatLazy Pattern | PpatUnpack (Loc String) | PpatException Pattern | PpatExtension Extension | PpatOpen (Loc Longident) Pattern deriving (Eq, Generic, Show) data OpenDescription = OpenDescription { popenLid :: Loc Longident, popenOverride :: OverrideFlag, popenLoc :: Location, popenAttributes :: Attributes } deriving (Eq, Generic, Show) data ModuleExpr = ModuleExpr { pmodDesc :: ModuleExprDesc, pmodLoc :: Location, pmodAttributes :: Attributes } deriving (Eq, Generic, Show) data ModuleExprDesc = PmodIdent (Loc Longident) | PmodStructure Structure | PmodFunctor (Loc String) (Maybe ModuleType) ModuleExpr | PmodApply ModuleExpr ModuleExpr | PmodConstraint ModuleExpr ModuleType | PmodUnpack Expression | PmodExtension Extension deriving (Eq, Generic, Show) data ModuleBinding = ModuleBinding { pmbName :: Loc String, pmbExpr :: ModuleExpr, pmbAttributes :: Attributes, pmbLoc :: Location } deriving (Eq, Generic, Show) data ValueBinding = ValueBinding { pvbPat :: Pattern, pvbExpr :: Expression, pvbAttributes :: Attributes, pvbLoc :: Location } deriving (Eq, Generic, Show) data Case = Case { pcLHS :: Pattern, pcGuard :: Maybe Expression, pcRHS :: Expression } deriving (Eq, Generic, Show) data ExtensionConstructor = ExtensionConstructor { pextName :: Loc String, pextKind :: ExtensionConstructorKind, pextLoc :: Location, } deriving (Eq, Generic, Show) data ExtensionConstructorKind = PextDecl ConstructorArguments (Maybe CoreType) | PextRebind (Loc Longident) deriving (Eq, Generic, Show) data TypeExtension = TypeExtension { ptyextPath :: Loc Longident, ptyextParams :: [(CoreType, Variance)], ptyextConstructors :: [ExtensionConstructor], ptyextPrivate :: PrivateFlag, ptyextAttributes :: Attributes } deriving (Eq, Generic, Show) data TypeException = TypeException { ptyexnConstructor :: ExtensionConstructor, ptyexnAttributes :: Attributes } deriving (Eq, Generic, Show) data RowField = Rtag (Loc Label) Attributes Bool [CoreType] | Rinherit CoreType deriving (Eq, Generic, Show) data ClassStructure = ClassStructure { pcstrSelf :: Pattern, pcstrFields :: [ClassField] } deriving (Eq, Generic, Show) data ClassField = ClassField { pcfDesc :: ClassFieldDesc, pcfLoc :: Location, pcfAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassFieldDesc = PcfInherit OverrideFlag ClassExpr (Maybe (Loc String)) | PcfVal (Loc Label) MutableFlag ClassFieldKind | PcfMethod (Loc Label) PrivateFlag ClassFieldKind | PcfConstraint CoreType CoreType | PcfInitializer Expression | PcfAttribute Attribute | PcfExtension Extension deriving (Eq, Generic, Show) data ClassExpr = ClassExpr { pclDesc :: ClassExprDesc, pclLoc :: Location, pclAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassExprDesc = PclConstr (Loc Longident) [CoreType] | PclStructure ClassStructure | PclFun ArgLabel (Maybe Expression) Pattern ClassExpr | PclApply ClassExpr [(ArgLabel, Expression)] | PclLet RecFlag [ValueBinding] ClassExpr | PclConstraint ClassExpr ClassType | PclExtension Extension | PclOpen OverrideFlag (Loc Longident) ClassExpr deriving (Eq, Generic, Show) data ClassType = ClassType { pctyDesc :: ClassTypeDesc, pctyLoc :: Location, pctyAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassTypeDesc = PctyConstr (Loc Longident) [CoreType] | PctySignature ClassSignature | PctyArrow ArgLabel CoreType ClassType | PctyExtension Extension | PctyOpen OverrideFlag (Loc Longident) ClassType deriving (Eq, Generic, Show) data ClassSignature = ClassSignature { pcsigSelf :: CoreType, pcsigFields :: [ClassTypeField] } deriving (Eq, Generic, Show) data ClassTypeField = ClassTypeField { pctfDesc :: ClassTypeFieldDesc, pctfLoc :: Location, pctfAttributes :: Attributes } deriving (Eq, Generic, Show) data ClassTypeFieldDesc = PctfInherit ClassType | PctfVal (Loc Label) MutableFlag VirtualFlag CoreType | PtfMethod (Loc Label) PrivateFlag VirtualFlag CoreType | PctfConstraint CoreType CoreType | PctfAttribute Attribute | PctfExtension Extension deriving (Eq, Generic, Show) data ClassFieldKind = CfkVirtual CoreType | CfkConcrete OverrideFlag Expression deriving (Eq, Generic, Show) data ObjectField = Otag (Loc Label) Attributes CoreType | Oinherit CoreType deriving (Eq, Generic, Show) data ModuleType = ModuleType { pmtyDesc :: ModuleTypeDesc, pmtyLoc :: Location, pmtyAttributes :: Attributes } deriving (Eq, Generic, Show) data ModuleTypeDesc = PmtyIdent (Loc Longident) | PmtySignature Signature | PmtyFunctor (Loc String) (Maybe ModuleType) ModuleType | PmtyWith ModuleType [WithConstraint] | PmtyTypeOf ModuleExpr | PmtyExtension Extension | PmtyAlias (Loc Longident) deriving (Eq, Generic, Show) data ModuleTypeDeclaration = ModuleTypeDeclaration { pmtdName :: Loc String, pmtdType :: Maybe ModuleType, pmtdAttributes :: Attributes, pmtdLoc :: Location } deriving (Eq, Generic, Show) data WithConstraint = PwithType (Loc Longident) TypeDeclaration | PwithModule (Loc Longident) (Loc Longident) | PwithTypeSubst (Loc Longident) TypeDeclaration | PwithModSubst (Loc Longident) (Loc Longident) deriving (Eq, Generic, Show) type PackageType = (Loc Longident, [(Loc Longident, CoreType)]) data ClassInfos a = ClassInfos { pciVirt :: VirtualFlag, pciParams :: [(CoreType, Variance)], pciName :: Loc String, pciExpr :: a, pciLoc :: Location } deriving (Eq, Generic, Show) type ClassDeclaration = ClassInfos ClassExpr type ClassTypeDeclaration = ClassInfos ClassType data IncludeInfos a = IncludeInfos { pinclMod :: a, pinclLoc :: Location, pinclAttributes :: Attributes } deriving (Eq, Generic, Show) type IncludeDeclaration = IncludeInfos ModuleExpr
27815fd48b2fd3cc827438231f22b9252bb18c824cc21ebeadd346335ed825eb
processone/ejabberd
ejabberd_sql_pt.erl
%%%------------------------------------------------------------------- %%% File : ejabberd_sql_pt.erl Author : < > Description : Parse transform for SQL queries Created : 20 Jan 2016 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%---------------------------------------------------------------------- -module(ejabberd_sql_pt). %% API -export([parse_transform/2, format_error/1]). -include("ejabberd_sql.hrl"). -record(state, {loc, 'query' = [], params = [], param_pos = 0, args = [], res = [], res_vars = [], res_pos = 0, server_host_used = false, used_vars = [], use_new_schema, need_timestamp_pass = false, need_array_pass = false}). -define(QUERY_RECORD, "sql_query"). -define(ESCAPE_RECORD, "sql_escape"). -define(ESCAPE_VAR, "__SQLEscape"). -define(MOD, sql__module_). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- %% Function: %% Description: %%-------------------------------------------------------------------- parse_transform(AST, _Options) -> put(warnings, []), NewAST = top_transform(AST), NewAST ++ get(warnings). format_error(no_server_host) -> "server_host field is not used". %%==================================================================== Internal functions %%==================================================================== transform(Form) -> case erl_syntax:type(Form) of application -> case erl_syntax_lib:analyze_application(Form) of {?SQL_MARK, 1} -> case erl_syntax:application_arguments(Form) of [Arg] -> case erl_syntax:type(Arg) of string -> transform_sql(Arg); _ -> throw({error, erl_syntax:get_pos(Form), "?SQL argument must be " "a constant string"}) end; _ -> throw({error, erl_syntax:get_pos(Form), "wrong number of ?SQL args"}) end; {?SQL_UPSERT_MARK, 2} -> case erl_syntax:application_arguments(Form) of [TableArg, FieldsArg] -> case {erl_syntax:type(TableArg), erl_syntax:is_proper_list(FieldsArg)}of {string, true} -> transform_upsert(Form, TableArg, FieldsArg); _ -> throw({error, erl_syntax:get_pos(Form), "?SQL_UPSERT arguments must be " "a constant string and a list"}) end; _ -> throw({error, erl_syntax:get_pos(Form), "wrong number of ?SQL_UPSERT args"}) end; {?SQL_INSERT_MARK, 2} -> case erl_syntax:application_arguments(Form) of [TableArg, FieldsArg] -> case {erl_syntax:type(TableArg), erl_syntax:is_proper_list(FieldsArg)}of {string, true} -> transform_insert(Form, TableArg, FieldsArg); _ -> throw({error, erl_syntax:get_pos(Form), "?SQL_INSERT arguments must be " "a constant string and a list"}) end; _ -> throw({error, erl_syntax:get_pos(Form), "wrong number of ?SQL_INSERT args"}) end; _ -> Form end; attribute -> case erl_syntax:atom_value(erl_syntax:attribute_name(Form)) of module -> case erl_syntax:attribute_arguments(Form) of [M | _] -> Module = erl_syntax:atom_value(M), put(?MOD, Module), Form; _ -> Form end; _ -> Form end; _ -> Form end. top_transform(Forms) when is_list(Forms) -> lists:map( fun(Form) -> try Form2 = erl_syntax_lib:map(fun transform/1, Form), Form3 = erl_syntax:revert(Form2), Form3 catch throw:{error, Line, Error} -> {error, {Line, erl_parse, Error}} end end, Forms). transform_sql(Arg) -> S = erl_syntax:string_value(Arg), Pos = erl_syntax:get_pos(Arg), ParseRes = parse(S, Pos, true), ParseResOld = parse(S, Pos, false), case ParseRes#state.server_host_used of {true, _SHVar} -> ok; false -> add_warning( Pos, no_server_host), [] end, case {ParseRes#state.need_array_pass, ParseRes#state.need_timestamp_pass} of {true, _} -> {PR1, PR2} = perform_array_pass(ParseRes), {PRO1, PRO2} = perform_array_pass(ParseResOld), set_pos(make_schema_check( erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(PR2, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(PR1)])]), erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(PRO2, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(PRO1)])])), Pos); {_, true} -> set_pos(make_schema_check( erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(ParseRes, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(ParseRes)])]), erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(ParseResOld, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(ParseResOld)])])), Pos); _ -> set_pos( make_schema_check( make_sql_query(ParseRes), make_sql_query(ParseResOld) ), Pos) end. transform_upsert(Form, TableArg, FieldsArg) -> Table = erl_syntax:string_value(TableArg), ParseRes = parse_upsert( erl_syntax:list_elements(FieldsArg)), Pos = erl_syntax:get_pos(Form), case lists:keymember( "server_host", 1, ParseRes) of true -> ok; false -> add_warning(Pos, no_server_host) end, ParseResOld = filter_upsert_sh(Table, ParseRes), set_pos( make_schema_check( make_sql_upsert(Table, ParseRes, Pos), make_sql_upsert(Table, ParseResOld, Pos) ), Pos). transform_insert(Form, TableArg, FieldsArg) -> Table = erl_syntax:string_value(TableArg), ParseRes = parse_insert( erl_syntax:list_elements(FieldsArg)), Pos = erl_syntax:get_pos(Form), case lists:keymember( "server_host", 1, ParseRes) of true -> ok; false -> add_warning(Pos, no_server_host) end, ParseResOld = filter_upsert_sh(Table, ParseRes), set_pos( make_schema_check( make_sql_insert(Table, ParseRes), make_sql_insert(Table, ParseResOld) ), Pos). parse(S, Loc, UseNewSchema) -> parse1(S, [], #state{loc = Loc, use_new_schema = UseNewSchema}). parse(S, ParamPos, Loc, UseNewSchema) -> parse1(S, [], #state{loc = Loc, param_pos = ParamPos, use_new_schema = UseNewSchema}). parse1([], Acc, State) -> State1 = append_string(lists:reverse(Acc), State), State1#state{'query' = lists:reverse(State1#state.'query'), params = lists:reverse(State1#state.params), args = lists:reverse(State1#state.args), res = lists:reverse(State1#state.res), res_vars = lists:reverse(State1#state.res_vars) }; parse1([$@, $( | S], Acc, State) -> State1 = append_string(lists:reverse(Acc), State), {Name, Type, S1, State2} = parse_name(S, false, State1), Var = "__V" ++ integer_to_list(State2#state.res_pos), EVar = erl_syntax:variable(Var), Convert = case Type of integer -> erl_syntax:application( erl_syntax:atom(binary_to_integer), [EVar]); string -> EVar; timestamp -> EVar; boolean -> erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(to_bool), [EVar]) end, State3 = append_string(Name, State2), State4 = State3#state{res_pos = State3#state.res_pos + 1, res = [Convert | State3#state.res], res_vars = [EVar | State3#state.res_vars]}, parse1(S1, [], State4); , $ ( | S ] , Acc , State ) - > State1 = append_string(lists:reverse(Acc), State), {Name, Type, S1, State2} = parse_name(S, true, State1), Var = State2#state.param_pos, State4 = case Type of host -> State3 = State2#state{server_host_used = {true, Name}, used_vars = [Name | State2#state.used_vars]}, case State#state.use_new_schema of true -> Convert = erl_syntax:application( erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(string)), [erl_syntax:variable(Name)]), State3#state{'query' = [{var, Var, Type}, {str, "server_host="} | State3#state.'query'], args = [Convert | State3#state.args], params = [Var | State3#state.params], param_pos = State3#state.param_pos + 1}; false -> append_string("0=0", State3) end; {list, InternalType} -> Convert = erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(to_list), [erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(InternalType)), erl_syntax:variable(Name)]), IT2 = case InternalType of string -> in_array_string; _ -> InternalType end, ConvertArr = erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(to_array), [erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(IT2)), erl_syntax:variable(Name)]), State2#state{'query' = [[{var, Var, Type}] | State2#state.'query'], need_array_pass = true, args = [[Convert, ConvertArr] | State2#state.args], params = [Var | State2#state.params], param_pos = State2#state.param_pos + 1, used_vars = [Name | State2#state.used_vars]}; _ -> {TS, Type2} = case Type of timestamp -> {true, string}; Other -> {State2#state.need_timestamp_pass, Other} end, Convert = erl_syntax:application( erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(Type2)), [erl_syntax:variable(Name)]), State2#state{'query' = [{var, Var, Type} | State2#state.'query'], need_timestamp_pass = TS, args = [Convert | State2#state.args], params = [Var | State2#state.params], param_pos = State2#state.param_pos + 1, used_vars = [Name | State2#state.used_vars]} end, parse1(S1, [], State4); parse1("%ESCAPE" ++ S, Acc, State) -> State1 = append_string(lists:reverse(Acc), State), Convert = erl_syntax:application( erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(like_escape)), []), Var = State1#state.param_pos, State2 = State1#state{'query' = [{var, Var, string} | State1#state.'query'], args = [Convert | State1#state.args], params = [Var | State1#state.params], param_pos = State1#state.param_pos + 1}, parse1(S, [], State2); parse1([C | S], Acc, State) -> parse1(S, [C | Acc], State). append_string([], State) -> State; append_string(S, State) -> State#state{query = [{str, S} | State#state.query]}. parse_name(S, IsArg, State) -> parse_name(S, [], 0, IsArg, State). parse_name([], _Acc, _Depth, _IsArg, State) -> throw({error, State#state.loc, "expected ')', found end of string"}); parse_name([$), $l, T | S], Acc, 0, true, State) -> Type = case T of $d -> {list, integer}; $s -> {list, string}; $b -> {list, boolean}; _ -> throw({error, State#state.loc, ["unknown type specifier 'l", T, "'"]}) end, {lists:reverse(Acc), Type, S, State}; parse_name([$), $l, T | _], _Acc, 0, false, State) -> throw({error, State#state.loc, ["list type 'l", T, "' is not allowed for outputs"]}); parse_name([$), T | S], Acc, 0, IsArg, State) -> Type = case T of $d -> integer; $s -> string; $b -> boolean; $t -> timestamp; $H when IsArg -> host; _ -> throw({error, State#state.loc, ["unknown type specifier '", T, "'"]}) end, {lists:reverse(Acc), Type, S, State}; parse_name([$)], _Acc, 0, _IsArg, State) -> throw({error, State#state.loc, "expected type specifier, found end of string"}); parse_name([$( = C | S], Acc, Depth, IsArg, State) -> parse_name(S, [C | Acc], Depth + 1, IsArg, State); parse_name([$) = C | S], Acc, Depth, IsArg, State) -> parse_name(S, [C | Acc], Depth - 1, IsArg, State); parse_name([C | S], Acc, Depth, IsArg, State) -> parse_name(S, [C | Acc], Depth, IsArg, State). make_var(V) -> Var = "__V" ++ integer_to_list(V), erl_syntax:variable(Var). perform_array_pass(State) -> {NQ, PQ, Rest} = lists:foldl( fun([{var, _, _} = Var], {N, P, {str, Str} = Prev}) -> Str2 = re:replace(Str, "(^|\s+)in\s*$", " = any(", [{return, list}]), {[Var, Prev | N], [{str, ")"}, Var, {str, Str2} | P], none}; ([{var, _, _}], _) -> throw({error, State#state.loc, ["List variable not following 'in' operator"]}); (Other, {N, P, none}) -> {N, P, Other}; (Other, {N, P, Prev}) -> {[Prev | N], [Prev | P], Other} end, {[], [], none}, State#state.query), {NQ2, PQ2} = case Rest of none -> {NQ, PQ}; _ -> {[Rest | NQ], [Rest | PQ]} end, {NA, PA} = lists:foldl( fun([V1, V2], {N, P}) -> {[V1 | N], [V2 | P]}; (Other, {N, P}) -> {[Other | N], [Other | P]} end, {[], []}, State#state.args), {State#state{query = lists:reverse(NQ2), args = lists:reverse(NA), need_array_pass = false}, State#state{query = lists:reverse(PQ2), args = lists:reverse(PA), need_array_pass = false}}. make_sql_query(State) -> make_sql_query(State, unknown). make_sql_query(State, Type) -> Hash = erlang:phash2(State#state{loc = undefined, use_new_schema = true}), SHash = <<"Q", (integer_to_binary(Hash))/binary>>, Query = pack_query(State#state.'query'), EQuery = lists:flatmap( fun({str, S}) -> [erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string(S))])]; ({var, V, timestamp}) when Type == pgsql -> [erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string("to_timestamp("))]), make_var(V), erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string(", 'YYYY-MM-DD HH24:MI:SS')"))])]; ({var, V, _}) -> [make_var(V)] end, Query), erl_syntax:record_expr( erl_syntax:atom(?QUERY_RECORD), [erl_syntax:record_field( erl_syntax:atom(hash), %erl_syntax:abstract(SHash) erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string(binary_to_list(SHash)))])), erl_syntax:record_field( erl_syntax:atom(args), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:variable(?ESCAPE_VAR)], none, [erl_syntax:list(State#state.args)] )])), erl_syntax:record_field( erl_syntax:atom(format_query), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:list(lists:map(fun make_var/1, State#state.params))], none, [erl_syntax:list(EQuery)] )])), erl_syntax:record_field( erl_syntax:atom(format_res), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:list(State#state.res_vars)], none, [erl_syntax:tuple(State#state.res)] )])), erl_syntax:record_field( erl_syntax:atom(loc), erl_syntax:abstract({get(?MOD), State#state.loc})) ]). pack_query([]) -> []; pack_query([{str, S1}, {str, S2} | Rest]) -> pack_query([{str, S1 ++ S2} | Rest]); pack_query([X | Rest]) -> [X | pack_query(Rest)]. parse_upsert(Fields) -> {Fs, _} = lists:foldr( fun(F, {Acc, Param}) -> case erl_syntax:type(F) of string -> V = erl_syntax:string_value(F), {_, _, State} = Res = parse_upsert_field( V, Param, erl_syntax:get_pos(F)), {[Res | Acc], State#state.param_pos}; _ -> throw({error, erl_syntax:get_pos(F), "?SQL_UPSERT field must be " "a constant string"}) end end, {[], 0}, Fields), Fs. %% key | {Update} parse_upsert_field([$! | S], ParamPos, Loc) -> {Name, ParseState} = parse_upsert_field1(S, [], ParamPos, Loc), {Name, key, ParseState}; parse_upsert_field([$- | S], ParamPos, Loc) -> {Name, ParseState} = parse_upsert_field1(S, [], ParamPos, Loc), {Name, {false}, ParseState}; parse_upsert_field(S, ParamPos, Loc) -> {Name, ParseState} = parse_upsert_field1(S, [], ParamPos, Loc), {Name, {true}, ParseState}. parse_upsert_field1([], _Acc, _ParamPos, Loc) -> throw({error, Loc, "?SQL_UPSERT fields must have the " "following form: \"[!-]name=value\""}); parse_upsert_field1([$= | S], Acc, ParamPos, Loc) -> {lists:reverse(Acc), parse(S, ParamPos, Loc, true)}; parse_upsert_field1([C | S], Acc, ParamPos, Loc) -> parse_upsert_field1(S, [C | Acc], ParamPos, Loc). make_sql_upsert(Table, ParseRes, Pos) -> check_upsert(ParseRes, Pos), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:atom(pgsql), erl_syntax:variable("__Version")], [erl_syntax:infix_expr( erl_syntax:variable("__Version"), erl_syntax:operator('>='), erl_syntax:integer(90500))], [make_sql_upsert_pgsql905(Table, ParseRes), erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:atom(pgsql), erl_syntax:variable("__Version")], [erl_syntax:infix_expr( erl_syntax:variable("__Version"), erl_syntax:operator('>='), erl_syntax:integer(90100))], [make_sql_upsert_pgsql901(Table, ParseRes), erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:atom(mysql), erl_syntax:underscore()], [], [make_sql_upsert_mysql(Table, ParseRes), erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:underscore(), erl_syntax:underscore()], none, [make_sql_upsert_generic(Table, ParseRes)]) ]). make_sql_upsert_generic(Table, ParseRes) -> Update = make_sql_query(make_sql_upsert_update(Table, ParseRes)), Insert = make_sql_query(make_sql_upsert_insert(Table, ParseRes)), InsertBranch = erl_syntax:case_expr( erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Insert]), [erl_syntax:clause( [erl_syntax:abstract({updated, 1})], none, [erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:variable("__UpdateRes")], none, [erl_syntax:variable("__UpdateRes")])]), erl_syntax:case_expr( erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Update]), [erl_syntax:clause( [erl_syntax:abstract({updated, 1})], none, [erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:underscore()], none, [InsertBranch])]). make_sql_upsert_update(Table, ParseRes) -> WPairs = lists:flatmap( fun({_Field, {_}, _ST}) -> []; ({Field, key, ST}) -> [ST#state{ 'query' = [{str, Field}, {str, "="}] ++ ST#state.'query' }] end, ParseRes), Where = join_states(WPairs, " AND "), SPairs = lists:flatmap( fun({_Field, key, _ST}) -> []; ({_Field, {false}, _ST}) -> []; ({Field, {true}, ST}) -> [ST#state{ 'query' = [{str, Field}, {str, "="}] ++ ST#state.'query' }] end, ParseRes), Set = join_states(SPairs, ", "), State = concat_states( [#state{'query' = [{str, "UPDATE "}, {str, Table}, {str, " SET "}]}, Set, #state{'query' = [{str, " WHERE "}]}, Where ]), State. make_sql_upsert_insert(Table, ParseRes) -> Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), Fields = lists:map( fun({Field, _, _ST}) -> #state{'query' = [{str, Field}]} end, ParseRes), State = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") VALUES ("}]}, join_states(Vals, ", "), #state{'query' = [{str, ");"}]} ]), State. make_sql_upsert_mysql(Table, ParseRes) -> Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), {Fields, Set} = lists:foldr( fun({Field, key, _ST}, {F, S}) -> {[#state{'query' = [{str, Field}]} | F], S}; ({Field, {false}, _ST}, {F, S}) -> {[#state{'query' = [{str, Field}]} | F], S}; ({Field, {true}, _ST}, {F, S}) -> {[#state{'query' = [{str, Field}]} | F], [#state{'query' = [{str, Field}, {str, "=VALUES("}, {str, Field}, {str, ")"}]} | S]} end, {[], []}, ParseRes), Insert = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") VALUES ("}]}, join_states(Vals, ", "), #state{'query' = [{str, ") ON DUPLICATE KEY UPDATE "}]}, join_states(Set, ", ") ]), erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [make_sql_query(Insert)]). make_sql_upsert_pgsql901(Table, ParseRes0) -> ParseRes = lists:map( fun({"family", A2, A3}) -> {"\"family\"", A2, A3}; (Other) -> Other end, ParseRes0), Update = make_sql_upsert_update(Table, ParseRes), Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), Fields = lists:map( fun({Field, _, _ST}) -> #state{'query' = [{str, Field}]} end, ParseRes), Insert = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") SELECT "}]}, join_states(Vals, ", "), #state{'query' = [{str, " WHERE NOT EXISTS (SELECT * FROM upsert)"}]} ]), State = concat_states( [#state{'query' = [{str, "WITH upsert AS ("}]}, Update, #state{'query' = [{str, " RETURNING *) "}]}, Insert ]), Upsert = make_sql_query(State, pgsql), erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Upsert]). make_sql_upsert_pgsql905(Table, ParseRes0) -> ParseRes = lists:map( fun({"family", A2, A3}) -> {"\"family\"", A2, A3}; (Other) -> Other end, ParseRes0), Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), Fields = lists:map( fun({Field, _, _ST}) -> #state{'query' = [{str, Field}]} end, ParseRes), SPairs = lists:flatmap( fun({_Field, key, _ST}) -> []; ({_Field, {false}, _ST}) -> []; ({Field, {true}, ST}) -> [ST#state{ 'query' = [{str, Field}, {str, "="}] ++ ST#state.'query' }] end, ParseRes), Set = join_states(SPairs, ", "), KeyFields = lists:flatmap( fun({Field, key, _ST}) -> [#state{'query' = [{str, Field}]}]; ({_Field, _, _ST}) -> [] end, ParseRes), State = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") VALUES ("}]}, join_states(Vals, ", "), #state{'query' = [{str, ") ON CONFLICT ("}]}, join_states(KeyFields, ", "), #state{'query' = [{str, ") DO UPDATE SET "}]}, Set ]), Upsert = make_sql_query(State, pgsql), erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Upsert]). check_upsert(ParseRes, Pos) -> Set = lists:filter( fun({_Field, Match, _ST}) -> Match /= key end, ParseRes), case Set of [] -> throw({error, Pos, "No ?SQL_UPSERT fields to set, use INSERT instead"}); _ -> ok end, ok. parse_insert(Fields) -> {Fs, _} = lists:foldr( fun(F, {Acc, Param}) -> case erl_syntax:type(F) of string -> V = erl_syntax:string_value(F), {_, _, State} = Res = parse_insert_field( V, Param, erl_syntax:get_pos(F)), {[Res | Acc], State#state.param_pos}; _ -> throw({error, erl_syntax:get_pos(F), "?SQL_INSERT field must be " "a constant string"}) end end, {[], 0}, Fields), Fs. parse_insert_field([$! | _S], _ParamPos, Loc) -> throw({error, Loc, "?SQL_INSERT fields must not start with \"!\""}); parse_insert_field([$- | _S], _ParamPos, Loc) -> throw({error, Loc, "?SQL_INSERT fields must not start with \"-\""}); parse_insert_field(S, ParamPos, Loc) -> {Name, ParseState} = parse_insert_field1(S, [], ParamPos, Loc), {Name, {true}, ParseState}. parse_insert_field1([], _Acc, _ParamPos, Loc) -> throw({error, Loc, "?SQL_INSERT fields must have the " "following form: \"name=value\""}); parse_insert_field1([$= | S], Acc, ParamPos, Loc) -> {lists:reverse(Acc), parse(S, ParamPos, Loc, true)}; parse_insert_field1([C | S], Acc, ParamPos, Loc) -> parse_insert_field1(S, [C | Acc], ParamPos, Loc). make_sql_insert(Table, ParseRes) -> make_sql_query(make_sql_upsert_insert(Table, ParseRes)). make_schema_check(Tree, Tree) -> Tree; make_schema_check(New, Old) -> erl_syntax:case_expr( erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(use_new_schema), []), [erl_syntax:clause( [erl_syntax:abstract(true)], none, [New]), erl_syntax:clause( [erl_syntax:abstract(false)], none, [Old])]). concat_states(States) -> lists:foldr( fun(ST11, ST2) -> ST1 = resolve_vars(ST11, ST2), ST1#state{ 'query' = ST1#state.'query' ++ ST2#state.'query', params = ST1#state.params ++ ST2#state.params, args = ST1#state.args ++ ST2#state.args, res = ST1#state.res ++ ST2#state.res, res_vars = ST1#state.res_vars ++ ST2#state.res_vars, loc = case ST1#state.loc of undefined -> ST2#state.loc; _ -> ST1#state.loc end } end, #state{}, States). resolve_vars(ST1, ST2) -> Max = lists:max([0 | ST1#state.params ++ ST2#state.params]), {Map, _} = lists:foldl( fun(Var, {Acc, New}) -> case lists:member(Var, ST2#state.params) of true -> {dict:store(Var, New, Acc), New + 1}; false -> {Acc, New} end end, {dict:new(), Max + 1}, ST1#state.params), NewParams = lists:map( fun(Var) -> case dict:find(Var, Map) of {ok, New} -> New; error -> Var end end, ST1#state.params), NewQuery = lists:map( fun({var, Var, Type}) -> case dict:find(Var, Map) of {ok, New} -> {var, New, Type}; error -> {var, Var, Type} end; (S) -> S end, ST1#state.'query'), ST1#state{params = NewParams, 'query' = NewQuery}. join_states([], _Sep) -> #state{}; join_states([H | T], Sep) -> J = [[H] | [[#state{'query' = [{str, Sep}]}, X] || X <- T]], concat_states(lists:append(J)). set_pos(Tree, Pos) -> erl_syntax_lib:map( fun(Node) -> case erl_syntax:get_pos(Node) of 0 -> erl_syntax:set_pos(Node, Pos); _ -> Node end end, Tree). filter_upsert_sh(Table, ParseRes) -> lists:filter( fun({Field, _Match, _ST}) -> Field /= "server_host" orelse Table == "route" end, ParseRes). -ifdef(ENABLE_PT_WARNINGS). add_warning(Pos, Warning) -> Marker = erl_syntax:revert( erl_syntax:warning_marker({Pos, ?MODULE, Warning})), put(warnings, [Marker | get(warnings)]), ok. -else. add_warning(_Pos, _Warning) -> ok. -endif.
null
https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/ejabberd_sql_pt.erl
erlang
------------------------------------------------------------------- File : ejabberd_sql_pt.erl This program is free software; you can redistribute it and/or 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. ---------------------------------------------------------------------- API ==================================================================== API ==================================================================== -------------------------------------------------------------------- Function: Description: -------------------------------------------------------------------- ==================================================================== ==================================================================== erl_syntax:abstract(SHash) key | {Update}
Author : < > Description : Parse transform for SQL queries Created : 20 Jan 2016 by < > ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(ejabberd_sql_pt). -export([parse_transform/2, format_error/1]). -include("ejabberd_sql.hrl"). -record(state, {loc, 'query' = [], params = [], param_pos = 0, args = [], res = [], res_vars = [], res_pos = 0, server_host_used = false, used_vars = [], use_new_schema, need_timestamp_pass = false, need_array_pass = false}). -define(QUERY_RECORD, "sql_query"). -define(ESCAPE_RECORD, "sql_escape"). -define(ESCAPE_VAR, "__SQLEscape"). -define(MOD, sql__module_). parse_transform(AST, _Options) -> put(warnings, []), NewAST = top_transform(AST), NewAST ++ get(warnings). format_error(no_server_host) -> "server_host field is not used". Internal functions transform(Form) -> case erl_syntax:type(Form) of application -> case erl_syntax_lib:analyze_application(Form) of {?SQL_MARK, 1} -> case erl_syntax:application_arguments(Form) of [Arg] -> case erl_syntax:type(Arg) of string -> transform_sql(Arg); _ -> throw({error, erl_syntax:get_pos(Form), "?SQL argument must be " "a constant string"}) end; _ -> throw({error, erl_syntax:get_pos(Form), "wrong number of ?SQL args"}) end; {?SQL_UPSERT_MARK, 2} -> case erl_syntax:application_arguments(Form) of [TableArg, FieldsArg] -> case {erl_syntax:type(TableArg), erl_syntax:is_proper_list(FieldsArg)}of {string, true} -> transform_upsert(Form, TableArg, FieldsArg); _ -> throw({error, erl_syntax:get_pos(Form), "?SQL_UPSERT arguments must be " "a constant string and a list"}) end; _ -> throw({error, erl_syntax:get_pos(Form), "wrong number of ?SQL_UPSERT args"}) end; {?SQL_INSERT_MARK, 2} -> case erl_syntax:application_arguments(Form) of [TableArg, FieldsArg] -> case {erl_syntax:type(TableArg), erl_syntax:is_proper_list(FieldsArg)}of {string, true} -> transform_insert(Form, TableArg, FieldsArg); _ -> throw({error, erl_syntax:get_pos(Form), "?SQL_INSERT arguments must be " "a constant string and a list"}) end; _ -> throw({error, erl_syntax:get_pos(Form), "wrong number of ?SQL_INSERT args"}) end; _ -> Form end; attribute -> case erl_syntax:atom_value(erl_syntax:attribute_name(Form)) of module -> case erl_syntax:attribute_arguments(Form) of [M | _] -> Module = erl_syntax:atom_value(M), put(?MOD, Module), Form; _ -> Form end; _ -> Form end; _ -> Form end. top_transform(Forms) when is_list(Forms) -> lists:map( fun(Form) -> try Form2 = erl_syntax_lib:map(fun transform/1, Form), Form3 = erl_syntax:revert(Form2), Form3 catch throw:{error, Line, Error} -> {error, {Line, erl_parse, Error}} end end, Forms). transform_sql(Arg) -> S = erl_syntax:string_value(Arg), Pos = erl_syntax:get_pos(Arg), ParseRes = parse(S, Pos, true), ParseResOld = parse(S, Pos, false), case ParseRes#state.server_host_used of {true, _SHVar} -> ok; false -> add_warning( Pos, no_server_host), [] end, case {ParseRes#state.need_array_pass, ParseRes#state.need_timestamp_pass} of {true, _} -> {PR1, PR2} = perform_array_pass(ParseRes), {PRO1, PRO2} = perform_array_pass(ParseResOld), set_pos(make_schema_check( erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(PR2, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(PR1)])]), erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(PRO2, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(PRO1)])])), Pos); {_, true} -> set_pos(make_schema_check( erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(ParseRes, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(ParseRes)])]), erl_syntax:list([erl_syntax:tuple([erl_syntax:atom(pgsql), make_sql_query(ParseResOld, pgsql)]), erl_syntax:tuple([erl_syntax:atom(any), make_sql_query(ParseResOld)])])), Pos); _ -> set_pos( make_schema_check( make_sql_query(ParseRes), make_sql_query(ParseResOld) ), Pos) end. transform_upsert(Form, TableArg, FieldsArg) -> Table = erl_syntax:string_value(TableArg), ParseRes = parse_upsert( erl_syntax:list_elements(FieldsArg)), Pos = erl_syntax:get_pos(Form), case lists:keymember( "server_host", 1, ParseRes) of true -> ok; false -> add_warning(Pos, no_server_host) end, ParseResOld = filter_upsert_sh(Table, ParseRes), set_pos( make_schema_check( make_sql_upsert(Table, ParseRes, Pos), make_sql_upsert(Table, ParseResOld, Pos) ), Pos). transform_insert(Form, TableArg, FieldsArg) -> Table = erl_syntax:string_value(TableArg), ParseRes = parse_insert( erl_syntax:list_elements(FieldsArg)), Pos = erl_syntax:get_pos(Form), case lists:keymember( "server_host", 1, ParseRes) of true -> ok; false -> add_warning(Pos, no_server_host) end, ParseResOld = filter_upsert_sh(Table, ParseRes), set_pos( make_schema_check( make_sql_insert(Table, ParseRes), make_sql_insert(Table, ParseResOld) ), Pos). parse(S, Loc, UseNewSchema) -> parse1(S, [], #state{loc = Loc, use_new_schema = UseNewSchema}). parse(S, ParamPos, Loc, UseNewSchema) -> parse1(S, [], #state{loc = Loc, param_pos = ParamPos, use_new_schema = UseNewSchema}). parse1([], Acc, State) -> State1 = append_string(lists:reverse(Acc), State), State1#state{'query' = lists:reverse(State1#state.'query'), params = lists:reverse(State1#state.params), args = lists:reverse(State1#state.args), res = lists:reverse(State1#state.res), res_vars = lists:reverse(State1#state.res_vars) }; parse1([$@, $( | S], Acc, State) -> State1 = append_string(lists:reverse(Acc), State), {Name, Type, S1, State2} = parse_name(S, false, State1), Var = "__V" ++ integer_to_list(State2#state.res_pos), EVar = erl_syntax:variable(Var), Convert = case Type of integer -> erl_syntax:application( erl_syntax:atom(binary_to_integer), [EVar]); string -> EVar; timestamp -> EVar; boolean -> erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(to_bool), [EVar]) end, State3 = append_string(Name, State2), State4 = State3#state{res_pos = State3#state.res_pos + 1, res = [Convert | State3#state.res], res_vars = [EVar | State3#state.res_vars]}, parse1(S1, [], State4); , $ ( | S ] , Acc , State ) - > State1 = append_string(lists:reverse(Acc), State), {Name, Type, S1, State2} = parse_name(S, true, State1), Var = State2#state.param_pos, State4 = case Type of host -> State3 = State2#state{server_host_used = {true, Name}, used_vars = [Name | State2#state.used_vars]}, case State#state.use_new_schema of true -> Convert = erl_syntax:application( erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(string)), [erl_syntax:variable(Name)]), State3#state{'query' = [{var, Var, Type}, {str, "server_host="} | State3#state.'query'], args = [Convert | State3#state.args], params = [Var | State3#state.params], param_pos = State3#state.param_pos + 1}; false -> append_string("0=0", State3) end; {list, InternalType} -> Convert = erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(to_list), [erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(InternalType)), erl_syntax:variable(Name)]), IT2 = case InternalType of string -> in_array_string; _ -> InternalType end, ConvertArr = erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(to_array), [erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(IT2)), erl_syntax:variable(Name)]), State2#state{'query' = [[{var, Var, Type}] | State2#state.'query'], need_array_pass = true, args = [[Convert, ConvertArr] | State2#state.args], params = [Var | State2#state.params], param_pos = State2#state.param_pos + 1, used_vars = [Name | State2#state.used_vars]}; _ -> {TS, Type2} = case Type of timestamp -> {true, string}; Other -> {State2#state.need_timestamp_pass, Other} end, Convert = erl_syntax:application( erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(Type2)), [erl_syntax:variable(Name)]), State2#state{'query' = [{var, Var, Type} | State2#state.'query'], need_timestamp_pass = TS, args = [Convert | State2#state.args], params = [Var | State2#state.params], param_pos = State2#state.param_pos + 1, used_vars = [Name | State2#state.used_vars]} end, parse1(S1, [], State4); parse1("%ESCAPE" ++ S, Acc, State) -> State1 = append_string(lists:reverse(Acc), State), Convert = erl_syntax:application( erl_syntax:record_access( erl_syntax:variable(?ESCAPE_VAR), erl_syntax:atom(?ESCAPE_RECORD), erl_syntax:atom(like_escape)), []), Var = State1#state.param_pos, State2 = State1#state{'query' = [{var, Var, string} | State1#state.'query'], args = [Convert | State1#state.args], params = [Var | State1#state.params], param_pos = State1#state.param_pos + 1}, parse1(S, [], State2); parse1([C | S], Acc, State) -> parse1(S, [C | Acc], State). append_string([], State) -> State; append_string(S, State) -> State#state{query = [{str, S} | State#state.query]}. parse_name(S, IsArg, State) -> parse_name(S, [], 0, IsArg, State). parse_name([], _Acc, _Depth, _IsArg, State) -> throw({error, State#state.loc, "expected ')', found end of string"}); parse_name([$), $l, T | S], Acc, 0, true, State) -> Type = case T of $d -> {list, integer}; $s -> {list, string}; $b -> {list, boolean}; _ -> throw({error, State#state.loc, ["unknown type specifier 'l", T, "'"]}) end, {lists:reverse(Acc), Type, S, State}; parse_name([$), $l, T | _], _Acc, 0, false, State) -> throw({error, State#state.loc, ["list type 'l", T, "' is not allowed for outputs"]}); parse_name([$), T | S], Acc, 0, IsArg, State) -> Type = case T of $d -> integer; $s -> string; $b -> boolean; $t -> timestamp; $H when IsArg -> host; _ -> throw({error, State#state.loc, ["unknown type specifier '", T, "'"]}) end, {lists:reverse(Acc), Type, S, State}; parse_name([$)], _Acc, 0, _IsArg, State) -> throw({error, State#state.loc, "expected type specifier, found end of string"}); parse_name([$( = C | S], Acc, Depth, IsArg, State) -> parse_name(S, [C | Acc], Depth + 1, IsArg, State); parse_name([$) = C | S], Acc, Depth, IsArg, State) -> parse_name(S, [C | Acc], Depth - 1, IsArg, State); parse_name([C | S], Acc, Depth, IsArg, State) -> parse_name(S, [C | Acc], Depth, IsArg, State). make_var(V) -> Var = "__V" ++ integer_to_list(V), erl_syntax:variable(Var). perform_array_pass(State) -> {NQ, PQ, Rest} = lists:foldl( fun([{var, _, _} = Var], {N, P, {str, Str} = Prev}) -> Str2 = re:replace(Str, "(^|\s+)in\s*$", " = any(", [{return, list}]), {[Var, Prev | N], [{str, ")"}, Var, {str, Str2} | P], none}; ([{var, _, _}], _) -> throw({error, State#state.loc, ["List variable not following 'in' operator"]}); (Other, {N, P, none}) -> {N, P, Other}; (Other, {N, P, Prev}) -> {[Prev | N], [Prev | P], Other} end, {[], [], none}, State#state.query), {NQ2, PQ2} = case Rest of none -> {NQ, PQ}; _ -> {[Rest | NQ], [Rest | PQ]} end, {NA, PA} = lists:foldl( fun([V1, V2], {N, P}) -> {[V1 | N], [V2 | P]}; (Other, {N, P}) -> {[Other | N], [Other | P]} end, {[], []}, State#state.args), {State#state{query = lists:reverse(NQ2), args = lists:reverse(NA), need_array_pass = false}, State#state{query = lists:reverse(PQ2), args = lists:reverse(PA), need_array_pass = false}}. make_sql_query(State) -> make_sql_query(State, unknown). make_sql_query(State, Type) -> Hash = erlang:phash2(State#state{loc = undefined, use_new_schema = true}), SHash = <<"Q", (integer_to_binary(Hash))/binary>>, Query = pack_query(State#state.'query'), EQuery = lists:flatmap( fun({str, S}) -> [erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string(S))])]; ({var, V, timestamp}) when Type == pgsql -> [erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string("to_timestamp("))]), make_var(V), erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string(", 'YYYY-MM-DD HH24:MI:SS')"))])]; ({var, V, _}) -> [make_var(V)] end, Query), erl_syntax:record_expr( erl_syntax:atom(?QUERY_RECORD), [erl_syntax:record_field( erl_syntax:atom(hash), erl_syntax:binary( [erl_syntax:binary_field( erl_syntax:string(binary_to_list(SHash)))])), erl_syntax:record_field( erl_syntax:atom(args), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:variable(?ESCAPE_VAR)], none, [erl_syntax:list(State#state.args)] )])), erl_syntax:record_field( erl_syntax:atom(format_query), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:list(lists:map(fun make_var/1, State#state.params))], none, [erl_syntax:list(EQuery)] )])), erl_syntax:record_field( erl_syntax:atom(format_res), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:list(State#state.res_vars)], none, [erl_syntax:tuple(State#state.res)] )])), erl_syntax:record_field( erl_syntax:atom(loc), erl_syntax:abstract({get(?MOD), State#state.loc})) ]). pack_query([]) -> []; pack_query([{str, S1}, {str, S2} | Rest]) -> pack_query([{str, S1 ++ S2} | Rest]); pack_query([X | Rest]) -> [X | pack_query(Rest)]. parse_upsert(Fields) -> {Fs, _} = lists:foldr( fun(F, {Acc, Param}) -> case erl_syntax:type(F) of string -> V = erl_syntax:string_value(F), {_, _, State} = Res = parse_upsert_field( V, Param, erl_syntax:get_pos(F)), {[Res | Acc], State#state.param_pos}; _ -> throw({error, erl_syntax:get_pos(F), "?SQL_UPSERT field must be " "a constant string"}) end end, {[], 0}, Fields), Fs. parse_upsert_field([$! | S], ParamPos, Loc) -> {Name, ParseState} = parse_upsert_field1(S, [], ParamPos, Loc), {Name, key, ParseState}; parse_upsert_field([$- | S], ParamPos, Loc) -> {Name, ParseState} = parse_upsert_field1(S, [], ParamPos, Loc), {Name, {false}, ParseState}; parse_upsert_field(S, ParamPos, Loc) -> {Name, ParseState} = parse_upsert_field1(S, [], ParamPos, Loc), {Name, {true}, ParseState}. parse_upsert_field1([], _Acc, _ParamPos, Loc) -> throw({error, Loc, "?SQL_UPSERT fields must have the " "following form: \"[!-]name=value\""}); parse_upsert_field1([$= | S], Acc, ParamPos, Loc) -> {lists:reverse(Acc), parse(S, ParamPos, Loc, true)}; parse_upsert_field1([C | S], Acc, ParamPos, Loc) -> parse_upsert_field1(S, [C | Acc], ParamPos, Loc). make_sql_upsert(Table, ParseRes, Pos) -> check_upsert(ParseRes, Pos), erl_syntax:fun_expr( [erl_syntax:clause( [erl_syntax:atom(pgsql), erl_syntax:variable("__Version")], [erl_syntax:infix_expr( erl_syntax:variable("__Version"), erl_syntax:operator('>='), erl_syntax:integer(90500))], [make_sql_upsert_pgsql905(Table, ParseRes), erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:atom(pgsql), erl_syntax:variable("__Version")], [erl_syntax:infix_expr( erl_syntax:variable("__Version"), erl_syntax:operator('>='), erl_syntax:integer(90100))], [make_sql_upsert_pgsql901(Table, ParseRes), erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:atom(mysql), erl_syntax:underscore()], [], [make_sql_upsert_mysql(Table, ParseRes), erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:underscore(), erl_syntax:underscore()], none, [make_sql_upsert_generic(Table, ParseRes)]) ]). make_sql_upsert_generic(Table, ParseRes) -> Update = make_sql_query(make_sql_upsert_update(Table, ParseRes)), Insert = make_sql_query(make_sql_upsert_insert(Table, ParseRes)), InsertBranch = erl_syntax:case_expr( erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Insert]), [erl_syntax:clause( [erl_syntax:abstract({updated, 1})], none, [erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:variable("__UpdateRes")], none, [erl_syntax:variable("__UpdateRes")])]), erl_syntax:case_expr( erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Update]), [erl_syntax:clause( [erl_syntax:abstract({updated, 1})], none, [erl_syntax:atom(ok)]), erl_syntax:clause( [erl_syntax:underscore()], none, [InsertBranch])]). make_sql_upsert_update(Table, ParseRes) -> WPairs = lists:flatmap( fun({_Field, {_}, _ST}) -> []; ({Field, key, ST}) -> [ST#state{ 'query' = [{str, Field}, {str, "="}] ++ ST#state.'query' }] end, ParseRes), Where = join_states(WPairs, " AND "), SPairs = lists:flatmap( fun({_Field, key, _ST}) -> []; ({_Field, {false}, _ST}) -> []; ({Field, {true}, ST}) -> [ST#state{ 'query' = [{str, Field}, {str, "="}] ++ ST#state.'query' }] end, ParseRes), Set = join_states(SPairs, ", "), State = concat_states( [#state{'query' = [{str, "UPDATE "}, {str, Table}, {str, " SET "}]}, Set, #state{'query' = [{str, " WHERE "}]}, Where ]), State. make_sql_upsert_insert(Table, ParseRes) -> Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), Fields = lists:map( fun({Field, _, _ST}) -> #state{'query' = [{str, Field}]} end, ParseRes), State = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") VALUES ("}]}, join_states(Vals, ", "), #state{'query' = [{str, ");"}]} ]), State. make_sql_upsert_mysql(Table, ParseRes) -> Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), {Fields, Set} = lists:foldr( fun({Field, key, _ST}, {F, S}) -> {[#state{'query' = [{str, Field}]} | F], S}; ({Field, {false}, _ST}, {F, S}) -> {[#state{'query' = [{str, Field}]} | F], S}; ({Field, {true}, _ST}, {F, S}) -> {[#state{'query' = [{str, Field}]} | F], [#state{'query' = [{str, Field}, {str, "=VALUES("}, {str, Field}, {str, ")"}]} | S]} end, {[], []}, ParseRes), Insert = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") VALUES ("}]}, join_states(Vals, ", "), #state{'query' = [{str, ") ON DUPLICATE KEY UPDATE "}]}, join_states(Set, ", ") ]), erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [make_sql_query(Insert)]). make_sql_upsert_pgsql901(Table, ParseRes0) -> ParseRes = lists:map( fun({"family", A2, A3}) -> {"\"family\"", A2, A3}; (Other) -> Other end, ParseRes0), Update = make_sql_upsert_update(Table, ParseRes), Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), Fields = lists:map( fun({Field, _, _ST}) -> #state{'query' = [{str, Field}]} end, ParseRes), Insert = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") SELECT "}]}, join_states(Vals, ", "), #state{'query' = [{str, " WHERE NOT EXISTS (SELECT * FROM upsert)"}]} ]), State = concat_states( [#state{'query' = [{str, "WITH upsert AS ("}]}, Update, #state{'query' = [{str, " RETURNING *) "}]}, Insert ]), Upsert = make_sql_query(State, pgsql), erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Upsert]). make_sql_upsert_pgsql905(Table, ParseRes0) -> ParseRes = lists:map( fun({"family", A2, A3}) -> {"\"family\"", A2, A3}; (Other) -> Other end, ParseRes0), Vals = lists:map( fun({_Field, _, ST}) -> ST end, ParseRes), Fields = lists:map( fun({Field, _, _ST}) -> #state{'query' = [{str, Field}]} end, ParseRes), SPairs = lists:flatmap( fun({_Field, key, _ST}) -> []; ({_Field, {false}, _ST}) -> []; ({Field, {true}, ST}) -> [ST#state{ 'query' = [{str, Field}, {str, "="}] ++ ST#state.'query' }] end, ParseRes), Set = join_states(SPairs, ", "), KeyFields = lists:flatmap( fun({Field, key, _ST}) -> [#state{'query' = [{str, Field}]}]; ({_Field, _, _ST}) -> [] end, ParseRes), State = concat_states( [#state{'query' = [{str, "INSERT INTO "}, {str, Table}, {str, "("}]}, join_states(Fields, ", "), #state{'query' = [{str, ") VALUES ("}]}, join_states(Vals, ", "), #state{'query' = [{str, ") ON CONFLICT ("}]}, join_states(KeyFields, ", "), #state{'query' = [{str, ") DO UPDATE SET "}]}, Set ]), Upsert = make_sql_query(State, pgsql), erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(sql_query_t), [Upsert]). check_upsert(ParseRes, Pos) -> Set = lists:filter( fun({_Field, Match, _ST}) -> Match /= key end, ParseRes), case Set of [] -> throw({error, Pos, "No ?SQL_UPSERT fields to set, use INSERT instead"}); _ -> ok end, ok. parse_insert(Fields) -> {Fs, _} = lists:foldr( fun(F, {Acc, Param}) -> case erl_syntax:type(F) of string -> V = erl_syntax:string_value(F), {_, _, State} = Res = parse_insert_field( V, Param, erl_syntax:get_pos(F)), {[Res | Acc], State#state.param_pos}; _ -> throw({error, erl_syntax:get_pos(F), "?SQL_INSERT field must be " "a constant string"}) end end, {[], 0}, Fields), Fs. parse_insert_field([$! | _S], _ParamPos, Loc) -> throw({error, Loc, "?SQL_INSERT fields must not start with \"!\""}); parse_insert_field([$- | _S], _ParamPos, Loc) -> throw({error, Loc, "?SQL_INSERT fields must not start with \"-\""}); parse_insert_field(S, ParamPos, Loc) -> {Name, ParseState} = parse_insert_field1(S, [], ParamPos, Loc), {Name, {true}, ParseState}. parse_insert_field1([], _Acc, _ParamPos, Loc) -> throw({error, Loc, "?SQL_INSERT fields must have the " "following form: \"name=value\""}); parse_insert_field1([$= | S], Acc, ParamPos, Loc) -> {lists:reverse(Acc), parse(S, ParamPos, Loc, true)}; parse_insert_field1([C | S], Acc, ParamPos, Loc) -> parse_insert_field1(S, [C | Acc], ParamPos, Loc). make_sql_insert(Table, ParseRes) -> make_sql_query(make_sql_upsert_insert(Table, ParseRes)). make_schema_check(Tree, Tree) -> Tree; make_schema_check(New, Old) -> erl_syntax:case_expr( erl_syntax:application( erl_syntax:atom(ejabberd_sql), erl_syntax:atom(use_new_schema), []), [erl_syntax:clause( [erl_syntax:abstract(true)], none, [New]), erl_syntax:clause( [erl_syntax:abstract(false)], none, [Old])]). concat_states(States) -> lists:foldr( fun(ST11, ST2) -> ST1 = resolve_vars(ST11, ST2), ST1#state{ 'query' = ST1#state.'query' ++ ST2#state.'query', params = ST1#state.params ++ ST2#state.params, args = ST1#state.args ++ ST2#state.args, res = ST1#state.res ++ ST2#state.res, res_vars = ST1#state.res_vars ++ ST2#state.res_vars, loc = case ST1#state.loc of undefined -> ST2#state.loc; _ -> ST1#state.loc end } end, #state{}, States). resolve_vars(ST1, ST2) -> Max = lists:max([0 | ST1#state.params ++ ST2#state.params]), {Map, _} = lists:foldl( fun(Var, {Acc, New}) -> case lists:member(Var, ST2#state.params) of true -> {dict:store(Var, New, Acc), New + 1}; false -> {Acc, New} end end, {dict:new(), Max + 1}, ST1#state.params), NewParams = lists:map( fun(Var) -> case dict:find(Var, Map) of {ok, New} -> New; error -> Var end end, ST1#state.params), NewQuery = lists:map( fun({var, Var, Type}) -> case dict:find(Var, Map) of {ok, New} -> {var, New, Type}; error -> {var, Var, Type} end; (S) -> S end, ST1#state.'query'), ST1#state{params = NewParams, 'query' = NewQuery}. join_states([], _Sep) -> #state{}; join_states([H | T], Sep) -> J = [[H] | [[#state{'query' = [{str, Sep}]}, X] || X <- T]], concat_states(lists:append(J)). set_pos(Tree, Pos) -> erl_syntax_lib:map( fun(Node) -> case erl_syntax:get_pos(Node) of 0 -> erl_syntax:set_pos(Node, Pos); _ -> Node end end, Tree). filter_upsert_sh(Table, ParseRes) -> lists:filter( fun({Field, _Match, _ST}) -> Field /= "server_host" orelse Table == "route" end, ParseRes). -ifdef(ENABLE_PT_WARNINGS). add_warning(Pos, Warning) -> Marker = erl_syntax:revert( erl_syntax:warning_marker({Pos, ?MODULE, Warning})), put(warnings, [Marker | get(warnings)]), ok. -else. add_warning(_Pos, _Warning) -> ok. -endif.
15d291a6a4f5aaad04dd81594c92399819a857dbd8a3db29cac281aba72fb162
kelsey-sorrels/zaffre
text_test.cljc
(ns zaffre.text-test (:require [zaffre.text :as ztext] [cashmere.core-graal :as cm] [taoensso.timbre :as log] [clojure.inspector :refer :all] [clojure.test :refer :all])) (log/set-level! :warn) (deftest should-word-wrap (are [input expected] (= expected (apply ztext/word-wrap input)) [5 "Not A"] ["Not A"])) (deftest should-cascade-style (are [input expected] (= expected (ztext/cascade-style {} input)) ;; pass through (cm/new-text-instance {:style {}} "abc") [:raw-text {} "abc"] ;; cascade multiple levels (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-text-instance {} "abc")])]) [:text {:fg :red :bg :blue} [ [:text {:fg :red :bg :blue} [ [:raw-text {:fg :red :bg :blue} "abc"]]]]] ;; children should override parent styles (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {} [ (cm/new-text-instance {:style {:fg :green :bg :black}} "abc")])]) [:text {:fg :red :bg :blue} [ [:text {:fg :red :bg :blue} [ [:raw-text {:fg :green :bg :black} "abc"]]]]])) (deftest should-seq-through-tree (are [input expected] (= expected (ztext/text-tree-seq input)) ;; pass through [:text {} [ [:text {} "abc"]]] [[:text {} [ [:text {} "abc"]]] [:text {} "abc"]] )) (deftest should-seq-through-leaves (are [input expected] (= expected (-> input ztext/text-tree-seq ztext/filter-leaves)) ;; seq multiple levels [:text {} [ [:text {} [ [:text {} "abc"]]]]] [[:text {} "abc"]] ;; should work with multiple leaf scenarios [:text {} [ [:text {} "abc"] [:text {} "def"] [:text {} [ [:text {} "hij"] [:text {} [ [:text {} "klm"] [:text {} "nop"]]] [:text {} "qrs"]]] [:text {} "tuv"] [:text {} "wxy"]]] [[:text {} "abc"] [:text {} "def"] [:text {} "hij"] [:text {} "klm"] [:text {} "nop"] [:text {} "qrs"] [:text {} "tuv"] [:text {} "wxy"]])) (deftest should-wrap (are [input expected] (= expected (ztext/word-wrap 26 input)) ;; pass through "You begin crafting a weapon. You'll need to start with an item." ["You begin crafting a " "weapon. You'll need to " "start with an item."] )) (deftest should-word-wrap-text-tree (are [input expected] (= expected (ztext/word-wrap-text-tree 26 1 input)) (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {} [ (cm/new-text-instance {:style {:fg :green :bg :black}} "_______")])]) [[["_______" {:fg :green, :bg :black} 7]]])) (deftest should-get-text (are [input expected] (= expected (ztext/text input)) (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {} [ (cm/new-text-instance {:style {:fg :green :bg :black}} "_______")])]) "_______"))
null
https://raw.githubusercontent.com/kelsey-sorrels/zaffre/eb16a9b2095b54c835d39fa035533e5083fe7b02/test/zaffre/text_test.cljc
clojure
pass through cascade multiple levels children should override parent styles pass through seq multiple levels should work with multiple leaf scenarios pass through
(ns zaffre.text-test (:require [zaffre.text :as ztext] [cashmere.core-graal :as cm] [taoensso.timbre :as log] [clojure.inspector :refer :all] [clojure.test :refer :all])) (log/set-level! :warn) (deftest should-word-wrap (are [input expected] (= expected (apply ztext/word-wrap input)) [5 "Not A"] ["Not A"])) (deftest should-cascade-style (are [input expected] (= expected (ztext/cascade-style {} input)) (cm/new-text-instance {:style {}} "abc") [:raw-text {} "abc"] (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-text-instance {} "abc")])]) [:text {:fg :red :bg :blue} [ [:text {:fg :red :bg :blue} [ [:raw-text {:fg :red :bg :blue} "abc"]]]]] (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {} [ (cm/new-text-instance {:style {:fg :green :bg :black}} "abc")])]) [:text {:fg :red :bg :blue} [ [:text {:fg :red :bg :blue} [ [:raw-text {:fg :green :bg :black} "abc"]]]]])) (deftest should-seq-through-tree (are [input expected] (= expected (ztext/text-tree-seq input)) [:text {} [ [:text {} "abc"]]] [[:text {} [ [:text {} "abc"]]] [:text {} "abc"]] )) (deftest should-seq-through-leaves (are [input expected] (= expected (-> input ztext/text-tree-seq ztext/filter-leaves)) [:text {} [ [:text {} [ [:text {} "abc"]]]]] [[:text {} "abc"]] [:text {} [ [:text {} "abc"] [:text {} "def"] [:text {} [ [:text {} "hij"] [:text {} [ [:text {} "klm"] [:text {} "nop"]]] [:text {} "qrs"]]] [:text {} "tuv"] [:text {} "wxy"]]] [[:text {} "abc"] [:text {} "def"] [:text {} "hij"] [:text {} "klm"] [:text {} "nop"] [:text {} "qrs"] [:text {} "tuv"] [:text {} "wxy"]])) (deftest should-wrap (are [input expected] (= expected (ztext/word-wrap 26 input)) "You begin crafting a weapon. You'll need to start with an item." ["You begin crafting a " "weapon. You'll need to " "start with an item."] )) (deftest should-word-wrap-text-tree (are [input expected] (= expected (ztext/word-wrap-text-tree 26 1 input)) (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {} [ (cm/new-text-instance {:style {:fg :green :bg :black}} "_______")])]) [[["_______" {:fg :green, :bg :black} 7]]])) (deftest should-get-text (are [input expected] (= expected (ztext/text input)) (cm/new-instance :text {:style {:fg :red :bg :blue}} [ (cm/new-instance :text {} [ (cm/new-text-instance {:style {:fg :green :bg :black}} "_______")])]) "_______"))
c1018a7360f24f11114404d313b739192d3d2a2f269b6997716506e9201654b4
alinpopa/qerl
qerl_stomp_utils.erl
-module(qerl_stomp_utils). -export([drop/2]). -import(binary, [replace/4]). -define(LF,10). -define(CR,13). -define(NULL,0). %% Drop specific byte from the given binary drop(_,<<>>) -> <<>>; drop(What,Bin) when is_binary(Bin) -> case What of cr -> replace(Bin,<<?CR>>,<<>>,[global]); lf -> replace(Bin,<<?LF>>,<<>>,[global]); null -> replace(Bin,<<?NULL>>,<<>>,[global]); _ -> Bin end; drop(_What,_Bin) -> <<>>. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). empty_binary_is_returned_when_passed_in_binary_is_empty_test() -> ?assertEqual(<<>>, drop(anything,<<>>)). should_remove_CR_from_binary_test() -> ?assertEqual(<<10,10,0,1,2,3>>, drop(cr,<<10,13,10,0,1,2,3>>)). should_remove_LF_from_binary_test() -> ?assertEqual(<<13,0,1,2>>, drop(lf,<<10,13,10,0,1,2>>)). should_remove_NULL_from_binary_test() -> ?assertEqual(<<10,10,13>>, drop(null,<<10,0,10,0,13,0>>)). -endif.
null
https://raw.githubusercontent.com/alinpopa/qerl/4c10c4617eea14d451101775a1feb20fb3709f9d/src/qerl_stomp_utils.erl
erlang
Drop specific byte from the given binary
-module(qerl_stomp_utils). -export([drop/2]). -import(binary, [replace/4]). -define(LF,10). -define(CR,13). -define(NULL,0). drop(_,<<>>) -> <<>>; drop(What,Bin) when is_binary(Bin) -> case What of cr -> replace(Bin,<<?CR>>,<<>>,[global]); lf -> replace(Bin,<<?LF>>,<<>>,[global]); null -> replace(Bin,<<?NULL>>,<<>>,[global]); _ -> Bin end; drop(_What,_Bin) -> <<>>. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). empty_binary_is_returned_when_passed_in_binary_is_empty_test() -> ?assertEqual(<<>>, drop(anything,<<>>)). should_remove_CR_from_binary_test() -> ?assertEqual(<<10,10,0,1,2,3>>, drop(cr,<<10,13,10,0,1,2,3>>)). should_remove_LF_from_binary_test() -> ?assertEqual(<<13,0,1,2>>, drop(lf,<<10,13,10,0,1,2>>)). should_remove_NULL_from_binary_test() -> ?assertEqual(<<10,10,13>>, drop(null,<<10,0,10,0,13,0>>)). -endif.
8641b75fe4b5fcd3f6a2cf4c8cbe8d580591558334ab71fedb541690589ddc95
clj-commons/claypoole
claypoole.clj
The Climate Corporation licenses this file to you under 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 ;; ;; See the NOTICE file distributed with this work for additional information ;; regarding copyright ownership. 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 com.climate.claypoole "Threadpool tools for Clojure. Claypoole provides parallel functions and macros that use threads from a pool and otherwise act like key builtins like future, pmap, for, and so on. See the file README.md for an introduction. A threadpool is just an ExecutorService with a fixed number of threads. In general, you can use your own ExecutorService in place of any threadpool, and you can treat a threadpool as you would any other ExecutorService." (:refer-clojure :exclude [future future-call pcalls pmap pvalues]) (:require [clojure.core :as core] [com.climate.claypoole.impl :as impl]) (:import [com.climate.claypoole.impl PriorityThreadpool PriorityThreadpoolImpl] [java.util.concurrent Callable ExecutorService Future CompletableFuture] [java.util.function Supplier])) (def ^:dynamic *parallel* "A dynamic binding to disable parallelism. If you do (binding [*parallel* false] body) then the body will have no parallelism. Disabling parallelism this way is handy for testing." true) (def ^:dynamic *default-pmap-buffer* "This is an advanced configuration option. You probably don't need to set this! When doing a pmap, Claypoole pushes input tasks into the threadpool. It normally tries to keep the threadpool full, plus it adds a buffer of size nthreads. If it can't find out the number of threads in the threadpool, it just tries to keep *default-pmap-buffer* tasks in the pool." 200) (defn ncpus "Get the number of available CPUs." [] (.. Runtime getRuntime availableProcessors)) #_{:clj-kondo/ignore [:unused-binding]} (defn thread-factory "Create a ThreadFactory with keyword options including thread daemon status :daemon, the thread name format :name (a string for format with one integer), and a thread priority :thread-priority. This is exposed as a public function because it's handy if you're instantiating your own ExecutorServices." [& {:keys [daemon thread-priority] pool-name :name :as args}] (->> args (apply concat) (apply impl/thread-factory))) (defn threadpool "Make a threadpool. It should be shutdown when no longer needed. A threadpool is just an ExecutorService with a fixed number of threads. In general, you can use your own ExecutorService in place of any threadpool, and you can treat a threadpool as you would any other ExecutorService. This takes optional keyword arguments: :daemon, a boolean indicating whether the threads are daemon threads, which will automatically die when the JVM exits, defaults to true) :name, a string giving the pool name, which will be the prefix of each thread name, resulting in threads named \"name-0\", \"name-1\", etc. Defaults to \"claypoole-[pool-number]\". :thread-priority, an integer in [Thread/MIN_PRIORITY, Thread/MAX_PRIORITY]. The effects of thread priority are system-dependent and should not be confused with Claypoole's priority threadpools that choose tasks based on a priority. For more info about Java thread priority see Note: Returns a ScheduledExecutorService rather than just an ExecutorService because it's the same thing with a few bonus features." NOTE : The Clojure compiler does n't seem to like the tests if we do n't ;; fully expand this typename. ^java.util.concurrent.ScheduledExecutorService ;; NOTE: Although I'm repeating myself, I list all the threadpool-factory ;; arguments explicitly for API clarity. [n & {:keys [daemon thread-priority] pool-name :name :or {daemon true}}] (impl/threadpool n :daemon daemon :name pool-name :thread-priority thread-priority)) (defn priority-threadpool "Make a threadpool that chooses tasks based on their priorities. Assign priorities to tasks by wrapping the pool with with-priority or with-priority-fn. You can also set a default priority with keyword argument :default-priority. Otherwise, this uses the same keyword arguments as threadpool, and functions just like any other ExecutorService." ^com.climate.claypoole.impl.PriorityThreadpool [n & {:keys [default-priority] :as args :or {default-priority 0}}] (PriorityThreadpool. (PriorityThreadpoolImpl. n ;; Use our thread factory options. (impl/apply-map impl/thread-factory args) default-priority) (constantly default-priority))) (defn with-priority-fn "Make a priority-threadpool wrapper that uses a given priority function. The priority function is applied to a pmap'd function's arguments. e.g. (upmap (with-priority-fn pool (fn [x _] x)) + [6 5 4] [1 2 3]) will use pool to run tasks [(+ 6 1) (+ 5 2) (+ 4 3)] with priorities [6 5 4]." ^com.climate.claypoole.impl.PriorityThreadpool [^com.climate.claypoole.impl.PriorityThreadpool pool priority-fn] (impl/with-priority-fn pool priority-fn)) (defn with-priority "Make a priority-threadpool wrapper with a given fixed priority. All tasks run with this pool wrapper will have the given priority. e.g. (def t1 (future (with-priority p 1) 1)) (def t2 (future (with-priority p 2) 2)) (def t3 (future (with-priority p 3) 3)) will use pool p to run these tasks with priorities 1, 2, and 3 respectively. If you nest priorities, the outermost one \"wins\", so this task will be run at priority 3: (def wp (with-priority p 1)) (def t1 (future (with-priority (with-priority wp 2) 3) :result)) " ^java.util.concurrent.ExecutorService [^ExecutorService pool priority] (with-priority-fn pool (constantly priority))) (defn threadpool? "Returns true iff the argument is a threadpool." [pool] (instance? ExecutorService pool)) (defn priority-threadpool? "Returns true iff the argument is a priority-threadpool." [pool] (instance? PriorityThreadpool pool)) (defn shutdown "Syntactic sugar to stop a pool cleanly. This will stop the pool from accepting any new requests." [^ExecutorService pool] (when (not (= pool clojure.lang.Agent/soloExecutor)) (.shutdown pool))) (defn shutdown! "Syntactic sugar to forcibly shutdown a pool. This will kill any running threads in the pool!" [^ExecutorService pool] (when (not (= pool clojure.lang.Agent/soloExecutor)) (.shutdownNow pool))) (defn shutdown? "Syntactic sugar to test if a pool is shutdown." [^ExecutorService pool] (.isShutdown pool)) (defmacro with-shutdown! "Lets a threadpool from an initializer, then evaluates body in a try expression, calling shutdown! on the threadpool to forcibly shut it down at the end. The threadpool initializer may be a threadpool. Alternately, it can be any threadpool argument accepted by pmap, e.g. a number, :builtin, or :serial, in which case it will create a threadpool just as pmap would. Be aware that any unfinished jobs at the end of the body will be killed! Examples: (with-shutdown! [pool (threadpool 6)] (doall (pmap pool identity (range 1000)))) (with-shutdown! [pool1 6 pool2 :serial] (doall (pmap pool1 identity (range 1000)))) Bad example: (with-shutdown! [pool 6] ;; Some of these tasks may be killed! (pmap pool identity (range 1000))) " [pool-syms-and-inits & body] (when-not (even? (count pool-syms-and-inits)) (throw (IllegalArgumentException. "with-shutdown! requires an even number of binding forms"))) (if (empty? pool-syms-and-inits) `(do ~@body) (let [[pool-sym pool-init & more] pool-syms-and-inits] `(let [pool-init# ~pool-init [_# ~pool-sym] (impl/->threadpool pool-init#)] (try (with-shutdown! ~more ~@body) (finally (when (threadpool? ~pool-sym) (shutdown! ~pool-sym)))))))) (defn serial? "Check if we should run computations on this threadpool in serial." [pool] (or (not *parallel*) (= pool :serial))) (defn future-call "Like clojure.core/future-call, but using a threadpool. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool f] (impl/validate-future-pool pool) (cond ;; If requested, run the future in serial. (serial? pool) (impl/dummy-future-call f) ;; If requested, use the default threadpool. (= :builtin pool) (future-call clojure.lang.Agent/soloExecutor f) :else (let [;; We have to get the casts right, or the compiler will choose ;; the (.submit ^Runnable) call, which returns nil. We don't ;; want that! ^ExecutorService pool* pool ^Callable f* (impl/binding-conveyor-fn f) fut (.submit pool* f*)] Make an object just like Clojure futures . (reify clojure.lang.IDeref (deref [_] (impl/deref-future fut)) clojure.lang.IBlockingDeref (deref [_ timeout-ms timeout-val] (impl/deref-future fut timeout-ms timeout-val)) clojure.lang.IPending (isRealized [_] (.isDone fut)) Future (get [_] (.get fut)) (get [_ timeout unit] (.get fut timeout unit)) (isCancelled [_] (.isCancelled fut)) (isDone [_] (.isDone fut)) (cancel [_ interrupt?] (.cancel fut interrupt?)))))) (defmacro future "Like clojure.core/future, but using a threadpool. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool & body] `(future-call ~pool (^{:once true} fn ~'future-body [] ~@body))) (defn completable-future-call "Like clojure.core/future-call, but using a threadpool, and returns a CompletableFuture. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool f] (impl/validate-future-pool pool) (cond ;; If requested, run the future in serial. (serial? pool) (CompletableFuture/completedFuture (f)) ;; If requested, use the default threadpool. (= :builtin pool) (completable-future-call clojure.lang.Agent/soloExecutor f) :else (let [f* (impl/binding-conveyor-fn f)] (CompletableFuture/supplyAsync (reify Supplier (get [_] (f*))) pool)))) (defmacro completable-future "Like clojure.core/future, but using a threadpool and returns a CompletableFuture. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool & body] `(completable-future-call ~pool (^{:once true} fn ~'completable-future-body [] ~@body))) (defn- buffer-blocking-seq "Make a lazy sequence that blocks when the map's (imaginary) buffer is full." [pool unordered-results] (let [buffer-size (if-let [pool-size (impl/get-pool-size pool)] (* 2 pool-size) *default-pmap-buffer*)] (concat (repeat buffer-size nil) unordered-results))) (defn- pmap-core "Given functions to customize for pmap or upmap, do the hard work of pmap." [pool ordered? f arg-seqs] (let [[shutdown? pool] (impl/->threadpool pool) ;; Use map to handle the argument sequences. args (apply map vector (map impl/unchunk arg-seqs)) ;; We set this to true to stop realizing more tasks. abort (atom false) ;; Set up queues of tasks and results [task-q tasks] (impl/queue-seq) [unordered-results-q unordered-results] (impl/queue-seq) ;; This is how we'll actually make things go. start-task (fn [_i a] ;; We can't directly make a future add itself to a ;; queue. Instead, we use a promise for indirection. (let [p (promise)] (deliver p (future-call pool (with-meta ;; Try to run the task, but definitely ;; add the future to the queue. #(try (apply f a) (catch Throwable t ;; If we've had an exception, stop ;; making new tasks. (reset! abort true) ;; Re-throw that throwable! (throw t)) (finally (impl/queue-seq-add! unordered-results-q @p))) ;; Add the args to the function's ;; metadata for prioritization. {:args a}))) @p)) ;; Start all the tasks in a real future, so we don't block. driver (core/future (try (doseq [[i a _] (map vector (range) args ;; The driver thread reads from this sequence ;; and ignores the result, just to get the side ;; effect of blocking when the map's ;; (imaginary) buffer is full. (buffer-blocking-seq pool unordered-results)) :while (not @abort)] (impl/queue-seq-add! task-q (start-task i a))) (finally (impl/queue-seq-end! task-q) (when shutdown? (shutdown pool))))) result-seq (if ordered? tasks (map second (impl/lazy-co-read tasks unordered-results)))] ;; Read results as available. (concat (map impl/deref-fixing-exceptions result-seq) Deref the read - future to get its exceptions , if it has any . (lazy-seq @driver)))) (defn- pmap-boilerplate "Do boilerplate pmap checks, then call the real pmap function." [pool ordered? f arg-seqs] (when (empty? arg-seqs) (throw (IllegalArgumentException. "pmap requires at least one sequence to map over"))) (if (serial? pool) (doall (apply map f arg-seqs)) (pmap-core pool ordered? f arg-seqs))) (defn pmap "Like clojure.core.pmap, except: 1. It is eager, returning an ordered sequence of completed results as they are available. 2. It uses a threadpool to control the desired level of parallelism. A word of caution: pmap will consume the entire input sequence and produce as much output as possible--if you pmap over (range) you'll get an Out of Memory Exception! Use this when you definitely want the work to be done. The threadpool may be one of 4 things: 1. An ExecutorService, e.g. one created by threadpool. 2. An integer. In this case, a threadpool will be created, and it will be destroyed when all the pmap tasks are complete. 3. The keyword :builtin. In this case, pmap will use the Clojure built-in agent threadpool. For pmap, that's probably not what you want, as you'll likely create a thread per task. 4. The keyword :serial. In this case, the computations will be performed in serial via (doall map). This may be helpful during profiling, for example. " [pool f & arg-seqs] (pmap-boilerplate pool true f arg-seqs)) (defn upmap "Like pmap, except that the return value is a sequence of results ordered by *completion time*, not by input order." [pool f & arg-seqs] (pmap-boilerplate pool false f arg-seqs)) (defn pcalls "Like clojure.core.pcalls, except it takes a threadpool. For more detail on its parallelism and on its threadpool argument, see pmap." [pool & fs] (pmap pool #(%) fs)) (defn upcalls "Like clojure.core.pcalls, except it takes a threadpool and returns results ordered by completion time. For more detail on its parallelism and on its threadpool argument, see upmap." [pool & fs] (upmap pool #(%) fs)) (defmacro pvalues "Like clojure.core.pvalues, except it takes a threadpool. For more detail on its parallelism and on its threadpool argument, see pmap." [pool & exprs] `(pcalls ~pool ~@(for [e exprs] `(fn [] ~e)))) (defmacro upvalues "Like clojure.core.pvalues, except it takes a threadpool and returns results ordered by completion time. For more detail on its parallelism and on its threadpool argument, see upmap." [pool & exprs] `(upcalls ~pool ~@(for [e exprs] `(fn [] ~e)))) (defmacro pfor "A parallel version of for. It is like for, except it takes a threadpool and is parallel. For more detail on its parallelism and on its threadpool argument, see pmap. Note that while the body is executed in parallel, the bindings are executed in serial, so while this will call complex-computation in parallel: (pfor pool [i (range 1000)] (complex-computation i)) this will not have useful parallelism: (pfor pool [i (range 1000) :let [result (complex-computation i)]] result) You can use the special binding :priority (which must be the last binding) to set the priorities of the tasks. (upfor (priority-threadpool 10) [i (range 1000) :priority (inc i)] (complex-computation i)) " [pool bindings & body] (impl/pfor-internal pool bindings body `pmap)) (defmacro upfor "Like pfor, except the return value is a sequence of results ordered by *completion time*, not by input order." [pool bindings & body] (impl/pfor-internal pool bindings body `upmap)) (defmacro pdoseq "Like doseq, but in parallel. Unlike the streaming sequence functions (e.g. pmap), pdoseq blocks until all the work is done. Similar to pfor, only the body is done in parallel. For more details, see pfor." [pool bindings & body] `(dorun (upfor ~pool ~bindings (do ~@body)))) (defn prun! "Like run!, but in parallel. Unlike the streaming sequence functions (e.g. pmap), prun! blocks until all the work is done." [pool proc coll] (dorun (upmap pool proc coll)))
null
https://raw.githubusercontent.com/clj-commons/claypoole/a5c7114b60fdd6ec215b88e0db5094e063a37b7e/src/clj/com/climate/claypoole.clj
clojure
License, Version 2.0 (the "License"); you may not use this file except in -2.0 See the NOTICE file distributed with this work for additional information regarding copyright ownership. Unless required by applicable law or agreed or implied. See the License for the specific language governing permissions and limitations under the License. fully expand this typename. NOTE: Although I'm repeating myself, I list all the threadpool-factory arguments explicitly for API clarity. Use our thread factory options. Some of these tasks may be killed! If requested, run the future in serial. If requested, use the default threadpool. We have to get the casts right, or the compiler will choose the (.submit ^Runnable) call, which returns nil. We don't want that! If requested, run the future in serial. If requested, use the default threadpool. Use map to handle the argument sequences. We set this to true to stop realizing more tasks. Set up queues of tasks and results This is how we'll actually make things go. We can't directly make a future add itself to a queue. Instead, we use a promise for indirection. Try to run the task, but definitely add the future to the queue. If we've had an exception, stop making new tasks. Re-throw that throwable! Add the args to the function's metadata for prioritization. Start all the tasks in a real future, so we don't block. The driver thread reads from this sequence and ignores the result, just to get the side effect of blocking when the map's (imaginary) buffer is full. Read results as available.
The Climate Corporation licenses this file to you under under the Apache compliance with the License . You may obtain a copy of the License at to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express (ns com.climate.claypoole "Threadpool tools for Clojure. Claypoole provides parallel functions and macros that use threads from a pool and otherwise act like key builtins like future, pmap, for, and so on. See the file README.md for an introduction. A threadpool is just an ExecutorService with a fixed number of threads. In general, you can use your own ExecutorService in place of any threadpool, and you can treat a threadpool as you would any other ExecutorService." (:refer-clojure :exclude [future future-call pcalls pmap pvalues]) (:require [clojure.core :as core] [com.climate.claypoole.impl :as impl]) (:import [com.climate.claypoole.impl PriorityThreadpool PriorityThreadpoolImpl] [java.util.concurrent Callable ExecutorService Future CompletableFuture] [java.util.function Supplier])) (def ^:dynamic *parallel* "A dynamic binding to disable parallelism. If you do (binding [*parallel* false] body) then the body will have no parallelism. Disabling parallelism this way is handy for testing." true) (def ^:dynamic *default-pmap-buffer* "This is an advanced configuration option. You probably don't need to set this! When doing a pmap, Claypoole pushes input tasks into the threadpool. It normally tries to keep the threadpool full, plus it adds a buffer of size nthreads. If it can't find out the number of threads in the threadpool, it just tries to keep *default-pmap-buffer* tasks in the pool." 200) (defn ncpus "Get the number of available CPUs." [] (.. Runtime getRuntime availableProcessors)) #_{:clj-kondo/ignore [:unused-binding]} (defn thread-factory "Create a ThreadFactory with keyword options including thread daemon status :daemon, the thread name format :name (a string for format with one integer), and a thread priority :thread-priority. This is exposed as a public function because it's handy if you're instantiating your own ExecutorServices." [& {:keys [daemon thread-priority] pool-name :name :as args}] (->> args (apply concat) (apply impl/thread-factory))) (defn threadpool "Make a threadpool. It should be shutdown when no longer needed. A threadpool is just an ExecutorService with a fixed number of threads. In general, you can use your own ExecutorService in place of any threadpool, and you can treat a threadpool as you would any other ExecutorService. This takes optional keyword arguments: :daemon, a boolean indicating whether the threads are daemon threads, which will automatically die when the JVM exits, defaults to true) :name, a string giving the pool name, which will be the prefix of each thread name, resulting in threads named \"name-0\", \"name-1\", etc. Defaults to \"claypoole-[pool-number]\". :thread-priority, an integer in [Thread/MIN_PRIORITY, Thread/MAX_PRIORITY]. The effects of thread priority are system-dependent and should not be confused with Claypoole's priority threadpools that choose tasks based on a priority. For more info about Java thread priority see Note: Returns a ScheduledExecutorService rather than just an ExecutorService because it's the same thing with a few bonus features." NOTE : The Clojure compiler does n't seem to like the tests if we do n't ^java.util.concurrent.ScheduledExecutorService [n & {:keys [daemon thread-priority] pool-name :name :or {daemon true}}] (impl/threadpool n :daemon daemon :name pool-name :thread-priority thread-priority)) (defn priority-threadpool "Make a threadpool that chooses tasks based on their priorities. Assign priorities to tasks by wrapping the pool with with-priority or with-priority-fn. You can also set a default priority with keyword argument :default-priority. Otherwise, this uses the same keyword arguments as threadpool, and functions just like any other ExecutorService." ^com.climate.claypoole.impl.PriorityThreadpool [n & {:keys [default-priority] :as args :or {default-priority 0}}] (PriorityThreadpool. (PriorityThreadpoolImpl. n (impl/apply-map impl/thread-factory args) default-priority) (constantly default-priority))) (defn with-priority-fn "Make a priority-threadpool wrapper that uses a given priority function. The priority function is applied to a pmap'd function's arguments. e.g. (upmap (with-priority-fn pool (fn [x _] x)) + [6 5 4] [1 2 3]) will use pool to run tasks [(+ 6 1) (+ 5 2) (+ 4 3)] with priorities [6 5 4]." ^com.climate.claypoole.impl.PriorityThreadpool [^com.climate.claypoole.impl.PriorityThreadpool pool priority-fn] (impl/with-priority-fn pool priority-fn)) (defn with-priority "Make a priority-threadpool wrapper with a given fixed priority. All tasks run with this pool wrapper will have the given priority. e.g. (def t1 (future (with-priority p 1) 1)) (def t2 (future (with-priority p 2) 2)) (def t3 (future (with-priority p 3) 3)) will use pool p to run these tasks with priorities 1, 2, and 3 respectively. If you nest priorities, the outermost one \"wins\", so this task will be run at priority 3: (def wp (with-priority p 1)) (def t1 (future (with-priority (with-priority wp 2) 3) :result)) " ^java.util.concurrent.ExecutorService [^ExecutorService pool priority] (with-priority-fn pool (constantly priority))) (defn threadpool? "Returns true iff the argument is a threadpool." [pool] (instance? ExecutorService pool)) (defn priority-threadpool? "Returns true iff the argument is a priority-threadpool." [pool] (instance? PriorityThreadpool pool)) (defn shutdown "Syntactic sugar to stop a pool cleanly. This will stop the pool from accepting any new requests." [^ExecutorService pool] (when (not (= pool clojure.lang.Agent/soloExecutor)) (.shutdown pool))) (defn shutdown! "Syntactic sugar to forcibly shutdown a pool. This will kill any running threads in the pool!" [^ExecutorService pool] (when (not (= pool clojure.lang.Agent/soloExecutor)) (.shutdownNow pool))) (defn shutdown? "Syntactic sugar to test if a pool is shutdown." [^ExecutorService pool] (.isShutdown pool)) (defmacro with-shutdown! "Lets a threadpool from an initializer, then evaluates body in a try expression, calling shutdown! on the threadpool to forcibly shut it down at the end. The threadpool initializer may be a threadpool. Alternately, it can be any threadpool argument accepted by pmap, e.g. a number, :builtin, or :serial, in which case it will create a threadpool just as pmap would. Be aware that any unfinished jobs at the end of the body will be killed! Examples: (with-shutdown! [pool (threadpool 6)] (doall (pmap pool identity (range 1000)))) (with-shutdown! [pool1 6 pool2 :serial] (doall (pmap pool1 identity (range 1000)))) Bad example: (with-shutdown! [pool 6] (pmap pool identity (range 1000))) " [pool-syms-and-inits & body] (when-not (even? (count pool-syms-and-inits)) (throw (IllegalArgumentException. "with-shutdown! requires an even number of binding forms"))) (if (empty? pool-syms-and-inits) `(do ~@body) (let [[pool-sym pool-init & more] pool-syms-and-inits] `(let [pool-init# ~pool-init [_# ~pool-sym] (impl/->threadpool pool-init#)] (try (with-shutdown! ~more ~@body) (finally (when (threadpool? ~pool-sym) (shutdown! ~pool-sym)))))))) (defn serial? "Check if we should run computations on this threadpool in serial." [pool] (or (not *parallel*) (= pool :serial))) (defn future-call "Like clojure.core/future-call, but using a threadpool. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool f] (impl/validate-future-pool pool) (cond (serial? pool) (impl/dummy-future-call f) (= :builtin pool) (future-call clojure.lang.Agent/soloExecutor f) ^ExecutorService pool* pool ^Callable f* (impl/binding-conveyor-fn f) fut (.submit pool* f*)] Make an object just like Clojure futures . (reify clojure.lang.IDeref (deref [_] (impl/deref-future fut)) clojure.lang.IBlockingDeref (deref [_ timeout-ms timeout-val] (impl/deref-future fut timeout-ms timeout-val)) clojure.lang.IPending (isRealized [_] (.isDone fut)) Future (get [_] (.get fut)) (get [_ timeout unit] (.get fut timeout unit)) (isCancelled [_] (.isCancelled fut)) (isDone [_] (.isDone fut)) (cancel [_ interrupt?] (.cancel fut interrupt?)))))) (defmacro future "Like clojure.core/future, but using a threadpool. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool & body] `(future-call ~pool (^{:once true} fn ~'future-body [] ~@body))) (defn completable-future-call "Like clojure.core/future-call, but using a threadpool, and returns a CompletableFuture. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool f] (impl/validate-future-pool pool) (cond (serial? pool) (CompletableFuture/completedFuture (f)) (= :builtin pool) (completable-future-call clojure.lang.Agent/soloExecutor f) :else (let [f* (impl/binding-conveyor-fn f)] (CompletableFuture/supplyAsync (reify Supplier (get [_] (f*))) pool)))) (defmacro completable-future "Like clojure.core/future, but using a threadpool and returns a CompletableFuture. The threadpool may be one of 3 things: 1. An ExecutorService, e.g. one created by threadpool. 2. The keyword :builtin. In this case, the future will use the built-in agent threadpool, the same threadpool used by an ordinary clojure.core/future. 3. The keyword :serial. In this case, the computation will be performed in serial. This may be helpful during profiling, for example. " [pool & body] `(completable-future-call ~pool (^{:once true} fn ~'completable-future-body [] ~@body))) (defn- buffer-blocking-seq "Make a lazy sequence that blocks when the map's (imaginary) buffer is full." [pool unordered-results] (let [buffer-size (if-let [pool-size (impl/get-pool-size pool)] (* 2 pool-size) *default-pmap-buffer*)] (concat (repeat buffer-size nil) unordered-results))) (defn- pmap-core "Given functions to customize for pmap or upmap, do the hard work of pmap." [pool ordered? f arg-seqs] (let [[shutdown? pool] (impl/->threadpool pool) args (apply map vector (map impl/unchunk arg-seqs)) abort (atom false) [task-q tasks] (impl/queue-seq) [unordered-results-q unordered-results] (impl/queue-seq) start-task (fn [_i a] (let [p (promise)] (deliver p (future-call pool (with-meta #(try (apply f a) (catch Throwable t (reset! abort true) (throw t)) (finally (impl/queue-seq-add! unordered-results-q @p))) {:args a}))) @p)) driver (core/future (try (doseq [[i a _] (map vector (range) args (buffer-blocking-seq pool unordered-results)) :while (not @abort)] (impl/queue-seq-add! task-q (start-task i a))) (finally (impl/queue-seq-end! task-q) (when shutdown? (shutdown pool))))) result-seq (if ordered? tasks (map second (impl/lazy-co-read tasks unordered-results)))] (concat (map impl/deref-fixing-exceptions result-seq) Deref the read - future to get its exceptions , if it has any . (lazy-seq @driver)))) (defn- pmap-boilerplate "Do boilerplate pmap checks, then call the real pmap function." [pool ordered? f arg-seqs] (when (empty? arg-seqs) (throw (IllegalArgumentException. "pmap requires at least one sequence to map over"))) (if (serial? pool) (doall (apply map f arg-seqs)) (pmap-core pool ordered? f arg-seqs))) (defn pmap "Like clojure.core.pmap, except: 1. It is eager, returning an ordered sequence of completed results as they are available. 2. It uses a threadpool to control the desired level of parallelism. A word of caution: pmap will consume the entire input sequence and produce as much output as possible--if you pmap over (range) you'll get an Out of Memory Exception! Use this when you definitely want the work to be done. The threadpool may be one of 4 things: 1. An ExecutorService, e.g. one created by threadpool. 2. An integer. In this case, a threadpool will be created, and it will be destroyed when all the pmap tasks are complete. 3. The keyword :builtin. In this case, pmap will use the Clojure built-in agent threadpool. For pmap, that's probably not what you want, as you'll likely create a thread per task. 4. The keyword :serial. In this case, the computations will be performed in serial via (doall map). This may be helpful during profiling, for example. " [pool f & arg-seqs] (pmap-boilerplate pool true f arg-seqs)) (defn upmap "Like pmap, except that the return value is a sequence of results ordered by *completion time*, not by input order." [pool f & arg-seqs] (pmap-boilerplate pool false f arg-seqs)) (defn pcalls "Like clojure.core.pcalls, except it takes a threadpool. For more detail on its parallelism and on its threadpool argument, see pmap." [pool & fs] (pmap pool #(%) fs)) (defn upcalls "Like clojure.core.pcalls, except it takes a threadpool and returns results ordered by completion time. For more detail on its parallelism and on its threadpool argument, see upmap." [pool & fs] (upmap pool #(%) fs)) (defmacro pvalues "Like clojure.core.pvalues, except it takes a threadpool. For more detail on its parallelism and on its threadpool argument, see pmap." [pool & exprs] `(pcalls ~pool ~@(for [e exprs] `(fn [] ~e)))) (defmacro upvalues "Like clojure.core.pvalues, except it takes a threadpool and returns results ordered by completion time. For more detail on its parallelism and on its threadpool argument, see upmap." [pool & exprs] `(upcalls ~pool ~@(for [e exprs] `(fn [] ~e)))) (defmacro pfor "A parallel version of for. It is like for, except it takes a threadpool and is parallel. For more detail on its parallelism and on its threadpool argument, see pmap. Note that while the body is executed in parallel, the bindings are executed in serial, so while this will call complex-computation in parallel: (pfor pool [i (range 1000)] (complex-computation i)) this will not have useful parallelism: (pfor pool [i (range 1000) :let [result (complex-computation i)]] result) You can use the special binding :priority (which must be the last binding) to set the priorities of the tasks. (upfor (priority-threadpool 10) [i (range 1000) :priority (inc i)] (complex-computation i)) " [pool bindings & body] (impl/pfor-internal pool bindings body `pmap)) (defmacro upfor "Like pfor, except the return value is a sequence of results ordered by *completion time*, not by input order." [pool bindings & body] (impl/pfor-internal pool bindings body `upmap)) (defmacro pdoseq "Like doseq, but in parallel. Unlike the streaming sequence functions (e.g. pmap), pdoseq blocks until all the work is done. Similar to pfor, only the body is done in parallel. For more details, see pfor." [pool bindings & body] `(dorun (upfor ~pool ~bindings (do ~@body)))) (defn prun! "Like run!, but in parallel. Unlike the streaming sequence functions (e.g. pmap), prun! blocks until all the work is done." [pool proc coll] (dorun (upmap pool proc coll)))
0271916b0d838e8fb69706f03732eb7ab14fb159ad350080892d9c99356bbfa0
jaredly/reason-language-server
location.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Lexing let absname = ref false This reference should be in Clflags , but it would create an additional dependency and make bootstrapping more difficult . dependency and make bootstrapping Camlp4 more difficult. *) type t = Current.location = { loc_start: position; loc_end: position; loc_ghost: bool };; let in_file name = let loc = { pos_fname = name; pos_lnum = 1; pos_bol = 0; pos_cnum = -1; } in { loc_start = loc; loc_end = loc; loc_ghost = true } ;; let none = in_file "_none_";; let curr lexbuf = { loc_start = lexbuf.lex_start_p; loc_end = lexbuf.lex_curr_p; loc_ghost = false };; let init lexbuf fname = lexbuf.lex_curr_p <- { pos_fname = fname; pos_lnum = 1; pos_bol = 0; pos_cnum = 0; } ;; let symbol_rloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = false; };; let symbol_gloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = true; };; let rhs_loc n = { loc_start = Parsing.rhs_start_pos n; loc_end = Parsing.rhs_end_pos n; loc_ghost = false; };; let input_name = ref "_none_" let input_lexbuf = ref (None : lexbuf option) (* Terminal info *) let status = ref Terminfo.Uninitialised let num_loc_lines = ref 0 (* number of lines already printed after input *) let print_updating_num_loc_lines ppf f arg = let open Format in let out_functions = pp_get_formatter_out_functions ppf () in let out_string str start len = let rec count i c = if i = start + len then c else if String.get str i = '\n' then count (succ i) (succ c) else count (succ i) c in num_loc_lines := !num_loc_lines + count start 0 ; out_functions.out_string str start len in pp_set_formatter_out_functions ppf { out_functions with out_string } ; f ppf arg ; pp_print_flush ppf (); pp_set_formatter_out_functions ppf out_functions (* Highlight the locations using standout mode. *) let highlight_terminfo ppf num_lines lb locs = Format.pp_print_flush ppf (); (* avoid mixing Format and normal output *) Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in (* Do nothing if the buffer does not contain the whole phrase. *) if pos0 < 0 then raise Exit; (* Count number of lines in phrase *) let lines = ref !num_loc_lines in for i = pos0 to lb.lex_buffer_len - 1 do if Bytes.get lb.lex_buffer i = '\n' then incr lines done; (* If too many lines, give up *) if !lines >= num_lines - 2 then raise Exit; (* Move cursor up that number of lines *) flush stdout; Terminfo.backup stdout !lines; (* Print the input, switching to standout for the location *) let bol = ref false in print_string "# "; for pos = 0 to lb.lex_buffer_len - pos0 - 1 do if !bol then (print_string " "; bol := false); if List.exists (fun loc -> pos = loc.loc_start.pos_cnum) locs then Terminfo.standout stdout true; if List.exists (fun loc -> pos = loc.loc_end.pos_cnum) locs then Terminfo.standout stdout false; let c = Bytes.get lb.lex_buffer (pos + pos0) in print_char c; bol := (c = '\n') done; (* Make sure standout mode is over *) Terminfo.standout stdout false; (* Position cursor back to original location *) Terminfo.resume stdout !num_loc_lines; flush stdout (* Highlight the location by printing it again. *) let highlight_dumb ppf lb loc = Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in (* Do nothing if the buffer does not contain the whole phrase. *) if pos0 < 0 then raise Exit; let end_pos = lb.lex_buffer_len - pos0 - 1 in (* Determine line numbers for the start and end points *) let line_start = ref 0 and line_end = ref 0 in for pos = 0 to end_pos do if Bytes.get lb.lex_buffer (pos + pos0) = '\n' then begin if loc.loc_start.pos_cnum > pos then incr line_start; if loc.loc_end.pos_cnum > pos then incr line_end; end done; Print character location ( useful for Emacs ) Format.fprintf ppf "@[<v>Characters %i-%i:@," loc.loc_start.pos_cnum loc.loc_end.pos_cnum; (* Print the input, underlining the location *) Format.pp_print_string ppf " "; let line = ref 0 in let pos_at_bol = ref 0 in for pos = 0 to end_pos do match Bytes.get lb.lex_buffer (pos + pos0) with | '\n' -> if !line = !line_start && !line = !line_end then begin loc is on one line : underline location Format.fprintf ppf "@, "; for _i = !pos_at_bol to loc.loc_start.pos_cnum - 1 do Format.pp_print_char ppf ' ' done; for _i = loc.loc_start.pos_cnum to loc.loc_end.pos_cnum - 1 do Format.pp_print_char ppf '^' done end; if !line >= !line_start && !line <= !line_end then begin Format.fprintf ppf "@,"; if pos < loc.loc_end.pos_cnum then Format.pp_print_string ppf " " end; incr line; pos_at_bol := pos + 1 | '\r' -> () (* discard *) | c -> if !line = !line_start && !line = !line_end then loc is on one line : print whole line Format.pp_print_char ppf c else if !line = !line_start then first line of multiline loc : print a dot for each char before loc_start print a dot for each char before loc_start *) if pos < loc.loc_start.pos_cnum then Format.pp_print_char ppf '.' else Format.pp_print_char ppf c else if !line = !line_end then last line of multiline loc : print a dot for each char after loc_end , even whitespaces after loc_end, even whitespaces *) if pos < loc.loc_end.pos_cnum then Format.pp_print_char ppf c else Format.pp_print_char ppf '.' else if !line > !line_start && !line < !line_end then intermediate line of multiline loc : print whole line Format.pp_print_char ppf c done; Format.fprintf ppf "@]" (* Highlight the location using one of the supported modes. *) let rec highlight_locations ppf locs = match !status with Terminfo.Uninitialised -> status := Terminfo.setup stdout; highlight_locations ppf locs | Terminfo.Bad_term -> begin match !input_lexbuf with None -> false | Some lb -> let norepeat = try Sys.getenv "TERM" = "norepeat" with Not_found -> false in if norepeat then false else let loc1 = List.hd locs in try highlight_dumb ppf lb loc1; true with Exit -> false end | Terminfo.Good_term num_lines -> begin match !input_lexbuf with None -> false | Some lb -> try highlight_terminfo ppf num_lines lb locs; true with Exit -> false end (* Print the location in some way or another *) open Format let absolute_path s = (* This function could go into Filename *) let open Filename in let s = if is_relative s then concat (Sys.getcwd ()) s else s in (* Now simplify . and .. components *) let rec aux s = let base = basename s in let dir = dirname s in if dir = s then dir else if base = current_dir_name then aux dir else if base = parent_dir_name then dirname (aux dir) else concat (aux dir) base in aux s let show_filename file = if !absname then absolute_path file else file let print_filename ppf file = Format.fprintf ppf "%s" (show_filename file) let reset () = num_loc_lines := 0 let (msg_file, msg_line, msg_chars, msg_to, msg_colon) = ("File \"", "\", line ", ", characters ", "-", ":") (* return file, line, char from the given position *) let get_pos_info pos = (pos.pos_fname, pos.pos_lnum, pos.pos_cnum - pos.pos_bol) ;; let setup_colors () = Misc.Color.setup !Clflags.color let print_loc ppf loc = setup_colors (); let (file, line, startchar) = get_pos_info loc.loc_start in let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in if file = "//toplevel//" then begin if highlight_locations ppf [loc] then () else fprintf ppf "Characters %i-%i" loc.loc_start.pos_cnum loc.loc_end.pos_cnum end else begin fprintf ppf "%s@{<loc>%a%s%i" msg_file print_filename file msg_line line; if startchar >= 0 then fprintf ppf "%s%i%s%i" msg_chars startchar msg_to endchar; fprintf ppf "@}" end ;; let default_printer ppf loc = setup_colors (); if loc.loc_start.pos_fname = "//toplevel//" && highlight_locations ppf [loc] then () else fprintf ppf "@{<loc>%a@}%s@," print_loc loc msg_colon ;; let printer = ref default_printer let print ppf loc = !printer ppf loc let error_prefix = "Error" let warning_prefix = "Warning" let print_error_prefix ppf = setup_colors (); fprintf ppf "@{<error>%s@}" error_prefix; ;; let print_compact ppf loc = if loc.loc_start.pos_fname = "//toplevel//" && highlight_locations ppf [loc] then () else begin let (file, line, startchar) = get_pos_info loc.loc_start in let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in fprintf ppf "%a:%i" print_filename file line; if startchar >= 0 then fprintf ppf ",%i--%i" startchar endchar end ;; let print_error ppf loc = fprintf ppf "%a%t:" print loc print_error_prefix; ;; let print_error_cur_file ppf () = print_error ppf (in_file !input_name);; let default_warning_printer loc ppf w = match Warnings.report w with | `Inactive -> () | `Active { Warnings. number; message; is_error; sub_locs } -> setup_colors (); fprintf ppf "@[<v>"; print ppf loc; if is_error then fprintf ppf "%t (%s %d): %s@," print_error_prefix (String.uncapitalize_ascii warning_prefix) number message else fprintf ppf "@{<warning>%s@} %d: %s@," warning_prefix number message; List.iter (fun (loc, msg) -> if loc <> none then fprintf ppf " %a %s@," print loc msg ) sub_locs; fprintf ppf "@]" ;; let warning_printer = ref default_warning_printer ;; let print_warning loc ppf w = print_updating_num_loc_lines ppf (!warning_printer loc) w ;; let formatter_for_warnings = ref err_formatter;; let prerr_warning loc w = print_warning loc !formatter_for_warnings w;; let echo_eof () = print_newline (); incr num_loc_lines type 'a loc = 'a Current.loc = { txt : 'a; loc : t; } let mkloc txt loc = { txt ; loc } let mknoloc txt = mkloc txt none type error = { loc: t; msg: string; sub: error list; if_highlight: string; (* alternative message if locations are highlighted *) } let pp_ksprintf ?before k fmt = let buf = Buffer.create 64 in let ppf = Format.formatter_of_buffer buf in Misc.Color.set_color_tag_handling ppf; begin match before with | None -> () | Some f -> f ppf end; kfprintf (fun _ -> pp_print_flush ppf (); let msg = Buffer.contents buf in k msg) ppf fmt (* Shift the formatter's offset by the length of the error prefix, which is always added by the compiler after the message has been formatted *) let print_phanton_error_prefix ppf = Format.pp_print_as ppf (String.length error_prefix + 2 (* ": " *)) "" let errorf ?(loc = none) ?(sub = []) ?(if_highlight = "") fmt = pp_ksprintf ~before:print_phanton_error_prefix (fun msg -> {loc; msg; sub; if_highlight}) fmt let error ?(loc = none) ?(sub = []) ?(if_highlight = "") msg = {loc; msg; sub; if_highlight} let error_of_exn : (exn -> error option) list ref = ref [] let register_error_of_exn f = error_of_exn := f :: !error_of_exn exception Already_displayed_error = Warnings.Errors let error_of_exn exn = match exn with | Already_displayed_error -> Some `Already_displayed | _ -> let rec loop = function | [] -> None | f :: rest -> match f exn with | Some error -> Some (`Ok error) | None -> loop rest in loop !error_of_exn let rec default_error_reporter ppf ({loc; msg; sub; if_highlight} as err) = let highlighted = if if_highlight <> "" && loc.loc_start.pos_fname = "//toplevel//" then let rec collect_locs locs {loc; sub; _} = List.fold_left collect_locs (loc :: locs) sub in let locs = collect_locs [] err in highlight_locations ppf locs else false in if highlighted then Format.pp_print_string ppf if_highlight else begin fprintf ppf "@[<v>%a %s" print_error loc msg; List.iter (Format.fprintf ppf "@,@[<2>%a@]" default_error_reporter) sub; fprintf ppf "@]" end let error_reporter = ref default_error_reporter let report_error ppf err = print_updating_num_loc_lines ppf !error_reporter err ;; let error_of_printer loc print x = errorf ~loc "%a@?" print x let error_of_printer_file print x = error_of_printer (in_file !input_name) print x let () = register_error_of_exn (function | Sys_error msg -> Some (errorf ~loc:(in_file !input_name) "I/O error: %s" msg) | Misc.HookExnWrapper {error = e; hook_name; hook_info={Misc.sourcefile}} -> let sub = match error_of_exn e with | None | Some `Already_displayed -> error (Printexc.to_string e) | Some (`Ok err) -> err in Some (errorf ~loc:(in_file sourcefile) "In hook %S:" hook_name ~sub:[sub]) | _ -> None ) external reraise : exn -> 'a = "%reraise" let rec report_exception_rec n ppf exn = try match error_of_exn exn with | None -> reraise exn | Some `Already_displayed -> () | Some (`Ok err) -> fprintf ppf "@[%a@]@." report_error err with exn when n > 0 -> report_exception_rec (n-1) ppf exn let report_exception ppf exn = report_exception_rec 5 ppf exn exception Error of error let () = register_error_of_exn (function | Error e -> Some e | _ -> None ) let raise_errorf ?(loc = none) ?(sub = []) ?(if_highlight = "") = pp_ksprintf ~before:print_phanton_error_prefix (fun msg -> raise (Error ({loc; msg; sub; if_highlight}))) let deprecated ?(def = none) ?(use = none) loc msg = prerr_warning loc (Warnings.Deprecated (msg, def, use))
null
https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/406/location.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Terminal info number of lines already printed after input Highlight the locations using standout mode. avoid mixing Format and normal output Do nothing if the buffer does not contain the whole phrase. Count number of lines in phrase If too many lines, give up Move cursor up that number of lines Print the input, switching to standout for the location Make sure standout mode is over Position cursor back to original location Highlight the location by printing it again. Do nothing if the buffer does not contain the whole phrase. Determine line numbers for the start and end points Print the input, underlining the location discard Highlight the location using one of the supported modes. Print the location in some way or another This function could go into Filename Now simplify . and .. components return file, line, char from the given position alternative message if locations are highlighted Shift the formatter's offset by the length of the error prefix, which is always added by the compiler after the message has been formatted ": "
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Lexing let absname = ref false This reference should be in Clflags , but it would create an additional dependency and make bootstrapping more difficult . dependency and make bootstrapping Camlp4 more difficult. *) type t = Current.location = { loc_start: position; loc_end: position; loc_ghost: bool };; let in_file name = let loc = { pos_fname = name; pos_lnum = 1; pos_bol = 0; pos_cnum = -1; } in { loc_start = loc; loc_end = loc; loc_ghost = true } ;; let none = in_file "_none_";; let curr lexbuf = { loc_start = lexbuf.lex_start_p; loc_end = lexbuf.lex_curr_p; loc_ghost = false };; let init lexbuf fname = lexbuf.lex_curr_p <- { pos_fname = fname; pos_lnum = 1; pos_bol = 0; pos_cnum = 0; } ;; let symbol_rloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = false; };; let symbol_gloc () = { loc_start = Parsing.symbol_start_pos (); loc_end = Parsing.symbol_end_pos (); loc_ghost = true; };; let rhs_loc n = { loc_start = Parsing.rhs_start_pos n; loc_end = Parsing.rhs_end_pos n; loc_ghost = false; };; let input_name = ref "_none_" let input_lexbuf = ref (None : lexbuf option) let status = ref Terminfo.Uninitialised let print_updating_num_loc_lines ppf f arg = let open Format in let out_functions = pp_get_formatter_out_functions ppf () in let out_string str start len = let rec count i c = if i = start + len then c else if String.get str i = '\n' then count (succ i) (succ c) else count (succ i) c in num_loc_lines := !num_loc_lines + count start 0 ; out_functions.out_string str start len in pp_set_formatter_out_functions ppf { out_functions with out_string } ; f ppf arg ; pp_print_flush ppf (); pp_set_formatter_out_functions ppf out_functions let highlight_terminfo ppf num_lines lb locs = Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in if pos0 < 0 then raise Exit; let lines = ref !num_loc_lines in for i = pos0 to lb.lex_buffer_len - 1 do if Bytes.get lb.lex_buffer i = '\n' then incr lines done; if !lines >= num_lines - 2 then raise Exit; flush stdout; Terminfo.backup stdout !lines; let bol = ref false in print_string "# "; for pos = 0 to lb.lex_buffer_len - pos0 - 1 do if !bol then (print_string " "; bol := false); if List.exists (fun loc -> pos = loc.loc_start.pos_cnum) locs then Terminfo.standout stdout true; if List.exists (fun loc -> pos = loc.loc_end.pos_cnum) locs then Terminfo.standout stdout false; let c = Bytes.get lb.lex_buffer (pos + pos0) in print_char c; bol := (c = '\n') done; Terminfo.standout stdout false; Terminfo.resume stdout !num_loc_lines; flush stdout let highlight_dumb ppf lb loc = Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer . let pos0 = -lb.lex_abs_pos in if pos0 < 0 then raise Exit; let end_pos = lb.lex_buffer_len - pos0 - 1 in let line_start = ref 0 and line_end = ref 0 in for pos = 0 to end_pos do if Bytes.get lb.lex_buffer (pos + pos0) = '\n' then begin if loc.loc_start.pos_cnum > pos then incr line_start; if loc.loc_end.pos_cnum > pos then incr line_end; end done; Print character location ( useful for Emacs ) Format.fprintf ppf "@[<v>Characters %i-%i:@," loc.loc_start.pos_cnum loc.loc_end.pos_cnum; Format.pp_print_string ppf " "; let line = ref 0 in let pos_at_bol = ref 0 in for pos = 0 to end_pos do match Bytes.get lb.lex_buffer (pos + pos0) with | '\n' -> if !line = !line_start && !line = !line_end then begin loc is on one line : underline location Format.fprintf ppf "@, "; for _i = !pos_at_bol to loc.loc_start.pos_cnum - 1 do Format.pp_print_char ppf ' ' done; for _i = loc.loc_start.pos_cnum to loc.loc_end.pos_cnum - 1 do Format.pp_print_char ppf '^' done end; if !line >= !line_start && !line <= !line_end then begin Format.fprintf ppf "@,"; if pos < loc.loc_end.pos_cnum then Format.pp_print_string ppf " " end; incr line; pos_at_bol := pos + 1 | c -> if !line = !line_start && !line = !line_end then loc is on one line : print whole line Format.pp_print_char ppf c else if !line = !line_start then first line of multiline loc : print a dot for each char before loc_start print a dot for each char before loc_start *) if pos < loc.loc_start.pos_cnum then Format.pp_print_char ppf '.' else Format.pp_print_char ppf c else if !line = !line_end then last line of multiline loc : print a dot for each char after loc_end , even whitespaces after loc_end, even whitespaces *) if pos < loc.loc_end.pos_cnum then Format.pp_print_char ppf c else Format.pp_print_char ppf '.' else if !line > !line_start && !line < !line_end then intermediate line of multiline loc : print whole line Format.pp_print_char ppf c done; Format.fprintf ppf "@]" let rec highlight_locations ppf locs = match !status with Terminfo.Uninitialised -> status := Terminfo.setup stdout; highlight_locations ppf locs | Terminfo.Bad_term -> begin match !input_lexbuf with None -> false | Some lb -> let norepeat = try Sys.getenv "TERM" = "norepeat" with Not_found -> false in if norepeat then false else let loc1 = List.hd locs in try highlight_dumb ppf lb loc1; true with Exit -> false end | Terminfo.Good_term num_lines -> begin match !input_lexbuf with None -> false | Some lb -> try highlight_terminfo ppf num_lines lb locs; true with Exit -> false end open Format let open Filename in let s = if is_relative s then concat (Sys.getcwd ()) s else s in let rec aux s = let base = basename s in let dir = dirname s in if dir = s then dir else if base = current_dir_name then aux dir else if base = parent_dir_name then dirname (aux dir) else concat (aux dir) base in aux s let show_filename file = if !absname then absolute_path file else file let print_filename ppf file = Format.fprintf ppf "%s" (show_filename file) let reset () = num_loc_lines := 0 let (msg_file, msg_line, msg_chars, msg_to, msg_colon) = ("File \"", "\", line ", ", characters ", "-", ":") let get_pos_info pos = (pos.pos_fname, pos.pos_lnum, pos.pos_cnum - pos.pos_bol) ;; let setup_colors () = Misc.Color.setup !Clflags.color let print_loc ppf loc = setup_colors (); let (file, line, startchar) = get_pos_info loc.loc_start in let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in if file = "//toplevel//" then begin if highlight_locations ppf [loc] then () else fprintf ppf "Characters %i-%i" loc.loc_start.pos_cnum loc.loc_end.pos_cnum end else begin fprintf ppf "%s@{<loc>%a%s%i" msg_file print_filename file msg_line line; if startchar >= 0 then fprintf ppf "%s%i%s%i" msg_chars startchar msg_to endchar; fprintf ppf "@}" end ;; let default_printer ppf loc = setup_colors (); if loc.loc_start.pos_fname = "//toplevel//" && highlight_locations ppf [loc] then () else fprintf ppf "@{<loc>%a@}%s@," print_loc loc msg_colon ;; let printer = ref default_printer let print ppf loc = !printer ppf loc let error_prefix = "Error" let warning_prefix = "Warning" let print_error_prefix ppf = setup_colors (); fprintf ppf "@{<error>%s@}" error_prefix; ;; let print_compact ppf loc = if loc.loc_start.pos_fname = "//toplevel//" && highlight_locations ppf [loc] then () else begin let (file, line, startchar) = get_pos_info loc.loc_start in let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in fprintf ppf "%a:%i" print_filename file line; if startchar >= 0 then fprintf ppf ",%i--%i" startchar endchar end ;; let print_error ppf loc = fprintf ppf "%a%t:" print loc print_error_prefix; ;; let print_error_cur_file ppf () = print_error ppf (in_file !input_name);; let default_warning_printer loc ppf w = match Warnings.report w with | `Inactive -> () | `Active { Warnings. number; message; is_error; sub_locs } -> setup_colors (); fprintf ppf "@[<v>"; print ppf loc; if is_error then fprintf ppf "%t (%s %d): %s@," print_error_prefix (String.uncapitalize_ascii warning_prefix) number message else fprintf ppf "@{<warning>%s@} %d: %s@," warning_prefix number message; List.iter (fun (loc, msg) -> if loc <> none then fprintf ppf " %a %s@," print loc msg ) sub_locs; fprintf ppf "@]" ;; let warning_printer = ref default_warning_printer ;; let print_warning loc ppf w = print_updating_num_loc_lines ppf (!warning_printer loc) w ;; let formatter_for_warnings = ref err_formatter;; let prerr_warning loc w = print_warning loc !formatter_for_warnings w;; let echo_eof () = print_newline (); incr num_loc_lines type 'a loc = 'a Current.loc = { txt : 'a; loc : t; } let mkloc txt loc = { txt ; loc } let mknoloc txt = mkloc txt none type error = { loc: t; msg: string; sub: error list; } let pp_ksprintf ?before k fmt = let buf = Buffer.create 64 in let ppf = Format.formatter_of_buffer buf in Misc.Color.set_color_tag_handling ppf; begin match before with | None -> () | Some f -> f ppf end; kfprintf (fun _ -> pp_print_flush ppf (); let msg = Buffer.contents buf in k msg) ppf fmt let print_phanton_error_prefix ppf = let errorf ?(loc = none) ?(sub = []) ?(if_highlight = "") fmt = pp_ksprintf ~before:print_phanton_error_prefix (fun msg -> {loc; msg; sub; if_highlight}) fmt let error ?(loc = none) ?(sub = []) ?(if_highlight = "") msg = {loc; msg; sub; if_highlight} let error_of_exn : (exn -> error option) list ref = ref [] let register_error_of_exn f = error_of_exn := f :: !error_of_exn exception Already_displayed_error = Warnings.Errors let error_of_exn exn = match exn with | Already_displayed_error -> Some `Already_displayed | _ -> let rec loop = function | [] -> None | f :: rest -> match f exn with | Some error -> Some (`Ok error) | None -> loop rest in loop !error_of_exn let rec default_error_reporter ppf ({loc; msg; sub; if_highlight} as err) = let highlighted = if if_highlight <> "" && loc.loc_start.pos_fname = "//toplevel//" then let rec collect_locs locs {loc; sub; _} = List.fold_left collect_locs (loc :: locs) sub in let locs = collect_locs [] err in highlight_locations ppf locs else false in if highlighted then Format.pp_print_string ppf if_highlight else begin fprintf ppf "@[<v>%a %s" print_error loc msg; List.iter (Format.fprintf ppf "@,@[<2>%a@]" default_error_reporter) sub; fprintf ppf "@]" end let error_reporter = ref default_error_reporter let report_error ppf err = print_updating_num_loc_lines ppf !error_reporter err ;; let error_of_printer loc print x = errorf ~loc "%a@?" print x let error_of_printer_file print x = error_of_printer (in_file !input_name) print x let () = register_error_of_exn (function | Sys_error msg -> Some (errorf ~loc:(in_file !input_name) "I/O error: %s" msg) | Misc.HookExnWrapper {error = e; hook_name; hook_info={Misc.sourcefile}} -> let sub = match error_of_exn e with | None | Some `Already_displayed -> error (Printexc.to_string e) | Some (`Ok err) -> err in Some (errorf ~loc:(in_file sourcefile) "In hook %S:" hook_name ~sub:[sub]) | _ -> None ) external reraise : exn -> 'a = "%reraise" let rec report_exception_rec n ppf exn = try match error_of_exn exn with | None -> reraise exn | Some `Already_displayed -> () | Some (`Ok err) -> fprintf ppf "@[%a@]@." report_error err with exn when n > 0 -> report_exception_rec (n-1) ppf exn let report_exception ppf exn = report_exception_rec 5 ppf exn exception Error of error let () = register_error_of_exn (function | Error e -> Some e | _ -> None ) let raise_errorf ?(loc = none) ?(sub = []) ?(if_highlight = "") = pp_ksprintf ~before:print_phanton_error_prefix (fun msg -> raise (Error ({loc; msg; sub; if_highlight}))) let deprecated ?(def = none) ?(use = none) loc msg = prerr_warning loc (Warnings.Deprecated (msg, def, use))
98afca3efad9f9dff56ee7cc0cc49894caf14b7913121ced34c978ecb610dd87
BranchTaken/Hemlock
test_fold2_until.ml
open! Basis.Rudiments open! Basis open Ordset let test () = let test ms0 ms1 = begin let ordset0 = of_list (module Uns) ms0 in let ordset1 = of_list (module Uns) ms1 in let ordset = union ordset0 ordset1 in let ms = to_list ordset in (* Compute the number of elements in the triangle defined by folding n times, each time * terminating upon encounter of a distinct set member. The size of the triangle is insensitive * to fold order. *) assert ((List.length ms) = (length ordset)); let n = length ordset in let triangle_sum = List.fold ms ~init:0L ~f:(fun accum m -> accum + fold2_until ordset0 ordset1 ~init:0L ~f:(fun accum a0_opt a1_opt -> match a0_opt, a1_opt with | Some a, Some _ | Some a, None | None, Some a -> (succ accum), (m = a) | None, None -> not_reached () ) ) in assert (triangle_sum = (n + 1L) * n / 2L); end in let test_lists = [ []; [0L]; [0L; 1L]; [0L; 1L; 2L]; [0L; 1L; 66L]; [0L; 1L; 66L; 91L]; ] in List.iteri test_lists ~f:(fun i ms0 -> List.iteri test_lists ~f:(fun j ms1 -> if i <= j then test ms0 ms1 ) ) let _ = test ()
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/07922d4658ca6ecf37dfd46f5aca31c8b58e06e4/bootstrap/test/basis/ordset/test_fold2_until.ml
ocaml
Compute the number of elements in the triangle defined by folding n times, each time * terminating upon encounter of a distinct set member. The size of the triangle is insensitive * to fold order.
open! Basis.Rudiments open! Basis open Ordset let test () = let test ms0 ms1 = begin let ordset0 = of_list (module Uns) ms0 in let ordset1 = of_list (module Uns) ms1 in let ordset = union ordset0 ordset1 in let ms = to_list ordset in assert ((List.length ms) = (length ordset)); let n = length ordset in let triangle_sum = List.fold ms ~init:0L ~f:(fun accum m -> accum + fold2_until ordset0 ordset1 ~init:0L ~f:(fun accum a0_opt a1_opt -> match a0_opt, a1_opt with | Some a, Some _ | Some a, None | None, Some a -> (succ accum), (m = a) | None, None -> not_reached () ) ) in assert (triangle_sum = (n + 1L) * n / 2L); end in let test_lists = [ []; [0L]; [0L; 1L]; [0L; 1L; 2L]; [0L; 1L; 66L]; [0L; 1L; 66L; 91L]; ] in List.iteri test_lists ~f:(fun i ms0 -> List.iteri test_lists ~f:(fun j ms1 -> if i <= j then test ms0 ms1 ) ) let _ = test ()
a8d3056dc4cf8f0c36841d4423536f271db49b9c44e9858f5edcae174656bf24
ghcjs/ghcjs-base
Array.hs
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI #-} module JavaScript.Array ( JSArray , MutableJSArray , create , length , lengthIO , null , fromList , fromListIO , toList , toListIO , index, (!) , read , write , append , push , pop , unshift , shift , reverse , take , takeIO , drop , dropIO , slice , sliceIO , freeze , unsafeFreeze , thaw , unsafeThaw ) where import Prelude hiding (length, drop, read, take, reverse, null) import qualified GHCJS.Prim as Prim import GHCJS.Types import JavaScript.Array.Internal (JSArray(..)) import JavaScript.Array.Internal import qualified JavaScript . Array . Internal as I fromList : : [ JSVal ] - > IO ( JSArray a ) fromList xs = fmap JSArray ( I.fromList xs ) { - # INLINE fromList # fromList :: [JSVal] -> IO (JSArray a) fromList xs = fmap JSArray (I.fromList xs) {-# INLINE fromList #-} toList :: JSArray a -> IO [JSVal] toList (JSArray x) = I.toList x # INLINE toList # create :: IO (JSArray a) create = fmap JSArray I.create # INLINE create # length :: JSArray a -> IO Int length (JSArray x) = I.length x # INLINE length # append :: JSArray a -> JSArray a -> IO (JSArray a) append (JSArray x) (JSArray y) = fmap JSArray (I.append x y) # INLINE append # -} (!) :: JSArray -> Int -> JSVal x ! n = index n x {-# INLINE (!) #-} index : : Int - > JSArray a - > IO JSVal index n ( JSArray x ) = I.index n x { - # INLINE index # index :: Int -> JSArray a -> IO JSVal index n (JSArray x) = I.index n x {-# INLINE index #-} write :: Int -> JSVal -> JSArray a -> IO () write n e (JSArray x) = I.write n e x # INLINE write # drop :: Int -> JSArray a -> IO (JSArray a) drop n (JSArray x) = fmap JSArray (I.drop n x) {-# INLINE drop #-} take :: Int -> JSArray a -> IO (JSArray a) take n (JSArray x) = fmap JSArray (I.take n x) {-# INLINE take #-} slice :: Int -> Int -> JSArray a -> IO (JSArray a) slice s n (JSArray x) = fmap JSArray (I.slice s n x) # INLINE slice # push :: JSVal -> JSArray a -> IO () push e (JSArray x) = I.push e x # INLINE push # pop :: JSArray a -> IO JSVal pop (JSArray x) = I.pop x # INLINE pop # unshift :: JSVal -> JSArray a -> IO () unshift e (JSArray x) = I.unshift e x # INLINE unshift # shift :: JSArray a -> IO JSVal shift (JSArray x) = I.shift x {-# INLINE shift #-} reverse :: JSArray a -> IO () reverse (JSArray x) = I.reverse x # INLINE reverse # -}
null
https://raw.githubusercontent.com/ghcjs/ghcjs-base/18f31dec5d9eae1ef35ff8bbf163394942efd227/JavaScript/Array.hs
haskell
# LANGUAGE ForeignFunctionInterface, JavaScriptFFI # # INLINE fromList # # INLINE (!) # # INLINE index # # INLINE drop # # INLINE take # # INLINE shift #
module JavaScript.Array ( JSArray , MutableJSArray , create , length , lengthIO , null , fromList , fromListIO , toList , toListIO , index, (!) , read , write , append , push , pop , unshift , shift , reverse , take , takeIO , drop , dropIO , slice , sliceIO , freeze , unsafeFreeze , thaw , unsafeThaw ) where import Prelude hiding (length, drop, read, take, reverse, null) import qualified GHCJS.Prim as Prim import GHCJS.Types import JavaScript.Array.Internal (JSArray(..)) import JavaScript.Array.Internal import qualified JavaScript . Array . Internal as I fromList : : [ JSVal ] - > IO ( JSArray a ) fromList xs = fmap JSArray ( I.fromList xs ) { - # INLINE fromList # fromList :: [JSVal] -> IO (JSArray a) fromList xs = fmap JSArray (I.fromList xs) toList :: JSArray a -> IO [JSVal] toList (JSArray x) = I.toList x # INLINE toList # create :: IO (JSArray a) create = fmap JSArray I.create # INLINE create # length :: JSArray a -> IO Int length (JSArray x) = I.length x # INLINE length # append :: JSArray a -> JSArray a -> IO (JSArray a) append (JSArray x) (JSArray y) = fmap JSArray (I.append x y) # INLINE append # -} (!) :: JSArray -> Int -> JSVal x ! n = index n x index : : Int - > JSArray a - > IO JSVal index n ( JSArray x ) = I.index n x { - # INLINE index # index :: Int -> JSArray a -> IO JSVal index n (JSArray x) = I.index n x write :: Int -> JSVal -> JSArray a -> IO () write n e (JSArray x) = I.write n e x # INLINE write # drop :: Int -> JSArray a -> IO (JSArray a) drop n (JSArray x) = fmap JSArray (I.drop n x) take :: Int -> JSArray a -> IO (JSArray a) take n (JSArray x) = fmap JSArray (I.take n x) slice :: Int -> Int -> JSArray a -> IO (JSArray a) slice s n (JSArray x) = fmap JSArray (I.slice s n x) # INLINE slice # push :: JSVal -> JSArray a -> IO () push e (JSArray x) = I.push e x # INLINE push # pop :: JSArray a -> IO JSVal pop (JSArray x) = I.pop x # INLINE pop # unshift :: JSVal -> JSArray a -> IO () unshift e (JSArray x) = I.unshift e x # INLINE unshift # shift :: JSArray a -> IO JSVal shift (JSArray x) = I.shift x reverse :: JSArray a -> IO () reverse (JSArray x) = I.reverse x # INLINE reverse # -}
4136256a54be37bd35ae4817cf4c5723af921df4540bcea11e997148772b4288
unison-code/unison
RelocateDefines.hs
| Copyright : Copyright ( c ) 2016 , RISE SICS AB License : BSD3 ( see the LICENSE file ) Maintainer : Copyright : Copyright (c) 2016, RISE SICS AB License : BSD3 (see the LICENSE file) Maintainer : -} Main authors : < > This file is part of Unison , see -code.github.io Main authors: Roberto Castaneda Lozano <> This file is part of Unison, see -code.github.io -} # LANGUAGE FlexibleContexts , PatternGuards # module Unison.Tools.Import.RelocateDefines (relocateDefines) where import Data.List import Common.Util import Unison relocateDefines f _target = fixpoint relocateDefine f relocateDefine f @ Function {fCode = code} | Nothing <- findRelocatableDefine code = f relocateDefine f @ Function {fCode = code} = let (Just d) = findRelocatableDefine code u = singleUser d (flatten code) code' = moveGloballyOperation d before (isIdOf u) code in f {fCode = code'} findRelocatableDefine code = find (isRelocatableDefine fCode) fCode where fCode = flatten code isRelocatableDefine code i | isDefine i && length (oDefs i) == 1 = case users (oSingleDef i) code of [u] -> let is = between (isIdOf i) (isIdOf u) code in not (isPhi u) && any (not . isDefine) is _ -> False | otherwise = False singleUser i code = fromSingleton (users (oSingleDef i) code)
null
https://raw.githubusercontent.com/unison-code/unison/9f8caf78230f956a57b50a327f8d1dca5839bf64/src/unison/src/Unison/Tools/Import/RelocateDefines.hs
haskell
| Copyright : Copyright ( c ) 2016 , RISE SICS AB License : BSD3 ( see the LICENSE file ) Maintainer : Copyright : Copyright (c) 2016, RISE SICS AB License : BSD3 (see the LICENSE file) Maintainer : -} Main authors : < > This file is part of Unison , see -code.github.io Main authors: Roberto Castaneda Lozano <> This file is part of Unison, see -code.github.io -} # LANGUAGE FlexibleContexts , PatternGuards # module Unison.Tools.Import.RelocateDefines (relocateDefines) where import Data.List import Common.Util import Unison relocateDefines f _target = fixpoint relocateDefine f relocateDefine f @ Function {fCode = code} | Nothing <- findRelocatableDefine code = f relocateDefine f @ Function {fCode = code} = let (Just d) = findRelocatableDefine code u = singleUser d (flatten code) code' = moveGloballyOperation d before (isIdOf u) code in f {fCode = code'} findRelocatableDefine code = find (isRelocatableDefine fCode) fCode where fCode = flatten code isRelocatableDefine code i | isDefine i && length (oDefs i) == 1 = case users (oSingleDef i) code of [u] -> let is = between (isIdOf i) (isIdOf u) code in not (isPhi u) && any (not . isDefine) is _ -> False | otherwise = False singleUser i code = fromSingleton (users (oSingleDef i) code)
2900af965e7786bd812a369c63a7ab16c2770fb92f3c29e3b591b847fe19d6e2
avsm/mirage-duniverse
ping.ml
let src = let src = Logs.Src.create "ping" ~doc:"Mirage ping" in Logs.Src.set_level src (Some Logs.Info); src module Log = (val Logs.src_log src : Logs.LOG) Construct a payload buffer of a given size let make_payload ~size () = let buf = Cstruct.create size in let pattern = "plz reply i'm so lonely" in for i = 0 to Cstruct.len buf - 1 do Cstruct.set_char buf i pattern.[i mod (String.length pattern)] done; buf let seq_no_to_send_time = Hashtbl.create 7 let nr_transmitted = ref 0 let nr_received = ref 0 let min_ms = ref max_float let max_ms = ref 0. (* to compute the standard deviation, we store the sum and the sum of squares *) let sum_ms = ref 0. let sum_ms_2 = ref 0. (* Send ICMP ECHO_REQUEST packets forever *) let send_echo_requests ~stack ~payload ~dst () = let rec send seq_no = let open Lwt.Infix in let id_no = 0x1234 in let req = Icmpv4_packet.({code = 0x00; ty = Icmpv4_wire.Echo_request; subheader = Id_and_seq (id_no, seq_no)}) in let header = Icmpv4_packet.Marshal.make_cstruct req ~payload in let echo_request = Cstruct.concat [ header; payload ] in Log.debug (fun f -> f "Sending ECHO_REQUEST id_no=%d seq_no=%d to %s" id_no seq_no (Ipaddr.V4.to_string dst)); Icmpv4_socket.write stack ~dst echo_request >>= function | Ok () -> Hashtbl.replace seq_no_to_send_time seq_no (Unix.gettimeofday ()); incr nr_transmitted; Lwt_unix.sleep 1. >>= fun () -> send (seq_no + 1) | Error e -> Log.err (fun f -> f "Error sending ICMP to %s: %a" (Ipaddr.V4.to_string dst) Icmpv4_socket.pp_error e); Lwt.return_unit in send 0 (* Return a thread and a receiver callback. The thread is woken up when we have received [count] packets *) let make_receiver ~count ~payload () = let open Lwt.Infix in let finished_t, finished_u = Lwt.task () in let callback buf = Log.debug (fun f -> f "Received IP %a" Cstruct.hexdump_pp buf); match Ipv4_packet.Unmarshal.of_cstruct buf with | Error msg -> Log.err (fun f -> f "Error unmarshalling IP datagram: %s" msg); Lwt.return_unit | Ok (ip, ip_payload) -> match Icmpv4_packet.Unmarshal.of_cstruct ip_payload with | Error msg -> Log.err (fun f -> f "Error unmarshalling ICMP message: %s" msg); Lwt.return_unit | Ok (reply, received_payload) -> let open Icmpv4_packet in begin match reply.subheader with | Next_hop_mtu _ | Pointer _ | Address _ | Unused -> Log.err (fun f -> f "received an ICMP message which wasn't an echo-request or reply"); Lwt.return_unit | Id_and_seq (id, seq) -> if reply.code <> 0 then Log.err (fun f -> f "received an ICMP ECHO_REQUEST with reply.code=%d" reply.code); if not(Cstruct.equal payload received_payload) then Log.err (fun f -> f "received an ICMP ECHO_REQUEST with an unexpected payload"); if not(Hashtbl.mem seq_no_to_send_time seq) then Log.err (fun f -> f "received an ICMP ECHO_REQUEST with an unexpected sequence number") else begin let secs = Unix.gettimeofday () -. (Hashtbl.find seq_no_to_send_time seq) in Hashtbl.remove seq_no_to_send_time seq; let ms = secs *. 1000.0 in Printf.printf "%d bytes from %s: icmp_seq=%d ttl=%d time=%f ms\n%!" (Cstruct.len payload) (Ipaddr.V4.to_string ip.Ipv4_packet.src) seq ip.Ipv4_packet.ttl ms; incr nr_received; min_ms := min !min_ms ms; max_ms := max !max_ms ms; sum_ms := !sum_ms +. ms; sum_ms_2 := !sum_ms_2 +. (ms *. ms); if Some !nr_received = count then begin Log.debug (fun f -> f "Finished after %d packets received" !nr_received); Lwt.wakeup_later finished_u (); end end; Lwt.return_unit end in finished_t, callback let ping (count:int option) (size:int) (timeout:int option) dst = let dst = Ipaddr.V4.of_string_exn dst in Lwt_main.run begin let open Lwt.Infix in let payload = make_payload ~size () in Icmpv4_socket.connect () >>= fun stack -> let finished, on_icmp_receive = make_receiver ~count ~payload () in let me = Ipaddr.V4.any in let listener = Icmpv4_socket.listen stack me on_icmp_receive in let timeout = match timeout with | None -> let forever, _ = Lwt.task () in forever | Some t -> Lwt_unix.sleep (float_of_int t) >>= fun () -> Log.debug (fun f -> f "Timed-out"); Lwt.return_unit in let sender = send_echo_requests ~stack ~payload ~dst () in let interrupted, interrupted_u = Lwt.task () in ignore(Lwt_unix.on_signal Sys.sigint (fun _ -> Lwt.wakeup_later interrupted_u ())); Lwt.pick [ finished; timeout; interrupted; listener; sender; ] >>= fun () -> Printf.printf "--- %s ping statistics ---\n" (Ipaddr.V4.to_string dst); let n = float_of_int (!nr_received) in let percent_loss = 100. *. (float_of_int (!nr_transmitted) -. n) /. (float_of_int (!nr_transmitted)) in Printf.printf "%d packets transmitted, %d packets received, %0.0f%% packet loss\n" !nr_transmitted !nr_received percent_loss; let avg_ms = !sum_ms /. n in let variance_ms = 1. /. (n -. 1.) *. (!sum_ms_2) -. 1. /. (n *. (n -. 1.)) *. (!sum_ms) *. (!sum_ms) in let stddev_ms = sqrt variance_ms in Printf.printf "round-trip min/avg/max/stddev = %.03f/%.03f/%.03f/%.03f ms\n" !min_ms avg_ms !max_ms stddev_ms; Lwt.return (`Ok ()) end open Cmdliner let exit_after_success = let doc = "Exit successfully after receiving one reply packet." in Arg.(value & flag & info [ "o" ] ~doc) let count = let doc = "Stop after sending (and receiving) count ECHO_RESPONSE packets. If not specified, ping will continue until interrupted." in Arg.(value & opt (some int) None & info [ "c" ] ~doc) let size = let doc = "Specify the number of data bytes to be sent." in Arg.(value & opt int 56 & info [ "s" ] ~doc) let timeout = let doc = "Specify a timeout, before ping exits regardless of how many packets have been received." in Arg.(value & opt (some int) None & info [ "t" ] ~doc) let destination = let doc ="Hostname or IP address of destination host" in Arg.(value & pos 0 string "" & info [] ~doc) let cmd = let doc = "Send ICMP ECHO_REQUEST packets and listen for ECHO_RESPONSES" in let man = [ `S "DESCRIPTION"; `P "Send a sequence of ICMP ECHO_REQUEST packets to a network host and count the responses. When the program exits, display some statistics."; ] in Term.(ret(pure ping $ count $ size $ timeout $ destination)), Term.info "ping" ~doc ~man let _ = Logs.set_reporter (Logs_fmt.reporter ()); match Term.eval cmd with | `Error _ -> exit 1 | _ -> exit 0
null
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tcpip/examples/ping/ping.ml
ocaml
to compute the standard deviation, we store the sum and the sum of squares Send ICMP ECHO_REQUEST packets forever Return a thread and a receiver callback. The thread is woken up when we have received [count] packets
let src = let src = Logs.Src.create "ping" ~doc:"Mirage ping" in Logs.Src.set_level src (Some Logs.Info); src module Log = (val Logs.src_log src : Logs.LOG) Construct a payload buffer of a given size let make_payload ~size () = let buf = Cstruct.create size in let pattern = "plz reply i'm so lonely" in for i = 0 to Cstruct.len buf - 1 do Cstruct.set_char buf i pattern.[i mod (String.length pattern)] done; buf let seq_no_to_send_time = Hashtbl.create 7 let nr_transmitted = ref 0 let nr_received = ref 0 let min_ms = ref max_float let max_ms = ref 0. let sum_ms = ref 0. let sum_ms_2 = ref 0. let send_echo_requests ~stack ~payload ~dst () = let rec send seq_no = let open Lwt.Infix in let id_no = 0x1234 in let req = Icmpv4_packet.({code = 0x00; ty = Icmpv4_wire.Echo_request; subheader = Id_and_seq (id_no, seq_no)}) in let header = Icmpv4_packet.Marshal.make_cstruct req ~payload in let echo_request = Cstruct.concat [ header; payload ] in Log.debug (fun f -> f "Sending ECHO_REQUEST id_no=%d seq_no=%d to %s" id_no seq_no (Ipaddr.V4.to_string dst)); Icmpv4_socket.write stack ~dst echo_request >>= function | Ok () -> Hashtbl.replace seq_no_to_send_time seq_no (Unix.gettimeofday ()); incr nr_transmitted; Lwt_unix.sleep 1. >>= fun () -> send (seq_no + 1) | Error e -> Log.err (fun f -> f "Error sending ICMP to %s: %a" (Ipaddr.V4.to_string dst) Icmpv4_socket.pp_error e); Lwt.return_unit in send 0 let make_receiver ~count ~payload () = let open Lwt.Infix in let finished_t, finished_u = Lwt.task () in let callback buf = Log.debug (fun f -> f "Received IP %a" Cstruct.hexdump_pp buf); match Ipv4_packet.Unmarshal.of_cstruct buf with | Error msg -> Log.err (fun f -> f "Error unmarshalling IP datagram: %s" msg); Lwt.return_unit | Ok (ip, ip_payload) -> match Icmpv4_packet.Unmarshal.of_cstruct ip_payload with | Error msg -> Log.err (fun f -> f "Error unmarshalling ICMP message: %s" msg); Lwt.return_unit | Ok (reply, received_payload) -> let open Icmpv4_packet in begin match reply.subheader with | Next_hop_mtu _ | Pointer _ | Address _ | Unused -> Log.err (fun f -> f "received an ICMP message which wasn't an echo-request or reply"); Lwt.return_unit | Id_and_seq (id, seq) -> if reply.code <> 0 then Log.err (fun f -> f "received an ICMP ECHO_REQUEST with reply.code=%d" reply.code); if not(Cstruct.equal payload received_payload) then Log.err (fun f -> f "received an ICMP ECHO_REQUEST with an unexpected payload"); if not(Hashtbl.mem seq_no_to_send_time seq) then Log.err (fun f -> f "received an ICMP ECHO_REQUEST with an unexpected sequence number") else begin let secs = Unix.gettimeofday () -. (Hashtbl.find seq_no_to_send_time seq) in Hashtbl.remove seq_no_to_send_time seq; let ms = secs *. 1000.0 in Printf.printf "%d bytes from %s: icmp_seq=%d ttl=%d time=%f ms\n%!" (Cstruct.len payload) (Ipaddr.V4.to_string ip.Ipv4_packet.src) seq ip.Ipv4_packet.ttl ms; incr nr_received; min_ms := min !min_ms ms; max_ms := max !max_ms ms; sum_ms := !sum_ms +. ms; sum_ms_2 := !sum_ms_2 +. (ms *. ms); if Some !nr_received = count then begin Log.debug (fun f -> f "Finished after %d packets received" !nr_received); Lwt.wakeup_later finished_u (); end end; Lwt.return_unit end in finished_t, callback let ping (count:int option) (size:int) (timeout:int option) dst = let dst = Ipaddr.V4.of_string_exn dst in Lwt_main.run begin let open Lwt.Infix in let payload = make_payload ~size () in Icmpv4_socket.connect () >>= fun stack -> let finished, on_icmp_receive = make_receiver ~count ~payload () in let me = Ipaddr.V4.any in let listener = Icmpv4_socket.listen stack me on_icmp_receive in let timeout = match timeout with | None -> let forever, _ = Lwt.task () in forever | Some t -> Lwt_unix.sleep (float_of_int t) >>= fun () -> Log.debug (fun f -> f "Timed-out"); Lwt.return_unit in let sender = send_echo_requests ~stack ~payload ~dst () in let interrupted, interrupted_u = Lwt.task () in ignore(Lwt_unix.on_signal Sys.sigint (fun _ -> Lwt.wakeup_later interrupted_u ())); Lwt.pick [ finished; timeout; interrupted; listener; sender; ] >>= fun () -> Printf.printf "--- %s ping statistics ---\n" (Ipaddr.V4.to_string dst); let n = float_of_int (!nr_received) in let percent_loss = 100. *. (float_of_int (!nr_transmitted) -. n) /. (float_of_int (!nr_transmitted)) in Printf.printf "%d packets transmitted, %d packets received, %0.0f%% packet loss\n" !nr_transmitted !nr_received percent_loss; let avg_ms = !sum_ms /. n in let variance_ms = 1. /. (n -. 1.) *. (!sum_ms_2) -. 1. /. (n *. (n -. 1.)) *. (!sum_ms) *. (!sum_ms) in let stddev_ms = sqrt variance_ms in Printf.printf "round-trip min/avg/max/stddev = %.03f/%.03f/%.03f/%.03f ms\n" !min_ms avg_ms !max_ms stddev_ms; Lwt.return (`Ok ()) end open Cmdliner let exit_after_success = let doc = "Exit successfully after receiving one reply packet." in Arg.(value & flag & info [ "o" ] ~doc) let count = let doc = "Stop after sending (and receiving) count ECHO_RESPONSE packets. If not specified, ping will continue until interrupted." in Arg.(value & opt (some int) None & info [ "c" ] ~doc) let size = let doc = "Specify the number of data bytes to be sent." in Arg.(value & opt int 56 & info [ "s" ] ~doc) let timeout = let doc = "Specify a timeout, before ping exits regardless of how many packets have been received." in Arg.(value & opt (some int) None & info [ "t" ] ~doc) let destination = let doc ="Hostname or IP address of destination host" in Arg.(value & pos 0 string "" & info [] ~doc) let cmd = let doc = "Send ICMP ECHO_REQUEST packets and listen for ECHO_RESPONSES" in let man = [ `S "DESCRIPTION"; `P "Send a sequence of ICMP ECHO_REQUEST packets to a network host and count the responses. When the program exits, display some statistics."; ] in Term.(ret(pure ping $ count $ size $ timeout $ destination)), Term.info "ping" ~doc ~man let _ = Logs.set_reporter (Logs_fmt.reporter ()); match Term.eval cmd with | `Error _ -> exit 1 | _ -> exit 0
511dcfc63394fbd345d0e5b5f1b62a8b0d9e453a2af113e981b0b8650094f1e4
danehuang/augurv2
KernSyn.hs
- Copyright 2017 under the Apache License , Version 2.0 ( the " License " ) ; - you may not use this file except in compliance with the License . - You may obtain a copy of the License at - - -2.0 - - Unless required by applicable law or agreed to in writing , software - distributed under the License is distributed on an " AS IS " BASIS , - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . - See the License for the specific language governing permissions and - limitations under the License . - Copyright 2017 Daniel Eachern Huang - - 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. -} # LANGUAGE TypeSynonymInstances , FlexibleInstances , MultiParamTypeClasses , DeriveFunctor , , DeriveTraversable , FlexibleContexts # module Core.KernSyn where import Text.PrettyPrint import Data.Foldable (Foldable) import Data.Traversable (Traversable) import AstUtil.Pretty import Core.DensSyn ---------------------------------------------------------------------- = KernSyn Description | [ Note ] Syntax for MCMC kernel . Syntax for MCMC kernel. -} ----------------------------------- -- == Syntax newtype KernU' b = KernU' { unKern :: KernU b } type KernU b = Kern (UserCode b) b data UserCode b = Empty | Proposal (Exp b) [(b, Gen b)] instance (Pretty b) => Pretty (UserCode b) where ppr Empty = text "Empty" ppr (Proposal e grids) = text "Proposal" <> braces (ppr e <+> pprGrids) where pprGrids = case grids of [] -> empty _ -> text "for" <+> sepBy commasp grids mkUserMWG :: b -> Exp b -> [(b, Gen b)] -> KernU b mkUserMWG v_mod e grids = Base (UserProp (MWG Empty Empty Empty Empty)) (Single v_mod) (dirac v_mod []) [] [] (Proposal e grids) mkUserHMC :: [b] -> Maybe (Double, Double) -> KernU b mkUserHMC v_mods opt = Base (GradProp (HMC Empty Empty simLen stepSize)) (Block v_mods) (prodFn (map (\v -> dirac v []) v_mods)) [] [] Empty where simLen = case opt of Just (simLen', _) -> simLen' Nothing -> 1.0 stepSize = case opt of Just (_, stepSize') -> stepSize' Nothing -> 0.05 mkUserDiscGibbs :: b -> KernU b mkUserDiscGibbs v_mod = Base (Gibbs (Disc Empty)) (Single v_mod) (dirac v_mod []) [] [] Empty mkUserConjGibbs :: b -> KernU b mkUserConjGibbs v_mod = Base (Gibbs (Conj Empty Empty)) (Single v_mod) (dirac v_mod []) [] [] Empty mkUserESlice :: b -> KernU b mkUserESlice v_mod = Base (Slice (Ellip Empty Empty)) (Single v_mod) (dirac v_mod []) [] [] Empty mkUserNUTS :: [b] -> Maybe Double -> KernU b mkUserNUTS v_mods opt = Base (GradProp (NUTS Empty Empty stepSize)) (Block v_mods) (prodFn (map (\v -> dirac v []) v_mods)) [] [] Empty where stepSize = case opt of Just stepSize' -> stepSize' Nothing -> 0.05 mkUserRSlice :: [b] -> Maybe (Double, Double) -> KernU b mkUserRSlice v_mods opt = Base (GradProp (Reflect Empty Empty simLen stepSize)) (Block v_mods) (prodFn (map (\v -> dirac v []) v_mods)) [] [] Empty where simLen = case opt of Just (simLen', _) -> simLen' Nothing -> 1.0 stepSize = case opt of Just (_, stepSize') -> stepSize' Nothing -> 0.05 data Kern code b = Base (KernKind code) (KernUnit b) (Fn b) [(b, AllocKind)] [b] code ^ kernel kind , kernel unit , unnormalized full - cond , , kernel parameters , full - cond likelihood code | Tensor (Kern code b) (Kern code b) deriving (Show, Functor, Foldable, Traversable) data KernUnit b = Single b | Block [b] deriving (Show, Functor, Foldable, Traversable) data KernKind code = UserProp (PropKind code) | GradProp (GradKind code) | Gibbs (GibbsKind code) | Slice (SliceKind code) deriving (Show) data AllocKind = Reset | Work deriving (Show) data PropKind code = Joint code -- ^ proposal | MWG code code code code -- ^ proposal, swap, likelihood, top-level deriving (Show) data GradKind code = HMC code code Double Double -- ^ gradient, proposal | NUTS code code Double -- ^ gradient, proposal | Reflect code code Double Double -- ^ gradient, proposal deriving (Show) data GibbsKind code = Disc code -- ^ sample | Conj code code -- ^ statistic, sample deriving (Show) data SliceKind code = Ellip code code -- ^ individual likelihood, proposal deriving (Show) ----------------------------------- -- == Instances -- === Pretty instance (Pretty b) => Pretty (KernU' b) where ppr (KernU' k) = f k where f (Base kind ku fcFn _ _ code) = vcat [ text "Kernel: " <+> ppr kind <> parens (ppr ku) , text "Full-cond: " <+> ppr fcFn , text "Code: " <+> ppr code ] f (Tensor k1 k2) = vcat [ f k1 , text "(*)", f k2 ] instance (Pretty b, Pretty code) => Pretty (Kern b code) where ppr (Base kind ku fcFn allocs kernParams code) = vcat [ ppr kind <> parens (ppr ku), ppr fcFn, sepBy commasp allocs, ppr code ] ppr (Tensor k1 k2) = vcat [ ppr k1 , text "(*)", ppr k2 ] instance (Pretty b) => Pretty (KernUnit b) where ppr (Single x) = ppr x ppr (Block xs) = sepBy commasp xs instance Pretty AllocKind where ppr Reset = text "reset" ppr Work = text "work" instance Pretty (KernKind code) where ppr (UserProp pk) = ppr pk <> text "-MH" ppr (GradProp gk) = ppr gk <> text "-MH" ppr (Gibbs gk) = ppr gk <> text "-Gibbs" ppr (Slice sk) = ppr sk <> text "-Slice" instance Pretty (PropKind code) where ppr (Joint _) = text "Joint" ppr (MWG _ _ _ _) = text "MWG" instance Pretty (GradKind code) where ppr (HMC _ _ _ _) = text "HMC" ppr (NUTS _ _ _) = text "NUTS" ppr (Reflect _ _ _ _) = text "Reflect" instance Pretty (GibbsKind code) where ppr (Disc _) = text "Disc" ppr (Conj _ _) = text "Conj" instance Pretty (SliceKind code) where ppr (Ellip _ _) = text "Ellip" ----------------------------------- -- == Operations on Syntax kuVars :: KernUnit b -> [b] kuVars (Single x) = [x] kuVars (Block xs) = xs mapCode :: (c1 -> c2) -> Kern c1 b -> Kern c2 b mapCode f (Base kind ku fc allocs kernParams like) = case kind of UserProp pk -> case pk of Joint prop -> Base (UserProp (Joint (f prop))) ku fc allocs kernParams (f like) MWG prop swap like top -> Base (UserProp (MWG (f prop) (f swap) (f like) (f top))) ku fc allocs kernParams (f like) GradProp gk -> case gk of HMC grad prop simLen stepSize -> Base (GradProp (HMC (f grad) (f prop) simLen stepSize)) ku fc allocs kernParams (f like) NUTS grad prop stepSize -> Base (GradProp (NUTS (f grad) (f prop) stepSize)) ku fc allocs kernParams (f like) Reflect grad prop simLen stepSize -> Base (GradProp (Reflect (f grad) (f prop) simLen stepSize)) ku fc allocs kernParams (f like) Gibbs gk -> case gk of Disc samp -> Base (Gibbs (Disc (f samp))) ku fc allocs kernParams (f like) Conj stat samp -> Base (Gibbs (Conj (f stat) (f samp))) ku fc allocs kernParams (f like) Slice sk -> case sk of Ellip like' prop -> Base (Slice (Ellip (f like') (f prop))) ku fc allocs kernParams (f like) mapCode f (Tensor k1 k2) = Tensor (mapCode f k1) (mapCode f k2) gatherCode :: Kern c b -> [c] gatherCode (Base kind _ _ _ _ like) = case kind of UserProp pk -> case pk of Joint prop -> [ like, prop ] MWG prop swap like' top -> [ prop, swap, like', top ] GradProp gk -> case gk of HMC grad prop _ _ -> [ like, grad, prop ] NUTS grad prop _ -> [ like, grad, prop ] Reflect grad prop _ _ -> [ like, grad, prop ] Gibbs gk -> case gk of Disc samp -> [ samp ] Conj stat samp -> [ stat, samp ] Slice sk -> case sk of Ellip like' prop -> [ like', prop ] gatherCode (Tensor k1 k2) = gatherCode k1 ++ gatherCode k2 gatherKernParams :: Kern c b -> [b] gatherKernParams (Base _ _ _ _ kernParams _) = kernParams gatherKernParams (Tensor k1 k2) = gatherKernParams k1 ++ gatherKernParams k2 needProp :: Kern b c -> Bool needProp (Base kind _ _ _ _ _) = case kind of UserProp _ -> True GradProp _ -> True Gibbs _ -> False Slice _ -> True needProp (Tensor k1 k2) = needProp k1 || needProp k2
null
https://raw.githubusercontent.com/danehuang/augurv2/480459bcc2eff898370a4e1b4f92b08ea3ab3f7b/compiler/augur/src/Core/KernSyn.hs
haskell
-------------------------------------------------------------------- --------------------------------- == Syntax ^ proposal ^ proposal, swap, likelihood, top-level ^ gradient, proposal ^ gradient, proposal ^ gradient, proposal ^ sample ^ statistic, sample ^ individual likelihood, proposal --------------------------------- == Instances === Pretty --------------------------------- == Operations on Syntax
- Copyright 2017 under the Apache License , Version 2.0 ( the " License " ) ; - you may not use this file except in compliance with the License . - You may obtain a copy of the License at - - -2.0 - - Unless required by applicable law or agreed to in writing , software - distributed under the License is distributed on an " AS IS " BASIS , - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . - See the License for the specific language governing permissions and - limitations under the License . - Copyright 2017 Daniel Eachern Huang - - 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. -} # LANGUAGE TypeSynonymInstances , FlexibleInstances , MultiParamTypeClasses , DeriveFunctor , , DeriveTraversable , FlexibleContexts # module Core.KernSyn where import Text.PrettyPrint import Data.Foldable (Foldable) import Data.Traversable (Traversable) import AstUtil.Pretty import Core.DensSyn = KernSyn Description | [ Note ] Syntax for MCMC kernel . Syntax for MCMC kernel. -} newtype KernU' b = KernU' { unKern :: KernU b } type KernU b = Kern (UserCode b) b data UserCode b = Empty | Proposal (Exp b) [(b, Gen b)] instance (Pretty b) => Pretty (UserCode b) where ppr Empty = text "Empty" ppr (Proposal e grids) = text "Proposal" <> braces (ppr e <+> pprGrids) where pprGrids = case grids of [] -> empty _ -> text "for" <+> sepBy commasp grids mkUserMWG :: b -> Exp b -> [(b, Gen b)] -> KernU b mkUserMWG v_mod e grids = Base (UserProp (MWG Empty Empty Empty Empty)) (Single v_mod) (dirac v_mod []) [] [] (Proposal e grids) mkUserHMC :: [b] -> Maybe (Double, Double) -> KernU b mkUserHMC v_mods opt = Base (GradProp (HMC Empty Empty simLen stepSize)) (Block v_mods) (prodFn (map (\v -> dirac v []) v_mods)) [] [] Empty where simLen = case opt of Just (simLen', _) -> simLen' Nothing -> 1.0 stepSize = case opt of Just (_, stepSize') -> stepSize' Nothing -> 0.05 mkUserDiscGibbs :: b -> KernU b mkUserDiscGibbs v_mod = Base (Gibbs (Disc Empty)) (Single v_mod) (dirac v_mod []) [] [] Empty mkUserConjGibbs :: b -> KernU b mkUserConjGibbs v_mod = Base (Gibbs (Conj Empty Empty)) (Single v_mod) (dirac v_mod []) [] [] Empty mkUserESlice :: b -> KernU b mkUserESlice v_mod = Base (Slice (Ellip Empty Empty)) (Single v_mod) (dirac v_mod []) [] [] Empty mkUserNUTS :: [b] -> Maybe Double -> KernU b mkUserNUTS v_mods opt = Base (GradProp (NUTS Empty Empty stepSize)) (Block v_mods) (prodFn (map (\v -> dirac v []) v_mods)) [] [] Empty where stepSize = case opt of Just stepSize' -> stepSize' Nothing -> 0.05 mkUserRSlice :: [b] -> Maybe (Double, Double) -> KernU b mkUserRSlice v_mods opt = Base (GradProp (Reflect Empty Empty simLen stepSize)) (Block v_mods) (prodFn (map (\v -> dirac v []) v_mods)) [] [] Empty where simLen = case opt of Just (simLen', _) -> simLen' Nothing -> 1.0 stepSize = case opt of Just (_, stepSize') -> stepSize' Nothing -> 0.05 data Kern code b = Base (KernKind code) (KernUnit b) (Fn b) [(b, AllocKind)] [b] code ^ kernel kind , kernel unit , unnormalized full - cond , , kernel parameters , full - cond likelihood code | Tensor (Kern code b) (Kern code b) deriving (Show, Functor, Foldable, Traversable) data KernUnit b = Single b | Block [b] deriving (Show, Functor, Foldable, Traversable) data KernKind code = UserProp (PropKind code) | GradProp (GradKind code) | Gibbs (GibbsKind code) | Slice (SliceKind code) deriving (Show) data AllocKind = Reset | Work deriving (Show) deriving (Show) deriving (Show) deriving (Show) deriving (Show) instance (Pretty b) => Pretty (KernU' b) where ppr (KernU' k) = f k where f (Base kind ku fcFn _ _ code) = vcat [ text "Kernel: " <+> ppr kind <> parens (ppr ku) , text "Full-cond: " <+> ppr fcFn , text "Code: " <+> ppr code ] f (Tensor k1 k2) = vcat [ f k1 , text "(*)", f k2 ] instance (Pretty b, Pretty code) => Pretty (Kern b code) where ppr (Base kind ku fcFn allocs kernParams code) = vcat [ ppr kind <> parens (ppr ku), ppr fcFn, sepBy commasp allocs, ppr code ] ppr (Tensor k1 k2) = vcat [ ppr k1 , text "(*)", ppr k2 ] instance (Pretty b) => Pretty (KernUnit b) where ppr (Single x) = ppr x ppr (Block xs) = sepBy commasp xs instance Pretty AllocKind where ppr Reset = text "reset" ppr Work = text "work" instance Pretty (KernKind code) where ppr (UserProp pk) = ppr pk <> text "-MH" ppr (GradProp gk) = ppr gk <> text "-MH" ppr (Gibbs gk) = ppr gk <> text "-Gibbs" ppr (Slice sk) = ppr sk <> text "-Slice" instance Pretty (PropKind code) where ppr (Joint _) = text "Joint" ppr (MWG _ _ _ _) = text "MWG" instance Pretty (GradKind code) where ppr (HMC _ _ _ _) = text "HMC" ppr (NUTS _ _ _) = text "NUTS" ppr (Reflect _ _ _ _) = text "Reflect" instance Pretty (GibbsKind code) where ppr (Disc _) = text "Disc" ppr (Conj _ _) = text "Conj" instance Pretty (SliceKind code) where ppr (Ellip _ _) = text "Ellip" kuVars :: KernUnit b -> [b] kuVars (Single x) = [x] kuVars (Block xs) = xs mapCode :: (c1 -> c2) -> Kern c1 b -> Kern c2 b mapCode f (Base kind ku fc allocs kernParams like) = case kind of UserProp pk -> case pk of Joint prop -> Base (UserProp (Joint (f prop))) ku fc allocs kernParams (f like) MWG prop swap like top -> Base (UserProp (MWG (f prop) (f swap) (f like) (f top))) ku fc allocs kernParams (f like) GradProp gk -> case gk of HMC grad prop simLen stepSize -> Base (GradProp (HMC (f grad) (f prop) simLen stepSize)) ku fc allocs kernParams (f like) NUTS grad prop stepSize -> Base (GradProp (NUTS (f grad) (f prop) stepSize)) ku fc allocs kernParams (f like) Reflect grad prop simLen stepSize -> Base (GradProp (Reflect (f grad) (f prop) simLen stepSize)) ku fc allocs kernParams (f like) Gibbs gk -> case gk of Disc samp -> Base (Gibbs (Disc (f samp))) ku fc allocs kernParams (f like) Conj stat samp -> Base (Gibbs (Conj (f stat) (f samp))) ku fc allocs kernParams (f like) Slice sk -> case sk of Ellip like' prop -> Base (Slice (Ellip (f like') (f prop))) ku fc allocs kernParams (f like) mapCode f (Tensor k1 k2) = Tensor (mapCode f k1) (mapCode f k2) gatherCode :: Kern c b -> [c] gatherCode (Base kind _ _ _ _ like) = case kind of UserProp pk -> case pk of Joint prop -> [ like, prop ] MWG prop swap like' top -> [ prop, swap, like', top ] GradProp gk -> case gk of HMC grad prop _ _ -> [ like, grad, prop ] NUTS grad prop _ -> [ like, grad, prop ] Reflect grad prop _ _ -> [ like, grad, prop ] Gibbs gk -> case gk of Disc samp -> [ samp ] Conj stat samp -> [ stat, samp ] Slice sk -> case sk of Ellip like' prop -> [ like', prop ] gatherCode (Tensor k1 k2) = gatherCode k1 ++ gatherCode k2 gatherKernParams :: Kern c b -> [b] gatherKernParams (Base _ _ _ _ kernParams _) = kernParams gatherKernParams (Tensor k1 k2) = gatherKernParams k1 ++ gatherKernParams k2 needProp :: Kern b c -> Bool needProp (Base kind _ _ _ _ _) = case kind of UserProp _ -> True GradProp _ -> True Gibbs _ -> False Slice _ -> True needProp (Tensor k1 k2) = needProp k1 || needProp k2
bcc89f7909f1258b9aed249e69be96b1f16e94266a4bf8520db1136306429430
tsoding/louis
Louis.hs
# LANGUAGE BinaryLiterals # # LANGUAGE QuasiQuotes # {-# LANGUAGE OverloadedStrings #-} -- | -- Module : Louis Copyright : ( c ) 2019 License : MIT -- Maintainer : -- Portability : portable -- -- >>> import Louis -- >>> import qualified Data.Text as T -- >>> putStrLn . T.unpack . T.unlines =<< braillizeFile "image.png" -- ⠀⠀⠀⡸⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⠀ ⢀ ⣴ ⣶ ⣶ ⣶ ⣦ ⣬ ⣉ ⠻ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⠀ ⣸ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⡿ ⣿ ⡆ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⡿ ⠿ ⠿ ⠿ ⢿ ⣿ ⣿ ⣿ ⣿ ⠀ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⠁ ⢠ ⣿ ⠡ ⠿ ⠿ ⠿ ⠿ ⣿ ⣿ ⣿ ⢃ ⣶ ⣿ ⣷ ⣶ ⣤ ⣍ ⡛ ⣿ ⣿ ⣤ ⣾ ⠋ ⠐ ⠲ ⠶ ⣦ ⣤ ⣌ ⡙ ⠋ ⢸ ⣿ ⠋ ⠙ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣦ ⣭ ⣉ ⣉ ⣙ ⣛ ⣋ ⣉ ⣉ ⣅ ⣿ ⣿ ⣷ ⣾ ⣿ ⣿ ⣿ ⡇ ⣿ ⡏ ⠀ ⢰ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣇ ⢹ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣬ ⡙ ⠛ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⡝ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣬ ⣍ ⣛ ⠻ ⠿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⠃ ⣦ ⡉ ⣰ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ -- ⣿⣿⣿⣿⣿⣿⣿⣿⣯⣾⣿⣿⣿⣿⣇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ -- ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ -- ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ -- ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ -- ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ module Louis ( braillizeDynamicImage , braillizeByteString , braillizeFile ) where import Data.Word import Data.Char import Data.Bits import Codec.Picture import qualified Data.Vector.Storable as V import Data.List import qualified Data.Text as T import Data.Functor.Compose import qualified Data.ByteString as BS type Chunk = Word8 renderChunk :: Chunk -> Char renderChunk x = chr (bgroup * groupSize + boffset + ord '⠀') where bgroup = let b1 = (x .&. 0b00001000) `shiftR` 3 b2 = (x .&. 0b10000000) `shiftR` 6 in fromIntegral (b1 .|. b2) boffset = let b1 = (x .&. 0b00000111) b2 = (x .&. 0b01110000) `shiftR` 1 in fromIntegral (b1 .|. b2) groupSize = 64 chunkifyGreyScale :: Image Pixel8 -> [[Chunk]] chunkifyGreyScale img = [ [chunkAt (i * 2, j * 4) | i <- [0 .. chunksWidth - 1]] | j <- [0 .. chunksHeight - 1] ] where width = imageWidth img height = imageHeight img chunksWidth = width `div` 2 chunksHeight = height `div` 4 squashBits :: [Word8] -> Word8 squashBits = foldl' (\acc x -> shiftL acc 1 .|. x) 0 threshold = let imgData = imageData img in round $ (/ (fromIntegral $ V.length imgData)) $ V.foldl' (+) (0.0 :: Float) $ V.map fromIntegral imgData k :: Pixel8 -> Word8 k x | x < threshold = 0 | otherwise = 1 f :: (Int, Int) -> Word8 f (x, y) | 0 <= x && x < width && 0 <= y && y < height = k $ pixelAt img x y | otherwise = 0 chunkAt :: (Int, Int) -> Chunk chunkAt (x, y) = squashBits $ reverse [f (i + x, j + y) | i <- [0, 1], j <- [0 .. 3]] greyScaleImage :: DynamicImage -> Image Pixel8 greyScaleImage = pixelMap greyScalePixel . convertRGBA8 -- reference: where greyScalePixel :: PixelRGBA8 -> Pixel8 greyScalePixel (PixelRGBA8 r g b a) = k where k = round ((r' * 0.299 + g' * 0.587 + b' * 0.114) * a') r' = fromIntegral r :: Float g' = fromIntegral g :: Float b' = fromIntegral b :: Float a' = (fromIntegral a :: Float) / 255.0 braillizeGreyScale :: Image Pixel8 -> [T.Text] braillizeGreyScale = map T.pack . getCompose . fmap renderChunk . Compose . chunkifyGreyScale resizeImageWidth :: Pixel a => Int -> Image a -> Image a resizeImageWidth width' image | width /= width' = let ratio :: Float ratio = fromIntegral width' / fromIntegral width height' = floor (fromIntegral height * ratio) y_interval :: Float y_interval = fromIntegral height / fromIntegral height' x_interval :: Float x_interval = fromIntegral width / fromIntegral width' resizedData = [ imgData V.! idx | y <- [0 .. (height' - 1)] , x <- [0 .. (width' - 1)] , let idx = floor (fromIntegral y * y_interval) * width + floor (fromIntegral x * x_interval) ] in Image width' height' $ V.fromList resizedData | otherwise = image where width = imageWidth image height = imageHeight image imgData = imageData image braillizeDynamicImage :: DynamicImage -> [T.Text] braillizeDynamicImage = braillizeGreyScale . resizeImageWidth 60 . greyScaleImage braillizeByteString :: BS.ByteString -> Either String [T.Text] braillizeByteString bytes = braillizeDynamicImage <$> decodeImage bytes braillizeFile :: FilePath -> IO [T.Text] braillizeFile filePath = do bytes <- BS.readFile filePath either error return $ braillizeByteString bytes
null
https://raw.githubusercontent.com/tsoding/louis/bc6b810161cc461a9e3ad0bb360f90440a07f3c6/src/Louis.hs
haskell
# LANGUAGE OverloadedStrings # | Module : Louis Maintainer : Portability : portable >>> import Louis >>> import qualified Data.Text as T >>> putStrLn . T.unpack . T.unlines =<< braillizeFile "image.png" ⠀⠀⠀⡸⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣯⣾⣿⣿⣿⣿⣇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ reference:
# LANGUAGE BinaryLiterals # # LANGUAGE QuasiQuotes # Copyright : ( c ) 2019 License : MIT ⠀ ⢀ ⣴ ⣶ ⣶ ⣶ ⣦ ⣬ ⣉ ⠻ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⠀ ⣸ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⡿ ⣿ ⡆ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⡿ ⠿ ⠿ ⠿ ⢿ ⣿ ⣿ ⣿ ⣿ ⠀ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⠁ ⢠ ⣿ ⠡ ⠿ ⠿ ⠿ ⠿ ⣿ ⣿ ⣿ ⢃ ⣶ ⣿ ⣷ ⣶ ⣤ ⣍ ⡛ ⣿ ⣿ ⣤ ⣾ ⠋ ⠐ ⠲ ⠶ ⣦ ⣤ ⣌ ⡙ ⠋ ⢸ ⣿ ⠋ ⠙ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣦ ⣭ ⣉ ⣉ ⣙ ⣛ ⣋ ⣉ ⣉ ⣅ ⣿ ⣿ ⣷ ⣾ ⣿ ⣿ ⣿ ⡇ ⣿ ⡏ ⠀ ⢰ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣇ ⢹ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣬ ⡙ ⠛ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⡝ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣬ ⣍ ⣛ ⠻ ⠿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⠃ ⣦ ⡉ ⣰ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ ⣿ module Louis ( braillizeDynamicImage , braillizeByteString , braillizeFile ) where import Data.Word import Data.Char import Data.Bits import Codec.Picture import qualified Data.Vector.Storable as V import Data.List import qualified Data.Text as T import Data.Functor.Compose import qualified Data.ByteString as BS type Chunk = Word8 renderChunk :: Chunk -> Char renderChunk x = chr (bgroup * groupSize + boffset + ord '⠀') where bgroup = let b1 = (x .&. 0b00001000) `shiftR` 3 b2 = (x .&. 0b10000000) `shiftR` 6 in fromIntegral (b1 .|. b2) boffset = let b1 = (x .&. 0b00000111) b2 = (x .&. 0b01110000) `shiftR` 1 in fromIntegral (b1 .|. b2) groupSize = 64 chunkifyGreyScale :: Image Pixel8 -> [[Chunk]] chunkifyGreyScale img = [ [chunkAt (i * 2, j * 4) | i <- [0 .. chunksWidth - 1]] | j <- [0 .. chunksHeight - 1] ] where width = imageWidth img height = imageHeight img chunksWidth = width `div` 2 chunksHeight = height `div` 4 squashBits :: [Word8] -> Word8 squashBits = foldl' (\acc x -> shiftL acc 1 .|. x) 0 threshold = let imgData = imageData img in round $ (/ (fromIntegral $ V.length imgData)) $ V.foldl' (+) (0.0 :: Float) $ V.map fromIntegral imgData k :: Pixel8 -> Word8 k x | x < threshold = 0 | otherwise = 1 f :: (Int, Int) -> Word8 f (x, y) | 0 <= x && x < width && 0 <= y && y < height = k $ pixelAt img x y | otherwise = 0 chunkAt :: (Int, Int) -> Chunk chunkAt (x, y) = squashBits $ reverse [f (i + x, j + y) | i <- [0, 1], j <- [0 .. 3]] greyScaleImage :: DynamicImage -> Image Pixel8 greyScaleImage = pixelMap greyScalePixel . convertRGBA8 where greyScalePixel :: PixelRGBA8 -> Pixel8 greyScalePixel (PixelRGBA8 r g b a) = k where k = round ((r' * 0.299 + g' * 0.587 + b' * 0.114) * a') r' = fromIntegral r :: Float g' = fromIntegral g :: Float b' = fromIntegral b :: Float a' = (fromIntegral a :: Float) / 255.0 braillizeGreyScale :: Image Pixel8 -> [T.Text] braillizeGreyScale = map T.pack . getCompose . fmap renderChunk . Compose . chunkifyGreyScale resizeImageWidth :: Pixel a => Int -> Image a -> Image a resizeImageWidth width' image | width /= width' = let ratio :: Float ratio = fromIntegral width' / fromIntegral width height' = floor (fromIntegral height * ratio) y_interval :: Float y_interval = fromIntegral height / fromIntegral height' x_interval :: Float x_interval = fromIntegral width / fromIntegral width' resizedData = [ imgData V.! idx | y <- [0 .. (height' - 1)] , x <- [0 .. (width' - 1)] , let idx = floor (fromIntegral y * y_interval) * width + floor (fromIntegral x * x_interval) ] in Image width' height' $ V.fromList resizedData | otherwise = image where width = imageWidth image height = imageHeight image imgData = imageData image braillizeDynamicImage :: DynamicImage -> [T.Text] braillizeDynamicImage = braillizeGreyScale . resizeImageWidth 60 . greyScaleImage braillizeByteString :: BS.ByteString -> Either String [T.Text] braillizeByteString bytes = braillizeDynamicImage <$> decodeImage bytes braillizeFile :: FilePath -> IO [T.Text] braillizeFile filePath = do bytes <- BS.readFile filePath either error return $ braillizeByteString bytes
d638936a08afc49103b3c326a4f41d5e57234e1f00d70c395c397cc761a3e50f
dedbox/racket-neuron
info.rkt
#lang info (define collection 'multi) (define deps '("neuron-lib" "neuron-doc")) (define implies '("neuron-lib" "neuron-doc"))
null
https://raw.githubusercontent.com/dedbox/racket-neuron/a8ecafec0c6398c35423348cb02ec229869c8b15/neuron/info.rkt
racket
#lang info (define collection 'multi) (define deps '("neuron-lib" "neuron-doc")) (define implies '("neuron-lib" "neuron-doc"))
eae9c844434fbfc1b81d036f3b2c9542546a7d7b6f903c3fa4e5f68343bd84dd
earl-ducaine/cl-garnet
gilt-compiler.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Package : COMMON - LISP - USER ; Base : 10 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; The Garnet User Interface Development Environment . ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This code was written as part of the Garnet project at ;;; Carnegie Mellon University , and has been placed in the public ; ; ; domain . If you are using this code or any part of Garnet , ; ; ; ;;; please contact to be put on the mailing list. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (in-package "COMMON-LISP-USER") (defvar *debug-gilt-mode* nil) ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (proclaim ;; (if *debug-gilt-mode* ( and ( boundp ' Garnet - Compile - Debug - Settings ) ;; Garnet-Compile-Debug-Settings) ;; ;; Global default settings. ( and ( boundp ' Default - Garnet - Proclaim ) ) ) ) ) (format t "Compiling Gilt...~%") check first to see if pathname variable is set (unless (boundp 'Garnet-Gilt-PathName) (error "Load 'Garnet-Loader' first to set Garnet-Gilt-PathName before loading this file.")) (eval-when (:execute :load-toplevel :compile-toplevel) (garnet-mkdir-if-needed Garnet-gilt-Pathname)) (defvar gilt-files '( ;; "gilt-functions" ;; "path-functions" ;; "filter-functions" ;; "gilt-font-imp" ;; "motif-gilt-font-props" ;; "gilt-gadget-utils" ;; "gilt-gadgets" ;; "motif-gilt-gadgets" ;; "gilt" ;; "motif-gilt-save" ;; "motif-gilt-read" ;; "color-imp" ;; "motif-color-props" ;; "line-imp" ;; "motif-line-props" ;; "fill-imp" ;; "motif-fill-props" ;; "align" ;; "value-control" ;; "enable-control" ;; "error-check" )) (dolist (file gilt-files) (let ((gilt-str (concatenate 'string "gilt:" file))) (garnet-compile gilt-str) (garnet-load gilt-str)) #+allegroV3.1(common-lisp-user::gc t)) ;; (garnet-copy-files Garnet-Gilt-Src Garnet-Gilt-Pathname ;; '("filter-functions-loader.lisp" " " " gilt-functions-loader.lisp " ;; "path-functions-loader.lisp" ;; )) (setf (get :garnet-modules :gilt) t) (setf (get :garnet-modules :gilt-functions) t) (format t "... Done Compiling Gilt~%")
null
https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/gilt/gilt-compiler.lisp
lisp
Syntax : Common - Lisp ; Package : COMMON - LISP - USER ; Base : 10 -*- ; ; This code was written as part of the Garnet project at ;;; ; ; ; ; please contact to be put on the mailing list. ;;; (eval-when (:compile-toplevel :load-toplevel :execute) (proclaim (if *debug-gilt-mode* Garnet-Compile-Debug-Settings) ;; Global default settings. "gilt-functions" "path-functions" "filter-functions" "gilt-font-imp" "motif-gilt-font-props" "gilt-gadget-utils" "gilt-gadgets" "motif-gilt-gadgets" "gilt" "motif-gilt-save" "motif-gilt-read" "color-imp" "motif-color-props" "line-imp" "motif-line-props" "fill-imp" "motif-fill-props" "align" "value-control" "enable-control" "error-check" (garnet-copy-files Garnet-Gilt-Src Garnet-Gilt-Pathname '("filter-functions-loader.lisp" "path-functions-loader.lisp" ))
(in-package "COMMON-LISP-USER") (defvar *debug-gilt-mode* nil) ( and ( boundp ' Garnet - Compile - Debug - Settings ) ( and ( boundp ' Default - Garnet - Proclaim ) ) ) ) ) (format t "Compiling Gilt...~%") check first to see if pathname variable is set (unless (boundp 'Garnet-Gilt-PathName) (error "Load 'Garnet-Loader' first to set Garnet-Gilt-PathName before loading this file.")) (eval-when (:execute :load-toplevel :compile-toplevel) (garnet-mkdir-if-needed Garnet-gilt-Pathname)) (defvar gilt-files '( )) (dolist (file gilt-files) (let ((gilt-str (concatenate 'string "gilt:" file))) (garnet-compile gilt-str) (garnet-load gilt-str)) #+allegroV3.1(common-lisp-user::gc t)) " " " gilt-functions-loader.lisp " (setf (get :garnet-modules :gilt) t) (setf (get :garnet-modules :gilt-functions) t) (format t "... Done Compiling Gilt~%")
cbc1272fff43653780bb217d7301b46eae10ab57d7f9c88a7bd189393f965535
reasonml/reason
migrate_parsetree_407_408.ml
(**************************************************************************) (* *) (* OCaml Migrate Parsetree *) (* *) (* *) Copyright 2017 Institut National de Recherche en Informatique et (* en Automatique (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. *) (* *) (**************************************************************************) include Migrate_parsetree_407_408_migrate $ open Printf let fields = [ " attribute " ; " attributes " ; " case " ; " cases " ; " class_declaration " ; " class_description " ; " class_expr " ; " class_field " ; " class_signature " ; " class_structure " ; " class_type " ; " class_type_declaration " ; " class_type_field " ; " constructor_declaration " ; " expr " ; " extension " ; " extension_constructor " ; " include_declaration " ; " include_description " ; " label_declaration " ; " location " ; " module_binding " ; " module_declaration " ; " module_expr " ; " module_type " ; " module_type_declaration " ; " open_description " ; " pat " ; " signature " ; " signature_item " ; " structure " ; " structure_item " ; " typ " ; " type_declaration " ; " type_extension " ; " type_kind " ; " value_binding " ; " value_description " ; " with_constraint " ; " payload " ] let foreach_field f = printf " \n " ; List.iter f fields let fields = [ "attribute"; "attributes"; "case"; "cases"; "class_declaration"; "class_description"; "class_expr"; "class_field"; "class_signature"; "class_structure"; "class_type"; "class_type_declaration"; "class_type_field"; "constructor_declaration"; "expr"; "extension"; "extension_constructor"; "include_declaration"; "include_description"; "label_declaration"; "location"; "module_binding"; "module_declaration"; "module_expr"; "module_type"; "module_type_declaration"; "open_description"; "pat"; "signature"; "signature_item"; "structure"; "structure_item"; "typ"; "type_declaration"; "type_extension"; "type_kind"; "value_binding"; "value_description"; "with_constraint"; "payload" ] let foreach_field f = printf "\n"; List.iter f fields *)(*$*) let copy_mapper = fun ({ From.Ast_mapper. (*$ foreach_field (printf "%s;\n")*) attribute; attributes; case; cases; class_declaration; class_description; class_expr; class_field; class_signature; class_structure; class_type; class_type_declaration; class_type_field; constructor_declaration; expr; extension; extension_constructor; include_declaration; include_description; label_declaration; location; module_binding; module_declaration; module_expr; module_type; module_type_declaration; open_description; pat; signature; signature_item; structure; structure_item; typ; type_declaration; type_extension; type_kind; value_binding; value_description; with_constraint; payload; (*$*) } as mapper) -> let module Def = Migrate_parsetree_def in let migration_error location feature = raise (Def.Migration_error (feature, location)) in let module R = Migrate_parsetree_408_407_migrate in { To.Ast_mapper. $ foreach_field ( fun s - > printf " % s = ( fun _ x - > copy_%s ( % s mapper ( R.copy_%s x)));\n " s s s s ) printf "%s = (fun _ x -> copy_%s (%s mapper (R.copy_%s x)));\n" s s s s) *) attribute = (fun _ x -> copy_attribute (attribute mapper (R.copy_attribute x))); attributes = (fun _ x -> copy_attributes (attributes mapper (R.copy_attributes x))); case = (fun _ x -> copy_case (case mapper (R.copy_case x))); cases = (fun _ x -> copy_cases (cases mapper (R.copy_cases x))); class_declaration = (fun _ x -> copy_class_declaration (class_declaration mapper (R.copy_class_declaration x))); class_description = (fun _ x -> copy_class_description (class_description mapper (R.copy_class_description x))); class_expr = (fun _ x -> copy_class_expr (class_expr mapper (R.copy_class_expr x))); class_field = (fun _ x -> copy_class_field (class_field mapper (R.copy_class_field x))); class_signature = (fun _ x -> copy_class_signature (class_signature mapper (R.copy_class_signature x))); class_structure = (fun _ x -> copy_class_structure (class_structure mapper (R.copy_class_structure x))); class_type = (fun _ x -> copy_class_type (class_type mapper (R.copy_class_type x))); class_type_declaration = (fun _ x -> copy_class_type_declaration (class_type_declaration mapper (R.copy_class_type_declaration x))); class_type_field = (fun _ x -> copy_class_type_field (class_type_field mapper (R.copy_class_type_field x))); constructor_declaration = (fun _ x -> copy_constructor_declaration (constructor_declaration mapper (R.copy_constructor_declaration x))); expr = (fun _ x -> copy_expr (expr mapper (R.copy_expr x))); extension = (fun _ x -> copy_extension (extension mapper (R.copy_extension x))); extension_constructor = (fun _ x -> copy_extension_constructor (extension_constructor mapper (R.copy_extension_constructor x))); include_declaration = (fun _ x -> copy_include_declaration (include_declaration mapper (R.copy_include_declaration x))); include_description = (fun _ x -> copy_include_description (include_description mapper (R.copy_include_description x))); label_declaration = (fun _ x -> copy_label_declaration (label_declaration mapper (R.copy_label_declaration x))); location = (fun _ x -> copy_location (location mapper (R.copy_location x))); module_binding = (fun _ x -> copy_module_binding (module_binding mapper (R.copy_module_binding x))); module_declaration = (fun _ x -> copy_module_declaration (module_declaration mapper (R.copy_module_declaration x))); module_expr = (fun _ x -> copy_module_expr (module_expr mapper (R.copy_module_expr x))); module_type = (fun _ x -> copy_module_type (module_type mapper (R.copy_module_type x))); module_type_declaration = (fun _ x -> copy_module_type_declaration (module_type_declaration mapper (R.copy_module_type_declaration x))); open_description = (fun _ x -> copy_open_description (open_description mapper (R.copy_open_description x))); pat = (fun _ x -> copy_pat (pat mapper (R.copy_pat x))); signature = (fun _ x -> copy_signature (signature mapper (R.copy_signature x))); signature_item = (fun _ x -> copy_signature_item (signature_item mapper (R.copy_signature_item x))); structure = (fun _ x -> copy_structure (structure mapper (R.copy_structure x))); structure_item = (fun _ x -> copy_structure_item (structure_item mapper (R.copy_structure_item x))); typ = (fun _ x -> copy_typ (typ mapper (R.copy_typ x))); type_declaration = (fun _ x -> copy_type_declaration (type_declaration mapper (R.copy_type_declaration x))); type_extension = (fun _ x -> copy_type_extension (type_extension mapper (R.copy_type_extension x))); type_kind = (fun _ x -> copy_type_kind (type_kind mapper (R.copy_type_kind x))); value_binding = (fun _ x -> copy_value_binding (value_binding mapper (R.copy_value_binding x))); value_description = (fun _ x -> copy_value_description (value_description mapper (R.copy_value_description x))); with_constraint = (fun _ x -> copy_with_constraint (with_constraint mapper (R.copy_with_constraint x))); payload = (fun _ x -> copy_payload (payload mapper (R.copy_payload x))); (*$*) The following ones were introduced in 4.08 . binding_op = (fun _ x -> migration_error x.pbop_op.Location.loc Def.Pexp_letop); module_substitution = (fun _ x -> migration_error x.pms_loc Def.Psig_modsubst); open_declaration = (fun _ x -> migration_error x.popen_loc Def.Pexp_open); type_exception = (fun _ x -> migration_error x.ptyexn_loc Def.Psig_typesubst); }
null
https://raw.githubusercontent.com/reasonml/reason/4f6ff7616bfa699059d642a3d16d8905d83555f6/src/vendored-omp/src/migrate_parsetree_407_408.ml
ocaml
************************************************************************ OCaml Migrate Parsetree en Automatique (INRIA). All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ $ $ foreach_field (printf "%s;\n") $ $
Copyright 2017 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the include Migrate_parsetree_407_408_migrate $ open Printf let fields = [ " attribute " ; " attributes " ; " case " ; " cases " ; " class_declaration " ; " class_description " ; " class_expr " ; " class_field " ; " class_signature " ; " class_structure " ; " class_type " ; " class_type_declaration " ; " class_type_field " ; " constructor_declaration " ; " expr " ; " extension " ; " extension_constructor " ; " include_declaration " ; " include_description " ; " label_declaration " ; " location " ; " module_binding " ; " module_declaration " ; " module_expr " ; " module_type " ; " module_type_declaration " ; " open_description " ; " pat " ; " signature " ; " signature_item " ; " structure " ; " structure_item " ; " typ " ; " type_declaration " ; " type_extension " ; " type_kind " ; " value_binding " ; " value_description " ; " with_constraint " ; " payload " ] let foreach_field f = printf " \n " ; List.iter f fields let fields = [ "attribute"; "attributes"; "case"; "cases"; "class_declaration"; "class_description"; "class_expr"; "class_field"; "class_signature"; "class_structure"; "class_type"; "class_type_declaration"; "class_type_field"; "constructor_declaration"; "expr"; "extension"; "extension_constructor"; "include_declaration"; "include_description"; "label_declaration"; "location"; "module_binding"; "module_declaration"; "module_expr"; "module_type"; "module_type_declaration"; "open_description"; "pat"; "signature"; "signature_item"; "structure"; "structure_item"; "typ"; "type_declaration"; "type_extension"; "type_kind"; "value_binding"; "value_description"; "with_constraint"; "payload" ] let foreach_field f = printf "\n"; List.iter f fields let copy_mapper = fun ({ From.Ast_mapper. attribute; attributes; case; cases; class_declaration; class_description; class_expr; class_field; class_signature; class_structure; class_type; class_type_declaration; class_type_field; constructor_declaration; expr; extension; extension_constructor; include_declaration; include_description; label_declaration; location; module_binding; module_declaration; module_expr; module_type; module_type_declaration; open_description; pat; signature; signature_item; structure; structure_item; typ; type_declaration; type_extension; type_kind; value_binding; value_description; with_constraint; payload; } as mapper) -> let module Def = Migrate_parsetree_def in let migration_error location feature = raise (Def.Migration_error (feature, location)) in let module R = Migrate_parsetree_408_407_migrate in { To.Ast_mapper. $ foreach_field ( fun s - > printf " % s = ( fun _ x - > copy_%s ( % s mapper ( R.copy_%s x)));\n " s s s s ) printf "%s = (fun _ x -> copy_%s (%s mapper (R.copy_%s x)));\n" s s s s) *) attribute = (fun _ x -> copy_attribute (attribute mapper (R.copy_attribute x))); attributes = (fun _ x -> copy_attributes (attributes mapper (R.copy_attributes x))); case = (fun _ x -> copy_case (case mapper (R.copy_case x))); cases = (fun _ x -> copy_cases (cases mapper (R.copy_cases x))); class_declaration = (fun _ x -> copy_class_declaration (class_declaration mapper (R.copy_class_declaration x))); class_description = (fun _ x -> copy_class_description (class_description mapper (R.copy_class_description x))); class_expr = (fun _ x -> copy_class_expr (class_expr mapper (R.copy_class_expr x))); class_field = (fun _ x -> copy_class_field (class_field mapper (R.copy_class_field x))); class_signature = (fun _ x -> copy_class_signature (class_signature mapper (R.copy_class_signature x))); class_structure = (fun _ x -> copy_class_structure (class_structure mapper (R.copy_class_structure x))); class_type = (fun _ x -> copy_class_type (class_type mapper (R.copy_class_type x))); class_type_declaration = (fun _ x -> copy_class_type_declaration (class_type_declaration mapper (R.copy_class_type_declaration x))); class_type_field = (fun _ x -> copy_class_type_field (class_type_field mapper (R.copy_class_type_field x))); constructor_declaration = (fun _ x -> copy_constructor_declaration (constructor_declaration mapper (R.copy_constructor_declaration x))); expr = (fun _ x -> copy_expr (expr mapper (R.copy_expr x))); extension = (fun _ x -> copy_extension (extension mapper (R.copy_extension x))); extension_constructor = (fun _ x -> copy_extension_constructor (extension_constructor mapper (R.copy_extension_constructor x))); include_declaration = (fun _ x -> copy_include_declaration (include_declaration mapper (R.copy_include_declaration x))); include_description = (fun _ x -> copy_include_description (include_description mapper (R.copy_include_description x))); label_declaration = (fun _ x -> copy_label_declaration (label_declaration mapper (R.copy_label_declaration x))); location = (fun _ x -> copy_location (location mapper (R.copy_location x))); module_binding = (fun _ x -> copy_module_binding (module_binding mapper (R.copy_module_binding x))); module_declaration = (fun _ x -> copy_module_declaration (module_declaration mapper (R.copy_module_declaration x))); module_expr = (fun _ x -> copy_module_expr (module_expr mapper (R.copy_module_expr x))); module_type = (fun _ x -> copy_module_type (module_type mapper (R.copy_module_type x))); module_type_declaration = (fun _ x -> copy_module_type_declaration (module_type_declaration mapper (R.copy_module_type_declaration x))); open_description = (fun _ x -> copy_open_description (open_description mapper (R.copy_open_description x))); pat = (fun _ x -> copy_pat (pat mapper (R.copy_pat x))); signature = (fun _ x -> copy_signature (signature mapper (R.copy_signature x))); signature_item = (fun _ x -> copy_signature_item (signature_item mapper (R.copy_signature_item x))); structure = (fun _ x -> copy_structure (structure mapper (R.copy_structure x))); structure_item = (fun _ x -> copy_structure_item (structure_item mapper (R.copy_structure_item x))); typ = (fun _ x -> copy_typ (typ mapper (R.copy_typ x))); type_declaration = (fun _ x -> copy_type_declaration (type_declaration mapper (R.copy_type_declaration x))); type_extension = (fun _ x -> copy_type_extension (type_extension mapper (R.copy_type_extension x))); type_kind = (fun _ x -> copy_type_kind (type_kind mapper (R.copy_type_kind x))); value_binding = (fun _ x -> copy_value_binding (value_binding mapper (R.copy_value_binding x))); value_description = (fun _ x -> copy_value_description (value_description mapper (R.copy_value_description x))); with_constraint = (fun _ x -> copy_with_constraint (with_constraint mapper (R.copy_with_constraint x))); payload = (fun _ x -> copy_payload (payload mapper (R.copy_payload x))); The following ones were introduced in 4.08 . binding_op = (fun _ x -> migration_error x.pbop_op.Location.loc Def.Pexp_letop); module_substitution = (fun _ x -> migration_error x.pms_loc Def.Psig_modsubst); open_declaration = (fun _ x -> migration_error x.popen_loc Def.Pexp_open); type_exception = (fun _ x -> migration_error x.ptyexn_loc Def.Psig_typesubst); }
f81ff0e27810ca278d9b2336f66d3b143c588fef7c748ab0f4818b834d3b3b69
dscarpetti/codax
test_logging.clj
(ns codax.test-logging) (def ^:dynamic *logging* false) (defn logln [& args] (when *logging* (apply println args)))
null
https://raw.githubusercontent.com/dscarpetti/codax/68edc73dbdfe4d33f5d08f658052edbc3de85121/test/codax/test_logging.clj
clojure
(ns codax.test-logging) (def ^:dynamic *logging* false) (defn logln [& args] (when *logging* (apply println args)))
fe921d5c022d38103a33a1a24290ba29728094233c98c9158eb4ef0a3a2f8ede
runtimeverification/haskell-backend
Condition.hs
module Test.Kore.Simplify.Condition ( test_simplify_local_functions, test_predicateSimplification, test_simplifyPredicates, ) where import Data.Map.Strict qualified as Map import Kore.Equation (Equation) import Kore.Internal.Condition ( Condition, Conditional (..), ) import Kore.Internal.Condition qualified as Condition import Kore.Internal.Condition qualified as Conditional import Kore.Internal.MultiAnd ( MultiAnd, ) import Kore.Internal.MultiAnd qualified as MultiAnd import Kore.Internal.MultiOr qualified as MultiOr import Kore.Internal.OrCondition ( OrCondition, ) import Kore.Internal.Predicate ( Predicate, makeAndPredicate, makeCeilPredicate, makeEqualsPredicate, makeFalsePredicate, makeTruePredicate, ) import Kore.Internal.SideCondition qualified as SideCondition ( top, ) import Kore.Internal.Substitution qualified as Substitution import Kore.Internal.TermLike import Kore.Rewrite.Axiom.Identifier qualified as AxiomIdentifier ( AxiomIdentifier (..), ) import Kore.Rewrite.RewritingVariable ( RewritingVariableName, ) import Kore.Simplify.Condition qualified as Condition import Kore.Simplify.Simplify import Kore.Simplify.SubstitutionSimplifier qualified as SubstitutionSimplifier import Kore.TopBottom import Prelude.Kore import Test.Kore.Equation.Common (axiom_) import Test.Kore.Rewrite.MockSymbols qualified as Mock import Test.Kore.Simplify qualified as Test import Test.Tasty import Test.Tasty.HUnit.Ext test_simplify_local_functions :: [TestTree] test_simplify_local_functions = [ -- Constructor at top test "contradiction: f(x) = a ∧ f(x) = b" f (Right a) (Right b) , test "contradiction: a = f(x) ∧ f(x) = b" f (Left a) (Right b) , test "contradiction: a = f(x) ∧ b = f(x)" f (Left a) (Left b) , test "contradiction: f(x) = a ∧ b = f(x)" f (Right a) (Left b) , -- Sort injection at top test "contradiction: f(x) = injA ∧ f(x) = injB" f (Right injA) (Right injB) , test "contradiction: injA = f(x) ∧ f(x) = injB" f (Left injA) (Right injB) , test "contradiction: injA = f(x) ∧ injB = f(x)" f (Left injA) (Left injB) , test "contradiction: f(x) = injA ∧ injB = f(x)" f (Right injA) (Left injB) , -- Int at top test "contradiction: f(x) = 2 ∧ f(x) = 3" fInt (Right int2) (Right int3) , test "contradiction: 2 = f(x) ∧ f(x) = 3" fInt (Left int2) (Right int3) , test "contradiction: 2 = f(x) ∧ 3 = f(x)" fInt (Left int2) (Left int3) , test "contradiction: f(x) = 2 ∧ 3 = f(x)" fInt (Right int2) (Left int3) , -- Bool at top test "contradiction: f(x) = true ∧ f(x) = false" fBool (Right boolTrue) (Right boolFalse) , test "contradiction: true = f(x) ∧ f(x) = false" fBool (Left boolTrue) (Right boolFalse) , test "contradiction: true = f(x) ∧ false = f(x)" fBool (Left boolTrue) (Left boolFalse) , test "contradiction: f(x) = true ∧ false = f(x)" fBool (Right boolTrue) (Left boolFalse) , -- String at top test "contradiction: f(x) = \"one\" ∧ f(x) = \"two\"" fString (Right strOne) (Right strTwo) , test "contradiction: \"one\" = f(x) ∧ f(x) = \"two\"" fString (Left strOne) (Right strTwo) , test "contradiction: \"one\" = f(x) ∧ \"two\" = f(x)" fString (Left strOne) (Left strTwo) , test "contradiction: f(x) = \"one\" ∧ \"two\" = f(x)" fString (Right strOne) (Left strTwo) ] where f = Mock.f (mkElemVar Mock.xConfig) fInt = Mock.fInt (mkElemVar Mock.xConfigInt) fBool = Mock.fBool (mkElemVar Mock.xConfigBool) fString = Mock.fString (mkElemVar Mock.xConfigString) defined = makeCeilPredicate f & Condition.fromPredicate a = Mock.a b = Mock.b injA = Mock.sortInjection10 Mock.a injB = Mock.sortInjection10 Mock.b int2 = Mock.builtinInt 2 int3 = Mock.builtinInt 3 boolTrue = Mock.builtinBool True boolFalse = Mock.builtinBool False strOne = Mock.builtinString "one" strTwo = Mock.builtinString "two" mkLocalDefn func (Left t) = makeEqualsPredicate t func mkLocalDefn func (Right t) = makeEqualsPredicate func t test name func eitherC1 eitherC2 = testCase name $ do let equals1 = mkLocalDefn func eitherC1 & Condition.fromPredicate equals2 = mkLocalDefn func eitherC2 & Condition.fromPredicate condition = defined <> equals1 <> defined <> equals2 actual <- simplify condition assertBool "Expected \\bottom" $ isBottom actual test_predicateSimplification :: [TestTree] test_predicateSimplification = [ testCase "Identity for top and bottom" $ do actualBottom <- simplify Conditional.bottomCondition assertEqual "" mempty actualBottom actualTop <- simplify Conditional.topCondition assertEqual "" (MultiOr.singleton Conditional.topCondition) actualTop , testCase "Applies substitution to predicate" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate (Mock.f Mock.a) (Mock.g Mock.b) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- simplify Conditional { term = () , predicate = makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.g (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Simplifies predicate after substitution" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate Mock.functional00 Mock.functional01 , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } actual <- simplify Conditional { term = () , predicate = makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.constr10 (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Simplifies predicate after substitution" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate Mock.a Mock.functional00 , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [ axiom_ (Mock.f Mock.functional00) Mock.functional00 , axiom_ (Mock.f Mock.functional01) Mock.a ] ) ] ) Conditional { term = () , predicate = makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Merges substitution from predicate simplification" $ do let expect = Conditional { term = () , predicate = makeTruePredicate , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [axiom_ (Mock.f Mock.b) (Mock.constr10 Mock.a)] ) ] ) Conditional { term = () , predicate = makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Reapplies substitution from predicate simplification" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate (Mock.f Mock.a) (Mock.g Mock.a) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [axiom_ (Mock.f Mock.b) (Mock.constr10 Mock.a)] ) ] ) Conditional { term = () , predicate = makeAndPredicate ( makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) ) ( makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.g Mock.a) ) , substitution = Substitution.unsafeWrap [ (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Simplifies after reapplying substitution" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate (Mock.g Mock.a) (Mock.g Mock.b) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [ axiom_ (Mock.f Mock.b) (Mock.constr10 Mock.a) , axiom_ (Mock.f Mock.a) (Mock.g Mock.b) ] ) ] ) Conditional { term = () , predicate = makeAndPredicate ( makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) ) ( makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.g Mock.a) ) , substitution = Substitution.unsafeWrap [ (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual ] test_simplifyPredicates :: [TestTree] test_simplifyPredicates = [ testCase "\\top => \\top" $ do [actual] <- simplifyPredicates MultiAnd.top assertEqual "" Condition.top actual , testCase "\\bottom and _ => \\bottom" $ do let predicate = MultiAnd.make [ makeFalsePredicate , makeEqualsPredicate (mkElemVar Mock.xConfig) Mock.a ] actual <- simplifyPredicates predicate assertEqual "" [] actual , testCase "_ and \\bottom => \\bottom" $ do let predicate = MultiAnd.make [ makeEqualsPredicate (mkElemVar Mock.xConfig) Mock.a , makeFalsePredicate ] actual <- simplifyPredicates predicate assertEqual "" [] actual ] simplify :: Condition RewritingVariableName -> IO (OrCondition RewritingVariableName) simplify condition = conditionRunSimplifier mempty condition conditionRunSimplifier :: Map.Map AxiomIdentifier.AxiomIdentifier [Equation RewritingVariableName] -> Condition RewritingVariableName -> IO (OrCondition RewritingVariableName) conditionRunSimplifier axiomEquations predicate = fmap MultiOr.make $ Test.testRunSimplifierBranch env $ simplifier SideCondition.top predicate where env = Mock.env{axiomEquations} ConditionSimplifier simplifier = Condition.create SubstitutionSimplifier.substitutionSimplifier simplifyPredicates :: MultiAnd (Predicate RewritingVariableName) -> IO [Condition RewritingVariableName] simplifyPredicates predicate = Condition.simplifyPredicates SideCondition.top predicate & Test.testRunSimplifierBranch Mock.env
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/454211800a577c6b8d13c28457ebcdfffe2a871c/kore/test/Test/Kore/Simplify/Condition.hs
haskell
Constructor at top Sort injection at top Int at top Bool at top String at top
module Test.Kore.Simplify.Condition ( test_simplify_local_functions, test_predicateSimplification, test_simplifyPredicates, ) where import Data.Map.Strict qualified as Map import Kore.Equation (Equation) import Kore.Internal.Condition ( Condition, Conditional (..), ) import Kore.Internal.Condition qualified as Condition import Kore.Internal.Condition qualified as Conditional import Kore.Internal.MultiAnd ( MultiAnd, ) import Kore.Internal.MultiAnd qualified as MultiAnd import Kore.Internal.MultiOr qualified as MultiOr import Kore.Internal.OrCondition ( OrCondition, ) import Kore.Internal.Predicate ( Predicate, makeAndPredicate, makeCeilPredicate, makeEqualsPredicate, makeFalsePredicate, makeTruePredicate, ) import Kore.Internal.SideCondition qualified as SideCondition ( top, ) import Kore.Internal.Substitution qualified as Substitution import Kore.Internal.TermLike import Kore.Rewrite.Axiom.Identifier qualified as AxiomIdentifier ( AxiomIdentifier (..), ) import Kore.Rewrite.RewritingVariable ( RewritingVariableName, ) import Kore.Simplify.Condition qualified as Condition import Kore.Simplify.Simplify import Kore.Simplify.SubstitutionSimplifier qualified as SubstitutionSimplifier import Kore.TopBottom import Prelude.Kore import Test.Kore.Equation.Common (axiom_) import Test.Kore.Rewrite.MockSymbols qualified as Mock import Test.Kore.Simplify qualified as Test import Test.Tasty import Test.Tasty.HUnit.Ext test_simplify_local_functions :: [TestTree] test_simplify_local_functions = test "contradiction: f(x) = a ∧ f(x) = b" f (Right a) (Right b) , test "contradiction: a = f(x) ∧ f(x) = b" f (Left a) (Right b) , test "contradiction: a = f(x) ∧ b = f(x)" f (Left a) (Left b) , test "contradiction: f(x) = a ∧ b = f(x)" f (Right a) (Left b) test "contradiction: f(x) = injA ∧ f(x) = injB" f (Right injA) (Right injB) , test "contradiction: injA = f(x) ∧ f(x) = injB" f (Left injA) (Right injB) , test "contradiction: injA = f(x) ∧ injB = f(x)" f (Left injA) (Left injB) , test "contradiction: f(x) = injA ∧ injB = f(x)" f (Right injA) (Left injB) test "contradiction: f(x) = 2 ∧ f(x) = 3" fInt (Right int2) (Right int3) , test "contradiction: 2 = f(x) ∧ f(x) = 3" fInt (Left int2) (Right int3) , test "contradiction: 2 = f(x) ∧ 3 = f(x)" fInt (Left int2) (Left int3) , test "contradiction: f(x) = 2 ∧ 3 = f(x)" fInt (Right int2) (Left int3) test "contradiction: f(x) = true ∧ f(x) = false" fBool (Right boolTrue) (Right boolFalse) , test "contradiction: true = f(x) ∧ f(x) = false" fBool (Left boolTrue) (Right boolFalse) , test "contradiction: true = f(x) ∧ false = f(x)" fBool (Left boolTrue) (Left boolFalse) , test "contradiction: f(x) = true ∧ false = f(x)" fBool (Right boolTrue) (Left boolFalse) test "contradiction: f(x) = \"one\" ∧ f(x) = \"two\"" fString (Right strOne) (Right strTwo) , test "contradiction: \"one\" = f(x) ∧ f(x) = \"two\"" fString (Left strOne) (Right strTwo) , test "contradiction: \"one\" = f(x) ∧ \"two\" = f(x)" fString (Left strOne) (Left strTwo) , test "contradiction: f(x) = \"one\" ∧ \"two\" = f(x)" fString (Right strOne) (Left strTwo) ] where f = Mock.f (mkElemVar Mock.xConfig) fInt = Mock.fInt (mkElemVar Mock.xConfigInt) fBool = Mock.fBool (mkElemVar Mock.xConfigBool) fString = Mock.fString (mkElemVar Mock.xConfigString) defined = makeCeilPredicate f & Condition.fromPredicate a = Mock.a b = Mock.b injA = Mock.sortInjection10 Mock.a injB = Mock.sortInjection10 Mock.b int2 = Mock.builtinInt 2 int3 = Mock.builtinInt 3 boolTrue = Mock.builtinBool True boolFalse = Mock.builtinBool False strOne = Mock.builtinString "one" strTwo = Mock.builtinString "two" mkLocalDefn func (Left t) = makeEqualsPredicate t func mkLocalDefn func (Right t) = makeEqualsPredicate func t test name func eitherC1 eitherC2 = testCase name $ do let equals1 = mkLocalDefn func eitherC1 & Condition.fromPredicate equals2 = mkLocalDefn func eitherC2 & Condition.fromPredicate condition = defined <> equals1 <> defined <> equals2 actual <- simplify condition assertBool "Expected \\bottom" $ isBottom actual test_predicateSimplification :: [TestTree] test_predicateSimplification = [ testCase "Identity for top and bottom" $ do actualBottom <- simplify Conditional.bottomCondition assertEqual "" mempty actualBottom actualTop <- simplify Conditional.topCondition assertEqual "" (MultiOr.singleton Conditional.topCondition) actualTop , testCase "Applies substitution to predicate" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate (Mock.f Mock.a) (Mock.g Mock.b) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- simplify Conditional { term = () , predicate = makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.g (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Simplifies predicate after substitution" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate Mock.functional00 Mock.functional01 , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } actual <- simplify Conditional { term = () , predicate = makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.constr10 (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Simplifies predicate after substitution" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate Mock.a Mock.functional00 , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [ axiom_ (Mock.f Mock.functional00) Mock.functional00 , axiom_ (Mock.f Mock.functional01) Mock.a ] ) ] ) Conditional { term = () , predicate = makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.functional00) , (inject Mock.yConfig, Mock.functional01) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Merges substitution from predicate simplification" $ do let expect = Conditional { term = () , predicate = makeTruePredicate , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [axiom_ (Mock.f Mock.b) (Mock.constr10 Mock.a)] ) ] ) Conditional { term = () , predicate = makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) , substitution = Substitution.unsafeWrap [ (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Reapplies substitution from predicate simplification" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate (Mock.f Mock.a) (Mock.g Mock.a) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [axiom_ (Mock.f Mock.b) (Mock.constr10 Mock.a)] ) ] ) Conditional { term = () , predicate = makeAndPredicate ( makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) ) ( makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.g Mock.a) ) , substitution = Substitution.unsafeWrap [ (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual , testCase "Simplifies after reapplying substitution" $ do let expect = Conditional { term = () , predicate = makeEqualsPredicate (Mock.g Mock.a) (Mock.g Mock.b) , substitution = Substitution.unsafeWrap [ (inject Mock.xConfig, Mock.a) , (inject Mock.yConfig, Mock.b) ] } actual <- conditionRunSimplifier ( Map.fromList [ ( AxiomIdentifier.Application Mock.fId , [ axiom_ (Mock.f Mock.b) (Mock.constr10 Mock.a) , axiom_ (Mock.f Mock.a) (Mock.g Mock.b) ] ) ] ) Conditional { term = () , predicate = makeAndPredicate ( makeEqualsPredicate (Mock.constr10 (mkElemVar Mock.xConfig)) (Mock.f (mkElemVar Mock.yConfig)) ) ( makeEqualsPredicate (Mock.f (mkElemVar Mock.xConfig)) (Mock.g Mock.a) ) , substitution = Substitution.unsafeWrap [ (inject Mock.yConfig, Mock.b) ] } assertEqual "" (MultiOr.singleton expect) actual ] test_simplifyPredicates :: [TestTree] test_simplifyPredicates = [ testCase "\\top => \\top" $ do [actual] <- simplifyPredicates MultiAnd.top assertEqual "" Condition.top actual , testCase "\\bottom and _ => \\bottom" $ do let predicate = MultiAnd.make [ makeFalsePredicate , makeEqualsPredicate (mkElemVar Mock.xConfig) Mock.a ] actual <- simplifyPredicates predicate assertEqual "" [] actual , testCase "_ and \\bottom => \\bottom" $ do let predicate = MultiAnd.make [ makeEqualsPredicate (mkElemVar Mock.xConfig) Mock.a , makeFalsePredicate ] actual <- simplifyPredicates predicate assertEqual "" [] actual ] simplify :: Condition RewritingVariableName -> IO (OrCondition RewritingVariableName) simplify condition = conditionRunSimplifier mempty condition conditionRunSimplifier :: Map.Map AxiomIdentifier.AxiomIdentifier [Equation RewritingVariableName] -> Condition RewritingVariableName -> IO (OrCondition RewritingVariableName) conditionRunSimplifier axiomEquations predicate = fmap MultiOr.make $ Test.testRunSimplifierBranch env $ simplifier SideCondition.top predicate where env = Mock.env{axiomEquations} ConditionSimplifier simplifier = Condition.create SubstitutionSimplifier.substitutionSimplifier simplifyPredicates :: MultiAnd (Predicate RewritingVariableName) -> IO [Condition RewritingVariableName] simplifyPredicates predicate = Condition.simplifyPredicates SideCondition.top predicate & Test.testRunSimplifierBranch Mock.env
e4b47c27dfd743b56f8a69d7cb32d49c2fb5da1d8d78a2693409487bfd1b9bb0
haskell-suite/haskell-tc
Pretty.hs
module Language.Haskell.TypeCheck.Pretty ( Pretty(..) , parensIf , module Text.PrettyPrint.ANSI.Leijen ) where import Text.PrettyPrint.ANSI.Leijen hiding (Pretty(..)) class Pretty a where prettyPrec :: Int -> a -> Doc prettyPrec _ = pretty pretty :: a -> Doc pretty = prettyPrec 0 # MINIMAL prettyPrec | pretty # instance Pretty a => Pretty [a] where prettyPrec _ = list . map pretty parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id
null
https://raw.githubusercontent.com/haskell-suite/haskell-tc/abf5e3cc624e0095cae14c3c1c695b76ea8ffcb9/src/Language/Haskell/TypeCheck/Pretty.hs
haskell
module Language.Haskell.TypeCheck.Pretty ( Pretty(..) , parensIf , module Text.PrettyPrint.ANSI.Leijen ) where import Text.PrettyPrint.ANSI.Leijen hiding (Pretty(..)) class Pretty a where prettyPrec :: Int -> a -> Doc prettyPrec _ = pretty pretty :: a -> Doc pretty = prettyPrec 0 # MINIMAL prettyPrec | pretty # instance Pretty a => Pretty [a] where prettyPrec _ = list . map pretty parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id
ed9e575a29bdcac8691bee6fc79bbb03bc5449cb5524048fe66a047fa0694254
jaked/ocamljs
camlinternalOO.ml
* This file is part of ocamljs , OCaml to Javascript compiler * Copyright ( C ) 2007 - 9 Skydeck , Inc * Copyright ( C ) 2010 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation ; either * version 2 of the License , or ( at your option ) any later version . * * This library 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 * Library General Public License for more details . * * You should have received a copy of the GNU Library General Public * License along with this library ; if not , write to the Free * Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA * This file is part of ocamljs, OCaml to Javascript compiler * Copyright (C) 2007-9 Skydeck, Inc * Copyright (C) 2010 Jake Donham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA *) open Ocamljs.Inline (***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ I d : camlinternalOO.ml 2008 - 01 - 11 16:13:18Z doligez $ open Obj (**** Object representation ****) let last_id = ref 0 let new_id () = let id = !last_id in incr last_id; id let set_id o id = let id0 = !id in Array.unsafe_set (Obj.magic o : int array) 1 id0; id := id0 + 1 (**** Object copy ****) let copy o = let c = << new $o$.constructor() >> in <:stmt< var s = $o$._s; var i; for (i=0; i < s; i++) $c$[i] = $o$[i]; >>; set_id c last_id; c (**** Compression options ****) (* Parameters *) type params = { mutable compact_table : bool; mutable copy_parent : bool; mutable clean_when_copying : bool; mutable retry_count : int; mutable bucket_small_size : int } let params = { compact_table = true; copy_parent = true; clean_when_copying = true; retry_count = 3; bucket_small_size = 16 } (**** Parameters ****) let step = Sys.word_size / 16 let initial_object_size = 2 (**** Items ****) type item = DummyA | DummyB | DummyC of int let dummy_item = (magic () : item) (**** Types ****) type tag type label = int type closure = item type t = DummyA | DummyB | DummyC of int type obj = t array external ret : (obj -> 'a) -> closure = "$dummyargfun" (**** Labels ****) let public_method_label s : tag = failwith "unused" (**** Sparse array ****) module Vars = Map.Make(struct type t = string let compare = compare end) type vars = int Vars.t module Meths = Map.Make(struct type t = string let compare = compare end) type meths = label Meths.t module Labs = Map.Make(struct type t = label let compare = compare end) type labs = bool Labs.t The compiler assumes that the first field of this structure is [ size ] . type table = { mutable size: int; mutable methods: closure array; mutable methods_by_name: meths; mutable methods_by_label: labs; mutable previous_states: (meths * labs * (label * item) list * vars * label list * string list) list; mutable hidden_meths: (label * item) list; mutable vars: vars; mutable initializers: (obj -> unit) list; mutable constructor: Obj.t } let dummy_table = { methods = [| dummy_item |]; methods_by_name = Meths.empty; methods_by_label = Labs.empty; previous_states = []; hidden_meths = []; vars = Vars.empty; initializers = []; size = 0; constructor = Obj.magic 0; } let table_count = ref 0 (* dummy_met should be a pointer, so use an atom *) let dummy_met : item = obj (Obj.new_block 0 0) (* if debugging is needed, this could be a good idea: *) let dummy_met ( ) = failwith " Undefined method " let rec fit_size n = if n <= 2 then n else fit_size ((n+1)/2) * 2 let new_table len = incr table_count; { methods = Array.create len dummy_met; methods_by_name = Meths.empty; methods_by_label = Labs.empty; previous_states = []; hidden_meths = []; vars = Vars.empty; initializers = []; size = initial_object_size; constructor = Obj.magic 0; } let resize array new_size = let old_size = Array.length array.methods in if new_size > old_size then begin let new_buck = Array.create new_size dummy_met in Array.blit array.methods 0 new_buck 0 old_size; array.methods <- new_buck end let put array label element = resize array (label + 1); array.methods.(label) <- element (**** Classes ****) let method_count = ref 0 let inst_var_count = ref 0 (* type t *) type meth = item let new_method table = let index = Array.length table.methods in resize table (index + 1); index let get_method_label table name = try Meths.find name table.methods_by_name with Not_found -> let label = new_method table in table.methods_by_name <- Meths.add name label table.methods_by_name; table.methods_by_label <- Labs.add label true table.methods_by_label; label let get_method_labels table names = Array.map (get_method_label table) names let set_method table label element = incr method_count; if Labs.find label table.methods_by_label then put table label element else table.hidden_meths <- (label, element) :: table.hidden_meths let get_method table label = try List.assoc label table.hidden_meths with Not_found -> table.methods.(label) let to_list arr = if arr == magic 0 then [] else Array.to_list arr let narrow table vars virt_meths concr_meths = let vars = to_list vars and virt_meths = to_list virt_meths and concr_meths = to_list concr_meths in let virt_meth_labs = List.map (get_method_label table) virt_meths in let concr_meth_labs = List.map (get_method_label table) concr_meths in table.previous_states <- (table.methods_by_name, table.methods_by_label, table.hidden_meths, table.vars, virt_meth_labs, vars) :: table.previous_states; table.vars <- Vars.fold (fun lab info tvars -> if List.mem lab vars then Vars.add lab info tvars else tvars) table.vars Vars.empty; let by_name = ref Meths.empty in let by_label = ref Labs.empty in List.iter2 (fun met label -> by_name := Meths.add met label !by_name; by_label := Labs.add label (try Labs.find label table.methods_by_label with Not_found -> true) !by_label) concr_meths concr_meth_labs; List.iter2 (fun met label -> by_name := Meths.add met label !by_name; by_label := Labs.add label false !by_label) virt_meths virt_meth_labs; table.methods_by_name <- !by_name; table.methods_by_label <- !by_label; table.hidden_meths <- List.fold_right (fun ((lab, _) as met) hm -> if List.mem lab virt_meth_labs then hm else met::hm) table.hidden_meths [] let widen table = let (by_name, by_label, saved_hidden_meths, saved_vars, virt_meths, vars) = List.hd table.previous_states in table.previous_states <- List.tl table.previous_states; table.vars <- List.fold_left (fun s v -> Vars.add v (Vars.find v table.vars) s) saved_vars vars; table.methods_by_name <- by_name; table.methods_by_label <- by_label; table.hidden_meths <- List.fold_right (fun ((lab, _) as met) hm -> if List.mem lab virt_meths then hm else met::hm) table.hidden_meths saved_hidden_meths let new_slot table = let index = table.size in table.size <- index + 1; index let new_variable table name = try Vars.find name table.vars with Not_found -> let index = new_slot table in if name <> "" then table.vars <- Vars.add name index table.vars; index let to_array arr = if arr = Obj.magic 0 then [||] else arr let new_methods_variables table meths vals = let meths = to_array meths in let nmeths = Array.length meths and nvals = Array.length vals in let res = Array.create (nmeths + nvals) 0 in for i = 0 to nmeths - 1 do res.(i) <- get_method_label table meths.(i) done; for i = 0 to nvals - 1 do res.(i+nmeths) <- new_variable table vals.(i) done; res let get_variable table name = try Vars.find name table.vars with Not_found -> assert false let get_variables table names = Array.map (get_variable table) names let add_initializer table f = table.initializers <- f::table.initializers module Keys = Map . Make(struct type t = tag array let compare = compare end ) let key_map = ref Keys.empty let get_key tags : item = try magic ( Keys.find tags ! key_map : tag array ) with Not_found - > key_map : = Keys.add tags tags ! key_map ; magic tags module Keys = Map.Make(struct type t = tag array let compare = compare end) let key_map = ref Keys.empty let get_key tags : item = try magic (Keys.find tags !key_map : tag array) with Not_found -> key_map := Keys.add tags tags !key_map; magic tags *) let create_table public_methods = if public_methods == magic 0 then new_table 0 else (* [public_methods] must be in ascending order for bytecode *) let table = new_table (Array.length public_methods) in Array.iteri (fun i met -> let lab = i in table.methods_by_name <- Meths.add met lab table.methods_by_name; table.methods_by_label <- Labs.add lab true table.methods_by_label) public_methods; table let init_class table = inst_var_count := !inst_var_count + table.size - 1; table.initializers <- List.rev table.initializers; table.constructor <- << function () { } >>; Meths.iter (fun met lab -> <:stmt< $table.constructor$.prototype[$met$] = $table.methods$[$lab$]; >>) table.methods_by_name; <:stmt< $table.constructor$.prototype._m = $table.methods$; $table.constructor$.prototype._s = $table.size$; >> let inherits cla vals virt_meths concr_meths (_, super, _, env) top = narrow cla vals virt_meths concr_meths; let init = if top then super cla env else Obj.repr (super cla) in widen cla; Array.concat [[| repr init |]; magic (Array.map (get_variable cla) (to_array vals) : int array); Array.map (fun nm -> repr (get_method cla (get_method_label cla nm) : closure)) (to_array concr_meths) ] let make_class pub_meths class_init = let table = create_table pub_meths in let env_init = class_init table in init_class table; (env_init (Obj.repr 0), class_init, env_init, Obj.repr 0) type init_table = { mutable env_init: t; mutable class_init: table -> t } let make_class_store pub_meths class_init init_table = let table = create_table pub_meths in let env_init = class_init table in init_class table; init_table.class_init <- class_init; init_table.env_init <- env_init let dummy_class loc = let undef = fun _ -> raise (Undefined_recursive_module loc) in (Obj.magic undef, undef, undef, Obj.repr 0) (**** Objects ****) let create_object table = (* XXX Appel de [obj_block] *) let obj = << new $table.constructor$() >> in set_id obj last_id; (Obj.obj obj) let create_object_opt obj_0 table = if (Obj.magic obj_0 : bool) then obj_0 else begin (* XXX Appel de [obj_block] *) let obj = << new $table.constructor$() >> in set_id obj last_id; (Obj.obj obj) end let rec iter_f obj = function [] -> () | f::l -> <:stmt< _m($f$, $obj$, []); >>; iter_f obj l let run_initializers obj table = let inits = table.initializers in if inits <> [] then iter_f obj inits let run_initializers_opt obj_0 obj table = if (Obj.magic obj_0 : bool) then obj else begin let inits = table.initializers in if inits <> [] then iter_f obj inits; obj end let create_object_and_run_initializers obj_0 table = if (Obj.magic obj_0 : bool) then obj_0 else begin let obj = create_object table in run_initializers obj table; obj end Equivalent primitive below let sendself obj lab = ( magic obj : ( obj - > t ) array array).(0).(lab ) obj let sendself obj lab = (magic obj : (obj -> t) array array).(0).(lab) obj *) external send : obj -> tag -> 'a = "%send" external sendcache : obj -> tag -> t -> int -> 'a = "%sendcache" external sendself : obj -> label -> 'a = "%sendself" external get_public_method : obj -> tag -> closure = "caml_get_public_method" "noalloc" (**** table collection access ****) type tables = Empty | Cons of closure * tables * tables type mut_tables = {key: closure; mutable data: tables; mutable next: tables} external mut : tables -> mut_tables = "%identity" let build_path n keys tables = let res = Cons (Obj.magic 0, Empty, Empty) in let r = ref res in for i = 0 to n do r := Cons (keys.(i), !r, Empty) done; tables.data <- !r; res let rec lookup_keys i keys tables = if i < 0 then tables else let key = keys.(i) in let rec lookup_key tables = if tables.key == key then lookup_keys (i-1) keys tables.data else if tables.next <> Empty then lookup_key (mut tables.next) else let next = Cons (key, Empty, Empty) in tables.next <- next; build_path (i-1) keys (mut next) in lookup_key (mut tables) let lookup_tables root keys = let root = mut root in if root.data <> Empty then lookup_keys (Array.length keys - 1) keys root.data else build_path (Array.length keys - 1) keys root (**** builtin methods ****) let get_const x = hack so if you say let foo x = ... method foo = foo then the result can be called from Javascript with o.foo(x ) instead of o.foo()(x ) hack so if you say let foo x = ... method foo = foo then the result can be called from Javascript with o.foo(x) instead of o.foo()(x) *) << typeof $x$ === "function" ? $x$ : $ret (fun obj -> x)$ >> let get_var n = ret (fun obj -> Array.unsafe_get << this >> n) let get_env e n = ret (fun obj -> Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n) let get_meth n = ret (fun obj -> sendself << this >> n) let set_var n = ret (fun obj x -> Array.unsafe_set << this >> n x) let app_const f x = ret (fun obj -> f x) let app_var f n = ret (fun obj -> f (Array.unsafe_get << this >> n)) let app_env f e n = ret (fun obj -> f (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n)) let app_meth f n = ret (fun obj -> f (sendself << this >> n)) let app_const_const f x y = ret (fun obj -> f x y) let app_const_var f x n = ret (fun obj -> f x (Array.unsafe_get << this >> n)) let app_const_meth f x n = ret (fun obj -> f x (sendself << this >> n)) let app_var_const f n x = ret (fun obj -> f (Array.unsafe_get << this >> n) x) let app_meth_const f n x = ret (fun obj -> f (sendself << this >> n) x) let app_const_env f x e n = ret (fun obj -> f x (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n)) let app_env_const f e n x = ret (fun obj -> f (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n) x) let meth_app_const n x = ret (fun obj -> (sendself << this >> n : _ -> _) x) let meth_app_var n m = ret (fun obj -> (sendself << this >> n : _ -> _) (Array.unsafe_get << this >> m)) let meth_app_env n e m = ret (fun obj -> (sendself << this >> n : _ -> _) (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) m)) let meth_app_meth n m = ret (fun obj -> (sendself << this >> n : _ -> _) (sendself << this >> m)) let send_const m x = ret (fun obj -> send x m) let send_var m n = ret (fun obj -> send (Obj.magic (Array.unsafe_get << this >> n) : obj) m) let send_env m e n = ret (fun obj -> send (Obj.magic (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n) : obj) m) let send_meth m n = ret (fun obj -> send (sendself << this >> n) m) type impl = GetConst | GetVar | GetEnv | GetMeth | SetVar | AppConst | AppVar | AppEnv | AppMeth | AppConstConst | AppConstVar | AppConstEnv | AppConstMeth | AppVarConst | AppEnvConst | AppMethConst | MethAppConst | MethAppVar | MethAppEnv | MethAppMeth | SendConst | SendVar | SendEnv | SendMeth | Closure of closure let method_impl table i arr = let next () = incr i; magic arr.(!i) in match next() with GetConst -> let x : t = next() in get_const x | GetVar -> let n = next() in get_var n | GetEnv -> let e = next() and n = next() in get_env e n | GetMeth -> let n = next() in get_meth n | SetVar -> let n = next() in set_var n | AppConst -> let f = next() and x = next() in app_const f x | AppVar -> let f = next() and n = next () in app_var f n | AppEnv -> let f = next() and e = next() and n = next() in app_env f e n | AppMeth -> let f = next() and n = next () in app_meth f n | AppConstConst -> let f = next() and x = next() and y = next() in app_const_const f x y | AppConstVar -> let f = next() and x = next() and n = next() in app_const_var f x n | AppConstEnv -> let f = next() and x = next() and e = next () and n = next() in app_const_env f x e n | AppConstMeth -> let f = next() and x = next() and n = next() in app_const_meth f x n | AppVarConst -> let f = next() and n = next() and x = next() in app_var_const f n x | AppEnvConst -> let f = next() and e = next () and n = next() and x = next() in app_env_const f e n x | AppMethConst -> let f = next() and n = next() and x = next() in app_meth_const f n x | MethAppConst -> let n = next() and x = next() in meth_app_const n x | MethAppVar -> let n = next() and m = next() in meth_app_var n m | MethAppEnv -> let n = next() and e = next() and m = next() in meth_app_env n e m | MethAppMeth -> let n = next() and m = next() in meth_app_meth n m | SendConst -> let m = next() and x = next() in send_const m x | SendVar -> let m = next() and n = next () in send_var m n | SendEnv -> let m = next() and e = next() and n = next() in send_env m e n | SendMeth -> let m = next() and n = next () in send_meth m n | Closure _ as clo -> magic clo let set_methods table methods = let len = Array.length methods and i = ref 0 in while !i < len do let label = methods.(!i) and clo = method_impl table i methods in set_method table label clo; incr i done (**** Statistics ****) type stats = { classes: int; methods: int; inst_vars: int; } let stats () = { classes = !table_count; methods = !method_count; inst_vars = !inst_var_count; }
null
https://raw.githubusercontent.com/jaked/ocamljs/378080ff1c8033bb15ed2bd29bf1443e301d7af8/src/stdlib/patches/3.12.0/camlinternalOO.ml
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* *** Object representation *** *** Object copy *** *** Compression options *** Parameters *** Parameters *** *** Items *** *** Types *** *** Labels *** *** Sparse array *** dummy_met should be a pointer, so use an atom if debugging is needed, this could be a good idea: *** Classes *** type t [public_methods] must be in ascending order for bytecode *** Objects *** XXX Appel de [obj_block] XXX Appel de [obj_block] *** table collection access *** *** builtin methods *** *** Statistics ***
* This file is part of ocamljs , OCaml to Javascript compiler * Copyright ( C ) 2007 - 9 Skydeck , Inc * Copyright ( C ) 2010 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation ; either * version 2 of the License , or ( at your option ) any later version . * * This library 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 * Library General Public License for more details . * * You should have received a copy of the GNU Library General Public * License along with this library ; if not , write to the Free * Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA * This file is part of ocamljs, OCaml to Javascript compiler * Copyright (C) 2007-9 Skydeck, Inc * Copyright (C) 2010 Jake Donham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA *) open Ocamljs.Inline , projet Cristal , INRIA Rocquencourt Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ I d : camlinternalOO.ml 2008 - 01 - 11 16:13:18Z doligez $ open Obj let last_id = ref 0 let new_id () = let id = !last_id in incr last_id; id let set_id o id = let id0 = !id in Array.unsafe_set (Obj.magic o : int array) 1 id0; id := id0 + 1 let copy o = let c = << new $o$.constructor() >> in <:stmt< var s = $o$._s; var i; for (i=0; i < s; i++) $c$[i] = $o$[i]; >>; set_id c last_id; c type params = { mutable compact_table : bool; mutable copy_parent : bool; mutable clean_when_copying : bool; mutable retry_count : int; mutable bucket_small_size : int } let params = { compact_table = true; copy_parent = true; clean_when_copying = true; retry_count = 3; bucket_small_size = 16 } let step = Sys.word_size / 16 let initial_object_size = 2 type item = DummyA | DummyB | DummyC of int let dummy_item = (magic () : item) type tag type label = int type closure = item type t = DummyA | DummyB | DummyC of int type obj = t array external ret : (obj -> 'a) -> closure = "$dummyargfun" let public_method_label s : tag = failwith "unused" module Vars = Map.Make(struct type t = string let compare = compare end) type vars = int Vars.t module Meths = Map.Make(struct type t = string let compare = compare end) type meths = label Meths.t module Labs = Map.Make(struct type t = label let compare = compare end) type labs = bool Labs.t The compiler assumes that the first field of this structure is [ size ] . type table = { mutable size: int; mutable methods: closure array; mutable methods_by_name: meths; mutable methods_by_label: labs; mutable previous_states: (meths * labs * (label * item) list * vars * label list * string list) list; mutable hidden_meths: (label * item) list; mutable vars: vars; mutable initializers: (obj -> unit) list; mutable constructor: Obj.t } let dummy_table = { methods = [| dummy_item |]; methods_by_name = Meths.empty; methods_by_label = Labs.empty; previous_states = []; hidden_meths = []; vars = Vars.empty; initializers = []; size = 0; constructor = Obj.magic 0; } let table_count = ref 0 let dummy_met : item = obj (Obj.new_block 0 0) let dummy_met ( ) = failwith " Undefined method " let rec fit_size n = if n <= 2 then n else fit_size ((n+1)/2) * 2 let new_table len = incr table_count; { methods = Array.create len dummy_met; methods_by_name = Meths.empty; methods_by_label = Labs.empty; previous_states = []; hidden_meths = []; vars = Vars.empty; initializers = []; size = initial_object_size; constructor = Obj.magic 0; } let resize array new_size = let old_size = Array.length array.methods in if new_size > old_size then begin let new_buck = Array.create new_size dummy_met in Array.blit array.methods 0 new_buck 0 old_size; array.methods <- new_buck end let put array label element = resize array (label + 1); array.methods.(label) <- element let method_count = ref 0 let inst_var_count = ref 0 type meth = item let new_method table = let index = Array.length table.methods in resize table (index + 1); index let get_method_label table name = try Meths.find name table.methods_by_name with Not_found -> let label = new_method table in table.methods_by_name <- Meths.add name label table.methods_by_name; table.methods_by_label <- Labs.add label true table.methods_by_label; label let get_method_labels table names = Array.map (get_method_label table) names let set_method table label element = incr method_count; if Labs.find label table.methods_by_label then put table label element else table.hidden_meths <- (label, element) :: table.hidden_meths let get_method table label = try List.assoc label table.hidden_meths with Not_found -> table.methods.(label) let to_list arr = if arr == magic 0 then [] else Array.to_list arr let narrow table vars virt_meths concr_meths = let vars = to_list vars and virt_meths = to_list virt_meths and concr_meths = to_list concr_meths in let virt_meth_labs = List.map (get_method_label table) virt_meths in let concr_meth_labs = List.map (get_method_label table) concr_meths in table.previous_states <- (table.methods_by_name, table.methods_by_label, table.hidden_meths, table.vars, virt_meth_labs, vars) :: table.previous_states; table.vars <- Vars.fold (fun lab info tvars -> if List.mem lab vars then Vars.add lab info tvars else tvars) table.vars Vars.empty; let by_name = ref Meths.empty in let by_label = ref Labs.empty in List.iter2 (fun met label -> by_name := Meths.add met label !by_name; by_label := Labs.add label (try Labs.find label table.methods_by_label with Not_found -> true) !by_label) concr_meths concr_meth_labs; List.iter2 (fun met label -> by_name := Meths.add met label !by_name; by_label := Labs.add label false !by_label) virt_meths virt_meth_labs; table.methods_by_name <- !by_name; table.methods_by_label <- !by_label; table.hidden_meths <- List.fold_right (fun ((lab, _) as met) hm -> if List.mem lab virt_meth_labs then hm else met::hm) table.hidden_meths [] let widen table = let (by_name, by_label, saved_hidden_meths, saved_vars, virt_meths, vars) = List.hd table.previous_states in table.previous_states <- List.tl table.previous_states; table.vars <- List.fold_left (fun s v -> Vars.add v (Vars.find v table.vars) s) saved_vars vars; table.methods_by_name <- by_name; table.methods_by_label <- by_label; table.hidden_meths <- List.fold_right (fun ((lab, _) as met) hm -> if List.mem lab virt_meths then hm else met::hm) table.hidden_meths saved_hidden_meths let new_slot table = let index = table.size in table.size <- index + 1; index let new_variable table name = try Vars.find name table.vars with Not_found -> let index = new_slot table in if name <> "" then table.vars <- Vars.add name index table.vars; index let to_array arr = if arr = Obj.magic 0 then [||] else arr let new_methods_variables table meths vals = let meths = to_array meths in let nmeths = Array.length meths and nvals = Array.length vals in let res = Array.create (nmeths + nvals) 0 in for i = 0 to nmeths - 1 do res.(i) <- get_method_label table meths.(i) done; for i = 0 to nvals - 1 do res.(i+nmeths) <- new_variable table vals.(i) done; res let get_variable table name = try Vars.find name table.vars with Not_found -> assert false let get_variables table names = Array.map (get_variable table) names let add_initializer table f = table.initializers <- f::table.initializers module Keys = Map . Make(struct type t = tag array let compare = compare end ) let key_map = ref Keys.empty let get_key tags : item = try magic ( Keys.find tags ! key_map : tag array ) with Not_found - > key_map : = Keys.add tags tags ! key_map ; magic tags module Keys = Map.Make(struct type t = tag array let compare = compare end) let key_map = ref Keys.empty let get_key tags : item = try magic (Keys.find tags !key_map : tag array) with Not_found -> key_map := Keys.add tags tags !key_map; magic tags *) let create_table public_methods = if public_methods == magic 0 then new_table 0 else let table = new_table (Array.length public_methods) in Array.iteri (fun i met -> let lab = i in table.methods_by_name <- Meths.add met lab table.methods_by_name; table.methods_by_label <- Labs.add lab true table.methods_by_label) public_methods; table let init_class table = inst_var_count := !inst_var_count + table.size - 1; table.initializers <- List.rev table.initializers; table.constructor <- << function () { } >>; Meths.iter (fun met lab -> <:stmt< $table.constructor$.prototype[$met$] = $table.methods$[$lab$]; >>) table.methods_by_name; <:stmt< $table.constructor$.prototype._m = $table.methods$; $table.constructor$.prototype._s = $table.size$; >> let inherits cla vals virt_meths concr_meths (_, super, _, env) top = narrow cla vals virt_meths concr_meths; let init = if top then super cla env else Obj.repr (super cla) in widen cla; Array.concat [[| repr init |]; magic (Array.map (get_variable cla) (to_array vals) : int array); Array.map (fun nm -> repr (get_method cla (get_method_label cla nm) : closure)) (to_array concr_meths) ] let make_class pub_meths class_init = let table = create_table pub_meths in let env_init = class_init table in init_class table; (env_init (Obj.repr 0), class_init, env_init, Obj.repr 0) type init_table = { mutable env_init: t; mutable class_init: table -> t } let make_class_store pub_meths class_init init_table = let table = create_table pub_meths in let env_init = class_init table in init_class table; init_table.class_init <- class_init; init_table.env_init <- env_init let dummy_class loc = let undef = fun _ -> raise (Undefined_recursive_module loc) in (Obj.magic undef, undef, undef, Obj.repr 0) let create_object table = let obj = << new $table.constructor$() >> in set_id obj last_id; (Obj.obj obj) let create_object_opt obj_0 table = if (Obj.magic obj_0 : bool) then obj_0 else begin let obj = << new $table.constructor$() >> in set_id obj last_id; (Obj.obj obj) end let rec iter_f obj = function [] -> () | f::l -> <:stmt< _m($f$, $obj$, []); >>; iter_f obj l let run_initializers obj table = let inits = table.initializers in if inits <> [] then iter_f obj inits let run_initializers_opt obj_0 obj table = if (Obj.magic obj_0 : bool) then obj else begin let inits = table.initializers in if inits <> [] then iter_f obj inits; obj end let create_object_and_run_initializers obj_0 table = if (Obj.magic obj_0 : bool) then obj_0 else begin let obj = create_object table in run_initializers obj table; obj end Equivalent primitive below let sendself obj lab = ( magic obj : ( obj - > t ) array array).(0).(lab ) obj let sendself obj lab = (magic obj : (obj -> t) array array).(0).(lab) obj *) external send : obj -> tag -> 'a = "%send" external sendcache : obj -> tag -> t -> int -> 'a = "%sendcache" external sendself : obj -> label -> 'a = "%sendself" external get_public_method : obj -> tag -> closure = "caml_get_public_method" "noalloc" type tables = Empty | Cons of closure * tables * tables type mut_tables = {key: closure; mutable data: tables; mutable next: tables} external mut : tables -> mut_tables = "%identity" let build_path n keys tables = let res = Cons (Obj.magic 0, Empty, Empty) in let r = ref res in for i = 0 to n do r := Cons (keys.(i), !r, Empty) done; tables.data <- !r; res let rec lookup_keys i keys tables = if i < 0 then tables else let key = keys.(i) in let rec lookup_key tables = if tables.key == key then lookup_keys (i-1) keys tables.data else if tables.next <> Empty then lookup_key (mut tables.next) else let next = Cons (key, Empty, Empty) in tables.next <- next; build_path (i-1) keys (mut next) in lookup_key (mut tables) let lookup_tables root keys = let root = mut root in if root.data <> Empty then lookup_keys (Array.length keys - 1) keys root.data else build_path (Array.length keys - 1) keys root let get_const x = hack so if you say let foo x = ... method foo = foo then the result can be called from Javascript with o.foo(x ) instead of o.foo()(x ) hack so if you say let foo x = ... method foo = foo then the result can be called from Javascript with o.foo(x) instead of o.foo()(x) *) << typeof $x$ === "function" ? $x$ : $ret (fun obj -> x)$ >> let get_var n = ret (fun obj -> Array.unsafe_get << this >> n) let get_env e n = ret (fun obj -> Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n) let get_meth n = ret (fun obj -> sendself << this >> n) let set_var n = ret (fun obj x -> Array.unsafe_set << this >> n x) let app_const f x = ret (fun obj -> f x) let app_var f n = ret (fun obj -> f (Array.unsafe_get << this >> n)) let app_env f e n = ret (fun obj -> f (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n)) let app_meth f n = ret (fun obj -> f (sendself << this >> n)) let app_const_const f x y = ret (fun obj -> f x y) let app_const_var f x n = ret (fun obj -> f x (Array.unsafe_get << this >> n)) let app_const_meth f x n = ret (fun obj -> f x (sendself << this >> n)) let app_var_const f n x = ret (fun obj -> f (Array.unsafe_get << this >> n) x) let app_meth_const f n x = ret (fun obj -> f (sendself << this >> n) x) let app_const_env f x e n = ret (fun obj -> f x (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n)) let app_env_const f e n x = ret (fun obj -> f (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n) x) let meth_app_const n x = ret (fun obj -> (sendself << this >> n : _ -> _) x) let meth_app_var n m = ret (fun obj -> (sendself << this >> n : _ -> _) (Array.unsafe_get << this >> m)) let meth_app_env n e m = ret (fun obj -> (sendself << this >> n : _ -> _) (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) m)) let meth_app_meth n m = ret (fun obj -> (sendself << this >> n : _ -> _) (sendself << this >> m)) let send_const m x = ret (fun obj -> send x m) let send_var m n = ret (fun obj -> send (Obj.magic (Array.unsafe_get << this >> n) : obj) m) let send_env m e n = ret (fun obj -> send (Obj.magic (Array.unsafe_get (Obj.magic (Array.unsafe_get << this >> e) : obj) n) : obj) m) let send_meth m n = ret (fun obj -> send (sendself << this >> n) m) type impl = GetConst | GetVar | GetEnv | GetMeth | SetVar | AppConst | AppVar | AppEnv | AppMeth | AppConstConst | AppConstVar | AppConstEnv | AppConstMeth | AppVarConst | AppEnvConst | AppMethConst | MethAppConst | MethAppVar | MethAppEnv | MethAppMeth | SendConst | SendVar | SendEnv | SendMeth | Closure of closure let method_impl table i arr = let next () = incr i; magic arr.(!i) in match next() with GetConst -> let x : t = next() in get_const x | GetVar -> let n = next() in get_var n | GetEnv -> let e = next() and n = next() in get_env e n | GetMeth -> let n = next() in get_meth n | SetVar -> let n = next() in set_var n | AppConst -> let f = next() and x = next() in app_const f x | AppVar -> let f = next() and n = next () in app_var f n | AppEnv -> let f = next() and e = next() and n = next() in app_env f e n | AppMeth -> let f = next() and n = next () in app_meth f n | AppConstConst -> let f = next() and x = next() and y = next() in app_const_const f x y | AppConstVar -> let f = next() and x = next() and n = next() in app_const_var f x n | AppConstEnv -> let f = next() and x = next() and e = next () and n = next() in app_const_env f x e n | AppConstMeth -> let f = next() and x = next() and n = next() in app_const_meth f x n | AppVarConst -> let f = next() and n = next() and x = next() in app_var_const f n x | AppEnvConst -> let f = next() and e = next () and n = next() and x = next() in app_env_const f e n x | AppMethConst -> let f = next() and n = next() and x = next() in app_meth_const f n x | MethAppConst -> let n = next() and x = next() in meth_app_const n x | MethAppVar -> let n = next() and m = next() in meth_app_var n m | MethAppEnv -> let n = next() and e = next() and m = next() in meth_app_env n e m | MethAppMeth -> let n = next() and m = next() in meth_app_meth n m | SendConst -> let m = next() and x = next() in send_const m x | SendVar -> let m = next() and n = next () in send_var m n | SendEnv -> let m = next() and e = next() and n = next() in send_env m e n | SendMeth -> let m = next() and n = next () in send_meth m n | Closure _ as clo -> magic clo let set_methods table methods = let len = Array.length methods and i = ref 0 in while !i < len do let label = methods.(!i) and clo = method_impl table i methods in set_method table label clo; incr i done type stats = { classes: int; methods: int; inst_vars: int; } let stats () = { classes = !table_count; methods = !method_count; inst_vars = !inst_var_count; }
1a619c81f4961ec008845fb290bad961cea087648afbcd6ff6474d4c568b43a4
erpuno/upl
upl_app.erl
-module(upl_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> upl_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/erpuno/upl/170f71900feadd1160305a589b13b0846b51772d/src/upl_app.erl
erlang
-module(upl_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> upl_sup:start_link(). stop(_State) -> ok.
96d3cec9d1cbb718158eb15c5b8a33a086963499a8318c535163172a1555ae6f
QDelta/fcomp
Gen.hs
module Core.Gen (genCore) where import qualified Data.Map as M import qualified Data.Set as S import Common.Def import Common.AST import Type.Inf import Core.Def import Prim.Name import Prim.Core type GlobalInfo = (M.Map Ident Int, S.Set Ident) -- constructor tag, global name genCore :: Program Name -> CoreProgram genCore (dataGroups, valGroups) = (coreConstrs, coreFns) where coreConstrs = primConstrs ++ defConstrs defConstrs = concatMap genConstrs defDataBinds defDataBinds = concatMap (\(RecData l) -> l) dataGroups cMap = genConstrInfo coreConstrs defValBinds = concatMap getValBinds valGroups gSet = genGIdents defValBinds defConstrs `S.union` primIdents gInfo = (cMap, gSet) coreFns = map (genFn gInfo) defValBinds genConstrInfo :: [CoreConstr] -> M.Map Ident Int genConstrInfo = foldl (\m (n, a, t) -> M.insert (getIdent n) t m) M.empty genGIdents :: [Bind Name] -> [CoreConstr] -> S.Set Ident genGIdents fnDefs constrs = foldl (\s (n, _) -> S.insert (getIdent n) s) S.empty fnDefs `S.union` foldl (\s (n, _, _) -> S.insert (getIdent n) s) S.empty constrs genConstrs :: DataBind Name -> [CoreConstr] genConstrs (name, _, constrs) = zipWith genC constrs [0..] where genC (name, tSigs) tag = (name, length tSigs, tag) genFn :: GlobalInfo -> Bind Name -> CoreFn genFn gInfo (name, expr) = (name, params, genExpr gInfo body) where (params, body) = deLam expr deLam :: Expr Name -> ([Ident], Expr Name) deLam (LambdaE ps expr) = (map getIdent ps, expr) deLam expr = ([], expr) genExpr :: GlobalInfo -> Expr Name -> CoreExpr genExpr _ (IntE n) = IntCE n genExpr (cMap, gSet) (VarE name) = let id = getIdent name in if id `S.member` gSet then if id `M.member` cMap then GConstrCE name else GFnCE name else LVarCE id genExpr gInfo (AppE e1 e2) = AppCE (gen e1) (gen e2) where gen = genExpr gInfo genExpr gInfo (CaseE e brs) = CaseCE ce coreBrs where ce = genExpr gInfo e coreBrs = map (genBranch gInfo) brs genExpr gInfo (LetE bind e) = LetCE (genBind gInfo bind) (genExpr gInfo e) genExpr gInfo (LetRecE binds e) = LetRecCE (map (genBind gInfo) binds) (genExpr gInfo e) genExpr gInfo (LambdaE params e) = LambdaCE (map getIdent params) (genExpr gInfo e) genBind :: GlobalInfo -> Bind Name -> CoreBind genBind gInfo (n, e) = (getIdent n, genExpr gInfo e) genBranch :: GlobalInfo -> Branch Name -> CoreBranch genBranch gInfo@(cMap, _) (name, binds, e) = (tag, map getIdent binds, genExpr gInfo e) where tag = cMap M.! getIdent name primConstrs :: [CoreConstr] primConstrs = map (\(s, arity, tag) -> (primNameMap M.! s, arity, tag)) primCoreConstrs primIdents :: S.Set Ident primIdents = S.fromList (enumFromTo minPrimIdent maxPrimIdent)
null
https://raw.githubusercontent.com/QDelta/fcomp/eceb8e4ab9b10ece7f4671689b96e73ea7a8e8b3/app/Core/Gen.hs
haskell
constructor tag, global name
module Core.Gen (genCore) where import qualified Data.Map as M import qualified Data.Set as S import Common.Def import Common.AST import Type.Inf import Core.Def import Prim.Name import Prim.Core genCore :: Program Name -> CoreProgram genCore (dataGroups, valGroups) = (coreConstrs, coreFns) where coreConstrs = primConstrs ++ defConstrs defConstrs = concatMap genConstrs defDataBinds defDataBinds = concatMap (\(RecData l) -> l) dataGroups cMap = genConstrInfo coreConstrs defValBinds = concatMap getValBinds valGroups gSet = genGIdents defValBinds defConstrs `S.union` primIdents gInfo = (cMap, gSet) coreFns = map (genFn gInfo) defValBinds genConstrInfo :: [CoreConstr] -> M.Map Ident Int genConstrInfo = foldl (\m (n, a, t) -> M.insert (getIdent n) t m) M.empty genGIdents :: [Bind Name] -> [CoreConstr] -> S.Set Ident genGIdents fnDefs constrs = foldl (\s (n, _) -> S.insert (getIdent n) s) S.empty fnDefs `S.union` foldl (\s (n, _, _) -> S.insert (getIdent n) s) S.empty constrs genConstrs :: DataBind Name -> [CoreConstr] genConstrs (name, _, constrs) = zipWith genC constrs [0..] where genC (name, tSigs) tag = (name, length tSigs, tag) genFn :: GlobalInfo -> Bind Name -> CoreFn genFn gInfo (name, expr) = (name, params, genExpr gInfo body) where (params, body) = deLam expr deLam :: Expr Name -> ([Ident], Expr Name) deLam (LambdaE ps expr) = (map getIdent ps, expr) deLam expr = ([], expr) genExpr :: GlobalInfo -> Expr Name -> CoreExpr genExpr _ (IntE n) = IntCE n genExpr (cMap, gSet) (VarE name) = let id = getIdent name in if id `S.member` gSet then if id `M.member` cMap then GConstrCE name else GFnCE name else LVarCE id genExpr gInfo (AppE e1 e2) = AppCE (gen e1) (gen e2) where gen = genExpr gInfo genExpr gInfo (CaseE e brs) = CaseCE ce coreBrs where ce = genExpr gInfo e coreBrs = map (genBranch gInfo) brs genExpr gInfo (LetE bind e) = LetCE (genBind gInfo bind) (genExpr gInfo e) genExpr gInfo (LetRecE binds e) = LetRecCE (map (genBind gInfo) binds) (genExpr gInfo e) genExpr gInfo (LambdaE params e) = LambdaCE (map getIdent params) (genExpr gInfo e) genBind :: GlobalInfo -> Bind Name -> CoreBind genBind gInfo (n, e) = (getIdent n, genExpr gInfo e) genBranch :: GlobalInfo -> Branch Name -> CoreBranch genBranch gInfo@(cMap, _) (name, binds, e) = (tag, map getIdent binds, genExpr gInfo e) where tag = cMap M.! getIdent name primConstrs :: [CoreConstr] primConstrs = map (\(s, arity, tag) -> (primNameMap M.! s, arity, tag)) primCoreConstrs primIdents :: S.Set Ident primIdents = S.fromList (enumFromTo minPrimIdent maxPrimIdent)
9fecda774986c5dcdbd0dd75f5125fbb0a023730e12b1a471262c1f76cfc0f17
zlatozar/study-paip
examples-krep1.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CH14 - FIRST ; Base : 10 -*- ;;; Code from Paradigms of Artificial Intelligence Programming Copyright ( c ) 1991 ;;;; File examples-krep1.lisp (in-package #:ch14-first) (defexamples 14.1 "Knowledge Representation and Reasoning" "" "In this chapter we explore means of indexing facts so that they can be" "retrieved and reasoned with efficiently." "" "Section 14.1 to 14.7 discuss problems with logical reasoning systems" "such as Prolog." "" (:section "14.8 A Solution to the Indexing Problem") "" "Here we show how to index facts in a kind of table that makes it easy to" "add, delete, and retrieve entries. We will develop an extension of the" "trie or discrimination tree data structure built in section 10.5 (page 344)." "" "Now we define a function to test the indexing routine. Compare the output" "with figure 14.1 on page 474." "" ((test-index) @ 478) "" "Here is an example of fetching from the index" ((fetch '(p ? c)) @ 480 => (((P B C) (P A C)) ((P A ?X)))) "We can make a change to rename variables before indexing facts." ((defun index (key) "Store key in a dtree node. Key must be (predicate . args); it is stored in the predicate's dtree." (dtree-index key (rename-variables key) ; store unique vars (get-dtree (predicate key)))) @ 481) "" "We have to reindex:" ((test-index)) "We are now ready to test the retrieval mechanism:" "" ((fetch '(p ?x c)) @ 481) ((retrieve '(p ?x c)) @ 481) ((retrieve-matches '(p ?x c)) => ((P A C) (P A C) (P B C))) ((retrieve-matches '(p ?x (?fn c))) => ((P A (?FN C)) (P A (F C)) (P B (F C)))) ((query-bind (?x ?fn) '(p ?x (?fn c)) (format t "~&P holds between ~a and ~a of c." ?x ?fn)) @ 482) )
null
https://raw.githubusercontent.com/zlatozar/study-paip/dfa1ca6118f718f5d47d8c63cbb7b4cad23671e1/ch14/examples-krep1.lisp
lisp
Syntax : COMMON - LISP ; Package : CH14 - FIRST ; Base : 10 -*- Code from Paradigms of Artificial Intelligence Programming File examples-krep1.lisp store unique vars
Copyright ( c ) 1991 (in-package #:ch14-first) (defexamples 14.1 "Knowledge Representation and Reasoning" "" "In this chapter we explore means of indexing facts so that they can be" "retrieved and reasoned with efficiently." "" "Section 14.1 to 14.7 discuss problems with logical reasoning systems" "such as Prolog." "" (:section "14.8 A Solution to the Indexing Problem") "" "Here we show how to index facts in a kind of table that makes it easy to" "add, delete, and retrieve entries. We will develop an extension of the" "trie or discrimination tree data structure built in section 10.5 (page 344)." "" "Now we define a function to test the indexing routine. Compare the output" "with figure 14.1 on page 474." "" ((test-index) @ 478) "" "Here is an example of fetching from the index" ((fetch '(p ? c)) @ 480 => (((P B C) (P A C)) ((P A ?X)))) "We can make a change to rename variables before indexing facts." ((defun index (key) it is stored in the predicate's dtree." (get-dtree (predicate key)))) @ 481) "" "We have to reindex:" ((test-index)) "We are now ready to test the retrieval mechanism:" "" ((fetch '(p ?x c)) @ 481) ((retrieve '(p ?x c)) @ 481) ((retrieve-matches '(p ?x c)) => ((P A C) (P A C) (P B C))) ((retrieve-matches '(p ?x (?fn c))) => ((P A (?FN C)) (P A (F C)) (P B (F C)))) ((query-bind (?x ?fn) '(p ?x (?fn c)) (format t "~&P holds between ~a and ~a of c." ?x ?fn)) @ 482) )
d8e39e8096a5e63101c50c9ba6922f0a99994f5a768aaa78297ee6ae835d4a8a
vernemq/vernemq
vmq_reg_sup.erl
Copyright 2018 Erlio GmbH Basel Switzerland ( ) %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(vmq_reg_sup). -behaviour(supervisor). %% API -export([ start_link/0, start_reg_view/1, stop_reg_view/1, reconfigure_registry/1 ]). %% Supervisor callbacks -export([init/1]). -define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args}, permanent, 5000, Type, [Mod]}). %%%=================================================================== %%% API functions %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the supervisor %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link() -> {ok, Pid} = supervisor:start_link({local, ?MODULE}, ?MODULE, []), DefaultRegView = vmq_config:get_env(default_reg_view, vmq_reg_trie), RegViews = lists:usort([DefaultRegView | vmq_config:get_env(reg_views, [])]), _ = [{ok, _} = start_reg_view(RV) || RV <- RegViews], {ok, Pid}. reconfigure_registry(Config) -> case lists:keyfind(reg_views, 1, Config) of {_, RegViews} -> DefaultRegView = vmq_config:get_env(default_reg_view, vmq_reg_trie), RequiredRegViews = lists:usort([DefaultRegView | RegViews]), InstalledRegViews = [ Id || {{reg_view, Id}, _, _, _} <- supervisor:which_children(?MODULE) ], ToBeInstalled = RequiredRegViews -- InstalledRegViews, ToBeUnInstalled = InstalledRegViews -- RequiredRegViews, install_reg_views(ToBeInstalled), uninstall_reg_views(ToBeUnInstalled); false -> ok end. install_reg_views([RV | RegViews]) -> case start_reg_view(RV) of {ok, _} -> lager:info("installed reg view ~p", [RV]), install_reg_views(RegViews); {error, Reason} -> lager:error("can't install reg view ~p due to ~p", [RV, Reason]), install_reg_views(RegViews) end; install_reg_views([]) -> ok. uninstall_reg_views([RV | RegViews]) -> case stop_reg_view(RV) of {error, Reason} -> lager:error("can't uninstall reg view ~p due to ~p", [RV, Reason]), uninstall_reg_views(RegViews); _ -> lager:info("uninstalled reg view ~p", [RV]), uninstall_reg_views(RegViews) end; uninstall_reg_views([]) -> ok. start_reg_view(ViewModule) -> supervisor:start_child(?MODULE, reg_view_child_spec(ViewModule)). stop_reg_view(ViewModule) -> ChildId = {reg_view, ViewModule}, case supervisor:terminate_child(?MODULE, ChildId) of ok -> supervisor:delete_child(?MODULE, ChildId); {error, Reason} -> {error, Reason} end. %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Whenever a supervisor is started using supervisor:start_link/[2,3], %% this function is called by the new process to find out about %% restart strategy, maximum restart frequency and child %% specifications. %% ) - > { ok , { SupFlags , [ ChildSpec ] } } | %% ignore | %% {error, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> {ok, {{one_for_one, 5, 10}, [ ?CHILD(vmq_reg_mgr, vmq_reg_mgr, worker, []), ?CHILD(vmq_retain_srv, vmq_retain_srv, worker, []), ?CHILD(vmq_reg_sync_action_sup, vmq_reg_sync_action_sup, supervisor, []), ?CHILD(vmq_reg_sync, vmq_reg_sync, worker, []) ]}}. %%%=================================================================== Internal functions %%%=================================================================== reg_view_child_spec(ViewModule) -> ?CHILD({reg_view, ViewModule}, ViewModule, worker, []).
null
https://raw.githubusercontent.com/vernemq/vernemq/234d253250cb5371b97ebb588622076fdabc6a5f/apps/vmq_server/src/vmq_reg_sup.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. API Supervisor callbacks =================================================================== API functions =================================================================== -------------------------------------------------------------------- @doc Starts the supervisor @end -------------------------------------------------------------------- =================================================================== Supervisor callbacks =================================================================== -------------------------------------------------------------------- @doc Whenever a supervisor is started using supervisor:start_link/[2,3], this function is called by the new process to find out about restart strategy, maximum restart frequency and child specifications. ignore | {error, Reason} @end -------------------------------------------------------------------- =================================================================== ===================================================================
Copyright 2018 Erlio GmbH Basel Switzerland ( ) Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(vmq_reg_sup). -behaviour(supervisor). -export([ start_link/0, start_reg_view/1, stop_reg_view/1, reconfigure_registry/1 ]). -export([init/1]). -define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args}, permanent, 5000, Type, [Mod]}). ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> {ok, Pid} = supervisor:start_link({local, ?MODULE}, ?MODULE, []), DefaultRegView = vmq_config:get_env(default_reg_view, vmq_reg_trie), RegViews = lists:usort([DefaultRegView | vmq_config:get_env(reg_views, [])]), _ = [{ok, _} = start_reg_view(RV) || RV <- RegViews], {ok, Pid}. reconfigure_registry(Config) -> case lists:keyfind(reg_views, 1, Config) of {_, RegViews} -> DefaultRegView = vmq_config:get_env(default_reg_view, vmq_reg_trie), RequiredRegViews = lists:usort([DefaultRegView | RegViews]), InstalledRegViews = [ Id || {{reg_view, Id}, _, _, _} <- supervisor:which_children(?MODULE) ], ToBeInstalled = RequiredRegViews -- InstalledRegViews, ToBeUnInstalled = InstalledRegViews -- RequiredRegViews, install_reg_views(ToBeInstalled), uninstall_reg_views(ToBeUnInstalled); false -> ok end. install_reg_views([RV | RegViews]) -> case start_reg_view(RV) of {ok, _} -> lager:info("installed reg view ~p", [RV]), install_reg_views(RegViews); {error, Reason} -> lager:error("can't install reg view ~p due to ~p", [RV, Reason]), install_reg_views(RegViews) end; install_reg_views([]) -> ok. uninstall_reg_views([RV | RegViews]) -> case stop_reg_view(RV) of {error, Reason} -> lager:error("can't uninstall reg view ~p due to ~p", [RV, Reason]), uninstall_reg_views(RegViews); _ -> lager:info("uninstalled reg view ~p", [RV]), uninstall_reg_views(RegViews) end; uninstall_reg_views([]) -> ok. start_reg_view(ViewModule) -> supervisor:start_child(?MODULE, reg_view_child_spec(ViewModule)). stop_reg_view(ViewModule) -> ChildId = {reg_view, ViewModule}, case supervisor:terminate_child(?MODULE, ChildId) of ok -> supervisor:delete_child(?MODULE, ChildId); {error, Reason} -> {error, Reason} end. @private ) - > { ok , { SupFlags , [ ChildSpec ] } } | init([]) -> {ok, {{one_for_one, 5, 10}, [ ?CHILD(vmq_reg_mgr, vmq_reg_mgr, worker, []), ?CHILD(vmq_retain_srv, vmq_retain_srv, worker, []), ?CHILD(vmq_reg_sync_action_sup, vmq_reg_sync_action_sup, supervisor, []), ?CHILD(vmq_reg_sync, vmq_reg_sync, worker, []) ]}}. Internal functions reg_view_child_spec(ViewModule) -> ?CHILD({reg_view, ViewModule}, ViewModule, worker, []).
c694b13071c030d5e6edd4ac9b7449470d2ecf2fb8314a8c3c0aa81a9a435b9a
ANSSI-FR/mabo
printers.ml
MaBo - MRT & BGP pretty printers * < > * Guillaume Valadon <> *) open Types open MrtTools (** Split a string into a string list using the character c as the delimiter. *) let rec split s c = try let w = String.index s c in (safe_sub s 0 w)::(split ((safe_sub s (w+1) ((String.length s) -w-1))) c) with |Not_found -> [s] * a list of strings with a delimiter . let rec join s l = match l with | [] -> "" | e::[] -> e | e::tail -> e ^ s ^ (join s tail) * Return the first u elements of a list . let rec list_until ?(i=0) l u = match l with | e::lst when i < u -> e::(list_until lst (u-1)) | _ -> [] (** Return the last u elements of a list. *) let rec list_from ?(i=0) l u = match l with | e::lst when i >= u -> e::(list_from lst (u-1)) | e::lst -> (list_from lst (u-1)) | _ -> [] * Convert an integer timestamp to a string formated as MM / DD / : MM let timestamp_to_string timestamp = let ts = Unix.gmtime (Int32.to_float timestamp) in Printf.sprintf "%.2i/%.2i/%.2i %.2i:%.2i:%.2i" (ts.Unix.tm_mon+1) ts.Unix.tm_mday (ts.Unix.tm_year-100) ts.Unix.tm_hour ts.Unix.tm_min ts.Unix.tm_sec (** Print an AS path *) let print_as_path ?(ap_str="ASPATH:") l = let rec pap l = let rec p l = match l with | ASN16(e)::lst | ASN32(e)::lst -> (Printf.sprintf "%lu" e)::(p lst) | [] -> [] in match l with | AS_SET(e)::lst -> " {" ^ (join "," (p e)) ^ "}" ^ (pap lst) | AS_SEQUENCE(e)::lst -> " " ^ (join " " (p e)) ^ (pap lst) | AS_CONFED_SET(e)::lst -> " [" ^ (join " " (p e)) ^ "]" ^ (pap lst) | AS_CONFED_SEQUENCE(e)::lst -> " (" ^ (join " " (p e)) ^ ")" ^ (pap lst) | Unknown_AS_PATH_TYPE(n)::lst -> " " ^ "Unknown PATH type:" ^ (string_of_int n) ^ (pap lst) | [] -> "" in match l with | [] -> Printf.printf "%s\n" ap_str | _ -> Printf.printf "%s%s\n" ap_str (pap l) (** Print the COMMUNITY attribute *) let print_communities l = let rec pc l = match l with | (65535,65281)::lst -> " " ^ "no-export" ^ (pc lst) | (asn, value)::lst -> " " ^ (Printf.sprintf "%i:%i" asn value) ^ (pc lst) | [] -> "" in Printf.printf "COMMUNITY:%s\n" (pc l) * Print the NLRI attribute let print_nlri l s = let rec print_nh l = match l with | IPv4(ip)::lst | IPv6(ip)::lst -> Printf.printf "NEXT_HOP: %s\n" ip; print_nh lst | UnknownIP(n)::lst -> print_nh lst | [] -> () in Printf.printf "MP_REACH_NLRI%s\n" s; print_nh l (** Print a list of prefixes *) let rec print_prefixes ?(spacing="") p = match p with | Prefix(IPv4(ip), plen)::lst | Prefix(IPv6(ip), plen)::lst -> Printf.printf "%s%s/%i\n" spacing ip plen; print_prefixes ~spacing:spacing lst | Prefix(UnknownIP(a), plen)::lst -> Printf.printf "%sUNKNOWN_IP %i\n" spacing a; print_prefixes ~spacing:spacing lst | [] -> () (** Print the FROM line *) let rec print_from ?(from_str="FROM: ") peers p_i = match List.length peers with | n when n > p_i -> (let _,ipa,asn = List.nth peers p_i in match ipa with | IPv6(a) | IPv4(a) -> Printf.printf "%s%s AS%lu\n" from_str a asn | UnknownIP(a) -> Printf.printf "%sUNKNOWN_IP %i AS%lu\n" from_str a asn) | n -> Printf.printf "%sPEER_NOT_FOUND (%d/%d)\n" from_str p_i n * Print a list of RIB entries let print_origin value = let origin_str = match value with | 0 -> "IGP" | 1 -> "EGP" | 2 -> "INCOMPLETE" | _ -> Printf.sprintf "%i (UNKNOWN)" value in Printf.printf "ORIGIN: %s\n" origin_str (** Sort the attributes according to their attr_type values. *) let sort_bgp_attributes attr_lst = List.sort compare attr_lst * Merge AS_PATH and AS4_PATH . The methodology is described in RFC 4893 , page 5 . The methodology is described in RFC 4893, page 5. *) let merge_as_path attr_lst = let internal attr_lst ap a4p = Retrieve AS PATH as a list of integers let rec get_asn paths = let rec p l = match l with | ASN16(e)::lst | ASN32(e)::lst -> e::(p lst) | [] -> [] in match paths with | AS_SEQUENCE(e)::lst | AS_SET(e)::lst -> (p e)@(get_asn lst) | Unknown_AS_PATH_TYPE(n)::lst -> [-1l]@(get_asn lst) | [] -> [] | AS_CONFED_SEQUENCE(e)::lst | AS_CONFED_SET(e)::lst -> let msg = "merge_as_path(): don't know what to do with AS_CONFED_* !\n" in raise (MRTParsingError msg) in let get_path attr = match List.hd attr with | BGPAttributeAS_PATH(_, p) | BGPAttributeAS4_PATH(_, p) -> p | _ -> [] in Compare the number of AS number in AS*_PATH let lap = get_asn (get_path ap) and la4p = get_asn (get_path a4p) and lenap = List.length (get_asn (get_path ap)) and lena4p = List.length (get_asn (get_path a4p)) in match lenap < lena4p with If AS_PATH is smaller than AS4_PATH keep AS_PATH | true -> List.filter (fun x -> match x with BGPAttributeAS4_PATH(_, _) -> false | _ -> true) attr_lst If AS_PATH is greater or equal to AS4_PATH keep merge them | false -> let new_path = (list_until lap (lenap-lena4p))@la4p in let new_as_set = [AS_SEQUENCE(List.map (fun x -> ASN32(x)) new_path)] in let new_attr_list = List.filter (fun x -> match x with | BGPAttributeAS4_PATH(_, _) -> true | _ -> false) attr_lst in (* Return BGPAttributeAS4_PATH only *) List.map (fun x -> match x with | BGPAttributeAS4_PATH(f, _) -> BGPAttributeAS4_PATH(f, new_as_set) | n -> n) new_attr_list in Isolate AS_PATH and AS4_PATH attributes let ap = List.filter (fun x -> match x with BGPAttributeAS_PATH(_, _) -> true | _ -> false) attr_lst in let a4p = List.filter (fun x -> match x with BGPAttributeAS4_PATH(_, _) -> true | _ -> false) attr_lst in (* Decide to keep or merge attributes. *) (match List.length ap, List.length a4p with | 0,0 -> [] | 1,0 -> ap | 0,1 -> a4p | 1,1 -> internal attr_lst ap a4p | a,b -> raise (MRTPrintingError (Printf.sprintf "merge_as_path: can't handle these set of AS*_PATH (%i %i) !\n" a b))) (** Print BGP attributes *) let rec print_attr l = match l with | BGPAttributeORIGIN(_, origin)::lst -> print_origin origin; print_attr lst | BGPAttributeAS4_PATH(_, path_segments)::lst | BGPAttributeAS_PATH(_, path_segments)::lst -> print_as_path path_segments; print_attr lst | BGPAttributeNEXT_HOP(_, next_hop)::lst -> Printf.printf "NEXT_HOP: %s\n" next_hop; print_attr lst | BGPAttributeAS4_AGGREGATOR(_, ASN16(asn), ip)::lst (* will never happen *) | BGPAttributeAS4_AGGREGATOR(_, ASN32(asn), ip)::lst | BGPAttributeAGGREGATOR(_, ASN16(asn), ip)::lst | BGPAttributeAGGREGATOR(_, ASN32(asn), ip)::lst -> (match asn with | 23456l -> () |_ -> Printf.printf "AGGREGATOR: AS%lu %s\n" asn ip); print_attr lst | BGPAttributeMULTI_EXIT_DISC(_, med)::lst -> Printf.printf "MULTI_EXIT_DISC: %lu\n" med; print_attr lst | BGPAttributeATOMIC_AGGREGATE(_)::lst -> Printf.printf "ATOMIC_AGGREGATE\n"; print_attr lst | BGPAttributeCOMMUNITY(_, communities)::lst -> print_communities communities; print_attr lst | BGPAttributeMP_REACH_NLRI(_, INET, _, nh_list, prefixes)::lst -> print_nlri nh_list ""; let rec print_prefixes p = match p with | Prefix(IPv4(prefix), plen)::l -> Printf.printf "NLRI: %s/%i\n" prefix plen | Prefix(_, _)::l -> print_prefixes l | [] -> () in print_prefixes prefixes; print_attr lst | BGPAttributeMP_REACH_NLRI(_, INET6, _, nh_list, _)::lst -> print_nlri nh_list "(IPv6 Unicast)"; print_attr lst | BGPAttributeMP_REACH_NLRI(_, _, _, _, _)::lst -> print_attr lst | BGPAttributeMP_REACH_NLRI_abbreviated(_, nh_list)::lst -> print_nlri nh_list "(IPv6 Unicast)"; print_attr lst | BGPAttributeMP_UNREACH_NLRI(_, _, _, _)::lst -> Printf.printf "MP_UNREACH_NLRI(IPv6 Unicast)\n"; print_attr lst | BGPAttributeUnknown(f,t)::lst -> Printf.printf " UNKNOWN_ATTR(%i, %i)\n" f t; print_attr lst | [] -> () * Print RIB entries . let rec print_ribentry ?(peers = []) l = match l with | RIBEntry(p_i, ts,_, rel):: lst -> print_from peers p_i; Printf.printf "ORIGINATED: %s\n" (timestamp_to_string ts); print_attr (merge_as_path (sort_bgp_attributes rel)); print_ribentry lst | [] -> () (** Print NLRI REACH & UNREACH *) let rec print_reach_nlri attr = let rec get_prefixes p = match p with | Prefix(IPv6(prefix), plen)::l -> (Printf.sprintf " %s/%i\n" prefix plen) ^ (get_prefixes l) | Prefix(_, _)::l -> get_prefixes l | [] -> "" in let rec internal attr ann_str with_str = match attr with | BGPAttributeMP_REACH_NLRI(_, INET6, _, _, prefixes)::lst -> internal lst (ann_str ^ (get_prefixes prefixes)) with_str | BGPAttributeMP_UNREACH_NLRI(_, INET6, _, prefixes)::lst -> internal lst ann_str (with_str ^ (get_prefixes prefixes)) | _::lst -> internal lst ann_str with_str | [] -> ann_str,with_str in let announce, withdraw = internal attr "" "" in (match String.length announce with | 0 -> () | _ -> Printf.printf "ANNOUNCE\n%s" announce); (match String.length withdraw with | 0 -> () | _ -> Printf.printf "WITHDRAW\n%s" withdraw) * Convert a FSM state to a string let fsm_state_to_str state = match state with | Idle -> "Idle" | Connect -> "Connect" | Active -> "Active" | OpenSent -> "Opensent" | OpenConfirm -> "Openconfirm" | Established -> "Established" | FSM_STATE_UNKNOWN n -> Printf.sprintf "UNKNOWN STATE %i" n (** Print the MRT header *) let rec get_peers l = match l with | PeerEntry(b, i, ASN16(a))::lst | PeerEntry(b, i, ASN32(a))::lst -> (b, i, a)::(get_peers lst) | _::lst -> get_peers lst | [] -> [] let print_mrt ?(peers = []) hdr = match hdr with | MRTHeader(ts, TABLE_DUMP_v2(PEER_INDEX_TABLE(bgpid, viewname, l))) -> let rec print l = match l with | PeerEntry(b, IPv4(i), ASN16(a))::lst | PeerEntry(b, IPv6(i), ASN16(a))::lst | PeerEntry(b, IPv4(i), ASN32(a))::lst | PeerEntry(b, IPv6(i), ASN32(a))::lst -> Printf.printf "PEER: %s %s %lu\n" b i a; print lst | _::lst -> print lst | [] -> () in Printf.printf "TIME: %s\n" (timestamp_to_string ts); print l | MRTHeader(ts, TABLE_DUMP_v2(RIB_IPV4_UNICAST(seq, Prefix(prefix46, plen_bits), l))) | MRTHeader(ts, TABLE_DUMP_v2(RIB_IPV6_UNICAST(seq, Prefix(prefix46, plen_bits), l))) -> let prefix_header = match prefix46 with | IPv4(prefix) -> (Printf.sprintf "TYPE: TABLE_DUMP_V2/IPV4_UNICAST\n") ^ (Printf.sprintf "PREFIX: %s/%i\n" prefix plen_bits) | IPv6(prefix) -> (Printf.sprintf "TYPE: TABLE_DUMP_V2/IPV6_UNICAST\n") ^ (Printf.sprintf "PREFIX: %s/%i\n" prefix plen_bits) | UnknownIP(a) -> (Printf.sprintf "TYPE: TABLE_DUMP_V2/UNKNOWNIP\n") ^ (Printf.sprintf "PREFIX: UNKNOWN_IP %i\n" a) in let dump_header = (Printf.sprintf "TIME: %s\n" (timestamp_to_string ts)) ^ prefix_header ^ (Printf.sprintf "SEQUENCE: %lu\n" seq) in let rec print_re l dump_hdr = match l with | re::lst -> Printf.printf "%s" dump_hdr; print_ribentry ~peers:peers [re]; print_newline (); print_re lst dump_hdr | [] -> () in print_re l dump_header | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(_), ASN16(_), _, _, _, BGP_OPEN(v, ASN16(myasn), htime, id, params)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(_), ASN32(_), _, _, _, BGP_OPEN(v, ASN16(myasn), htime, id, params)))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Open\n"; Printf.printf "VERSION: %d\n" v; Printf.printf "AS: %lu\n" myasn; Printf.printf "HOLD_TIME: %d\n" htime; Printf.printf "ID: %s\n" id; Printf.printf "OPT_PARM_LEN: %d\n" (List.length params); print_newline () | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv4(pi), IPv4(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv6(pi), IPv6(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv6(pi), IPv6(li), BGP_UPDATE(wr, attr, prefixes)))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Update\n"; Printf.printf "FROM: %s AS%lu\n" pi pa; Printf.printf "TO: %s AS%lu\n" li la; print_attr (merge_as_path (sort_bgp_attributes attr)); print_reach_nlri attr; (* IPv6 only *) (match List.length wr with | 0 -> () | n -> Printf.printf "WITHDRAW\n"; print_prefixes ~spacing:" " wr); (match List.length prefixes with | 0 -> () | n -> Printf.printf "ANNOUNCE\n"; print_prefixes ~spacing:" " prefixes); print_newline () | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv4(pi), IPv4(li), BGP_KEEPALIVE))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_KEEPALIVE))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv6(pi), IPv6(li), BGP_KEEPALIVE))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv6(pi), IPv6(li), BGP_KEEPALIVE))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Keepalive\n"; Printf.printf "FROM: %s AS%lu\n" pi pa; Printf.printf "TO: %s AS%lu\n" li la; print_newline () | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv4(pi), IPv4(li), BGP_NOTIFICATION(c, sc, d)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_NOTIFICATION(c, sc, d)))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv6(pi), IPv6(li), BGP_NOTIFICATION(c, sc, d)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv6(pi), IPv6(li), BGP_NOTIFICATION(c, sc, d)))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Notification %i %i %s\n" c sc d; Printf.printf "FROM: %s AS%lu\n" pi pa; Printf.printf "TO: %s AS%lu\n" li la; print_newline () | MRTHeader(ts, BGP4MP(STATE_CHANGE(ASN16(pa), ASN16(la), ii, afi, IPv4(pi), IPv4(li), old_state, new_state))) | MRTHeader(ts, BGP4MP(STATE_CHANGE(ASN16(pa), ASN16(la), ii, afi, IPv6(pi), IPv6(li), old_state, new_state))) | MRTHeader(ts, BGP4MP(STATE_CHANGE_AS4(ASN32(pa), ASN32(la), ii, afi, IPv4(pi), IPv4(li), old_state, new_state))) | MRTHeader(ts, BGP4MP(STATE_CHANGE_AS4(ASN32(pa), ASN32(la), ii, afi, IPv6(pi), IPv6(li), old_state, new_state))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/STATE_CHANGE\n"; Printf.printf "PEER: %s AS%lu\n" pi pa; Printf.printf "STATE: %s/%s\n" (fsm_state_to_str old_state) (fsm_state_to_str new_state); print_newline () | MRTHeader(_, _) -> ()
null
https://raw.githubusercontent.com/ANSSI-FR/mabo/19000c66f7ecf58eb9cfa66a4cc75a4c76f3ab20/src/printers.ml
ocaml
* Split a string into a string list using the character c as the delimiter. * Return the last u elements of a list. * Print an AS path * Print the COMMUNITY attribute * Print a list of prefixes * Print the FROM line * Sort the attributes according to their attr_type values. Return BGPAttributeAS4_PATH only Decide to keep or merge attributes. * Print BGP attributes will never happen * Print NLRI REACH & UNREACH * Print the MRT header IPv6 only
MaBo - MRT & BGP pretty printers * < > * Guillaume Valadon <> *) open Types open MrtTools let rec split s c = try let w = String.index s c in (safe_sub s 0 w)::(split ((safe_sub s (w+1) ((String.length s) -w-1))) c) with |Not_found -> [s] * a list of strings with a delimiter . let rec join s l = match l with | [] -> "" | e::[] -> e | e::tail -> e ^ s ^ (join s tail) * Return the first u elements of a list . let rec list_until ?(i=0) l u = match l with | e::lst when i < u -> e::(list_until lst (u-1)) | _ -> [] let rec list_from ?(i=0) l u = match l with | e::lst when i >= u -> e::(list_from lst (u-1)) | e::lst -> (list_from lst (u-1)) | _ -> [] * Convert an integer timestamp to a string formated as MM / DD / : MM let timestamp_to_string timestamp = let ts = Unix.gmtime (Int32.to_float timestamp) in Printf.sprintf "%.2i/%.2i/%.2i %.2i:%.2i:%.2i" (ts.Unix.tm_mon+1) ts.Unix.tm_mday (ts.Unix.tm_year-100) ts.Unix.tm_hour ts.Unix.tm_min ts.Unix.tm_sec let print_as_path ?(ap_str="ASPATH:") l = let rec pap l = let rec p l = match l with | ASN16(e)::lst | ASN32(e)::lst -> (Printf.sprintf "%lu" e)::(p lst) | [] -> [] in match l with | AS_SET(e)::lst -> " {" ^ (join "," (p e)) ^ "}" ^ (pap lst) | AS_SEQUENCE(e)::lst -> " " ^ (join " " (p e)) ^ (pap lst) | AS_CONFED_SET(e)::lst -> " [" ^ (join " " (p e)) ^ "]" ^ (pap lst) | AS_CONFED_SEQUENCE(e)::lst -> " (" ^ (join " " (p e)) ^ ")" ^ (pap lst) | Unknown_AS_PATH_TYPE(n)::lst -> " " ^ "Unknown PATH type:" ^ (string_of_int n) ^ (pap lst) | [] -> "" in match l with | [] -> Printf.printf "%s\n" ap_str | _ -> Printf.printf "%s%s\n" ap_str (pap l) let print_communities l = let rec pc l = match l with | (65535,65281)::lst -> " " ^ "no-export" ^ (pc lst) | (asn, value)::lst -> " " ^ (Printf.sprintf "%i:%i" asn value) ^ (pc lst) | [] -> "" in Printf.printf "COMMUNITY:%s\n" (pc l) * Print the NLRI attribute let print_nlri l s = let rec print_nh l = match l with | IPv4(ip)::lst | IPv6(ip)::lst -> Printf.printf "NEXT_HOP: %s\n" ip; print_nh lst | UnknownIP(n)::lst -> print_nh lst | [] -> () in Printf.printf "MP_REACH_NLRI%s\n" s; print_nh l let rec print_prefixes ?(spacing="") p = match p with | Prefix(IPv4(ip), plen)::lst | Prefix(IPv6(ip), plen)::lst -> Printf.printf "%s%s/%i\n" spacing ip plen; print_prefixes ~spacing:spacing lst | Prefix(UnknownIP(a), plen)::lst -> Printf.printf "%sUNKNOWN_IP %i\n" spacing a; print_prefixes ~spacing:spacing lst | [] -> () let rec print_from ?(from_str="FROM: ") peers p_i = match List.length peers with | n when n > p_i -> (let _,ipa,asn = List.nth peers p_i in match ipa with | IPv6(a) | IPv4(a) -> Printf.printf "%s%s AS%lu\n" from_str a asn | UnknownIP(a) -> Printf.printf "%sUNKNOWN_IP %i AS%lu\n" from_str a asn) | n -> Printf.printf "%sPEER_NOT_FOUND (%d/%d)\n" from_str p_i n * Print a list of RIB entries let print_origin value = let origin_str = match value with | 0 -> "IGP" | 1 -> "EGP" | 2 -> "INCOMPLETE" | _ -> Printf.sprintf "%i (UNKNOWN)" value in Printf.printf "ORIGIN: %s\n" origin_str let sort_bgp_attributes attr_lst = List.sort compare attr_lst * Merge AS_PATH and AS4_PATH . The methodology is described in RFC 4893 , page 5 . The methodology is described in RFC 4893, page 5. *) let merge_as_path attr_lst = let internal attr_lst ap a4p = Retrieve AS PATH as a list of integers let rec get_asn paths = let rec p l = match l with | ASN16(e)::lst | ASN32(e)::lst -> e::(p lst) | [] -> [] in match paths with | AS_SEQUENCE(e)::lst | AS_SET(e)::lst -> (p e)@(get_asn lst) | Unknown_AS_PATH_TYPE(n)::lst -> [-1l]@(get_asn lst) | [] -> [] | AS_CONFED_SEQUENCE(e)::lst | AS_CONFED_SET(e)::lst -> let msg = "merge_as_path(): don't know what to do with AS_CONFED_* !\n" in raise (MRTParsingError msg) in let get_path attr = match List.hd attr with | BGPAttributeAS_PATH(_, p) | BGPAttributeAS4_PATH(_, p) -> p | _ -> [] in Compare the number of AS number in AS*_PATH let lap = get_asn (get_path ap) and la4p = get_asn (get_path a4p) and lenap = List.length (get_asn (get_path ap)) and lena4p = List.length (get_asn (get_path a4p)) in match lenap < lena4p with If AS_PATH is smaller than AS4_PATH keep AS_PATH | true -> List.filter (fun x -> match x with BGPAttributeAS4_PATH(_, _) -> false | _ -> true) attr_lst If AS_PATH is greater or equal to AS4_PATH keep merge them | false -> let new_path = (list_until lap (lenap-lena4p))@la4p in let new_as_set = [AS_SEQUENCE(List.map (fun x -> ASN32(x)) new_path)] in let new_attr_list = List.filter (fun x -> match x with | BGPAttributeAS4_PATH(_, _) -> true | _ -> false) attr_lst in List.map (fun x -> match x with | BGPAttributeAS4_PATH(f, _) -> BGPAttributeAS4_PATH(f, new_as_set) | n -> n) new_attr_list in Isolate AS_PATH and AS4_PATH attributes let ap = List.filter (fun x -> match x with BGPAttributeAS_PATH(_, _) -> true | _ -> false) attr_lst in let a4p = List.filter (fun x -> match x with BGPAttributeAS4_PATH(_, _) -> true | _ -> false) attr_lst in (match List.length ap, List.length a4p with | 0,0 -> [] | 1,0 -> ap | 0,1 -> a4p | 1,1 -> internal attr_lst ap a4p | a,b -> raise (MRTPrintingError (Printf.sprintf "merge_as_path: can't handle these set of AS*_PATH (%i %i) !\n" a b))) let rec print_attr l = match l with | BGPAttributeORIGIN(_, origin)::lst -> print_origin origin; print_attr lst | BGPAttributeAS4_PATH(_, path_segments)::lst | BGPAttributeAS_PATH(_, path_segments)::lst -> print_as_path path_segments; print_attr lst | BGPAttributeNEXT_HOP(_, next_hop)::lst -> Printf.printf "NEXT_HOP: %s\n" next_hop; print_attr lst | BGPAttributeAS4_AGGREGATOR(_, ASN32(asn), ip)::lst | BGPAttributeAGGREGATOR(_, ASN16(asn), ip)::lst | BGPAttributeAGGREGATOR(_, ASN32(asn), ip)::lst -> (match asn with | 23456l -> () |_ -> Printf.printf "AGGREGATOR: AS%lu %s\n" asn ip); print_attr lst | BGPAttributeMULTI_EXIT_DISC(_, med)::lst -> Printf.printf "MULTI_EXIT_DISC: %lu\n" med; print_attr lst | BGPAttributeATOMIC_AGGREGATE(_)::lst -> Printf.printf "ATOMIC_AGGREGATE\n"; print_attr lst | BGPAttributeCOMMUNITY(_, communities)::lst -> print_communities communities; print_attr lst | BGPAttributeMP_REACH_NLRI(_, INET, _, nh_list, prefixes)::lst -> print_nlri nh_list ""; let rec print_prefixes p = match p with | Prefix(IPv4(prefix), plen)::l -> Printf.printf "NLRI: %s/%i\n" prefix plen | Prefix(_, _)::l -> print_prefixes l | [] -> () in print_prefixes prefixes; print_attr lst | BGPAttributeMP_REACH_NLRI(_, INET6, _, nh_list, _)::lst -> print_nlri nh_list "(IPv6 Unicast)"; print_attr lst | BGPAttributeMP_REACH_NLRI(_, _, _, _, _)::lst -> print_attr lst | BGPAttributeMP_REACH_NLRI_abbreviated(_, nh_list)::lst -> print_nlri nh_list "(IPv6 Unicast)"; print_attr lst | BGPAttributeMP_UNREACH_NLRI(_, _, _, _)::lst -> Printf.printf "MP_UNREACH_NLRI(IPv6 Unicast)\n"; print_attr lst | BGPAttributeUnknown(f,t)::lst -> Printf.printf " UNKNOWN_ATTR(%i, %i)\n" f t; print_attr lst | [] -> () * Print RIB entries . let rec print_ribentry ?(peers = []) l = match l with | RIBEntry(p_i, ts,_, rel):: lst -> print_from peers p_i; Printf.printf "ORIGINATED: %s\n" (timestamp_to_string ts); print_attr (merge_as_path (sort_bgp_attributes rel)); print_ribentry lst | [] -> () let rec print_reach_nlri attr = let rec get_prefixes p = match p with | Prefix(IPv6(prefix), plen)::l -> (Printf.sprintf " %s/%i\n" prefix plen) ^ (get_prefixes l) | Prefix(_, _)::l -> get_prefixes l | [] -> "" in let rec internal attr ann_str with_str = match attr with | BGPAttributeMP_REACH_NLRI(_, INET6, _, _, prefixes)::lst -> internal lst (ann_str ^ (get_prefixes prefixes)) with_str | BGPAttributeMP_UNREACH_NLRI(_, INET6, _, prefixes)::lst -> internal lst ann_str (with_str ^ (get_prefixes prefixes)) | _::lst -> internal lst ann_str with_str | [] -> ann_str,with_str in let announce, withdraw = internal attr "" "" in (match String.length announce with | 0 -> () | _ -> Printf.printf "ANNOUNCE\n%s" announce); (match String.length withdraw with | 0 -> () | _ -> Printf.printf "WITHDRAW\n%s" withdraw) * Convert a FSM state to a string let fsm_state_to_str state = match state with | Idle -> "Idle" | Connect -> "Connect" | Active -> "Active" | OpenSent -> "Opensent" | OpenConfirm -> "Openconfirm" | Established -> "Established" | FSM_STATE_UNKNOWN n -> Printf.sprintf "UNKNOWN STATE %i" n let rec get_peers l = match l with | PeerEntry(b, i, ASN16(a))::lst | PeerEntry(b, i, ASN32(a))::lst -> (b, i, a)::(get_peers lst) | _::lst -> get_peers lst | [] -> [] let print_mrt ?(peers = []) hdr = match hdr with | MRTHeader(ts, TABLE_DUMP_v2(PEER_INDEX_TABLE(bgpid, viewname, l))) -> let rec print l = match l with | PeerEntry(b, IPv4(i), ASN16(a))::lst | PeerEntry(b, IPv6(i), ASN16(a))::lst | PeerEntry(b, IPv4(i), ASN32(a))::lst | PeerEntry(b, IPv6(i), ASN32(a))::lst -> Printf.printf "PEER: %s %s %lu\n" b i a; print lst | _::lst -> print lst | [] -> () in Printf.printf "TIME: %s\n" (timestamp_to_string ts); print l | MRTHeader(ts, TABLE_DUMP_v2(RIB_IPV4_UNICAST(seq, Prefix(prefix46, plen_bits), l))) | MRTHeader(ts, TABLE_DUMP_v2(RIB_IPV6_UNICAST(seq, Prefix(prefix46, plen_bits), l))) -> let prefix_header = match prefix46 with | IPv4(prefix) -> (Printf.sprintf "TYPE: TABLE_DUMP_V2/IPV4_UNICAST\n") ^ (Printf.sprintf "PREFIX: %s/%i\n" prefix plen_bits) | IPv6(prefix) -> (Printf.sprintf "TYPE: TABLE_DUMP_V2/IPV6_UNICAST\n") ^ (Printf.sprintf "PREFIX: %s/%i\n" prefix plen_bits) | UnknownIP(a) -> (Printf.sprintf "TYPE: TABLE_DUMP_V2/UNKNOWNIP\n") ^ (Printf.sprintf "PREFIX: UNKNOWN_IP %i\n" a) in let dump_header = (Printf.sprintf "TIME: %s\n" (timestamp_to_string ts)) ^ prefix_header ^ (Printf.sprintf "SEQUENCE: %lu\n" seq) in let rec print_re l dump_hdr = match l with | re::lst -> Printf.printf "%s" dump_hdr; print_ribentry ~peers:peers [re]; print_newline (); print_re lst dump_hdr | [] -> () in print_re l dump_header | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(_), ASN16(_), _, _, _, BGP_OPEN(v, ASN16(myasn), htime, id, params)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(_), ASN32(_), _, _, _, BGP_OPEN(v, ASN16(myasn), htime, id, params)))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Open\n"; Printf.printf "VERSION: %d\n" v; Printf.printf "AS: %lu\n" myasn; Printf.printf "HOLD_TIME: %d\n" htime; Printf.printf "ID: %s\n" id; Printf.printf "OPT_PARM_LEN: %d\n" (List.length params); print_newline () | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv4(pi), IPv4(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv6(pi), IPv6(li), BGP_UPDATE(wr, attr, prefixes)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv6(pi), IPv6(li), BGP_UPDATE(wr, attr, prefixes)))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Update\n"; Printf.printf "FROM: %s AS%lu\n" pi pa; Printf.printf "TO: %s AS%lu\n" li la; print_attr (merge_as_path (sort_bgp_attributes attr)); (match List.length wr with | 0 -> () | n -> Printf.printf "WITHDRAW\n"; print_prefixes ~spacing:" " wr); (match List.length prefixes with | 0 -> () | n -> Printf.printf "ANNOUNCE\n"; print_prefixes ~spacing:" " prefixes); print_newline () | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv4(pi), IPv4(li), BGP_KEEPALIVE))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_KEEPALIVE))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv6(pi), IPv6(li), BGP_KEEPALIVE))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv6(pi), IPv6(li), BGP_KEEPALIVE))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Keepalive\n"; Printf.printf "FROM: %s AS%lu\n" pi pa; Printf.printf "TO: %s AS%lu\n" li la; print_newline () | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv4(pi), IPv4(li), BGP_NOTIFICATION(c, sc, d)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv4(pi), IPv4(li), BGP_NOTIFICATION(c, sc, d)))) | MRTHeader(ts, BGP4MP(MESSAGE(ASN16(pa), ASN16(la), ii, IPv6(pi), IPv6(li), BGP_NOTIFICATION(c, sc, d)))) | MRTHeader(ts, BGP4MP(MESSAGE_AS4(ASN32(pa), ASN32(la), ii, IPv6(pi), IPv6(li), BGP_NOTIFICATION(c, sc, d)))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/MESSAGE/Notification %i %i %s\n" c sc d; Printf.printf "FROM: %s AS%lu\n" pi pa; Printf.printf "TO: %s AS%lu\n" li la; print_newline () | MRTHeader(ts, BGP4MP(STATE_CHANGE(ASN16(pa), ASN16(la), ii, afi, IPv4(pi), IPv4(li), old_state, new_state))) | MRTHeader(ts, BGP4MP(STATE_CHANGE(ASN16(pa), ASN16(la), ii, afi, IPv6(pi), IPv6(li), old_state, new_state))) | MRTHeader(ts, BGP4MP(STATE_CHANGE_AS4(ASN32(pa), ASN32(la), ii, afi, IPv4(pi), IPv4(li), old_state, new_state))) | MRTHeader(ts, BGP4MP(STATE_CHANGE_AS4(ASN32(pa), ASN32(la), ii, afi, IPv6(pi), IPv6(li), old_state, new_state))) -> Printf.printf "TIME: %s\n" (timestamp_to_string ts); Printf.printf "TYPE: BGP4MP/STATE_CHANGE\n"; Printf.printf "PEER: %s AS%lu\n" pi pa; Printf.printf "STATE: %s/%s\n" (fsm_state_to_str old_state) (fsm_state_to_str new_state); print_newline () | MRTHeader(_, _) -> ()
95b69f1d5ec1c17de68921153777a1fe1cd5b93928488162f9db6e220da6acf3
LaurentMazare/ocaml-tqdm
utils.ml
open Base let format_rate rate = match Float.classify rate with | Infinite | Nan | Zero -> "n/a" | Normal | Subnormal -> if Float.( < ) rate 1e-3 then Printf.sprintf "s/%5.0fit" (1. /. rate) else if Float.( < ) rate 1. then Printf.sprintf "s/%5.2fit" (1. /. rate) else if Float.( < ) rate 1e3 then Printf.sprintf "%5.2fit/s" rate else if Float.( < ) rate 1e5 then Printf.sprintf "%5.0fit/s" rate else Printf.sprintf "%5.0fkit/s" (rate *. 1e-3) module Time = struct module Span = struct type t = float let divmod n m = n / m, n % m let format seconds = match Float.classify seconds with | Infinite -> "inf" | Nan -> "nan" | Subnormal | Normal | Zero -> let sign, seconds = if Float.( < ) seconds 0. then "-", -.seconds else "", seconds in let seconds = Int.of_float seconds in let minutes, seconds = divmod seconds 60 in let hours, minutes = divmod minutes 60 in if hours <> 0 then Printf.sprintf "%s%dh%0.2dm%0.2ds" sign hours minutes seconds else Printf.sprintf "%s%0.2dm%0.2ds" sign minutes seconds let of_secs = Fn.id let to_secs = Fn.id end type t = float let now () = Unix.gettimeofday () let diff = ( -. ) end
null
https://raw.githubusercontent.com/LaurentMazare/ocaml-tqdm/a69e02408007038c2cb0cbb4793f564d5725a2ec/src/utils.ml
ocaml
open Base let format_rate rate = match Float.classify rate with | Infinite | Nan | Zero -> "n/a" | Normal | Subnormal -> if Float.( < ) rate 1e-3 then Printf.sprintf "s/%5.0fit" (1. /. rate) else if Float.( < ) rate 1. then Printf.sprintf "s/%5.2fit" (1. /. rate) else if Float.( < ) rate 1e3 then Printf.sprintf "%5.2fit/s" rate else if Float.( < ) rate 1e5 then Printf.sprintf "%5.0fit/s" rate else Printf.sprintf "%5.0fkit/s" (rate *. 1e-3) module Time = struct module Span = struct type t = float let divmod n m = n / m, n % m let format seconds = match Float.classify seconds with | Infinite -> "inf" | Nan -> "nan" | Subnormal | Normal | Zero -> let sign, seconds = if Float.( < ) seconds 0. then "-", -.seconds else "", seconds in let seconds = Int.of_float seconds in let minutes, seconds = divmod seconds 60 in let hours, minutes = divmod minutes 60 in if hours <> 0 then Printf.sprintf "%s%dh%0.2dm%0.2ds" sign hours minutes seconds else Printf.sprintf "%s%0.2dm%0.2ds" sign minutes seconds let of_secs = Fn.id let to_secs = Fn.id end type t = float let now () = Unix.gettimeofday () let diff = ( -. ) end
59177e09cdf05eb7109d0ad9a3eb541812983265396eef334521ccd12dc75065
acl2/acl2
doc.lisp
C Library ; Copyright ( C ) 2023 Kestrel Institute ( ) Copyright ( C ) 2023 Kestrel Technology LLC ( ) ; License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . ; Author : ( ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "C") (include-book "kestrel/event-macros/xdoc-constructors" :dir :system) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defxdoc atc :parents (c) :short "ATC (<b>A</b>CL2 <b>T</b>o <b>C</b>), a proof-generating C code generator for ACL2." :long (xdoc::topstring ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section-intro (xdoc::p "This manual page contains user-level reference documentation for ATC. Users who are new to ATC should start with the " (xdoc::seetopic "atc-tutorial" "tutorial") ", which provides user-level pedagogical information on how ATC works and how to use ATC effectively.") (xdoc::p "This manual page refers to the official C standard in the manner explained in " (xdoc::seetopic "c" "the top-level XDOC topic of our C library") ".")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section-form (xdoc::codeblock "(atc t1 ... tp" " :output-dir ... ; default \".\"" " :file-name ... ; no default" " :header ... ; default nil" " :pretty-printing ... ; default nil" " :proofs ... ; default t" " :const-name ... ; default :auto" " :print ... ; default :result" " )")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section-inputs (xdoc::desc "@('t1'), ..., @('tp')" (xdoc::p "Names of ACL2 targets to translate to C.") (xdoc::p "Each @('ti') must be a symbol that satisfies exactly one of the following conditions:") (xdoc::ul (xdoc::li "It is the symbol of an ACL2 function.") (xdoc::li "Its @(tsee symbol-name) is the name of a C structure type shallowly embedded in ACL2, introduced via @(tsee defstruct).") (xdoc::li "Its @(tsee symbol-name) is the name of a C external object shallowly embedded in ACL2, introduced via @(tsee defobject).")) (xdoc::p "It is an error if two or more of the above conditions hold, because in that case the target does not unambiguously identify a function or a structure type or an external object.") (xdoc::p "The @(tsee symbol-name)s of the targets must be all distinct. Even though C has different name spaces for (i) structure types and (ii) functions and external objects [C:6.2.3], in C code generated by ATC these are treated as if they were in the same name space, so they must all have distinct names.") (xdoc::p "There must be at least one target function.") (xdoc::p "Each recursive target function must be called by at least one recursive or non-recursive target function that follows it in the list @('(t1 ... tp)').") (xdoc::p "Each target function must satisfy the conditions discussed in the section `Representation of C Code in ACL2'.")) (xdoc::desc "@(':output-dir') &mdash; default \".\"" (xdoc::p "Path of the directory where the generated C code goes.") (xdoc::p "This must be an ACL2 string that is a valid path to an existing directory in the file system; the path may be absolute, or relative to the " (xdoc::seetopic "cbd" "connected book directory") ". The default is the connected book directory.")) (xdoc::desc "@(':file-name') &mdash; no default" (xdoc::p "Name of the files that contain the generated C code, without the @('.h') or @('.c') extension.") (xdoc::p "This must be a non-empty ACL2 string that consists of ASCII letters, digits, underscores, and dashes. The full names of the generated files are obtained by appending the extension @('.h') or @('.c') to this string.") (xdoc::p "The files are generated in the directory specified by @(':output-dir'). The files may or may not exist: if they do not exist, they are created; if they exist, they are overwritten.")) (xdoc::desc "@(':header') &mdash; default @('nil')" (xdoc::p "Specifies whether a header (i.e. a @('.h') file) should be generated or not.") (xdoc::p "This must be one of the following:") (xdoc::ul (xdoc::li "@('t'), to generate a header.") (xdoc::li "@('nil'), to not generate a header.")) (xdoc::p "A source file (i.e. a @('.c') file is always generated; the @(':header') input only affects the generation of the header.") (xdoc::p "If ATC is used to generate C code that is not standalone but is meant to be called by external C code, the @(':header') input should be @('t'), so that the external C code can include the header. If ATC is used to generate standalone C code, presumably including a function called @('main') with appropriate types, then @(':header') input should be @('nil').")) (xdoc::desc "@(':pretty-printing') &mdash; default @('nil')" (xdoc::p "Specifies options for how the generated C code is pretty-printed.") (xdoc::p "This must be a " (xdoc::seetopic "acl2::keyword-value-listp" "keyword-value list") " @('(opt-name1 opt-value1 opt-name2 opt-value2 ...)') where each @('opt-namek') is a keyword among the ones described below, and each @('opt-valuek') is one of the allowed values for the corresponding keyword as described below.") (xdoc::p "The following pretty-printing options are supported:") (xdoc::ul (xdoc::li "@(':parenthesize-nested-conditionals t/nil'), where @('t/nil') is either @('t') or @('nil'). This option specifies whether a conditional expression that is the `then' or `else' branch of another conditional expression is parenthesized or not. The parentheses are not necessary according to the precedence rules of C, but may help make the code more readable. The default value of this option is @('nil'), which means that no parentheses are added. If this option is @('t'), then parentheses are added. For example, based on whether this option is @('nil') or @('t'), an expression may be printed as either" (xdoc::codeblock "a ? b ? c : d : e ? f g") "or" (xdoc::codeblock "a ? (b ? c : e) : (e ? f : g)") ".")) (xdoc::p "This is currently the only supported pretty-printing option. More options, to control additional aspects of the pretty-print of the C code, may be added in the future.")) (xdoc::desc "@(':proofs') &mdash; default @('t')" (xdoc::p "Specifies whether proofs should be generated or not.") (xdoc::p "This must be one of the following:") (xdoc::ul (xdoc::li "@('t'), to generate proofs.") (xdoc::li "@('nil'), to not generate proofs.")) (xdoc::p "While it is obviously recommended to generate proofs, setting this to @('nil') may be useful in case proof generation is (temporarily) broken.")) (xdoc::desc "@(':const-name') &mdash; default @(':auto')" (xdoc::p "Name of the generated ACL2 named constant that holds the abstract syntax tree of the generated C program.") (xdoc::p "This must be one of the following:") (xdoc::ul (xdoc::li "@(':auto'), to use the symbol @('*program*') in the @('\"C\"') package.") (xdoc::li "Any other symbol, to use as the name of the constant.")) (xdoc::p "This input must be absent if @(':proofs') is @('nil'). The named constant is generated only if @(':proofs') is @('t').") (xdoc::p "In the rest of this documentation page, let @('*program*') be the symbol specified by this input, if applicable (i.e. when @(':proofs') is @('t')).")) (xdoc::desc "@(':print') &mdash; default @(':result')" (xdoc::p "Specifies what is printed on the screen.") (xdoc::p "It must be one of the following:") (xdoc::ul (xdoc::li "@(':error'), to print only error output (if any).") (xdoc::li "@(':result'), to print, besides any error output, also the " (xdoc::seetopic "acl2::event-macro-results" "results") " of ATC. This is the default value of the @(':print') input.") (xdoc::li "@(':info'), to print, besides any error output and the results, also some additional information about the internal operation of ATC.") (xdoc::li "@(':all'), to print, besides any error output, the results, and the additional information, also ACL2's output in response to all the submitted events.")) (xdoc::p "The errors are printed as " (xdoc::seetopic "set-inhibit-output-lst" "error output") ". The results and the additional information are printed as " (xdoc::seetopic "set-inhibit-output-lst" "comment output") ". The ACL2 output enabled by @(':print :all') may consist of " (xdoc::seetopic "set-inhibit-output-lst" "output of various kinds") ".") (xdoc::p "If @(':print') is @(':error') or @(':result') or @(':info'), ATC suppresses all kinds of outputs (via @(tsee with-output)) except for error and comment output. Otherwise, ATC does not suppress any output. However, the actual output depends on which outputs are enabled or not prior to the call of ATC, including any @(tsee with-output) that may wrap the call of ATC."))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section "Representation of C Code in ACL2" (xdoc::p "Currently ATC supports the ACL2 representation of a single source file (i.e. a file with extension @('.c')), optionally accompanied by a header (i.e. a file with extension @('.h')), based on the @(':header') input. If @(':header') is @('nil'), the source file consists of one or more C function definitions, zero or more C external object declarations, and zero or more C structure type declarations. If @(':header') is @('t'), the header consists of one or more function declarations, zero or more C external object declarations without initializers, and zero or more C structure type declarations, while the source file consists of one or more function definitions and zero or more C external object declarations with initializers, corresponding to the function declarations and the external object declarations in the header.") (xdoc::p "Each C structure type declaration is represented by a @(tsee defstruct), whose name is passed as one of the targets @('ti') to ATC. The symbol name, which is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") " (this is enforced by @(tsee defstruct)), represents the tag of the C structure type.") (xdoc::p "Each C external object declaration is represented by a @(tsee defobject), whose name is passed as one of the targets @('ti') to ATC. The symbol name, which is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") " (this is enforced by @(tsee defobject)), represents the name of the C external object.") (xdoc::p "Each C function definition (and declaration in the header, if present) is represented by an ACL2 function definition. These are the non-recursive target ACL2 functions @('ti') passed to ATC; the recursive target ACL2 functions @('ti') passed as inputs represent loops in the C functions instead, as explained below.") (xdoc::p "The order of the C structure types and external objects and functions in the files is the same as the order of the corresponding targets in the list @('(t1 ... tp)') passed to ATC.") (xdoc::p "Each target function @('fn') must be in logic mode and guard-verified. The function must not occur in its own guard, which is rare but allowed in ACL2.") (xdoc::p "The symbol name of each non-recursive function target @('fn') must be a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ". That symbol name is used as the name of the corresponding C function. Therefore, the non-recursive target functions must have all distinct symbol names; even if they are in different packages, they must have distinct symbol names (the package names are ignored). There is no restriction on the symbol names of the recursive target functions: these represent C loops, not C functions; the names of the recursive target functions are not represented at all in the C code.") (xdoc::p "The symbol name of each formal parameter of each function target @('fn'), both non-recursive and recursive, must be a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ". When @('fn') is non-recursive, the symbol names of its parameters are used as the names of the formal parameters of the corresponding C function, in the same order, except for the formal parameters that represent external objects, as defined below. Therefore, the formal parameters of each @('fn') must have all distinct symbol names; even if they are in different packages, they must have distinct symbol names (the package names are ignored). When @('fn') is recursive, the symbol names of its parameters are used as names of C variables, as explained below.") (xdoc::p "When @('fn') is recursive, it must have at least one formal parameter. When @('fn') is non-recursive, it may have any number of formal parameters, including none.") (xdoc::p "If @('fn') is recursive, it must be singly (not mutually) recursive, its well-founded relation must be @(tsee o<), and its measure must yield a natural number. The latter requirement is checked via an applicability condition, as described in the `Applicability Conditions' section.") (xdoc::p "The guard of each @('fn') must include, for every formal parameter @('x'), exactly one conjunct of one of the following forms, possibly wrapped with @(tsee mbt), which determines the C type of the corresponding parameter of the C function, or designates the formal parameter as representing an access to an object defined by @(tsee defobject):") (xdoc::ul (xdoc::li "@('(scharp x)'), representing @('signed char').") (xdoc::li "@('(ucharp x)'), representing @('unsigned char').") (xdoc::li "@('(sshortp x)'), representing @('signed short').") (xdoc::li "@('(ushortp x)'), representing @('unsigned short').") (xdoc::li "@('(sintp x)'), representing @('signed int').") (xdoc::li "@('(uintp x)'), representing @('unsigned int').") (xdoc::li "@('(slongp x)'), representing @('signed long').") (xdoc::li "@('(ulongp x)'), representing @('unsigned long').") (xdoc::li "@('(sllongp x)'), representing @('signed long long').") (xdoc::li "@('(ullongp x)'), representing @('unsigned long long').") (xdoc::li "@('(star (scharp x))'), representing @('signed char *').") (xdoc::li "@('(star (ucharp x))'), representing @('unsigned char *').") (xdoc::li "@('(star (sshortp x))'), representing @('signed short *').") (xdoc::li "@('(star (ushortp x))'), representing @('unsigned short *').") (xdoc::li "@('(star (sintp x))'), representing @('signed int *').") (xdoc::li "@('(star (uintp x))'), representing @('unsigned int *').") (xdoc::li "@('(star (slongp x))'), representing @('signed long *').") (xdoc::li "@('(star (ulongp x))'), representing @('unsigned long *').") (xdoc::li "@('(star (sllongp x))'), representing @('signed long long *').") (xdoc::li "@('(star (ullongp x))'), representing @('unsigned long long *').") (xdoc::li "@('(schar-arrayp x)'), representing @('signed char []').") (xdoc::li "@('(uchar-arrayp x)'), representing @('unsigned char []').") (xdoc::li "@('(sshort-arrayp x)'), representing @('signed short []').") (xdoc::li "@('(ushort-arrayp x)'), representing @('unsigned short []').") (xdoc::li "@('(sint-arrayp x)'), representing @('signed int []').") (xdoc::li "@('(uint-arrayp x)'), representing @('unsigned int []').") (xdoc::li "@('(slong-arrayp x)'), representing @('signed long []').") (xdoc::li "@('(ulong-arrayp x)'), representing @('unsigned long []').") (xdoc::li "@('(sllong-arrayp x)'), representing @('signed long long []').") (xdoc::li "@('(ullong-arrayp x)'), representing @('unsigned long long []').") (xdoc::li "@('(struct-<tag>-p x)'), where @('<tag>') is one of the @(tsee defstruct) targets @('ti'), representing the corresponding C structure type, @('struct <tag>'). The structure type must not have a flexible array member. The @('<tag>') target must precede @('fn') in the list of targets @('(t1 ... tp)').") (xdoc::li "@('(star (struct-<tag>-p x))'), where @('<tag>') is one of the @(tsee defstruct) targets @('ti'), representing a pointer type to the corresponding C structure type, @('struct <tag> *'). The @('<tag>') target must precede @('fn') in the list of targets @('(t1 ... tp)').") (xdoc::li "@('(object-<name>-p x)'), where @('<name>') is one of the @(tsee defobject) targets @('ti'), representing an access to the external object, which must be an explicit formal parameter in functional ACL2, while the C function accesses it directly. The @('<name>') target must precede @('fn') in the list of targets @('(t1 ... tp)').")) (xdoc::p "The conjuncts may be at any level of nesting, but must be extractable by flattening the @(tsee and) structure of the guard term: only conjuncts extractable this way count for the purpose of determining the C types of the formal parameters and which formal parameters represent accesses to external objects. The rest of the guard (i.e. other than the conjuncts above) is not explicitly represented in the C code.") (xdoc::p "Note the distinction between pointer types @('<integer type> *') and array types @('<integer type> []') in the list above. Even though these types are equivalent for function parameters, and in fact array types are adjusted to pointer types for function parameters according to [C], pointed-to integers and integer arrays are different in the ACL2 representation of C. (More in general, even in handwritten C code, using array types instead of pointer types for function parameters is useful to convey the intention that something is a pointer to (the first or some) element of an integer array as opposed to a pointer to a single integer.)") (xdoc::p "The aforementioned option of wrapping the conjuncts with @(tsee mbt) is useful for cases in which the function have stronger guards that imply those conjuncts. It would be inelegant to add redundant conjuncts to the guard (presumably via external transformations) for the sole purpose of communicating function parameter types to ATC. By allowing @(tsee mbt), the redundancy can be explicated and proved (as part of guard verification), while making it easy for ATC to obtain the types.") (xdoc::p "The return type of the C function corresponding to each non-recursive target function @('fn') is automatically determined from the body, as explained below.") (xdoc::p "The " (xdoc::seetopic "acl2::function-definedness" "unnormalized body") " of each @('fn') must be as follows:") (xdoc::ul (xdoc::li "If @('fn') is non-recursive, the unnormalized body must be a statement term for @('fn') with loop flag @('nil') returning type @('T') and affecting variables @('vars') (as defined below), where each variable in @('vars') is a formal parameter of @('fn') with pointer or array type and where @('T') is not @('void') if @('vars') is @('nil'). The return type of the C function represented by @('fn') is @('T').") (xdoc::li "If @('fn') is recursive, the unnormalized body must be a loop term for @('fn') affecting variables @('vars') (as defined below), where each variable in @('vars') is a formal parameter of @('fn').")) (xdoc::p "The above-mentioned notions of (i) statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars') and (ii) loop term for @('fn') affecting @('vars') are defined below, along with the notions of (iii) expression term for @('fn') returning @('T') and affecting @('vars'), (iv) pure expression term for @('fn') returning @('T'), (v) expression term for @('fn') returning boolean, (vi) C type of a variable, and (vii) assignable variable.") (xdoc::p "A <i>statement term for</i> @('fn') <i>with loop flag</i> @('L') <i>returning</i> @('T') and <i>affecting</i> @('vars'), where @('fn') is a target function, @('L') is either @('t') or @('nil'), @('T') is a C type (possibly @('void')), and @('vars') is a list of distinct symbols, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "An expression term for @('fn') returning @('T') and affecting @('vars'), when @('L') is @('nil'), @('T') is a non-@('void') non-pointer non-array C type, and @('vars') is @('nil'). That is, an expression term returning a C value is also a statement term returning that C value. This represents a C @('return') statement whose expression is represented by the same term, viewed as an expression term.") (xdoc::li "A term @('(mv ret var1 ... varn)'), when @('ret') is an expression term for @('fn') returning @('T') and affecting no variables, @('L') is @('nil'), @('T') is a non-@('void') non-pointer non-array type, 1 . This represents a C @('return') statement whose expression is represented by @('ret'); the @(tsee mv) and the variables in @('vars') represent no actual C code: they just represent variables that may have been modified by preceding code.") (xdoc::li "A term @('var'), when @('L') is @('nil'), @('T') is @('void'), and @('vars') is the singleton list @('(var)'). This represents no actual C code: it just serves to conclude preceding code that may modify @('var').") (xdoc::li "A term @('(mv var1 ... varn)'), when @('L') is @('nil'), @('T') is @('void'), 1 . This represents no actual C code: it just serves to conclude preceding code that may modify @('var1'), ..., @('varn').") (xdoc::li "A call of @('fn') on variables identical to its formal parameters, when the C types of the variables are the same as the C types of the formal parameters, @('L') is @('t'), @('T') is @('void'), and @('fn') is recursive. This represents no actual C code: it just serves to conclude the computation in the body of the loop represented by @('fn').") (xdoc::li "A call of @(tsee if) on (i) a test of the form @('(mbt ...)') or @('(mbt$ ...)'), (ii) a `then' branch that is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'), and (iii) an `else' branch that may be any ACL2 term. This represents the same C code represented by the `then' branch. Both the test and the `else' branch are ignored, because ATC generates C code under guard assumptions.") (xdoc::li "A call of @(tsee if) on (i) a test that is an expression term for @('fn') returning boolean and (ii) branches that are statement terms for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C @('if') conditional statement whose test expression is represented by the test term and whose branch blocks are represented by the branch terms.") (xdoc::li "A term @('(let ((var (declar term))) body)'), when the symbol name of @('var') is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ", the symbol name of @('var') is distinct from the symbol names of all the other ACL2 variables in scope, @('term') is an expression term for @('fn') returning a non-@('void') non-pointer non-array C type and affecting no variables, and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @(tsee declar), a declaration of a C local variable represented by @('var'), initialized with the C expression represented by @('term'), followed by the C code represented by @('body'). The C type of the variable is determined from the initializer.") (xdoc::li "A term @('(let ((var (assign term))) body)'), when @('var') is assignable, @('term') is an expression term for @('fn') returning the same non-@('void') non-pointer non-array C type as the C type of @('var') and affecting no variables, and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @(tsee assign), an assignment to the C local variable or function parameter represented by @('var'), with the C expression represented by @('term') as right-hand side, followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (<type>-write term))) body)'), when @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is in scope, @('var') has a pointer type whose referenced type is the C integer type corresponding to @('<type>'), @('var') is one of the symbols in @('vars'), @('term') is a pure expression term for @('fn') returning the C integer type corresponding to @('<type>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to the pointer variable represented by @('var') with the value of the expression represented by @('term'); the wrapper @('<type>-write') signifies the writing to an integer by pointer.") (xdoc::li "A term @('(let ((var (<type1>-array-write-<type2> var term1 term2))) body)'), when @('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is in scope, @('var') has an array type whose element type is the C integer type corresponding to @('<type1>'), @('var') is one of the symbols in @('vars'), @('term1') is a pure expression term for @('fn') returning the C integer type corresponding to @('<type2>'), @('term2') is a pure expression term for @('fn') returning the C integer type corresponding to @('<type1>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to an element of the array represented by @('var') with the subscript expression represented by @('term1') with the new element expression represented by @('term2'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member> term var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer type in the @(tsee defstruct), @('var') is assignable, @('var') has the C structure type represented by @('<tag>'), @('term') is a pure expression term for @('fn') returning the C integer type of @('<member>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to a member of the structure represented by @('var') by value (i.e. using @('.')) with the new value expression represented by @('term'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member> term var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer type in the @(tsee defstruct), @('var') is in scope, @('var') has a pointer type whose referenced type is the C structure type represented by @('<tag>'), @('var') is one of the symbols in @('vars'), @('term') is a pure expression term for @('fn') returning the C integer type of @('<member>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to a member of the structure represented by @('var') by pointer (i.e. using @('->')) with the new value expression represented by @('term'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member>-<type> term1 term2 var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer array type in the @(tsee defstruct) with element type @('<type2>'), @('<type>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is assignable, @('var') has the C structure type represented by @('<tag>'), @('term1') is a pure expression term for @('fn') returning the C type corresponding to @('<type2>'), @('term2') is a pure expression term for @('fn') returning the C type corresponding to @('<type>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to an element of a member of the structure represented by @('var') by value (i.e. using @('.')) using @('term1') as the index with the new value expression represented by @('term2'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member>-<type> term1 term2 var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer array type in the @(tsee defstruct) with element type @('<type2>'), @('<type>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is in scope, @('var') has a pointer type whose referenced type is the C structure type represented by @('<tag>'), @('var') is one of the symbols in @('vars'), @('term1') is a pure expression term for @('fn') returning the C type corresponding to @('<type2>'), @('term2') is a pure expression term for @('fn') returning the C type corresponding to @('<type>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to an element of a member of the structure represented by @('var') by pointer (i.e. using @('->')) using @('term1') as the index with the new value expression represented by @('term2'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var term)) body)'), when @('var') is assignable, @('var') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is a statement term for @('fn') with loop flag @('nil') returning @('void') and affecting @('var') that is either a call of a target function that precedes @('fn') in the list of targets @('(t1 ... tp)') whose body term returns @('void') and affects @('var') or an @(tsee if) whose test is an expression term returning boolean (not a test @('(mbt ...)') or @('(mbt$ ...)')), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents the C code represented by @('term'), which may modify the variable represented by @('var'), followed by the C code represented by @('body').") (xdoc::li "A term @('(mv-let (var var1 ... varn) (declarn term) body)'), when the symbol name of @('var') is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ", the symbol name of @('var') is distinct from the symbol names of all the other ACL2 variables in scope, each @('vari') is assignable, each @('vari') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is an expression term for @('fn') returning a non-@('void') non-pointer non-array C type and affecting the variables @('(var1 ... varn)'), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @('declarn'), a declaration of a C local variable represented by @('var'), initialized with the C expression represented by @('term'), followed by the C code represented by @('body'). Note that @('declarn') stands for @('declar1'), @('declar2'), etc., based on whether @('n') is 1, 2, etc.; this @('n') is the number of side-effected variables @('var1'), ..., @('varn'), which is one less than the variables bound by the @(tsee mv-let). The C type of the variable is determined from the initializer.") (xdoc::li "A term @('(mv-let (var var1 ... varn) (assignn term) body)'), when @('var') is assignable, each @('vari') is assignable, each @('vari') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is an expression term for @('fn') returning the same non-@('void') non-pointer non-array C type as the C type of @('var') and affecting the variables @('(var1 ... varn)'), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @('assignn'), an assignment to the C local variable or function parameter represented by @('var'), with the C expression represented by @('term') as right-hand side, followed by the C code represented by @('body'). Note that @('assignn') stands for @('assign1'), @('assign2'), etc., based on whether @('n') is 1, 2, etc.; this @('n') is the number of side-effected variables @('var1'), ..., @('varn'), which is one less than the variables bound by the @(tsee mv-let).") (xdoc::li "A term @('(mv-let (var1 ... varn) term body)'), 1 , each @('vari') is assignable, each @('vari') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is a statement term for @('fn') with loop flag @('nil') returning @('void') and affecting @('(var1 ... varn)') that is either a call of a recursive target function that precedes @('fn') in the list of targets @('(t1 ... tp)') whose body term returns @('void') and affects @('(var1 ... varn)') or an @(tsee if) whose test is an expression term returning boolean (not a test @('(mbt ...)') or @('(mbt$ ...)')), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents the C code represented by @('term'), which may modify the variables represented by @('var1'), ..., @('varn'), followed by the C code represented by @('body').") (xdoc::li "A call of a recursive target function @('fn0') that precedes @('fn') in the list of targets @('(t1 ... tp)'), on variables identical to its formal parameters, when the C types of the variables are the same as the C types of the formal parameters of @('fn0'), @('L') is @('nil'), @('T') is @('void'), @('vars') is not @('nil'), and the body of @('fn0') is a loop term for @('fn0') affecting @('vars'). This represents the C @('while') statement represented by the body of @('fn0'), as explained below.") (xdoc::li "A call of a non-recursive target function @('fn0') that precedes @('fn') in the list of targets @('(t1 ... tp)'), on pure expression terms for @('fn') returning non-@('void') C types, when the C types of the terms are the same as the C types of the formal parameters, each term of pointer or array type is a variable identical to the corresponding formal parameter of @('fn0'), @('L') is @('nil'), @('T') is @('void'), and the body of @('fn0') is a statement term for @('fn0') returning @('void') and affecting @('vars'). This represents an expression statement whose expression is call of the C function corresponding to @('fn0').")) (xdoc::p "A <i>loop term for</i> @('fn') <i>affecting</i> @('vars'), where @('fn') is a target function and @('vars') is a non-empty list of distinct symbols, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A call of @(tsee if) on (i) a test of the form @('(mbt ...)') or @('(mbt$ ...)'), (ii) a `then' branch that is a loop term for @('fn') affecting @('vars'), and (iii) an `else' branch that may be any ACL2 term. This represents the same C code represented by the `then' branch. Both the test and the `else' branch are ignored, because ATC generates C code under guard assumptions.") (xdoc::li "A call of @(tsee if) on (i) a test that is an expression term for @('fn') returning boolean, (ii) a `then' branch that is a statement term for @('fn') with loop flag @('t') returning @('void') and affecting @('vars'), and (iii) an `else' branch that is either the variable @('var') when @('vars') is the singleton @('(var)'), or the term @('(mv var1 ... varn)') 1 . This represents the C @('while') statement whose controlling expression is represented by the test and whose body is represented by the `then' branch; the `else' branch represents no actual C code, because it just serves to complete the @(tsee if).")) (xdoc::p "An <i>expression term for</i> @('fn') <i>returning</i> @('T') and <i>affecting</i> @('vars'), where @('fn') is a target function, @('T') is a non-@('void') C type, and @('vars') is a list of distinct symbols, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A pure expression term for @('fn') returning @('T'), when @('vars') is @('nil').") (xdoc::li "A call of a non-recursive target function @('fn0') that precedes @('fn') in the list of targets @('(t1 ... tp)'), on pure expression terms for @('fn') returning C types, when the types of the terms are equal to the C types of the formal parameters of @('fn0'), each term of pointer or array type is a variable identical to the corresponding formal parameter of @('fn0'), and the body of @('fn0') is a statement term for @('fn0') returning @('T') and affecting @('vars'). This represents a call of the corresponding C function.")) (xdoc::p "A <i>pure expression term for</i> @('fn') <i>returning</i> @('T'), where @('fn') is a target function and @('T') is a non-@('void') C type, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A formal parameter of @('fn'), when @('T') is the type of the formal parameter. This represents either the corresponding C formal parameter (as an expression), or the corresponding C external object (as an expression), as explained earlier.") (xdoc::li "A variable introduced by @(tsee let) with @(tsee declar) (as described above), when @('T') is the type of the variable. This represents the corresponding C local variable (as an expression).") (xdoc::li "A call of a function @('<type>-<base>-const') on a quoted integer, when @('<type>') is among" (xdoc::ul (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('<base>') is among" (xdoc::ul (xdoc::li "@('dec')") (xdoc::li "@('oct')") (xdoc::li "@('hex')")) "@('T') is the C type corresponding to @('<type>') and the quoted integer is non-negative and in the range of @('T'). This represents a C integer constant of the C type indicated by the name of the function, expressed in decimal, octal, or hexadecimal base.") (xdoc::li "A call of a function @('<op>-<type>') on a pure expression term for @('fn') returning @('U'), when @('<op>') is among" (xdoc::ul (xdoc::li "@('plus')") (xdoc::li "@('minus')") (xdoc::li "@('bitnot')") (xdoc::li "@('lognot')")) "@('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type corresponding to the return type of @('<op>-<type>') and @('U') is the C type corresponding to @('<type>'). This represents the C operator indicated by the name of the function applied to a value of the type indicated by the name of the function. The guard verification requirement ensures that the operator yields a well-defined result. These functions covers all the C unary operators (using the nomenclature in [C]).") (xdoc::li "A call of a function @('<op>-<type1>-<type2>') on pure expression terms for @('fn') returning @('U') and @('V'), when @('<op>') is among" (xdoc::ul (xdoc::li "@('add')") (xdoc::li "@('sub')") (xdoc::li "@('mul')") (xdoc::li "@('div')") (xdoc::li "@('rem')") (xdoc::li "@('shl')") (xdoc::li "@('shr')") (xdoc::li "@('lt')") (xdoc::li "@('gt')") (xdoc::li "@('le')") (xdoc::li "@('ge')") (xdoc::li "@('eq')") (xdoc::li "@('ne')") (xdoc::li "@('bitand')") (xdoc::li "@('bitxor')") (xdoc::li "@('bitior')")) "@('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type corresponding to the return type of @('<op>-<type1>-<type2>'), @('U') is the C type corresponding to @('<type1>'), and @('V') is the C type corresponding to @('<type2>'). This represents the C operator indicated by the name of the function applied to values of the types indicated by the name of the function. The guard verification requirement ensures that the operator yields a well-defined result. These functions covers all the C strict pure binary operators; the non-strict operators @('&&') and @('||'), and the non-pure operators @('='), @('+='), etc., are represented differently.") (xdoc::li "A call of a function @('<type1>-from-<type2>') on a pure expression term for @('fn') returning @('U'), when @('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "and also differ from each other, @('T') is the C type corresponding to @('<type1>') and @('U') is the C type corresponding to @('<type2>'). This represents a cast to the type indicated by the first part of the function name. The guard verification requirement ensures that the conversion yields a well-defined result. Even though conversions happen automatically in certain circumstances in C, these functions always represent explicit casts; implict conversions are represented implicitly, e.g. via the function for a unary operator that promotes the operand.") (xdoc::li "A call of @('<type>-read') on a pure expression term for @('fn') returning @('U'), when @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type corresponding to @('<type>'), and @('U') is the pointer type to @('T'). This represents the application of the indirection operator @('*') to the expression represented by the argument of @('<type>-read').") (xdoc::li "A call of @('<type1>-array-read-<type2>') on pure expression terms for @('fn') returning @('U') and @('V'), when @('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type correponding to @('<type1>'), @('U') is the array type of element type @('T'), and @('V') is the C type correponding to @('<type2>'). This represents an array subscripting expression. The guard verification requirement ensures that the array access is well-defined.") (xdoc::li "A call of @('struct-<tag>-read-<member>') on a pure expression term for @('fn') returning @('U') when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer type in the @(tsee defstruct), @('T') is the C integer type of @('<member>'), and @('U') is the C structure type represented by @('<tag>') or the pointer type to that C structure type. This represents an access to a structure member, by value if @('U') is the C structure type (i.e. using @('.')) or by pointer if @('U') is the pointer type to the C structure type (i.e. using @('->')).") (xdoc::li "A call of @('struct-<tag>-read-<member>-<type>') on pure expression terms for @('fn') returning @('U') and @('V') when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C element type of the array type of @('<member>'), @('U') is the C type corresponding to @('<type>'), and @('V') is the C structure type represented by @('<tag>') or the pointer type to that C structure type. This represents an access to an element of a structure member, by value if @('V') is the C structure type (i.e. using @('.')) or by pointer if @('V') is the pointer type to the C structure type (i.e. using @('->')).") (xdoc::li "A call of @(tsee sint-from-boolean) on an expression term for @('fn') returning boolean that is a call of @(tsee and) or @(tsee or) (not a call of any @('boolean-from-<type>')), when @('T') is @('int'). This converts an expression term returning boolean to a pure expression term returning @('int'). The restriction of the argument term of @(tsee sint-from-boolean) to be a call of @(tsee and) and @(tsee or) is so that such a call always represents the C @('int') 0 or 1, which is what @(tsee sint-from-boolean) returns; the conversion from boolean to @('int') is only in ACL2, not present in the C code, which just has the represented expression.") (xdoc::li "A call of @(tsee condexpr) on a call of @(tsee if) on (i) a test that is an expression term for @('fn') returning boolean and (ii) branches that are pure expression terms for @('fn') returning @('T'). This represents a C @('?:') conditional expression whose test expression is represented by the test term and whose branch expressions are represented by the branch terms.")) (xdoc::p "An <i>expression term for</i> @('fn') <i>returning boolean</i>, where @('fn') is a target function, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A call of a function @('boolean-from-<type>') on a pure expression term for @('fn') returning @('U'), when @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('U') is the C type corresponding to @('<type>'). This converts a pure expression term returning a C type to an expression term returning boolean.") (xdoc::li "A call of one of the following macros on expression terms for @('fn') returning booleans:" (xdoc::ul (xdoc::li "@(tsee and)") (xdoc::li "@(tsee or)")) "This represents the corresponding C logical operator conjunction @('&&') or disjunction @('||')); conjunctions and disjunctions are represented non-strictly.")) (xdoc::p "The <i>C type of a variable</i> @('var') is defined as follows:") (xdoc::ul (xdoc::li "If @('var') is a formal parameter that does not represent an access to an external object, the C type is the one derived from the guard as explained earlier.") (xdoc::li "If @('var') is a formal parameter that represents an access to an external object, the C type is derived from the definition of the recognizer @('object-<name>-p') generated by @(tsee defobject) for that object. This may be an integer type or an integer array type; see @(tsee defobject).") (xdoc::li "If @('var') is not a formal parameter, it must be introduced by a @(tsee let) with @(tsee declar) or an @(tsee mv-let) with @('declarn'), and its C type is the one of the term argument of @(tsee declar) or @('declarn').")) (xdoc::p "The C type of a variable is never @('void').") (xdoc::p "A variable @('var') bound in a @(tsee let) or @(tsee mv-let) in a target function @('fn') is <i>assignable</i> when it is in scope, i.e. it is identical to a function parameter or to a variable bound in an enclosing @(tsee let) or @(tsee mv-let), and additionally any of the conditions given below holds. The conditions make reference to the C scopes represented by the ACL2 terms that the @(tsee let) or @(tsee mv-let) is part of: there is a C scope for the whole file, then each function body is a nested C scope, and then each @(tsee if) branch whose test is an expression term returning a boolean (i.e. whose test is not @(tsee mbt) or @(tsee mbt$)) is a further nested C scope. The conditions are the following:") (xdoc::ul (xdoc::li "The function parameter or outer variable is in the same C scope where @('var') occurs.") (xdoc::li "The variable @('var') is among @('vars'), i.e. it is being affected.") (xdoc::li "No variables are being affected, i.e. @('vars') is @('nil').")) (xdoc::p "Any of these conditions ensures that, in the ACL2 code, the old value of the variable cannot be accessed after the new binding: (i) if the first condition holds, the new binding hides the old variable; (ii) if the second condition holds, it means that the outer binding will receive the value at the end of the changes to the variables; and (iii) if the third condition holds, there is no subsequent code because there is no change to the variables. These justify destructively updating the variable in the C code.") (xdoc::p "Statement terms represent C statements, while expression terms represent C expressions. The expression terms returning booleans return ACL2 boolean values, while the statement terms, including expression terms returning C values, return ACL2 values that represent C values: the distinction between boolean terms and other kinds of terms stems from the need to represent C's non-strictness in ACL2: C's non-strict constructs are @('if') statements, @('?:') expressions, @('&&') expressions, and @('||') expressions; ACL2's only non-strict construct is @(tsee if) (which the macros @(tsee and) and @(tsee or) expand to). Pure expression terms returning C values represent C expressions without side effects; C function calls may be side-effect-free, but in general we do not consider them pure, so they are represented by expression terms returning C values that are not pure expression terms returning C values. Expression terms returning booleans are always pure; so they do not need the explicit designation `pure' because they are the only expression terms returning booleans handled by ATC. Recursive ACL2 functions represent C loops, where those recursive functions are called. The loop flag @('L') serves to ensure that the body of a loop function ends with a recursive call on all paths (i.e. at all the leaves of its @(tsee if) structure, and that recursive calls of the loop function occur nowhere else.") (xdoc::p "The body of the C function represented by each non-recursive @('fn') is the compound statement consisting of the block items (i.e. statements and declarations) represented by the ACL2 function's body (which is a statement term).") (xdoc::p "The restriction that each function @('fn') may only call a function that precedes it in the list of targets @('(t1 ... tp)'), means that no (direct or indirect) recursion is allowed in the C code and the target functions must be specified in a topological order of their call graph.") (xdoc::p "The guard verification requirement ensures that the constraints about C types described above holds, for code reachable under guards. Code unreachable under guards is rare but possible. In order to generate C code that is always statically well-formed, ATC independently checks the constraints about C types.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-subsection "Translated Terms" (xdoc::p "The description of the representation of C code in ACL2 above talks about " (xdoc::seetopic "acl2::term" "untranslated terms") ", but ATC operates on " (xdoc::seetopic "acl2::term" "translated terms") ", since it looks at unnormalized bodies of ACL2 functions. This section describes how the untranslated terms mentioned above appear as translated terms: these are the patterns that ATC looks for.") (xdoc::p "An untranslated term @('(and a b)') is translated to") (xdoc::codeblock "(if a b \'nil)") (xdoc::p "An untranslated term @('(or a b)') it translated to") (xdoc::codeblock "(if a a b)") (xdoc::p "An untranslated term @('(mbt x)') is translated to") (xdoc::codeblock "(return-last \'acl2::mbe1-raw \'t x)") (xdoc::p "An untranslated term @('(mbt$ x)') is translated to") (xdoc::codeblock "(return-last \'acl2::mbe1-raw \'t (if x \'t \'nil))") (xdoc::p "An untranslated term @('(mv var1 ... varn)') is translated to") (xdoc::codeblock "(cons var1 (cons ... (cons varn \' nil)...))") (xdoc::p "An untranslated term @('(let ((var (declar term))) body)') is translated to") (xdoc::codeblock "((lambda (var) body) (declar term))") (xdoc::p "An untranslated term @('(let ((var (assign term))) body)') is translated to") (xdoc::codeblock "((lambda (var) body) (assign term))") (xdoc::p "An untranslated term @('(let ((var term)) body)') is translated to") (xdoc::codeblock "((lambda (var) body) term)") (xdoc::p "An untranslated term @('(mv-let (var var1 ... varn) (declarn term) body)') is translated to") (xdoc::codeblock "((lambda (mv)" " ((lambda (var var1 ... varn) body)" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " ((lambda (mv)" " ((lambda (*0 *1 *2 ... *n)" " (cons (declar *0) (cons *1 ... (cons *n 'nil))))" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " term))") (xdoc::p "An untranslated term @('(mv-let (var var1 ... varn) (assignn term) body)') is translated to") (xdoc::codeblock "((lambda (mv)" " ((lambda (var var1 ... varn) body)" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " ((lambda (mv)" " ((lambda (*0 *1 *2 ... *n)" " (cons (assign *0) (cons *1 ... (cons *n 'nil))))" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " term))") (xdoc::p "An untranslated term @('(mv-let (var1 var2 ... varn) term body)') is translated to") (xdoc::codeblock "((lambda (mv)" " ((lambda (var1 ... varn) body)" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n-1 mv)))" " term)") (xdoc::p "Since ATC operates on translated terms, there is no direct restriction on the untranslated bodies of the functions, which in particular may use any macro or any named constant, so long as their translated form satisfies all the requirements stated in this ATC documentation; the restrictions on the translated bodies thus impose indirect restrictions on the untranslated bodies. Note also that ATC treats, for instance, a translated term of the form @('(if a b \'nil)') as if it were the translation of @('(and a b)') in an untranslated function body, even though that untranslated function body may include @('(if a b \'nil)') directly, or some other macro that expands to that: this does not cause any problem, because if two untranslated terms become the same translated term, then they are equivalent for ATC's purposes."))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section xdoc::*evmac-section-appconds-title* (xdoc::p "In addition to the requirements on the inputs stated above, the following " (xdoc::seetopic "acl2::event-macro-applicability-conditions" "applicability conditions") " must be proved. The proofs are attempted when ATC is called. No hints can be supplied to ATC for these applicability conditions; (possibly local) lemmas must be provided before calling ATC that suffice for these applicability conditions to be proved without hints.") (xdoc::evmac-appcond ":natp-of-measure-of-fn" (xdoc::&& (xdoc::p "The measure of the recursive target function @('fn') must yield a natural number:") (xdoc::codeblock "(natp <fn-measure>)") (xdoc::p "where @('<fn-measure>') is the measure of @('fn').") (xdoc::p "There is one such applicability condition for each recursive target function @('fn')."))) (xdoc::p "These applicability conditions do not need to be proved if @(':proofs') is @('nil').")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section-generated ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-subsection "Constant" (xdoc::p "ATC generates an event") (xdoc::codeblock "(defconst *program* ...)") (xdoc::p "where @('...') is the abstract syntax tree of the generated C files, which ATC also pretty-prints and writes to the path(s) specified by the @(':output-dir') and @(':file-name') inputs.") (xdoc::p "If the @(':proofs') input is @('nil'), this constant is not generated.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-subsection "Theorems" (xdoc::p "ATC generates an event") (xdoc::codeblock "(defthm *program*-well-formed ...)") (xdoc::p "where @('...') is an assertion about @('*program*') stating that the generated (abstract syntax tree of the) files is statically well-formed, i.e. it compiles according to [C].") (xdoc::p "If the @(':proofs') input is @('nil'), this theorem is not generated.") (xdoc::p "For each target function @('fn'), ATC generates an event") (xdoc::codeblock "(defthm *program*-fn-correct ...)") (xdoc::p "where @('...') is an assertion about @('fn') and @('*program*') stating that, under the guard of @('fn'), executing the C dynamic semantics on the C function generated from @('fn') yields the same result as the function @('fn'). That is, the C function is functionally equivalent to the ACL2 function.") (xdoc::p "If the ACL2 function takes arrays or pointers to structures as inputs, the generated correctness theorem includes hypotheses saying that the arrays and structures are all at different addresses. The formal model of C that the proofs rely on assumes that arrays and structures do not overlap. Thus, the guarantees provided by the generated theorems about the C code hold only if pointers to distinct, non-overlapping arrays and structures are passed to the generated C functions.") (xdoc::p "If the @(':proofs') input is @('nil'), this theorem is not generated."))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section "Generated C Code" (xdoc::p "ATC generates a single source file, optionally accompanied by a header, as explained in Section `Representation of C Code in ACL2'.") (xdoc::p "The guard verification requirement stated earlier for each function implies that the generated C operations never exhibit undefined behavior, provided that they are called with values whose ACL2 counterparts satisfy the guard of the function.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-subsection "Compiling and Running the C Code" (xdoc::p "The generated C code can be compiled and run as any other C code. For instance, one can use @('gcc') on macOS or Linux.") (xdoc::p "As mention in the description of the @(':header') input above, if a header is generated, external code should include the header, and the generated source file should be compiled and linked with the external code to obtain a full application. To test the generated code, one can write a separate source file with a @('main') function, and compile all files together. By default, an executable @('a.out') is generated (if using @('gcc') on macOS or Linux).") (xdoc::p "The community books directory @('kestrel/c/atc/tests') contains some examples of C code generation and handwritten C code to test the generated code."))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (xdoc::evmac-section "Redundancy" (xdoc::p "A call of ATC is redundant if and only if it is identical to a previous successful call of ATC."))))
null
https://raw.githubusercontent.com/acl2/acl2/1e94e0bfb92e8caa9e90d9d5fe6afbed655bf8db/books/kestrel/c/atc/doc.lisp
lisp
and
C Library Copyright ( C ) 2023 Kestrel Institute ( ) Copyright ( C ) 2023 Kestrel Technology LLC ( ) License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . Author : ( ) (in-package "C") (include-book "kestrel/event-macros/xdoc-constructors" :dir :system) (defxdoc atc :parents (c) :short "ATC (<b>A</b>CL2 <b>T</b>o <b>C</b>), a proof-generating C code generator for ACL2." :long (xdoc::topstring (xdoc::evmac-section-intro (xdoc::p "This manual page contains user-level reference documentation for ATC. Users who are new to ATC should start with the " (xdoc::seetopic "atc-tutorial" "tutorial") ", which provides user-level pedagogical information on how ATC works and how to use ATC effectively.") (xdoc::p "This manual page refers to the official C standard in the manner explained in " (xdoc::seetopic "c" "the top-level XDOC topic of our C library") ".")) (xdoc::evmac-section-form (xdoc::codeblock "(atc t1 ... tp" " :output-dir ... ; default \".\"" " :file-name ... ; no default" " :header ... ; default nil" " :pretty-printing ... ; default nil" " :proofs ... ; default t" " :const-name ... ; default :auto" " :print ... ; default :result" " )")) (xdoc::evmac-section-inputs (xdoc::desc "@('t1'), ..., @('tp')" (xdoc::p "Names of ACL2 targets to translate to C.") (xdoc::p "Each @('ti') must be a symbol that satisfies exactly one of the following conditions:") (xdoc::ul (xdoc::li "It is the symbol of an ACL2 function.") (xdoc::li "Its @(tsee symbol-name) is the name of a C structure type shallowly embedded in ACL2, introduced via @(tsee defstruct).") (xdoc::li "Its @(tsee symbol-name) is the name of a C external object shallowly embedded in ACL2, introduced via @(tsee defobject).")) (xdoc::p "It is an error if two or more of the above conditions hold, because in that case the target does not unambiguously identify a function or a structure type or an external object.") (xdoc::p "The @(tsee symbol-name)s of the targets must be all distinct. Even though C has different name spaces for (i) structure types and (ii) functions and external objects [C:6.2.3], in C code generated by ATC these are treated as if they were in the same name space, so they must all have distinct names.") (xdoc::p "There must be at least one target function.") (xdoc::p "Each recursive target function must be called by at least one recursive or non-recursive target function that follows it in the list @('(t1 ... tp)').") (xdoc::p "Each target function must satisfy the conditions discussed in the section `Representation of C Code in ACL2'.")) (xdoc::desc "@(':output-dir') &mdash; default \".\"" (xdoc::p "Path of the directory where the generated C code goes.") (xdoc::p "This must be an ACL2 string that is the path may be absolute, or relative to the " (xdoc::seetopic "cbd" "connected book directory") ". The default is the connected book directory.")) (xdoc::desc "@(':file-name') &mdash; no default" (xdoc::p "Name of the files that contain the generated C code, without the @('.h') or @('.c') extension.") (xdoc::p "This must be a non-empty ACL2 string that consists of ASCII letters, digits, underscores, and dashes. The full names of the generated files are obtained by appending the extension @('.h') or @('.c') to this string.") (xdoc::p "The files are generated in the directory specified by @(':output-dir'). The files may or may not exist: if they exist, they are overwritten.")) (xdoc::desc "@(':header') &mdash; default @('nil')" (xdoc::p "Specifies whether a header (i.e. a @('.h') file) should be generated or not.") (xdoc::p "This must be one of the following:") (xdoc::ul (xdoc::li "@('t'), to generate a header.") (xdoc::li "@('nil'), to not generate a header.")) (xdoc::p the @(':header') input only affects the generation of the header.") (xdoc::p "If ATC is used to generate C code that is not standalone but is meant to be called by external C code, the @(':header') input should be @('t'), so that the external C code can include the header. If ATC is used to generate standalone C code, presumably including a function called @('main') with appropriate types, then @(':header') input should be @('nil').")) (xdoc::desc "@(':pretty-printing') &mdash; default @('nil')" (xdoc::p "Specifies options for how the generated C code is pretty-printed.") (xdoc::p "This must be a " (xdoc::seetopic "acl2::keyword-value-listp" "keyword-value list") " @('(opt-name1 opt-value1 opt-name2 opt-value2 ...)') where each @('opt-namek') is a keyword among the ones described below, and each @('opt-valuek') is one of the allowed values for the corresponding keyword as described below.") (xdoc::p "The following pretty-printing options are supported:") (xdoc::ul (xdoc::li "@(':parenthesize-nested-conditionals t/nil'), where @('t/nil') is either @('t') or @('nil'). This option specifies whether a conditional expression that is the `then' or `else' branch of another conditional expression is parenthesized or not. The parentheses are not necessary according to the precedence rules of C, but may help make the code more readable. The default value of this option is @('nil'), which means that no parentheses are added. If this option is @('t'), then parentheses are added. For example, based on whether this option is @('nil') or @('t'), an expression may be printed as either" (xdoc::codeblock "a ? b ? c : d : e ? f g") "or" (xdoc::codeblock "a ? (b ? c : e) : (e ? f : g)") ".")) (xdoc::p "This is currently the only supported pretty-printing option. More options, to control additional aspects of the pretty-print of the C code, may be added in the future.")) (xdoc::desc "@(':proofs') &mdash; default @('t')" (xdoc::p "Specifies whether proofs should be generated or not.") (xdoc::p "This must be one of the following:") (xdoc::ul (xdoc::li "@('t'), to generate proofs.") (xdoc::li "@('nil'), to not generate proofs.")) (xdoc::p "While it is obviously recommended to generate proofs, setting this to @('nil') may be useful in case proof generation is (temporarily) broken.")) (xdoc::desc "@(':const-name') &mdash; default @(':auto')" (xdoc::p "Name of the generated ACL2 named constant that holds the abstract syntax tree of the generated C program.") (xdoc::p "This must be one of the following:") (xdoc::ul (xdoc::li "@(':auto'), to use the symbol @('*program*') in the @('\"C\"') package.") (xdoc::li "Any other symbol, to use as the name of the constant.")) (xdoc::p "This input must be absent if @(':proofs') is @('nil'). The named constant is generated only if @(':proofs') is @('t').") (xdoc::p "In the rest of this documentation page, let @('*program*') be the symbol specified by this input, if applicable (i.e. when @(':proofs') is @('t')).")) (xdoc::desc "@(':print') &mdash; default @(':result')" (xdoc::p "Specifies what is printed on the screen.") (xdoc::p "It must be one of the following:") (xdoc::ul (xdoc::li "@(':error'), to print only error output (if any).") (xdoc::li "@(':result'), to print, besides any error output, also the " (xdoc::seetopic "acl2::event-macro-results" "results") " of ATC. This is the default value of the @(':print') input.") (xdoc::li "@(':info'), to print, besides any error output and the results, also some additional information about the internal operation of ATC.") (xdoc::li "@(':all'), to print, besides any error output, the results, and the additional information, also ACL2's output in response to all the submitted events.")) (xdoc::p "The errors are printed as " (xdoc::seetopic "set-inhibit-output-lst" "error output") ". The results and the additional information are printed as " (xdoc::seetopic "set-inhibit-output-lst" "comment output") ". The ACL2 output enabled by @(':print :all') may consist of " (xdoc::seetopic "set-inhibit-output-lst" "output of various kinds") ".") (xdoc::p "If @(':print') is @(':error') or @(':result') or @(':info'), ATC suppresses all kinds of outputs (via @(tsee with-output)) except for error and comment output. Otherwise, ATC does not suppress any output. However, the actual output depends on which outputs are enabled or not prior to the call of ATC, including any @(tsee with-output) that may wrap the call of ATC."))) (xdoc::evmac-section "Representation of C Code in ACL2" (xdoc::p "Currently ATC supports the ACL2 representation of a single source file (i.e. a file with extension @('.c')), optionally accompanied by a header (i.e. a file with extension @('.h')), based on the @(':header') input. If @(':header') is @('nil'), the source file consists of one or more C function definitions, zero or more C external object declarations, and zero or more C structure type declarations. If @(':header') is @('t'), the header consists of one or more function declarations, zero or more C external object declarations without initializers, and zero or more C structure type declarations, while the source file consists of one or more function definitions and zero or more C external object declarations with initializers, corresponding to the function declarations and the external object declarations in the header.") (xdoc::p "Each C structure type declaration is represented by a @(tsee defstruct), whose name is passed as one of the targets @('ti') to ATC. The symbol name, which is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") " (this is enforced by @(tsee defstruct)), represents the tag of the C structure type.") (xdoc::p "Each C external object declaration is represented by a @(tsee defobject), whose name is passed as one of the targets @('ti') to ATC. The symbol name, which is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") " (this is enforced by @(tsee defobject)), represents the name of the C external object.") (xdoc::p "Each C function definition (and declaration in the header, if present) is represented by an ACL2 function definition. the recursive target ACL2 functions @('ti') passed as inputs represent loops in the C functions instead, as explained below.") (xdoc::p "The order of the C structure types and external objects and functions in the files is the same as the order of the corresponding targets in the list @('(t1 ... tp)') passed to ATC.") (xdoc::p "Each target function @('fn') must be in logic mode and guard-verified. The function must not occur in its own guard, which is rare but allowed in ACL2.") (xdoc::p "The symbol name of each non-recursive function target @('fn') must be a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ". That symbol name is used as the name of the corresponding C function. Therefore, the non-recursive target functions even if they are in different packages, they must have distinct symbol names (the package names are ignored). There is no restriction on the symbol names of the recursive target functions: the names of the recursive target functions are not represented at all in the C code.") (xdoc::p "The symbol name of each formal parameter of each function target @('fn'), both non-recursive and recursive, must be a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ". When @('fn') is non-recursive, the symbol names of its parameters are used as the names of the formal parameters of the corresponding C function, in the same order, except for the formal parameters that represent external objects, as defined below. Therefore, the formal parameters of each @('fn') even if they are in different packages, they must have distinct symbol names (the package names are ignored). When @('fn') is recursive, the symbol names of its parameters are used as names of C variables, as explained below.") (xdoc::p "When @('fn') is recursive, it must have at least one formal parameter. When @('fn') is non-recursive, it may have any number of formal parameters, including none.") (xdoc::p "If @('fn') is recursive, it must be singly (not mutually) recursive, its well-founded relation must be @(tsee o<), and its measure must yield a natural number. The latter requirement is checked via an applicability condition, as described in the `Applicability Conditions' section.") (xdoc::p "The guard of each @('fn') must include, for every formal parameter @('x'), exactly one conjunct of one of the following forms, possibly wrapped with @(tsee mbt), which determines the C type of the corresponding parameter of the C function, or designates the formal parameter as representing an access to an object defined by @(tsee defobject):") (xdoc::ul (xdoc::li "@('(scharp x)'), representing @('signed char').") (xdoc::li "@('(ucharp x)'), representing @('unsigned char').") (xdoc::li "@('(sshortp x)'), representing @('signed short').") (xdoc::li "@('(ushortp x)'), representing @('unsigned short').") (xdoc::li "@('(sintp x)'), representing @('signed int').") (xdoc::li "@('(uintp x)'), representing @('unsigned int').") (xdoc::li "@('(slongp x)'), representing @('signed long').") (xdoc::li "@('(ulongp x)'), representing @('unsigned long').") (xdoc::li "@('(sllongp x)'), representing @('signed long long').") (xdoc::li "@('(ullongp x)'), representing @('unsigned long long').") (xdoc::li "@('(star (scharp x))'), representing @('signed char *').") (xdoc::li "@('(star (ucharp x))'), representing @('unsigned char *').") (xdoc::li "@('(star (sshortp x))'), representing @('signed short *').") (xdoc::li "@('(star (ushortp x))'), representing @('unsigned short *').") (xdoc::li "@('(star (sintp x))'), representing @('signed int *').") (xdoc::li "@('(star (uintp x))'), representing @('unsigned int *').") (xdoc::li "@('(star (slongp x))'), representing @('signed long *').") (xdoc::li "@('(star (ulongp x))'), representing @('unsigned long *').") (xdoc::li "@('(star (sllongp x))'), representing @('signed long long *').") (xdoc::li "@('(star (ullongp x))'), representing @('unsigned long long *').") (xdoc::li "@('(schar-arrayp x)'), representing @('signed char []').") (xdoc::li "@('(uchar-arrayp x)'), representing @('unsigned char []').") (xdoc::li "@('(sshort-arrayp x)'), representing @('signed short []').") (xdoc::li "@('(ushort-arrayp x)'), representing @('unsigned short []').") (xdoc::li "@('(sint-arrayp x)'), representing @('signed int []').") (xdoc::li "@('(uint-arrayp x)'), representing @('unsigned int []').") (xdoc::li "@('(slong-arrayp x)'), representing @('signed long []').") (xdoc::li "@('(ulong-arrayp x)'), representing @('unsigned long []').") (xdoc::li "@('(sllong-arrayp x)'), representing @('signed long long []').") (xdoc::li "@('(ullong-arrayp x)'), representing @('unsigned long long []').") (xdoc::li "@('(struct-<tag>-p x)'), where @('<tag>') is one of the @(tsee defstruct) targets @('ti'), representing the corresponding C structure type, @('struct <tag>'). The structure type must not have a flexible array member. The @('<tag>') target must precede @('fn') in the list of targets @('(t1 ... tp)').") (xdoc::li "@('(star (struct-<tag>-p x))'), where @('<tag>') is one of the @(tsee defstruct) targets @('ti'), representing a pointer type to the corresponding C structure type, @('struct <tag> *'). The @('<tag>') target must precede @('fn') in the list of targets @('(t1 ... tp)').") (xdoc::li "@('(object-<name>-p x)'), where @('<name>') is one of the @(tsee defobject) targets @('ti'), representing an access to the external object, which must be an explicit formal parameter in functional ACL2, while the C function accesses it directly. The @('<name>') target must precede @('fn') in the list of targets @('(t1 ... tp)').")) (xdoc::p "The conjuncts may be at any level of nesting, but must be extractable by flattening the @(tsee and) structure of the guard term: only conjuncts extractable this way count for the purpose of determining the C types of the formal parameters and which formal parameters represent accesses to external objects. The rest of the guard (i.e. other than the conjuncts above) is not explicitly represented in the C code.") (xdoc::p "Note the distinction between pointer types @('<integer type> *') and array types @('<integer type> []') in the list above. Even though these types are equivalent for function parameters, and in fact array types are adjusted to pointer types for function parameters according to [C], pointed-to integers and integer arrays are different in the ACL2 representation of C. (More in general, even in handwritten C code, using array types instead of pointer types for function parameters is useful to convey the intention that something is a pointer to (the first or some) element of an integer array as opposed to a pointer to a single integer.)") (xdoc::p "The aforementioned option of wrapping the conjuncts with @(tsee mbt) is useful for cases in which the function have stronger guards that imply those conjuncts. It would be inelegant to add redundant conjuncts to the guard (presumably via external transformations) for the sole purpose of communicating function parameter types to ATC. By allowing @(tsee mbt), the redundancy can be explicated and proved (as part of guard verification), while making it easy for ATC to obtain the types.") (xdoc::p "The return type of the C function corresponding to each non-recursive target function @('fn') is automatically determined from the body, as explained below.") (xdoc::p "The " (xdoc::seetopic "acl2::function-definedness" "unnormalized body") " of each @('fn') must be as follows:") (xdoc::ul (xdoc::li "If @('fn') is non-recursive, the unnormalized body must be a statement term for @('fn') with loop flag @('nil') returning type @('T') and affecting variables @('vars') (as defined below), where each variable in @('vars') is a formal parameter of @('fn') with pointer or array type and where @('T') is not @('void') if @('vars') is @('nil'). The return type of the C function represented by @('fn') is @('T').") (xdoc::li "If @('fn') is recursive, the unnormalized body must be a loop term for @('fn') affecting variables @('vars') (as defined below), where each variable in @('vars') is a formal parameter of @('fn').")) (xdoc::p "The above-mentioned notions of (i) statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars') and (ii) loop term for @('fn') affecting @('vars') are defined below, along with the notions of (iii) expression term for @('fn') returning @('T') and affecting @('vars'), (iv) pure expression term for @('fn') returning @('T'), (v) expression term for @('fn') returning boolean, (vi) C type of a variable, and (vii) assignable variable.") (xdoc::p "A <i>statement term for</i> @('fn') <i>with loop flag</i> @('L') <i>returning</i> @('T') and <i>affecting</i> @('vars'), where @('fn') is a target function, @('L') is either @('t') or @('nil'), @('T') is a C type (possibly @('void')), and @('vars') is a list of distinct symbols, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "An expression term for @('fn') returning @('T') and affecting @('vars'), when @('L') is @('nil'), @('T') is a non-@('void') non-pointer non-array C type, and @('vars') is @('nil'). That is, an expression term returning a C value is also a statement term returning that C value. This represents a C @('return') statement whose expression is represented by the same term, viewed as an expression term.") (xdoc::li "A term @('(mv ret var1 ... varn)'), when @('ret') is an expression term for @('fn') returning @('T') and affecting no variables, @('L') is @('nil'), @('T') is a non-@('void') non-pointer non-array type, 1 . This represents a C @('return') statement the @(tsee mv) and the variables in @('vars') represent no actual C code: they just represent variables that may have been modified by preceding code.") (xdoc::li "A term @('var'), when @('L') is @('nil'), @('T') is @('void'), and @('vars') is the singleton list @('(var)'). This represents no actual C code: it just serves to conclude preceding code that may modify @('var').") (xdoc::li "A term @('(mv var1 ... varn)'), when @('L') is @('nil'), @('T') is @('void'), 1 . This represents no actual C code: it just serves to conclude preceding code that may modify @('var1'), ..., @('varn').") (xdoc::li "A call of @('fn') on variables identical to its formal parameters, when the C types of the variables are the same as the C types of the formal parameters, @('L') is @('t'), @('T') is @('void'), and @('fn') is recursive. This represents no actual C code: it just serves to conclude the computation in the body of the loop represented by @('fn').") (xdoc::li "A call of @(tsee if) on (i) a test of the form @('(mbt ...)') or @('(mbt$ ...)'), (ii) a `then' branch that is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'), and (iii) an `else' branch that may be any ACL2 term. This represents the same C code represented by the `then' branch. Both the test and the `else' branch are ignored, because ATC generates C code under guard assumptions.") (xdoc::li "A call of @(tsee if) on (i) a test that is an expression term for @('fn') returning boolean and (ii) branches that are statement terms for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C @('if') conditional statement whose test expression is represented by the test term and whose branch blocks are represented by the branch terms.") (xdoc::li "A term @('(let ((var (declar term))) body)'), when the symbol name of @('var') is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ", the symbol name of @('var') is distinct from the symbol names of all the other ACL2 variables in scope, @('term') is an expression term for @('fn') returning a non-@('void') non-pointer non-array C type and affecting no variables, and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @(tsee declar), a declaration of a C local variable represented by @('var'), initialized with the C expression represented by @('term'), followed by the C code represented by @('body'). The C type of the variable is determined from the initializer.") (xdoc::li "A term @('(let ((var (assign term))) body)'), when @('var') is assignable, @('term') is an expression term for @('fn') returning the same non-@('void') non-pointer non-array C type as the C type of @('var') and affecting no variables, and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @(tsee assign), an assignment to the C local variable or function parameter represented by @('var'), with the C expression represented by @('term') as right-hand side, followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (<type>-write term))) body)'), when @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is in scope, @('var') has a pointer type whose referenced type is the C integer type corresponding to @('<type>'), @('var') is one of the symbols in @('vars'), @('term') is a pure expression term for @('fn') returning the C integer type corresponding to @('<type>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to the pointer variable represented by @('var') the wrapper @('<type>-write') signifies the writing to an integer by pointer.") (xdoc::li "A term @('(let ((var (<type1>-array-write-<type2> var term1 term2))) body)'), when @('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is in scope, @('var') has an array type whose element type is the C integer type corresponding to @('<type1>'), @('var') is one of the symbols in @('vars'), @('term1') is a pure expression term for @('fn') returning the C integer type corresponding to @('<type2>'), @('term2') is a pure expression term for @('fn') returning the C integer type corresponding to @('<type1>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to an element of the array represented by @('var') with the subscript expression represented by @('term1') with the new element expression represented by @('term2'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member> term var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer type in the @(tsee defstruct), @('var') is assignable, @('var') has the C structure type represented by @('<tag>'), @('term') is a pure expression term for @('fn') returning the C integer type of @('<member>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to a member of the structure represented by @('var') by value (i.e. using @('.')) with the new value expression represented by @('term'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member> term var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer type in the @(tsee defstruct), @('var') is in scope, @('var') has a pointer type whose referenced type is the C structure type represented by @('<tag>'), @('var') is one of the symbols in @('vars'), @('term') is a pure expression term for @('fn') returning the C integer type of @('<member>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to a member of the structure represented by @('var') by pointer (i.e. using @('->')) with the new value expression represented by @('term'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member>-<type> term1 term2 var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer array type in the @(tsee defstruct) with element type @('<type2>'), @('<type>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is assignable, @('var') has the C structure type represented by @('<tag>'), @('term1') is a pure expression term for @('fn') returning the C type corresponding to @('<type2>'), @('term2') is a pure expression term for @('fn') returning the C type corresponding to @('<type>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to an element of a member of the structure represented by @('var') by value (i.e. using @('.')) using @('term1') as the index with the new value expression represented by @('term2'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var (struct-<tag>-write-<member>-<type> term1 term2 var))) body)'), when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer array type in the @(tsee defstruct) with element type @('<type2>'), @('<type>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('var') is in scope, @('var') has a pointer type whose referenced type is the C structure type represented by @('<tag>'), @('var') is one of the symbols in @('vars'), @('term1') is a pure expression term for @('fn') returning the C type corresponding to @('<type2>'), @('term2') is a pure expression term for @('fn') returning the C type corresponding to @('<type>'), @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents a C assignment to an element of a member of the structure represented by @('var') by pointer (i.e. using @('->')) using @('term1') as the index with the new value expression represented by @('term2'), followed by the C code represented by @('body').") (xdoc::li "A term @('(let ((var term)) body)'), when @('var') is assignable, @('var') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is a statement term for @('fn') with loop flag @('nil') returning @('void') and affecting @('var') that is either a call of a target function that precedes @('fn') in the list of targets @('(t1 ... tp)') whose body term returns @('void') and affects @('var') or an @(tsee if) whose test is an expression term returning boolean (not a test @('(mbt ...)') or @('(mbt$ ...)')), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents the C code represented by @('term'), which may modify the variable represented by @('var'), followed by the C code represented by @('body').") (xdoc::li "A term @('(mv-let (var var1 ... varn) (declarn term) body)'), when the symbol name of @('var') is a " (xdoc::seetopic "portable-ascii-identifiers" "portable ASCII C identifier") ", the symbol name of @('var') is distinct from the symbol names of all the other ACL2 variables in scope, each @('vari') is assignable, each @('vari') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is an expression term for @('fn') returning a non-@('void') non-pointer non-array C type and affecting the variables @('(var1 ... varn)'), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @('declarn'), a declaration of a C local variable represented by @('var'), initialized with the C expression represented by @('term'), followed by the C code represented by @('body'). Note that @('declarn') stands for @('declar1'), @('declar2'), etc., this @('n') is the number of side-effected variables @('var1'), ..., @('varn'), which is one less than the variables bound by the @(tsee mv-let). The C type of the variable is determined from the initializer.") (xdoc::li "A term @('(mv-let (var var1 ... varn) (assignn term) body)'), when @('var') is assignable, each @('vari') is assignable, each @('vari') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is an expression term for @('fn') returning the same non-@('void') non-pointer non-array C type as the C type of @('var') and affecting the variables @('(var1 ... varn)'), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents, as indicated by the wrapper @('assignn'), an assignment to the C local variable or function parameter represented by @('var'), with the C expression represented by @('term') as right-hand side, followed by the C code represented by @('body'). Note that @('assignn') stands for @('assign1'), @('assign2'), etc., this @('n') is the number of side-effected variables @('var1'), ..., @('varn'), which is one less than the variables bound by the @(tsee mv-let).") (xdoc::li "A term @('(mv-let (var1 ... varn) term body)'), 1 , each @('vari') is assignable, each @('vari') is among @('vars') if it is a formal parameter of @('fn') that has pointer or array type if @('fn') is non-recursive, @('term') is a statement term for @('fn') with loop flag @('nil') returning @('void') and affecting @('(var1 ... varn)') that is either a call of a recursive target function that precedes @('fn') in the list of targets @('(t1 ... tp)') whose body term returns @('void') and affects @('(var1 ... varn)') or an @(tsee if) whose test is an expression term returning boolean (not a test @('(mbt ...)') or @('(mbt$ ...)')), and @('body') is a statement term for @('fn') with loop flag @('L') returning @('T') and affecting @('vars'). This represents the C code represented by @('term'), which may modify the variables represented by @('var1'), ..., @('varn'), followed by the C code represented by @('body').") (xdoc::li "A call of a recursive target function @('fn0') that precedes @('fn') in the list of targets @('(t1 ... tp)'), on variables identical to its formal parameters, when the C types of the variables are the same as the C types of the formal parameters of @('fn0'), @('L') is @('nil'), @('T') is @('void'), @('vars') is not @('nil'), and the body of @('fn0') is a loop term for @('fn0') affecting @('vars'). This represents the C @('while') statement represented by the body of @('fn0'), as explained below.") (xdoc::li "A call of a non-recursive target function @('fn0') that precedes @('fn') in the list of targets @('(t1 ... tp)'), on pure expression terms for @('fn') returning non-@('void') C types, when the C types of the terms are the same as the C types of the formal parameters, each term of pointer or array type is a variable identical to the corresponding formal parameter of @('fn0'), @('L') is @('nil'), @('T') is @('void'), and the body of @('fn0') is a statement term for @('fn0') returning @('void') and affecting @('vars'). This represents an expression statement whose expression is call of the C function corresponding to @('fn0').")) (xdoc::p "A <i>loop term for</i> @('fn') <i>affecting</i> @('vars'), where @('fn') is a target function and @('vars') is a non-empty list of distinct symbols, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A call of @(tsee if) on (i) a test of the form @('(mbt ...)') or @('(mbt$ ...)'), (ii) a `then' branch that is a loop term for @('fn') affecting @('vars'), and (iii) an `else' branch that may be any ACL2 term. This represents the same C code represented by the `then' branch. Both the test and the `else' branch are ignored, because ATC generates C code under guard assumptions.") (xdoc::li "A call of @(tsee if) on (i) a test that is an expression term for @('fn') returning boolean, (ii) a `then' branch that is a statement term for @('fn') with loop flag @('t') returning @('void') and affecting @('vars'), and (iii) an `else' branch that is either the variable @('var') when @('vars') is the singleton @('(var)'), or the term @('(mv var1 ... varn)') 1 . This represents the C @('while') statement whose controlling expression is represented by the test the `else' branch represents no actual C code, because it just serves to complete the @(tsee if).")) (xdoc::p "An <i>expression term for</i> @('fn') <i>returning</i> @('T') and <i>affecting</i> @('vars'), where @('fn') is a target function, @('T') is a non-@('void') C type, and @('vars') is a list of distinct symbols, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A pure expression term for @('fn') returning @('T'), when @('vars') is @('nil').") (xdoc::li "A call of a non-recursive target function @('fn0') that precedes @('fn') in the list of targets @('(t1 ... tp)'), on pure expression terms for @('fn') returning C types, when the types of the terms are equal to the C types of the formal parameters of @('fn0'), each term of pointer or array type is a variable identical to the corresponding formal parameter of @('fn0'), and the body of @('fn0') is a statement term for @('fn0') returning @('T') and affecting @('vars'). This represents a call of the corresponding C function.")) (xdoc::p "A <i>pure expression term for</i> @('fn') <i>returning</i> @('T'), where @('fn') is a target function and @('T') is a non-@('void') C type, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A formal parameter of @('fn'), when @('T') is the type of the formal parameter. This represents either the corresponding C formal parameter (as an expression), or the corresponding C external object (as an expression), as explained earlier.") (xdoc::li "A variable introduced by @(tsee let) with @(tsee declar) (as described above), when @('T') is the type of the variable. This represents the corresponding C local variable (as an expression).") (xdoc::li "A call of a function @('<type>-<base>-const') on a quoted integer, when @('<type>') is among" (xdoc::ul (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('<base>') is among" (xdoc::ul (xdoc::li "@('dec')") (xdoc::li "@('oct')") (xdoc::li "@('hex')")) "@('T') is the C type corresponding to @('<type>') and the quoted integer is non-negative and in the range of @('T'). This represents a C integer constant of the C type indicated by the name of the function, expressed in decimal, octal, or hexadecimal base.") (xdoc::li "A call of a function @('<op>-<type>') on a pure expression term for @('fn') returning @('U'), when @('<op>') is among" (xdoc::ul (xdoc::li "@('plus')") (xdoc::li "@('minus')") (xdoc::li "@('bitnot')") (xdoc::li "@('lognot')")) "@('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type corresponding to the return type of @('<op>-<type>') and @('U') is the C type corresponding to @('<type>'). This represents the C operator indicated by the name of the function applied to a value of the type indicated by the name of the function. The guard verification requirement ensures that the operator yields a well-defined result. These functions covers all the C unary operators (using the nomenclature in [C]).") (xdoc::li "A call of a function @('<op>-<type1>-<type2>') on pure expression terms for @('fn') returning @('U') and @('V'), when @('<op>') is among" (xdoc::ul (xdoc::li "@('add')") (xdoc::li "@('sub')") (xdoc::li "@('mul')") (xdoc::li "@('div')") (xdoc::li "@('rem')") (xdoc::li "@('shl')") (xdoc::li "@('shr')") (xdoc::li "@('lt')") (xdoc::li "@('gt')") (xdoc::li "@('le')") (xdoc::li "@('ge')") (xdoc::li "@('eq')") (xdoc::li "@('ne')") (xdoc::li "@('bitand')") (xdoc::li "@('bitxor')") (xdoc::li "@('bitior')")) "@('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type corresponding to the return type of @('<op>-<type1>-<type2>'), @('U') is the C type corresponding to @('<type1>'), and @('V') is the C type corresponding to @('<type2>'). This represents the C operator indicated by the name of the function applied to values of the types indicated by the name of the function. The guard verification requirement ensures that the operator yields a well-defined result. the non-strict operators @('&&') and @('||'), and the non-pure operators @('='), @('+='), etc., are represented differently.") (xdoc::li "A call of a function @('<type1>-from-<type2>') on a pure expression term for @('fn') returning @('U'), when @('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "and also differ from each other, @('T') is the C type corresponding to @('<type1>') and @('U') is the C type corresponding to @('<type2>'). This represents a cast to the type indicated by the first part of the function name. The guard verification requirement ensures that the conversion yields a well-defined result. Even though conversions happen automatically in certain circumstances in C, implict conversions are represented implicitly, e.g. via the function for a unary operator that promotes the operand.") (xdoc::li "A call of @('<type>-read') on a pure expression term for @('fn') returning @('U'), when @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type corresponding to @('<type>'), and @('U') is the pointer type to @('T'). This represents the application of the indirection operator @('*') to the expression represented by the argument of @('<type>-read').") (xdoc::li "A call of @('<type1>-array-read-<type2>') on pure expression terms for @('fn') returning @('U') and @('V'), when @('<type1>') and @('<type2>') are among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C type correponding to @('<type1>'), @('U') is the array type of element type @('T'), and @('V') is the C type correponding to @('<type2>'). This represents an array subscripting expression. The guard verification requirement ensures that the array access is well-defined.") (xdoc::li "A call of @('struct-<tag>-read-<member>') on a pure expression term for @('fn') returning @('U') when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<member>') has an integer type in the @(tsee defstruct), @('T') is the C integer type of @('<member>'), and @('U') is the C structure type represented by @('<tag>') or the pointer type to that C structure type. This represents an access to a structure member, by value if @('U') is the C structure type (i.e. using @('.')) or by pointer if @('U') is the pointer type to the C structure type (i.e. using @('->')).") (xdoc::li "A call of @('struct-<tag>-read-<member>-<type>') on pure expression terms for @('fn') returning @('U') and @('V') when @('<tag>') is a @(tsee defstruct) name, @('<member>') is the name of one of the members of that @(tsee defstruct), @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('T') is the C element type of the array type of @('<member>'), @('U') is the C type corresponding to @('<type>'), and @('V') is the C structure type represented by @('<tag>') or the pointer type to that C structure type. This represents an access to an element of a structure member, by value if @('V') is the C structure type (i.e. using @('.')) or by pointer if @('V') is the pointer type to the C structure type (i.e. using @('->')).") (xdoc::li "A call of @(tsee sint-from-boolean) on an expression term for @('fn') returning boolean that is a call of @(tsee and) or @(tsee or) (not a call of any @('boolean-from-<type>')), when @('T') is @('int'). This converts an expression term returning boolean to a pure expression term returning @('int'). The restriction of the argument term of @(tsee sint-from-boolean) to be a call of @(tsee and) and @(tsee or) is so that such a call always represents the C @('int') 0 or 1, the conversion from boolean to @('int') is only in ACL2, not present in the C code, which just has the represented expression.") (xdoc::li "A call of @(tsee condexpr) on a call of @(tsee if) on (i) a test that is an expression term for @('fn') returning boolean and (ii) branches that are pure expression terms for @('fn') returning @('T'). This represents a C @('?:') conditional expression whose test expression is represented by the test term and whose branch expressions are represented by the branch terms.")) (xdoc::p "An <i>expression term for</i> @('fn') <i>returning boolean</i>, where @('fn') is a target function, is inductively defined as one of the following:") (xdoc::ul (xdoc::li "A call of a function @('boolean-from-<type>') on a pure expression term for @('fn') returning @('U'), when @('<type>') is among" (xdoc::ul (xdoc::li "@('schar')") (xdoc::li "@('uchar')") (xdoc::li "@('sshort')") (xdoc::li "@('ushort')") (xdoc::li "@('sint')") (xdoc::li "@('uint')") (xdoc::li "@('slong')") (xdoc::li "@('ulong')") (xdoc::li "@('sllong')") (xdoc::li "@('ullong')")) "@('U') is the C type corresponding to @('<type>'). This converts a pure expression term returning a C type to an expression term returning boolean.") (xdoc::li "A call of one of the following macros on expression terms for @('fn') returning booleans:" (xdoc::ul (xdoc::li "@(tsee and)") (xdoc::li "@(tsee or)")) "This represents the corresponding C logical operator conjunctions and disjunctions are represented non-strictly.")) (xdoc::p "The <i>C type of a variable</i> @('var') is defined as follows:") (xdoc::ul (xdoc::li "If @('var') is a formal parameter that does not represent an access to an external object, the C type is the one derived from the guard as explained earlier.") (xdoc::li "If @('var') is a formal parameter that represents an access to an external object, the C type is derived from the definition of the recognizer @('object-<name>-p') generated by @(tsee defobject) for that object. see @(tsee defobject).") (xdoc::li "If @('var') is not a formal parameter, it must be introduced by a @(tsee let) with @(tsee declar) or an @(tsee mv-let) with @('declarn'), and its C type is the one of the term argument of @(tsee declar) or @('declarn').")) (xdoc::p "The C type of a variable is never @('void').") (xdoc::p "A variable @('var') bound in a @(tsee let) or @(tsee mv-let) in a target function @('fn') is <i>assignable</i> when it is in scope, i.e. it is identical to a function parameter or to a variable bound in an enclosing @(tsee let) or @(tsee mv-let), and additionally any of the conditions given below holds. The conditions make reference to the C scopes represented by the ACL2 terms that the @(tsee let) or @(tsee mv-let) is part of: there is a C scope for the whole file, then each function body is a nested C scope, and then each @(tsee if) branch whose test is an expression term returning a boolean (i.e. whose test is not @(tsee mbt) or @(tsee mbt$)) is a further nested C scope. The conditions are the following:") (xdoc::ul (xdoc::li "The function parameter or outer variable is in the same C scope where @('var') occurs.") (xdoc::li "The variable @('var') is among @('vars'), i.e. it is being affected.") (xdoc::li "No variables are being affected, i.e. @('vars') is @('nil').")) (xdoc::p "Any of these conditions ensures that, in the ACL2 code, the old value of the variable cannot be accessed after the new binding: (i) if the first condition holds, (ii) if the second condition holds, it means that the outer binding will receive the value (iii) if the third condition holds, there is no subsequent code because there is no change to the variables. These justify destructively updating the variable in the C code.") (xdoc::p "Statement terms represent C statements, while expression terms represent C expressions. The expression terms returning booleans return ACL2 boolean values, while the statement terms, including expression terms returning C values, return ACL2 values that represent C values: the distinction between boolean terms and other kinds of terms stems from the need to represent C's non-strictness in ACL2: C's non-strict constructs are @('if') statements, @('?:') expressions, @('&&') expressions, and ACL2's only non-strict construct is @(tsee if) (which the macros @(tsee and) and @(tsee or) expand to). Pure expression terms returning C values C function calls may be side-effect-free, but in general we do not consider them pure, so they are represented by expression terms returning C values that are not pure expression terms returning C values. so they do not need the explicit designation `pure' because they are the only expression terms returning booleans handled by ATC. Recursive ACL2 functions represent C loops, where those recursive functions are called. The loop flag @('L') serves to ensure that the body of a loop function ends with a recursive call on all paths (i.e. at all the leaves of its @(tsee if) structure, and that recursive calls of the loop function occur nowhere else.") (xdoc::p "The body of the C function represented by each non-recursive @('fn') is the compound statement consisting of the block items (i.e. statements and declarations) represented by the ACL2 function's body (which is a statement term).") (xdoc::p "The restriction that each function @('fn') may only call a function that precedes it in the list of targets @('(t1 ... tp)'), means that no (direct or indirect) recursion is allowed in the C code and the target functions must be specified in a topological order of their call graph.") (xdoc::p "The guard verification requirement ensures that the constraints about C types described above holds, for code reachable under guards. Code unreachable under guards is rare but possible. In order to generate C code that is always statically well-formed, ATC independently checks the constraints about C types.") (xdoc::evmac-subsection "Translated Terms" (xdoc::p "The description of the representation of C code in ACL2 above talks about " (xdoc::seetopic "acl2::term" "untranslated terms") ", but ATC operates on " (xdoc::seetopic "acl2::term" "translated terms") ", since it looks at unnormalized bodies of ACL2 functions. This section describes how the untranslated terms mentioned above appear as translated terms: these are the patterns that ATC looks for.") (xdoc::p "An untranslated term @('(and a b)') is translated to") (xdoc::codeblock "(if a b \'nil)") (xdoc::p "An untranslated term @('(or a b)') it translated to") (xdoc::codeblock "(if a a b)") (xdoc::p "An untranslated term @('(mbt x)') is translated to") (xdoc::codeblock "(return-last \'acl2::mbe1-raw \'t x)") (xdoc::p "An untranslated term @('(mbt$ x)') is translated to") (xdoc::codeblock "(return-last \'acl2::mbe1-raw \'t (if x \'t \'nil))") (xdoc::p "An untranslated term @('(mv var1 ... varn)') is translated to") (xdoc::codeblock "(cons var1 (cons ... (cons varn \' nil)...))") (xdoc::p "An untranslated term @('(let ((var (declar term))) body)') is translated to") (xdoc::codeblock "((lambda (var) body) (declar term))") (xdoc::p "An untranslated term @('(let ((var (assign term))) body)') is translated to") (xdoc::codeblock "((lambda (var) body) (assign term))") (xdoc::p "An untranslated term @('(let ((var term)) body)') is translated to") (xdoc::codeblock "((lambda (var) body) term)") (xdoc::p "An untranslated term @('(mv-let (var var1 ... varn) (declarn term) body)') is translated to") (xdoc::codeblock "((lambda (mv)" " ((lambda (var var1 ... varn) body)" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " ((lambda (mv)" " ((lambda (*0 *1 *2 ... *n)" " (cons (declar *0) (cons *1 ... (cons *n 'nil))))" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " term))") (xdoc::p "An untranslated term @('(mv-let (var var1 ... varn) (assignn term) body)') is translated to") (xdoc::codeblock "((lambda (mv)" " ((lambda (var var1 ... varn) body)" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " ((lambda (mv)" " ((lambda (*0 *1 *2 ... *n)" " (cons (assign *0) (cons *1 ... (cons *n 'nil))))" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n mv)))" " term))") (xdoc::p "An untranslated term @('(mv-let (var1 var2 ... varn) term body)') is translated to") (xdoc::codeblock "((lambda (mv)" " ((lambda (var1 ... varn) body)" " (mv-nth \'0 mv)" " (mv-nth \'1 mv)" " ..." " (mv-nth \'n-1 mv)))" " term)") (xdoc::p "Since ATC operates on translated terms, there is no direct restriction on the untranslated bodies of the functions, which in particular may use any macro or any named constant, so long as their translated form the restrictions on the translated bodies thus impose indirect restrictions on the untranslated bodies. Note also that ATC treats, for instance, a translated term of the form @('(if a b \'nil)') as if it were the translation of @('(and a b)') in an untranslated function body, even though that untranslated function body may include @('(if a b \'nil)') directly, or some other macro that expands to that: this does not cause any problem, because if two untranslated terms become the same translated term, then they are equivalent for ATC's purposes."))) (xdoc::evmac-section xdoc::*evmac-section-appconds-title* (xdoc::p "In addition to the requirements on the inputs stated above, the following " (xdoc::seetopic "acl2::event-macro-applicability-conditions" "applicability conditions") " must be proved. The proofs are attempted when ATC is called. (possibly local) lemmas must be provided before calling ATC that suffice for these applicability conditions to be proved without hints.") (xdoc::evmac-appcond ":natp-of-measure-of-fn" (xdoc::&& (xdoc::p "The measure of the recursive target function @('fn') must yield a natural number:") (xdoc::codeblock "(natp <fn-measure>)") (xdoc::p "where @('<fn-measure>') is the measure of @('fn').") (xdoc::p "There is one such applicability condition for each recursive target function @('fn')."))) (xdoc::p "These applicability conditions do not need to be proved if @(':proofs') is @('nil').")) (xdoc::evmac-section-generated (xdoc::evmac-subsection "Constant" (xdoc::p "ATC generates an event") (xdoc::codeblock "(defconst *program* ...)") (xdoc::p "where @('...') is the abstract syntax tree of the generated C files, which ATC also pretty-prints and writes to the path(s) specified by the @(':output-dir') and @(':file-name') inputs.") (xdoc::p "If the @(':proofs') input is @('nil'), this constant is not generated.")) (xdoc::evmac-subsection "Theorems" (xdoc::p "ATC generates an event") (xdoc::codeblock "(defthm *program*-well-formed ...)") (xdoc::p "where @('...') is an assertion about @('*program*') stating that the generated (abstract syntax tree of the) files is statically well-formed, i.e. it compiles according to [C].") (xdoc::p "If the @(':proofs') input is @('nil'), this theorem is not generated.") (xdoc::p "For each target function @('fn'), ATC generates an event") (xdoc::codeblock "(defthm *program*-fn-correct ...)") (xdoc::p "where @('...') is an assertion about @('fn') and @('*program*') stating that, under the guard of @('fn'), executing the C dynamic semantics on the C function generated from @('fn') yields the same result as the function @('fn'). That is, the C function is functionally equivalent to the ACL2 function.") (xdoc::p "If the ACL2 function takes arrays or pointers to structures as inputs, the generated correctness theorem includes hypotheses saying that the arrays and structures are all at different addresses. The formal model of C that the proofs rely on assumes that arrays and structures do not overlap. Thus, the guarantees provided by the generated theorems about the C code hold only if pointers to distinct, non-overlapping arrays and structures are passed to the generated C functions.") (xdoc::p "If the @(':proofs') input is @('nil'), this theorem is not generated."))) (xdoc::evmac-section "Generated C Code" (xdoc::p "ATC generates a single source file, optionally accompanied by a header, as explained in Section `Representation of C Code in ACL2'.") (xdoc::p "The guard verification requirement stated earlier for each function implies that the generated C operations never exhibit undefined behavior, provided that they are called with values whose ACL2 counterparts satisfy the guard of the function.") (xdoc::evmac-subsection "Compiling and Running the C Code" (xdoc::p "The generated C code can be compiled and run as any other C code. For instance, one can use @('gcc') on macOS or Linux.") (xdoc::p "As mention in the description of the @(':header') input above, if a header is generated, external code should include the header, and the generated source file should be compiled and linked with the external code to obtain a full application. To test the generated code, one can write a separate source file with a @('main') function, and compile all files together. By default, an executable @('a.out') is generated (if using @('gcc') on macOS or Linux).") (xdoc::p "The community books directory @('kestrel/c/atc/tests') contains some examples of C code generation and handwritten C code to test the generated code."))) (xdoc::evmac-section "Redundancy" (xdoc::p "A call of ATC is redundant if and only if it is identical to a previous successful call of ATC."))))
b64b65da14286430a17ad82b00fed8da6f73ca4b13582ad56b1d7aca2655c93e
gvolpe/haskell-book-exercises
cipherspecs.hs
module CipherSpecs where import Test.QuickCheck import VigenereCipher (encode, decode) TODO : It does not work for " a\NAK " find out why vigenereSpec :: String -> Bool vigenereSpec x = x == (decode (encode x)) cipherSpec :: IO () cipherSpec = do quickCheck vigenereSpec
null
https://raw.githubusercontent.com/gvolpe/haskell-book-exercises/5c1b9d8dc729ee5a90c8709b9c889cbacb30a2cb/chapter14/wordnumber/tests/cipherspecs.hs
haskell
module CipherSpecs where import Test.QuickCheck import VigenereCipher (encode, decode) TODO : It does not work for " a\NAK " find out why vigenereSpec :: String -> Bool vigenereSpec x = x == (decode (encode x)) cipherSpec :: IO () cipherSpec = do quickCheck vigenereSpec
5aa3429c8912f433505b509950d7cf33c150627f402e459414ff5a0a79f40e02
nikita-volkov/rerebase
NonEmpty.hs
module Data.List.NonEmpty ( module Rebase.Data.List.NonEmpty ) where import Rebase.Data.List.NonEmpty
null
https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/List/NonEmpty.hs
haskell
module Data.List.NonEmpty ( module Rebase.Data.List.NonEmpty ) where import Rebase.Data.List.NonEmpty
131badc4169743e6649e218c55bc62dbb37470ab094eaae32e42438670665780
moby/vpnkit
fs9p.ml
open Lwt.Infix open Fs9p_error.Infix module P = Protocol_9p let src = Logs.Src.create "fs9p" ~doc:"VFS to 9p" module Log = (val Logs.src_log src : Logs.LOG) let pp_fid = let str x = P.Types.Fid.sexp_of_t x |> Sexplib.Sexp.to_string in Fmt.of_to_string str type 'a or_err = 'a Protocol_9p.Error.t Lwt.t let ok x = Lwt.return (Ok x) let map_error x = Fs9p_error.map_error x let error fmt = Fmt.kstr (fun s -> Lwt.return (Fs9p_error.error "%s" s)) fmt let err_not_a_dir name = error "%S is not a directory" name let err_can't_set_length_of_dir = error "Can't set length of a directory" let err_can't_walk_from_file = error "Can't walk from a file" let err_can't_seek_dir = error "Can't seek in a directory" let err_unknown_fid fid = error "Unknown fid %a" pp_fid fid let err_fid_in_use fid = error "Fid %a already in use" pp_fid fid let err_dot = error "'.' is not valid in 9p" let err_read_not_open = error "Can't read from unopened fid" let err_already_open = error "Already open" let err_create_open = error "Can't create in an opened fid" let err_write_not_open = error "Can't write to unopened fid" let err_write_dir = error "Can't write to directories" let err_rename_root = error "Can't rename /" let err_multiple_updates = error "Can't rename/truncate/chmod at the same time" let max_chunk_size = Int32.of_int (100 * 1024) module type S = sig type flow val accept : root:Vfs.Dir.t -> msg:string -> flow -> unit or_err end 9p inodes : wrap VFS inodes with . module Inode = struct include Vfs.Inode All you can do with an open dir is list it type open_dir = { offset : int64; unread : t list } let _pp_open_dir ppf t = Fmt.pf ppf "offset:%Ld unread:[%a]" t.offset Fmt.(list pp) t.unread let offset t = t.offset let unread t = t.unread type fd = [ `OpenFile of Vfs.File.fd | `OpenDir of open_dir ] let qid t = match kind t with | `File _ -> P.Types.Qid.file ~id:(ino t) ~version:0l () | `Dir _ -> P.Types.Qid.dir ~id:(ino t) ~version:0l () end 9p operations . module Op9p = struct let rwx = [ `Read; `Write; `Execute ] let rw = [ `Read; `Write ] let rx = [ `Read; `Execute ] let r = [ `Read ] let stat ~info inode = let ext ?extension () = (* Note: we always need an extension for the Unix protocol, or mortdeus will crash *) if info.P.Info.version <> P.Types.Version.unix then None else Some (P.Types.Stat.make_extension ?extension ~n_uid:0l ~n_gid:0l ~n_muid:0l ()) in ( match Inode.kind inode with | `Dir _ -> let dir = P.Types.FileMode.make ~owner:rwx ~group:rwx ~other:rx ~is_directory:true () in ok (0L, dir, ext ()) | `File f -> Vfs.File.stat f >>= map_error >>*= fun info -> let file, u = match info.Vfs.perm with | `Normal -> (P.Types.FileMode.make ~owner:rw ~group:rw ~other:r (), ext ()) | `Exec -> (P.Types.FileMode.make ~owner:rwx ~group:rwx ~other:rx (), ext ()) | `Link target -> let u = ext ~extension:target () in ( P.Types.FileMode.make ~is_symlink:true ~owner:rwx ~group:rwx ~other:rx (), u ) in ok (info.Vfs.length, file, u) ) >>*= fun (length, mode, u) -> let qid = Inode.qid inode in let name = Inode.basename inode in ok (P.Types.Stat.make ~qid ~mode ~length ~name ?u ()) let rename dir inode new_name = match Inode.kind dir with | `File _ -> assert false | `Dir d -> Vfs.Dir.rename d inode new_name >>= map_error >>*= fun () -> Inode.set_basename inode new_name; ok () let truncate inode length = match Inode.kind inode with | `Dir _ when length = 0L -> ok () | `Dir _ -> err_can't_set_length_of_dir | `File f -> Vfs.File.truncate f length >>= map_error let mode_of_9p m ext = if m.P.Types.FileMode.is_directory then Ok `Dir else if m.P.Types.FileMode.is_symlink then match ext with | Some target -> Ok (`Link target) | None -> Fs9p_error.error "Missing target for symlink!" else if List.mem `Execute m.P.Types.FileMode.owner then Ok `Exec else Ok `Normal let chmod inode mode extension = Lwt.return (mode_of_9p mode extension) >>*= fun perm -> match (Inode.kind inode, perm) with | `Dir _, `Dir -> Lwt.return Vfs.Error.perm >>= map_error | `File f, (#Vfs.perm as perm) -> Vfs.File.chmod f perm >>= map_error | _ -> error "Incorrect is_directory flag for chmod" let read inode = match Inode.kind inode with | `File file -> Vfs.File.open_ file >>= map_error >>*= fun o -> ok (`OpenFile o) | `Dir dir -> Vfs.Dir.ls dir >>= map_error >>*= fun items -> ok (`OpenDir { Inode.offset = 0L; unread = items }) let read_dir ~info ~offset ~count state = if offset <> Inode.offset state then err_can't_seek_dir TODO : allow 0 to restart else let buffer = Cstruct.create count in let rec aux buf = function | [] -> ok (buf, []) (* Done *) | x :: xs as items -> ( stat ~info x >>*= fun x_info -> match P.Types.Stat.write x_info buf with | Ok buf -> aux buf xs | Error _ -> ok (buf, items) ) (* No more room *) in aux buffer (Inode.unread state) >>*= fun (unused, remaining) -> let data = Cstruct.sub buffer 0 (count - Cstruct.length unused) in let len = Cstruct.length data in (* Linux will abort if we return an error. Instead, just return 0 items. Linux will free up space in its buffer and try again. *) (* if len = 0 && remaining <> [] then err_buffer_too_small *) let offset = Int64.add (Inode.offset state) (Int64.of_int len) in let new_state = { Inode.offset; unread = remaining } in ok (new_state, data) let create ~parent ~perm ~extension name = match Inode.kind parent with | `Dir d -> (Lwt.return (mode_of_9p perm extension) >>*= function | `Dir -> Vfs.Dir.mkdir d name >>= map_error | #Vfs.perm as perm -> Vfs.Dir.mkfile d ~perm name >>= map_error) >>*= fun inode -> read inode >>*= fun open_file -> ok (inode, open_file) | `File _ -> err_not_a_dir (Inode.basename parent) let remove inode = match Inode.kind inode with | `File f -> Vfs.File.remove f >>= map_error | `Dir d -> Vfs.Dir.remove d >>= map_error end module Make (Flow : Mirage_flow.S) = struct type flow = Flow.flow (** Handle incoming requests from the client. *) module Dispatcher = struct type fd = { inode : Inode.t; parents : Inode.t list; closest first mutable state : [ `Ready | Inode.fd ]; } type t = Vfs.Dir.t (* The root directory *) type connection = { root : t; info : Protocol_9p.Info.t; mutable fds : fd P.Types.Fid.Map.t; } let connect root info = let fds = P.Types.Fid.Map.empty in { root; info; fds } let lookup connection fid = try ok (P.Types.Fid.Map.find fid connection.fds) with Not_found -> err_unknown_fid fid let alloc_fid ?may_reuse connection newfid fd = let alloc () = connection.fds <- P.Types.Fid.Map.add newfid fd connection.fds; ok () in match may_reuse with | Some old when old = newfid -> alloc () | Some _ | None -> if P.Types.Fid.Map.mem newfid connection.fds then err_fid_in_use newfid else alloc () (* Returns the final inode, the path that led to it, and the new parents. *) let rec do_walk ~parents ~wqids inode = function | [] -> ok (inode, List.rev wqids, parents) | x :: xs -> ( match Inode.kind inode with | `File _ -> err_can't_walk_from_file | `Dir dir -> ( match x with | "." -> err_dot | ".." -> ( match parents with | [] -> ok (inode, parents) (* /.. = / *) | p :: ps -> ok (p, ps) ) | x -> Vfs.Dir.lookup dir x >>= map_error >>*= fun x_inode -> ok (x_inode, inode :: parents) ) >>*= fun (inode, parents) -> let wqids = Inode.qid inode :: wqids in do_walk ~parents ~wqids inode xs ) let walk connection ~cancel:_ { P.Request.Walk.fid; newfid; wnames } = lookup connection fid >>*= fun fd -> do_walk ~parents:fd.parents ~wqids:[] fd.inode wnames >>*= fun (inode, wqids, parents) -> let fd = { inode; parents; state = `Ready } in alloc_fid ~may_reuse:fid connection newfid fd >>*= fun () -> ok { P.Response.Walk.wqids } let attach connection ~cancel:_ { P.Request.Attach.fid; _ } = let fd = { inode = Inode.dir "/" connection.root; parents = []; state = `Ready } in alloc_fid connection fid fd >>*= fun () -> ok { P.Response.Attach.qid = Inode.qid fd.inode } let clunk_fid connection fid = connection.fds <- P.Types.Fid.Map.remove fid connection.fds let clunk connection ~cancel:_ { P.Request.Clunk.fid } = let old = connection.fds in clunk_fid connection fid; if connection.fds == old then error "Unknown fid %a" pp_fid fid else ok () let stat connection ~cancel:_ { P.Request.Stat.fid } = lookup connection fid >>*= fun fd -> Op9p.stat ~info:connection.info fd.inode >>*= fun stat -> ok { P.Response.Stat.stat } let read connection ~cancel:_ { P.Request.Read.fid; offset; count } = let count = Int32.to_int (min count max_chunk_size) in lookup connection fid >>*= fun fd -> match fd.state with | `Ready -> err_read_not_open | `OpenFile file -> Vfs.File.read file ~offset ~count >>= map_error >>*= fun data -> ok { P.Response.Read.data } | `OpenDir d -> Op9p.read_dir ~info:connection.info ~offset ~count d >>*= fun (new_state, data) -> fd.state <- `OpenDir new_state; ok { P.Response.Read.data } let open_ connection ~cancel:_ { P.Request.Open.fid; _ } = lookup connection fid >>*= fun fd -> match fd.state with | `OpenDir _ | `OpenFile _ -> err_already_open | `Ready -> Op9p.read fd.inode >>*= fun state -> fd.state <- state; ok { P.Response.Open.qid = Inode.qid fd.inode; iounit = 0l } let create connection ~cancel:_ { P.Request.Create.fid; perm; name; extension; _ } = lookup connection fid >>*= fun fd -> if fd.state <> `Ready then err_create_open else Op9p.create ~parent:fd.inode ~perm ~extension name >>*= fun (inode, open_file) -> let fd = { inode; parents = fd.inode :: fd.parents; state = open_file } in connection.fds <- P.Types.Fid.Map.add fid fd connection.fds; ok { P.Response.Create.qid = Inode.qid inode; iounit = 0l } let write connection ~cancel:_ { P.Request.Write.fid; offset; data } = lookup connection fid >>*= fun fd -> match fd.state with | `Ready -> err_write_not_open | `OpenDir _ -> err_write_dir | `OpenFile file -> Vfs.File.write file ~offset data >>= map_error >>*= fun () -> let count = Int32.of_int (Cstruct.length data) in ok { P.Response.Write.count } let remove connection ~cancel:_ { P.Request.Remove.fid } = lookup connection fid >>*= fun fd -> Op9p.remove fd.inode >|= fun err -> clunk_fid connection fid; err let rename fd name = match fd.parents with | [] -> err_rename_root | p :: _ -> Op9p.rename p fd.inode name let get_ext = function | None -> None | Some ext -> Some ext.P.Types.Stat.extension let wstat connection ~cancel:_ { P.Request.Wstat.fid; stat } = lookup connection fid >>*= fun fd -> let { P.Types.Stat.name; length; mtime; gid; mode; u; _ } = stat in (* It's illegal to set [ty], [dev], [qid], [atime], [uid], [muid] and [u], but checking if we're setting to the current value is tedious, so ignore: *) ignore mtime; Linux needs to set mtime ignore gid; (* We don't care about permissions *) let name = if name = "" then None else Some name in let length = if P.Types.Int64.is_any length then None else Some length in let mode = if P.Types.FileMode.is_any mode then None else Some mode in match (name, length, mode) with | Some n, None, None -> rename fd n | None, Some l, None -> Op9p.truncate fd.inode l | None, None, Some m -> Op9p.chmod fd.inode m (get_ext u) | None, None, None -> ok () | _ -> (* Hard to support atomically, and unlikely to be useful. *) err_multiple_updates end module Server = P.Server.Make (Log) (Flow) (Dispatcher) let accept ~root ~msg flow = Log.info (fun l -> l "accepted a new connection on %s" msg); Server.connect root flow () >>= function | Error _ as e -> Flow.close flow >|= fun () -> e | Ok t -> Close the flow when the 9P connection shuts down Server.after_disconnect t >>= fun () -> Flow.close flow >>= fun () -> ok () end
null
https://raw.githubusercontent.com/moby/vpnkit/eb9ba90261fcfe167888d209339d4d8fb0985243/src/fs9p/fs9p.ml
ocaml
Note: we always need an extension for the Unix protocol, or mortdeus will crash Done No more room Linux will abort if we return an error. Instead, just return 0 items. Linux will free up space in its buffer and try again. if len = 0 && remaining <> [] then err_buffer_too_small * Handle incoming requests from the client. The root directory Returns the final inode, the path that led to it, and the new parents. /.. = / It's illegal to set [ty], [dev], [qid], [atime], [uid], [muid] and [u], but checking if we're setting to the current value is tedious, so ignore: We don't care about permissions Hard to support atomically, and unlikely to be useful.
open Lwt.Infix open Fs9p_error.Infix module P = Protocol_9p let src = Logs.Src.create "fs9p" ~doc:"VFS to 9p" module Log = (val Logs.src_log src : Logs.LOG) let pp_fid = let str x = P.Types.Fid.sexp_of_t x |> Sexplib.Sexp.to_string in Fmt.of_to_string str type 'a or_err = 'a Protocol_9p.Error.t Lwt.t let ok x = Lwt.return (Ok x) let map_error x = Fs9p_error.map_error x let error fmt = Fmt.kstr (fun s -> Lwt.return (Fs9p_error.error "%s" s)) fmt let err_not_a_dir name = error "%S is not a directory" name let err_can't_set_length_of_dir = error "Can't set length of a directory" let err_can't_walk_from_file = error "Can't walk from a file" let err_can't_seek_dir = error "Can't seek in a directory" let err_unknown_fid fid = error "Unknown fid %a" pp_fid fid let err_fid_in_use fid = error "Fid %a already in use" pp_fid fid let err_dot = error "'.' is not valid in 9p" let err_read_not_open = error "Can't read from unopened fid" let err_already_open = error "Already open" let err_create_open = error "Can't create in an opened fid" let err_write_not_open = error "Can't write to unopened fid" let err_write_dir = error "Can't write to directories" let err_rename_root = error "Can't rename /" let err_multiple_updates = error "Can't rename/truncate/chmod at the same time" let max_chunk_size = Int32.of_int (100 * 1024) module type S = sig type flow val accept : root:Vfs.Dir.t -> msg:string -> flow -> unit or_err end 9p inodes : wrap VFS inodes with . module Inode = struct include Vfs.Inode All you can do with an open dir is list it type open_dir = { offset : int64; unread : t list } let _pp_open_dir ppf t = Fmt.pf ppf "offset:%Ld unread:[%a]" t.offset Fmt.(list pp) t.unread let offset t = t.offset let unread t = t.unread type fd = [ `OpenFile of Vfs.File.fd | `OpenDir of open_dir ] let qid t = match kind t with | `File _ -> P.Types.Qid.file ~id:(ino t) ~version:0l () | `Dir _ -> P.Types.Qid.dir ~id:(ino t) ~version:0l () end 9p operations . module Op9p = struct let rwx = [ `Read; `Write; `Execute ] let rw = [ `Read; `Write ] let rx = [ `Read; `Execute ] let r = [ `Read ] let stat ~info inode = let ext ?extension () = if info.P.Info.version <> P.Types.Version.unix then None else Some (P.Types.Stat.make_extension ?extension ~n_uid:0l ~n_gid:0l ~n_muid:0l ()) in ( match Inode.kind inode with | `Dir _ -> let dir = P.Types.FileMode.make ~owner:rwx ~group:rwx ~other:rx ~is_directory:true () in ok (0L, dir, ext ()) | `File f -> Vfs.File.stat f >>= map_error >>*= fun info -> let file, u = match info.Vfs.perm with | `Normal -> (P.Types.FileMode.make ~owner:rw ~group:rw ~other:r (), ext ()) | `Exec -> (P.Types.FileMode.make ~owner:rwx ~group:rwx ~other:rx (), ext ()) | `Link target -> let u = ext ~extension:target () in ( P.Types.FileMode.make ~is_symlink:true ~owner:rwx ~group:rwx ~other:rx (), u ) in ok (info.Vfs.length, file, u) ) >>*= fun (length, mode, u) -> let qid = Inode.qid inode in let name = Inode.basename inode in ok (P.Types.Stat.make ~qid ~mode ~length ~name ?u ()) let rename dir inode new_name = match Inode.kind dir with | `File _ -> assert false | `Dir d -> Vfs.Dir.rename d inode new_name >>= map_error >>*= fun () -> Inode.set_basename inode new_name; ok () let truncate inode length = match Inode.kind inode with | `Dir _ when length = 0L -> ok () | `Dir _ -> err_can't_set_length_of_dir | `File f -> Vfs.File.truncate f length >>= map_error let mode_of_9p m ext = if m.P.Types.FileMode.is_directory then Ok `Dir else if m.P.Types.FileMode.is_symlink then match ext with | Some target -> Ok (`Link target) | None -> Fs9p_error.error "Missing target for symlink!" else if List.mem `Execute m.P.Types.FileMode.owner then Ok `Exec else Ok `Normal let chmod inode mode extension = Lwt.return (mode_of_9p mode extension) >>*= fun perm -> match (Inode.kind inode, perm) with | `Dir _, `Dir -> Lwt.return Vfs.Error.perm >>= map_error | `File f, (#Vfs.perm as perm) -> Vfs.File.chmod f perm >>= map_error | _ -> error "Incorrect is_directory flag for chmod" let read inode = match Inode.kind inode with | `File file -> Vfs.File.open_ file >>= map_error >>*= fun o -> ok (`OpenFile o) | `Dir dir -> Vfs.Dir.ls dir >>= map_error >>*= fun items -> ok (`OpenDir { Inode.offset = 0L; unread = items }) let read_dir ~info ~offset ~count state = if offset <> Inode.offset state then err_can't_seek_dir TODO : allow 0 to restart else let buffer = Cstruct.create count in let rec aux buf = function | x :: xs as items -> ( stat ~info x >>*= fun x_info -> match P.Types.Stat.write x_info buf with | Ok buf -> aux buf xs | Error _ -> ok (buf, items) ) in aux buffer (Inode.unread state) >>*= fun (unused, remaining) -> let data = Cstruct.sub buffer 0 (count - Cstruct.length unused) in let len = Cstruct.length data in let offset = Int64.add (Inode.offset state) (Int64.of_int len) in let new_state = { Inode.offset; unread = remaining } in ok (new_state, data) let create ~parent ~perm ~extension name = match Inode.kind parent with | `Dir d -> (Lwt.return (mode_of_9p perm extension) >>*= function | `Dir -> Vfs.Dir.mkdir d name >>= map_error | #Vfs.perm as perm -> Vfs.Dir.mkfile d ~perm name >>= map_error) >>*= fun inode -> read inode >>*= fun open_file -> ok (inode, open_file) | `File _ -> err_not_a_dir (Inode.basename parent) let remove inode = match Inode.kind inode with | `File f -> Vfs.File.remove f >>= map_error | `Dir d -> Vfs.Dir.remove d >>= map_error end module Make (Flow : Mirage_flow.S) = struct type flow = Flow.flow module Dispatcher = struct type fd = { inode : Inode.t; parents : Inode.t list; closest first mutable state : [ `Ready | Inode.fd ]; } type connection = { root : t; info : Protocol_9p.Info.t; mutable fds : fd P.Types.Fid.Map.t; } let connect root info = let fds = P.Types.Fid.Map.empty in { root; info; fds } let lookup connection fid = try ok (P.Types.Fid.Map.find fid connection.fds) with Not_found -> err_unknown_fid fid let alloc_fid ?may_reuse connection newfid fd = let alloc () = connection.fds <- P.Types.Fid.Map.add newfid fd connection.fds; ok () in match may_reuse with | Some old when old = newfid -> alloc () | Some _ | None -> if P.Types.Fid.Map.mem newfid connection.fds then err_fid_in_use newfid else alloc () let rec do_walk ~parents ~wqids inode = function | [] -> ok (inode, List.rev wqids, parents) | x :: xs -> ( match Inode.kind inode with | `File _ -> err_can't_walk_from_file | `Dir dir -> ( match x with | "." -> err_dot | ".." -> ( match parents with | p :: ps -> ok (p, ps) ) | x -> Vfs.Dir.lookup dir x >>= map_error >>*= fun x_inode -> ok (x_inode, inode :: parents) ) >>*= fun (inode, parents) -> let wqids = Inode.qid inode :: wqids in do_walk ~parents ~wqids inode xs ) let walk connection ~cancel:_ { P.Request.Walk.fid; newfid; wnames } = lookup connection fid >>*= fun fd -> do_walk ~parents:fd.parents ~wqids:[] fd.inode wnames >>*= fun (inode, wqids, parents) -> let fd = { inode; parents; state = `Ready } in alloc_fid ~may_reuse:fid connection newfid fd >>*= fun () -> ok { P.Response.Walk.wqids } let attach connection ~cancel:_ { P.Request.Attach.fid; _ } = let fd = { inode = Inode.dir "/" connection.root; parents = []; state = `Ready } in alloc_fid connection fid fd >>*= fun () -> ok { P.Response.Attach.qid = Inode.qid fd.inode } let clunk_fid connection fid = connection.fds <- P.Types.Fid.Map.remove fid connection.fds let clunk connection ~cancel:_ { P.Request.Clunk.fid } = let old = connection.fds in clunk_fid connection fid; if connection.fds == old then error "Unknown fid %a" pp_fid fid else ok () let stat connection ~cancel:_ { P.Request.Stat.fid } = lookup connection fid >>*= fun fd -> Op9p.stat ~info:connection.info fd.inode >>*= fun stat -> ok { P.Response.Stat.stat } let read connection ~cancel:_ { P.Request.Read.fid; offset; count } = let count = Int32.to_int (min count max_chunk_size) in lookup connection fid >>*= fun fd -> match fd.state with | `Ready -> err_read_not_open | `OpenFile file -> Vfs.File.read file ~offset ~count >>= map_error >>*= fun data -> ok { P.Response.Read.data } | `OpenDir d -> Op9p.read_dir ~info:connection.info ~offset ~count d >>*= fun (new_state, data) -> fd.state <- `OpenDir new_state; ok { P.Response.Read.data } let open_ connection ~cancel:_ { P.Request.Open.fid; _ } = lookup connection fid >>*= fun fd -> match fd.state with | `OpenDir _ | `OpenFile _ -> err_already_open | `Ready -> Op9p.read fd.inode >>*= fun state -> fd.state <- state; ok { P.Response.Open.qid = Inode.qid fd.inode; iounit = 0l } let create connection ~cancel:_ { P.Request.Create.fid; perm; name; extension; _ } = lookup connection fid >>*= fun fd -> if fd.state <> `Ready then err_create_open else Op9p.create ~parent:fd.inode ~perm ~extension name >>*= fun (inode, open_file) -> let fd = { inode; parents = fd.inode :: fd.parents; state = open_file } in connection.fds <- P.Types.Fid.Map.add fid fd connection.fds; ok { P.Response.Create.qid = Inode.qid inode; iounit = 0l } let write connection ~cancel:_ { P.Request.Write.fid; offset; data } = lookup connection fid >>*= fun fd -> match fd.state with | `Ready -> err_write_not_open | `OpenDir _ -> err_write_dir | `OpenFile file -> Vfs.File.write file ~offset data >>= map_error >>*= fun () -> let count = Int32.of_int (Cstruct.length data) in ok { P.Response.Write.count } let remove connection ~cancel:_ { P.Request.Remove.fid } = lookup connection fid >>*= fun fd -> Op9p.remove fd.inode >|= fun err -> clunk_fid connection fid; err let rename fd name = match fd.parents with | [] -> err_rename_root | p :: _ -> Op9p.rename p fd.inode name let get_ext = function | None -> None | Some ext -> Some ext.P.Types.Stat.extension let wstat connection ~cancel:_ { P.Request.Wstat.fid; stat } = lookup connection fid >>*= fun fd -> let { P.Types.Stat.name; length; mtime; gid; mode; u; _ } = stat in ignore mtime; Linux needs to set mtime ignore gid; let name = if name = "" then None else Some name in let length = if P.Types.Int64.is_any length then None else Some length in let mode = if P.Types.FileMode.is_any mode then None else Some mode in match (name, length, mode) with | Some n, None, None -> rename fd n | None, Some l, None -> Op9p.truncate fd.inode l | None, None, Some m -> Op9p.chmod fd.inode m (get_ext u) | None, None, None -> ok () | _ -> err_multiple_updates end module Server = P.Server.Make (Log) (Flow) (Dispatcher) let accept ~root ~msg flow = Log.info (fun l -> l "accepted a new connection on %s" msg); Server.connect root flow () >>= function | Error _ as e -> Flow.close flow >|= fun () -> e | Ok t -> Close the flow when the 9P connection shuts down Server.after_disconnect t >>= fun () -> Flow.close flow >>= fun () -> ok () end
9af1f106eb1b02f203fd154c0499bf672672fd52e4dbe37c06088ebb4dadee3d
spell-music/temporal-music-notation
Scales.hs
-- | Specific scales. Scale constructor makes scale that starts -- at the given frequency. module Temporal.Music.Scales ( -- * just scales ji3, ji5, ji7, pyth, hindGb, hindFs, justBP, partchean, luScale, superJust, harmonicJust, sruti, -- * Irregular scales eqt, eqts, eqBP, hind, -- * Subscales | extracting 5 - tone scales out of 12 - tone scales minor5, major5, bluesMinor5, bluesMajor5, egyptian5, | extracting 7 - tone scales out of 12 - tone scales major, minor, ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian) where import Temporal.Music.Pitch(Hz, Interval, Scale(..), scaleLength, fromIntervals) import qualified Data.Vector as V sliceScale :: Int -> [Int] -> Scale -> Scale sliceScale octaveLength ids x | octaveLength == (V.length $ scaleSteps x) = Scale (scaleBase x) (scaleOctave x) $ V.fromList $ map (scaleSteps x V.! ) ids | otherwise = error ("scale must have " ++ show octaveLength ++ " tones in octave") --------------------------------------------------- 12 - tone modes 5 tone minor5 = slice12 minor5Is major5 = slice12 major5Is egyptian5 = slice12 egyptian5Is bluesMinor5 = slice12 bluesMinor5Is bluesMajor5 = slice12 bluesMajor5Is major5Is = pentaIs egyptian5Is = rot 1 $ pentaIs bluesMinor5Is = rot 2 $ pentaIs bluesMajor5Is = rot 3 $ pentaIs minor5Is = rot 4 $ pentaIs pentaIs = [2, 2, 3, 2, 2] 7 tone major, minor, ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian :: Scale -> Scale major = slice12 majorIs minor = slice12 minorIs ionian = slice12 ionianIs dorian = slice12 dorianIs phrygian = slice12 phrygianIs lydian = slice12 lydianIs mixolydian = slice12 mixolydianIs aeolian = slice12 aeolianIs locrian = slice12 locrianIs majorIs = [2, 2, 1, 2, 2, 2, 1] minorIs = aeolianIs ionianIs = rot 0 majorIs dorianIs = rot 1 majorIs phrygianIs = rot 2 majorIs lydianIs = rot 3 majorIs mixolydianIs = rot 4 majorIs aeolianIs = rot 5 majorIs locrianIs = rot 7 majorIs slice12 :: [Int] -> (Scale -> Scale) slice12 ids = sliceScale 12 (fromIs ids) fromIs = (0:) . fst . foldl f ([], 0) . init where f (res, i) x = (res ++ [i + x], i + x) rot :: Int -> [a] -> [a] rot n xs = drop n xs ++ take n xs --------------------------------------------------- -- equal temperament -- | 12 tone equal temperament scale eqt :: Hz -> Scale eqt = fromIntervals 2 (map ((2 **) . (/12)) [0 .. 11]) -- | general equal temperament scale eqts :: Hz -> Scale eqts = res where n = scaleLength $ res 0 res = fromIntervals 2 $ (map ((2 **) . (/fromIntegral n) . fromIntegral) [0 .. n-1]) | hindemithean scale with mean of fs and for tritone hind :: Hz -> Scale hind = hindemitheanGen $ 0.5 * (ji5 (-1, 2, 1) + ji5 (2, -2, -1)) | equal Bohlen - Pierce scale eqBP :: Hz -> Scale eqBP = fromIntervals 3 (map ((3 **) . (/13) . fromIntegral) [0 .. 12]) --------------------------------------------------- -- | pythagorean scale pyth :: Hz -> Scale pyth = fromIntervals 2 $ map toPyth -- 0 1 2 3 4 5 [(0, 0), (-5, 3), (2, -1), (-3, 2), (4, -2), (-1, 1), 6 7 8 9 10 11 (-6, 4), (1, 0), (-4, 3), (3, -1), (-2, 2), (5, -2)] toPyth :: (Int, Int) -> Interval toPyth (a, b) = ji3 (b, a) | 3 - limit basis @(2 , 3\/2)@ ji3 :: (Int, Int) -> Interval ji3 (a, b) = (2 ^^ a) * (1.5 ^^ b) -------------------------------------------------------- -- Just intonation 5 - limit -- | 5 - limit basis @(2 , 3\/2 , 5\/4)@ ji5 :: (Int, Int, Int) -> Interval ji5 (a, b, c) = (2 ^^ a) * (1.5 ^^ b) * (1.25 ^^ c) -- | hindemithean scale with fs for tritone hindFs :: Hz -> Scale hindFs = hindemitheanGen $ ji5 (-1, 2, 1) | hindemithean scale with gb for tritone hindGb :: Hz -> Scale hindGb = hindemitheanGen $ ji5 (2, -2, -1) hindemitheanGen :: Interval -> Hz -> Scale hindemitheanGen tritone = fromIntervals 2 $ map ji5 0 1 , 2 , 3 , 4 , 5 [(0, 0, 0), (1, -1, -1), (-1, 2, 0), (0, 1, -1), (0, 0, 1), (1, -1, 0)] 6 ++ [tritone] ++ map ji5 7 8 , 9 , 10 , [(0, 1, 0), (1, 0, -1), (1, -1, 1), (2, -2, 0), (0, 1, 1)] 7 - limit | 7 - limit basis @(2 , 3\/2 , 5\/4 , 7\/6)@ ji7 :: (Int, Int, Int, Int) -> Interval ji7 (a, b, c, d) = (2 ^^ a) * (1.5 ^^ b) * (1.25 ^^ c) * ((7/6) ^^ d) | just Bohlen - Pierce scale justBP :: Hz -> Scale justBP = fromIntervals 3 0 1 , 2 , 3 , [1, 27/25, 25/21, 9/7, 4 , 5 , 6 , 7 7/5, 75/49, 5/3, 9/5, 8 , 9 , 10 , 11 49/25, 15/7, 7/3, 63/25, 12 25/9] | 43 - tone scale partchean :: Hz -> Scale partchean = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 81/80, 33/32, 21/20, 16/15, 5 , 6 , 7 , 8 , 9 , 12/11, 11/10, 10/9, 9/8, 8/7, 10 , 11 , 12 , 13 , 14 7/6, 32/27, 6/5, 11/9, 5/4, 15 , 16 , 17 , 18 , 19 , 14/11, 9/7, 21/16, 4/3, 27/20, 20 , 21 , 22 , 23 , 24 , 11/8, 7/5, 10/7, 16/11, 40/27, 25 , 26 , 27 , 28 , 29 , 3/2, 32/21, 14/9, 11/7, 8/5, 30 , 31 , 32 , 33 , 34 , 18/11, 5/3, 27/16, 12/7, 7/4, 35 , 36 , 37 , 38 , 39 , 16/9, 9/5, 20/11, 11/6, 15/8, 40 , 41 , 42 , 40/21, 64/33, 160/81] | Chinese Lu 12 - tone scale luScale :: Hz -> Scale luScale = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 18/17, 9/8, 6/5, 54/43, 5 , 6 , 7 , 8 , 9 , 4/3, 27/19, 3/2, 27/17, 27/16, 10 , 11 , 12 , 13 , 14 9/5, 36/19] | super just 12 - tone scale superJust :: Hz -> Scale superJust = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 17/16, 9/8, 6/5, 5/4, 5 , 6 , 7 , 8 , 9 , 4/3, 11/8, 3/2, 13/8, 5/3, 10 , 11 , 12 , 13 , 14 7/4, 15/8] | harmonic 12 - tone scale harmonicJust :: Hz -> Scale harmonicJust = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 17/16, 9/8, 19/16, 5/4, 5 , 6 , 7 , 8 , 9 , 21/16, 11/8, 3/2, 13/8, 27/16, 10 , 11 , 12 , 13 , 14 7/4, 15/8] | Indian Sruti 22 - tone scale sruti :: Hz -> Scale sruti = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 256/243, 16/15, 10/9, 9/8, 5 , 6 , 7 , 8 , 9 , 32/27, 6/5, 5/4, 81/64, 4/3, 10 , 11 , 12 , 13 , 14 , 27/20, 45/32, 729/512, 3/2, 128/81, 15 , 16 , 17 , 18 , 19 , 8/5, 5/3, 27/16, 16/9, 9/5, 20 , 21 , 15/8, 243/128]
null
https://raw.githubusercontent.com/spell-music/temporal-music-notation/48e556e59e08c845aac40ea101266b144eab31c5/src/Temporal/Music/Scales.hs
haskell
| Specific scales. Scale constructor makes scale that starts at the given frequency. * just scales * Irregular scales * Subscales ------------------------------------------------- ------------------------------------------------- equal temperament | 12 tone equal temperament scale | general equal temperament scale ------------------------------------------------- | pythagorean scale 0 1 2 3 4 5 ------------------------------------------------------ Just intonation | hindemithean scale with fs for tritone
module Temporal.Music.Scales ( ji3, ji5, ji7, pyth, hindGb, hindFs, justBP, partchean, luScale, superJust, harmonicJust, sruti, eqt, eqts, eqBP, hind, | extracting 5 - tone scales out of 12 - tone scales minor5, major5, bluesMinor5, bluesMajor5, egyptian5, | extracting 7 - tone scales out of 12 - tone scales major, minor, ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian) where import Temporal.Music.Pitch(Hz, Interval, Scale(..), scaleLength, fromIntervals) import qualified Data.Vector as V sliceScale :: Int -> [Int] -> Scale -> Scale sliceScale octaveLength ids x | octaveLength == (V.length $ scaleSteps x) = Scale (scaleBase x) (scaleOctave x) $ V.fromList $ map (scaleSteps x V.! ) ids | otherwise = error ("scale must have " ++ show octaveLength ++ " tones in octave") 12 - tone modes 5 tone minor5 = slice12 minor5Is major5 = slice12 major5Is egyptian5 = slice12 egyptian5Is bluesMinor5 = slice12 bluesMinor5Is bluesMajor5 = slice12 bluesMajor5Is major5Is = pentaIs egyptian5Is = rot 1 $ pentaIs bluesMinor5Is = rot 2 $ pentaIs bluesMajor5Is = rot 3 $ pentaIs minor5Is = rot 4 $ pentaIs pentaIs = [2, 2, 3, 2, 2] 7 tone major, minor, ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian :: Scale -> Scale major = slice12 majorIs minor = slice12 minorIs ionian = slice12 ionianIs dorian = slice12 dorianIs phrygian = slice12 phrygianIs lydian = slice12 lydianIs mixolydian = slice12 mixolydianIs aeolian = slice12 aeolianIs locrian = slice12 locrianIs majorIs = [2, 2, 1, 2, 2, 2, 1] minorIs = aeolianIs ionianIs = rot 0 majorIs dorianIs = rot 1 majorIs phrygianIs = rot 2 majorIs lydianIs = rot 3 majorIs mixolydianIs = rot 4 majorIs aeolianIs = rot 5 majorIs locrianIs = rot 7 majorIs slice12 :: [Int] -> (Scale -> Scale) slice12 ids = sliceScale 12 (fromIs ids) fromIs = (0:) . fst . foldl f ([], 0) . init where f (res, i) x = (res ++ [i + x], i + x) rot :: Int -> [a] -> [a] rot n xs = drop n xs ++ take n xs eqt :: Hz -> Scale eqt = fromIntervals 2 (map ((2 **) . (/12)) [0 .. 11]) eqts :: Hz -> Scale eqts = res where n = scaleLength $ res 0 res = fromIntervals 2 $ (map ((2 **) . (/fromIntegral n) . fromIntegral) [0 .. n-1]) | hindemithean scale with mean of fs and for tritone hind :: Hz -> Scale hind = hindemitheanGen $ 0.5 * (ji5 (-1, 2, 1) + ji5 (2, -2, -1)) | equal Bohlen - Pierce scale eqBP :: Hz -> Scale eqBP = fromIntervals 3 (map ((3 **) . (/13) . fromIntegral) [0 .. 12]) pyth :: Hz -> Scale pyth = fromIntervals 2 $ map toPyth [(0, 0), (-5, 3), (2, -1), (-3, 2), (4, -2), (-1, 1), 6 7 8 9 10 11 (-6, 4), (1, 0), (-4, 3), (3, -1), (-2, 2), (5, -2)] toPyth :: (Int, Int) -> Interval toPyth (a, b) = ji3 (b, a) | 3 - limit basis @(2 , 3\/2)@ ji3 :: (Int, Int) -> Interval ji3 (a, b) = (2 ^^ a) * (1.5 ^^ b) 5 - limit | 5 - limit basis @(2 , 3\/2 , 5\/4)@ ji5 :: (Int, Int, Int) -> Interval ji5 (a, b, c) = (2 ^^ a) * (1.5 ^^ b) * (1.25 ^^ c) hindFs :: Hz -> Scale hindFs = hindemitheanGen $ ji5 (-1, 2, 1) | hindemithean scale with gb for tritone hindGb :: Hz -> Scale hindGb = hindemitheanGen $ ji5 (2, -2, -1) hindemitheanGen :: Interval -> Hz -> Scale hindemitheanGen tritone = fromIntervals 2 $ map ji5 0 1 , 2 , 3 , 4 , 5 [(0, 0, 0), (1, -1, -1), (-1, 2, 0), (0, 1, -1), (0, 0, 1), (1, -1, 0)] 6 ++ [tritone] ++ map ji5 7 8 , 9 , 10 , [(0, 1, 0), (1, 0, -1), (1, -1, 1), (2, -2, 0), (0, 1, 1)] 7 - limit | 7 - limit basis @(2 , 3\/2 , 5\/4 , 7\/6)@ ji7 :: (Int, Int, Int, Int) -> Interval ji7 (a, b, c, d) = (2 ^^ a) * (1.5 ^^ b) * (1.25 ^^ c) * ((7/6) ^^ d) | just Bohlen - Pierce scale justBP :: Hz -> Scale justBP = fromIntervals 3 0 1 , 2 , 3 , [1, 27/25, 25/21, 9/7, 4 , 5 , 6 , 7 7/5, 75/49, 5/3, 9/5, 8 , 9 , 10 , 11 49/25, 15/7, 7/3, 63/25, 12 25/9] | 43 - tone scale partchean :: Hz -> Scale partchean = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 81/80, 33/32, 21/20, 16/15, 5 , 6 , 7 , 8 , 9 , 12/11, 11/10, 10/9, 9/8, 8/7, 10 , 11 , 12 , 13 , 14 7/6, 32/27, 6/5, 11/9, 5/4, 15 , 16 , 17 , 18 , 19 , 14/11, 9/7, 21/16, 4/3, 27/20, 20 , 21 , 22 , 23 , 24 , 11/8, 7/5, 10/7, 16/11, 40/27, 25 , 26 , 27 , 28 , 29 , 3/2, 32/21, 14/9, 11/7, 8/5, 30 , 31 , 32 , 33 , 34 , 18/11, 5/3, 27/16, 12/7, 7/4, 35 , 36 , 37 , 38 , 39 , 16/9, 9/5, 20/11, 11/6, 15/8, 40 , 41 , 42 , 40/21, 64/33, 160/81] | Chinese Lu 12 - tone scale luScale :: Hz -> Scale luScale = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 18/17, 9/8, 6/5, 54/43, 5 , 6 , 7 , 8 , 9 , 4/3, 27/19, 3/2, 27/17, 27/16, 10 , 11 , 12 , 13 , 14 9/5, 36/19] | super just 12 - tone scale superJust :: Hz -> Scale superJust = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 17/16, 9/8, 6/5, 5/4, 5 , 6 , 7 , 8 , 9 , 4/3, 11/8, 3/2, 13/8, 5/3, 10 , 11 , 12 , 13 , 14 7/4, 15/8] | harmonic 12 - tone scale harmonicJust :: Hz -> Scale harmonicJust = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 17/16, 9/8, 19/16, 5/4, 5 , 6 , 7 , 8 , 9 , 21/16, 11/8, 3/2, 13/8, 27/16, 10 , 11 , 12 , 13 , 14 7/4, 15/8] | Indian Sruti 22 - tone scale sruti :: Hz -> Scale sruti = fromIntervals 2 0 , 1 , 2 , 3 , 4 , [1, 256/243, 16/15, 10/9, 9/8, 5 , 6 , 7 , 8 , 9 , 32/27, 6/5, 5/4, 81/64, 4/3, 10 , 11 , 12 , 13 , 14 , 27/20, 45/32, 729/512, 3/2, 128/81, 15 , 16 , 17 , 18 , 19 , 8/5, 5/3, 27/16, 16/9, 9/5, 20 , 21 , 15/8, 243/128]
54e77f8742a32ff726d76a051087914bbfb4539a8942f8998599903b5191dc5a
ocaml-multicore/tezos
block_locator.mli
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2019 - 2021 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) * A locator [ t ] is a data structure which roughly represents a list of block hashes in the chain . These hashes go from the top of the chain to the bottom . It is sparse in the sense that the distance between two hashes increases exponentially when we move away from the head . The distance between two hashes of a locator is randomized to prevent attacks . The seed is determined uniquely from the [ peer_id ] of the sender and the receiver so that the distance between two hashes can be recomputed locally . This is the purpose of the function [ to_steps ] . The [ step ] representation is mostly used by the [ peer_validator ] and the [ bootstrap_pipeline ] modules . The last step of a locator may be truncated . It is the case when the last step hits the caboose . Thus , such a [ non - strict ] step can be terminated by : - The genesis : it is the case in both [ Archive ] and [ Full ] modes as the caboose is always located down to the genesis block , but it is also the case in a [ Rolling ] mode early state ( when caboose = genesis ) . - Any block : it is the case in [ Rolling ] mode when the caboose is higher than the genesis . Indeed , the caboose can be located ( almost ) anywhere . of block hashes in the chain. These hashes go from the top of the chain to the bottom. It is sparse in the sense that the distance between two hashes increases exponentially when we move away from the head. The distance between two hashes of a locator is randomized to prevent attacks. The seed is determined uniquely from the [peer_id] of the sender and the receiver so that the distance between two hashes can be recomputed locally. This is the purpose of the function [to_steps]. The [step] representation is mostly used by the [peer_validator] and the [bootstrap_pipeline] modules. The last step of a locator may be truncated. It is the case when the last step hits the caboose. Thus, such a [non-strict] step can be terminated by: - The genesis: it is the case in both [Archive] and [Full] modes as the caboose is always located down to the genesis block, but it is also the case in a [Rolling] mode early state (when caboose = genesis). - Any block: it is the case in [Rolling] mode when the caboose is higher than the genesis. Indeed, the caboose can be located (almost) anywhere. *) (** Type for sparse block locators (/à la/ Bitcoin). *) type t = { head_hash : Block_hash.t; head_header : Block_header.t; history : Block_hash.t list; } val pp : Format.formatter -> t -> unit val pp_short : Format.formatter -> t -> unit val encoding : t Data_encoding.t val bounded_encoding : max_header_size:int -> max_length:int -> unit -> t Data_encoding.t (** Argument to the seed used to randomize the locator. *) type seed = {sender_id : P2p_peer.Id.t; receiver_id : P2p_peer.Id.t} (** [estimated_length seed locator] estimates the length of the chain represented by [locator] using [seed]. *) val estimated_length : seed -> t -> int (** [compute ~get_predecessor ~caboose ~size block_hash header seed] returns a sparse block locator whose header is the given [header] and whose sparse block is computed using [seed] to compute random jumps from the [block_hash], adding the [caboose] at the end of the sparse block. The sparse block locator contains at most [size + 1] elements, including the caboose. *) val compute : get_predecessor:(Block_hash.t -> int -> Block_hash.t option Lwt.t) -> caboose:Block_hash.t -> size:int -> Block_hash.t -> Block_header.t -> seed -> t Lwt.t * A ' step ' in a locator is a couple of consecutive hashes in the locator , and the expected difference of level between the two blocks ( or an upper bounds when [ strict_step = false ] ) . locator, and the expected difference of level between the two blocks (or an upper bounds when [strict_step = false]). *) type step = { block : Block_hash.t; predecessor : Block_hash.t; step : int; strict_step : bool; } val pp_step : Format.formatter -> step -> unit * [ to_steps seed t ] builds all the ' steps ' composing the locator using the given [ seed ] , starting with the oldest one ( typically the predecessor of the first step will be the ` caboose ` ) . All steps contains [ strict_step = true ] , except the oldest one . using the given [seed], starting with the oldest one (typically the predecessor of the first step will be the `caboose`). All steps contains [strict_step = true], except the oldest one. *) val to_steps : seed -> t -> step list (** [to_steps_truncate ~limit ~save_point seed t] behaves as [to_steps] except that when the sum of all the steps already done, and the steps to do in order to reach the next block is superior to [limit], we return a truncated list of steps, setting the [predecessor] of the last step as [save_point] and its field [strict] to [false]. *) val to_steps_truncate : limit:int -> save_point:Block_hash.t -> seed -> t -> step list (** A block can either be known valid, invalid or unknown. *) type validity = Unknown | Known_valid | Known_invalid * [ unknown_prefix ~is_known t ] either returns : - [ ( , ( h , hist ) ) ] when we find a known valid block in the locator history ( w.r.t . [ is_known ] ) , where [ h ] is the given locator header and [ hist ] is the unknown prefix ending with the known valid block . - [ ( Known_invalid , ( h , hist ) ) ] when we find a known invalid block ( w.r.t . [ is_known ] ) in the locator history , where [ h ] is the given locator header and [ hist ] is the unknown prefix ending with the known invalid block . - [ ( Unknown , ( h , hist ) ) ] when no block is known valid nor invalid ( w.r.t . [ is_known ] ) , where [ ( h , hist ) ] is the given [ locator ] . - [(Known_valid, (h, hist))] when we find a known valid block in the locator history (w.r.t. [is_known]), where [h] is the given locator header and [hist] is the unknown prefix ending with the known valid block. - [(Known_invalid, (h, hist))] when we find a known invalid block (w.r.t. [is_known]) in the locator history, where [h] is the given locator header and [hist] is the unknown prefix ending with the known invalid block. - [(Unknown, (h, hist))] when no block is known valid nor invalid (w.r.t. [is_known]), where [(h, hist)] is the given [locator]. *) val unknown_prefix : is_known:(Block_hash.t -> validity Lwt.t) -> t -> (validity * t) Lwt.t
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/lib_base/block_locator.mli
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Type for sparse block locators (/à la/ Bitcoin). * Argument to the seed used to randomize the locator. * [estimated_length seed locator] estimates the length of the chain represented by [locator] using [seed]. * [compute ~get_predecessor ~caboose ~size block_hash header seed] returns a sparse block locator whose header is the given [header] and whose sparse block is computed using [seed] to compute random jumps from the [block_hash], adding the [caboose] at the end of the sparse block. The sparse block locator contains at most [size + 1] elements, including the caboose. * [to_steps_truncate ~limit ~save_point seed t] behaves as [to_steps] except that when the sum of all the steps already done, and the steps to do in order to reach the next block is superior to [limit], we return a truncated list of steps, setting the [predecessor] of the last step as [save_point] and its field [strict] to [false]. * A block can either be known valid, invalid or unknown.
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2019 - 2021 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING * A locator [ t ] is a data structure which roughly represents a list of block hashes in the chain . These hashes go from the top of the chain to the bottom . It is sparse in the sense that the distance between two hashes increases exponentially when we move away from the head . The distance between two hashes of a locator is randomized to prevent attacks . The seed is determined uniquely from the [ peer_id ] of the sender and the receiver so that the distance between two hashes can be recomputed locally . This is the purpose of the function [ to_steps ] . The [ step ] representation is mostly used by the [ peer_validator ] and the [ bootstrap_pipeline ] modules . The last step of a locator may be truncated . It is the case when the last step hits the caboose . Thus , such a [ non - strict ] step can be terminated by : - The genesis : it is the case in both [ Archive ] and [ Full ] modes as the caboose is always located down to the genesis block , but it is also the case in a [ Rolling ] mode early state ( when caboose = genesis ) . - Any block : it is the case in [ Rolling ] mode when the caboose is higher than the genesis . Indeed , the caboose can be located ( almost ) anywhere . of block hashes in the chain. These hashes go from the top of the chain to the bottom. It is sparse in the sense that the distance between two hashes increases exponentially when we move away from the head. The distance between two hashes of a locator is randomized to prevent attacks. The seed is determined uniquely from the [peer_id] of the sender and the receiver so that the distance between two hashes can be recomputed locally. This is the purpose of the function [to_steps]. The [step] representation is mostly used by the [peer_validator] and the [bootstrap_pipeline] modules. The last step of a locator may be truncated. It is the case when the last step hits the caboose. Thus, such a [non-strict] step can be terminated by: - The genesis: it is the case in both [Archive] and [Full] modes as the caboose is always located down to the genesis block, but it is also the case in a [Rolling] mode early state (when caboose = genesis). - Any block: it is the case in [Rolling] mode when the caboose is higher than the genesis. Indeed, the caboose can be located (almost) anywhere. *) type t = { head_hash : Block_hash.t; head_header : Block_header.t; history : Block_hash.t list; } val pp : Format.formatter -> t -> unit val pp_short : Format.formatter -> t -> unit val encoding : t Data_encoding.t val bounded_encoding : max_header_size:int -> max_length:int -> unit -> t Data_encoding.t type seed = {sender_id : P2p_peer.Id.t; receiver_id : P2p_peer.Id.t} val estimated_length : seed -> t -> int val compute : get_predecessor:(Block_hash.t -> int -> Block_hash.t option Lwt.t) -> caboose:Block_hash.t -> size:int -> Block_hash.t -> Block_header.t -> seed -> t Lwt.t * A ' step ' in a locator is a couple of consecutive hashes in the locator , and the expected difference of level between the two blocks ( or an upper bounds when [ strict_step = false ] ) . locator, and the expected difference of level between the two blocks (or an upper bounds when [strict_step = false]). *) type step = { block : Block_hash.t; predecessor : Block_hash.t; step : int; strict_step : bool; } val pp_step : Format.formatter -> step -> unit * [ to_steps seed t ] builds all the ' steps ' composing the locator using the given [ seed ] , starting with the oldest one ( typically the predecessor of the first step will be the ` caboose ` ) . All steps contains [ strict_step = true ] , except the oldest one . using the given [seed], starting with the oldest one (typically the predecessor of the first step will be the `caboose`). All steps contains [strict_step = true], except the oldest one. *) val to_steps : seed -> t -> step list val to_steps_truncate : limit:int -> save_point:Block_hash.t -> seed -> t -> step list type validity = Unknown | Known_valid | Known_invalid * [ unknown_prefix ~is_known t ] either returns : - [ ( , ( h , hist ) ) ] when we find a known valid block in the locator history ( w.r.t . [ is_known ] ) , where [ h ] is the given locator header and [ hist ] is the unknown prefix ending with the known valid block . - [ ( Known_invalid , ( h , hist ) ) ] when we find a known invalid block ( w.r.t . [ is_known ] ) in the locator history , where [ h ] is the given locator header and [ hist ] is the unknown prefix ending with the known invalid block . - [ ( Unknown , ( h , hist ) ) ] when no block is known valid nor invalid ( w.r.t . [ is_known ] ) , where [ ( h , hist ) ] is the given [ locator ] . - [(Known_valid, (h, hist))] when we find a known valid block in the locator history (w.r.t. [is_known]), where [h] is the given locator header and [hist] is the unknown prefix ending with the known valid block. - [(Known_invalid, (h, hist))] when we find a known invalid block (w.r.t. [is_known]) in the locator history, where [h] is the given locator header and [hist] is the unknown prefix ending with the known invalid block. - [(Unknown, (h, hist))] when no block is known valid nor invalid (w.r.t. [is_known]), where [(h, hist)] is the given [locator]. *) val unknown_prefix : is_known:(Block_hash.t -> validity Lwt.t) -> t -> (validity * t) Lwt.t
01a0697561d75a74d5873bb8125fe734c1a4b86046ac01cb7982937424874eec
re-ops/re-cipes
python.clj
(ns re-cipes.python "Installing latest python versions" (:require [re-cog.resources.exec :refer [run]] [re-cog.common.recipe :refer (require-recipe)] [re-cog.resources.package :refer (package repository update-)])) (require-recipe) (def-inline python-3.7 "Setting up python 3.7" [] (repository "ppa:deadsnakes/ppa" :present) (update-) (package "python3.7" :present)) (def-inline python-3 "Installing system python 3" [] (package "python3" :present) (package "python3-pip" :present))
null
https://raw.githubusercontent.com/re-ops/re-cipes/183bdb637e54df1c6f20e8d529132e0c004e8ead/src/re_cipes/python.clj
clojure
(ns re-cipes.python "Installing latest python versions" (:require [re-cog.resources.exec :refer [run]] [re-cog.common.recipe :refer (require-recipe)] [re-cog.resources.package :refer (package repository update-)])) (require-recipe) (def-inline python-3.7 "Setting up python 3.7" [] (repository "ppa:deadsnakes/ppa" :present) (update-) (package "python3.7" :present)) (def-inline python-3 "Installing system python 3" [] (package "python3" :present) (package "python3-pip" :present))
c1af0782bf4903322b203d79f6ea45f3512282f94d6e4f5d7646be121ce905d7
hubski/hubski
publications.rkt
This file has been VERSIONED into the hub repo . ;; DO NOT change it from hub. Change in github.com/hubski/hubski, ;; and update the versioned file. Contributors WILL update this ;; file in hub without checking for changes. #lang racket (require json) (require "arc-utils.rkt") (provide jsexpr->pub-sexp pub-sexp->jsexpr publication-jsexpr? try-string->jsexpr pub-sexp->pub-hash publication-is-public nil->null safe-unlist hash-ref-or-nil un-nil-list list-add-hash-member list-add-hash-member-bool list-add-hash-member-symbol list-add-hash-member-list list-add-hash-member-votes ) ;; Whether the publication is publically viewable, or private to certain users. ;; \todo add contract (define (publication-is-public p) (not (or (hash-ref p 'mail) (hash-ref p 'draft) (hash-ref p 'deleted)))) (define (try-string->jsexpr s) (with-handlers ([exn:fail:read? (lambda (e) 'nil)]) (string->jsexpr s))) (define (hash-ref-or-nil h memb) (if (hash-has-key? h memb) (hash-ref h memb) 'nil)) (define (null->nil v) (if (equal? v 'null) 'nil v)) (define (list-add-hash-member h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (if (equal? val '()) (cons (list sexp-memb 'nil) l) (cons (list sexp-memb val) l)))) (define (list-add-hash-member-symbol h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (cons (list sexp-memb (string->symbol val)) l))) (define (list-add-hash-member-bool h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (cons (list sexp-memb (bool->arc-bool val)) l))) ; returns a list of the given value. Used because Arc pub lists are doubled for some reason. (define (list-add-hash-member-list h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (if (or (equal? val 'nil) (equal? val '())) (cons (list sexp-memb 'nil) l) (cons (list sexp-memb (list (hash-ref h memb))) l)))) (define (list-add-hash-member-list-of-nil h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (if (or (equal? val 'nil) (equal? val '())) (cons (list sexp-memb '(nil)) l) (cons (list sexp-memb (list (hash-ref h memb))) l)))) (define (vote-hash->list h publication-id) (list (hash-ref h 'id) publication-id (hash-ref h 'user) (if (hash-ref h 'up) 'up 'down) (hash-ref h 'num))) (define (list-add-hash-member-votes h l) (let* ([id (hash-ref h 'id)] [memb 'votes] [sexp-memb 'votes] [votes (null->nil (hash-ref-or-nil h memb))] [votes-list (map (lambda (v) (vote-hash->list v id)) votes)]) (if (equal? votes-list '()) (cons (list sexp-memb 'nil) l) (cons (list sexp-memb votes-list) l)))) (define (ctags-hash->list h) (letrec ([ctags-iter (lambda (i l) (if (equal? i #f) l (let* ([user (symbol->string (hash-iterate-key h i))] [tag (hash-iterate-value h i)] [newl (list* (list tag user) l)]) (ctags-iter (hash-iterate-next h i) newl))))]) (ctags-iter (hash-iterate-first h) '()))) ;; (define (list-add-hash-member-community-tags h l) ;; (let* ([memb 'community_tags] ;; [sexp-member 'ctags] ;; [ctags (null->nil (hash-ref-or-nil h memb))]) ; ( write " lahmct " ) ( write ctags ) ( write newline ) ;; (if (hash-empty? h) ;; (cons (list sexp-member 'nil) l) ;; (cons (list sexp-member (h->list (hash-ref h memb))) l)))) ; \todo write a pipeline macro? (define (jsexpr->pub-sexp-not-null j) (list-add-hash-member j 'keys 'keys (list-add-hash-member j 'parent_id 'parent (list-add-hash-member-bool j 'draft 'draft (list-add-hash-member-bool j 'deleted 'deleted (list-add-hash-member j 'cubbed_by 'cubbedby (list-add-hash-member j 'badged_kids 'badgedkids (list-add-hash-member j 'saved_by 'savedby (list-add-hash-member j 'community_tag 'ctag ; ptag? (list-add-hash-member-bool j 'mail 'mail (list-add-hash-member j 'cc 'cc (list-add-hash-member j 'date 'date (list-add-hash-member j 'tag2 'tag2 (list-add-hash-member j 'badged_by 'badgedby (list-add-hash-member-votes j (list-add-hash-member j 'id 'id (list-add-hash-member j 'title 'title (list-add-hash-member j 'text 'text (list-add-hash-member j 'kids 'kids (list-add-hash-member j 'shared_by 'sharedby (list-add-hash-member j 'time 'time (list-add-hash-member-symbol j 'type 'type (list-add-hash-member j 'md 'md (list-add-hash-member j 'url 'url (list-add-hash-member-list j 'domain 'domain (list-add-hash-member j 'tag 'tag (list-add-hash-member j 'score 'score (list-add-hash-member j 'user 'by (list-add-hash-member-bool j 'no_kill 'nokill (list-add-hash-member-bool j 'locked 'locked '() )))))))))))))))))))))))))))))) (define (pub-sexp->pub-hash s) (letrec ([acc (lambda (s h) (if (equal? s '()) h (let* ([head (first s)] [key (first head)] [value (second head)]) (hash-set! h key value) (acc (rest s) h))))]) (acc s (make-hasheq)))) (define (votes-list-list->votes-list-hash l) (if (list? l) (map (lambda (vote) (vote-list->hash vote)) l) l)) we ca n't just use hash->list because the hash has member hashes which must be converted (define (jsexpr->pub-sexp j) (if (equal? j 'null) 'null (jsexpr->pub-sexp-not-null j))) (define (safe-unlist l) (if (list? l) (car l) l)) (define (un-nil-list l) (if (and (list? l) (equal? (length l) 1) (equal? (car l) 'nil)) '() l)) (define (nil->null v) (if (equal? v 'nil) 'null v)) (define get-string (compose1 nil->null safe-unlist hash-ref-or-nil)) (define get-bool (compose1 arc-bool->bool safe-unlist hash-ref-or-nil)) (define get-list (compose1 nil->null un-nil-list hash-ref-or-nil)) (define (vote-list->hash vote) (let* ([vote-id (first vote)] sometimes vote has an IP in the middle , and is thus length 6 , with user , up , num one farther in the list . [username (if (equal? (length vote) 5) (third vote) (fourth vote))] [up-atom (if (equal? (length vote) 5) (fourth vote) (fifth vote))] [up (equal? up-atom 'up)] [num (if (equal? (length vote) 5) (fifth vote) (sixth vote))]) (hasheq 'id vote-id 'up up 'user username 'num num))) (define (community-tags-list->hash h ctags) (letrec ([acc (lambda (ctags chash) (if (empty? ctags) chash (let* ([ctag (first ctags)] [tag-str (first ctag)] [user-str (second ctag)] [newhash (hash-set chash (string->symbol user-str) tag-str)]) (acc (rest ctags) newhash))))]) (acc ctags (make-immutable-hash)))) (define (pub-sexp->jsexpr-not-null p) (let ([h (make-hash p)]) (hasheq 'keys (get-string h 'keys) 'parent_id (get-string h 'parent) 'draft (get-bool h 'draft) 'deleted (get-bool h 'deleted) 'cubbed_by (get-list h 'cubbedby) 'badged_kids (get-list h 'badgedkids) 'saved_by (get-list h 'savedby) 'community_tag (get-list h 'ctag) ; ptag? 'mail (get-bool h 'mail) 'cc (get-list h 'cc) 'date (get-string h 'date) 'tag2 (get-string h 'tag2) 'badged_by (get-list h 'badgedby) 'votes (votes-list-list->votes-list-hash (get-string h 'votes)) 'id (get-string h 'id) 'title (get-string h 'title) 'text (get-string h 'text) 'kids (get-list h 'kids) 'shared_by (get-list h 'sharedby) 'time (get-string h 'time) 'type (symbol->string (get-string h 'type)) 'md (get-string h 'mdn) 'url (get-string h 'url) 'domain (get-list h 'domain) 'tag (get-string h 'tag) 'score (get-string h 'score) 'user (get-string h 'by) 'no_kill (get-bool h 'nokill) 'locked (get-bool h 'locked) ))) (define (pub-sexp->jsexpr p) (if (or (equal? p 'null) (equal? p 'nil) (equal? p '())) 'null (pub-sexp->jsexpr-not-null p))) (define (publication-jsexpr-vote? v) (and (hash? v) (hash-has-key? v 'id) (number? (hash-ref v 'id)) (hash-has-key? v 'up) (boolean? (hash-ref v 'up)) (hash-has-key? v 'user) (string? (hash-ref v 'user)) (hash-has-key? v 'num) (number? (hash-ref v 'num)))) (define (publication-jsexpr-votes? l) (cond [(empty? l) #t] [(pair? l) (and (publication-jsexpr-vote? (first l)) (publication-jsexpr-votes? (rest l)))] [else #f])) ; \todo validate the types of values (define (publication-jsexpr? p) (and (hash? p) ;; (hash-has-key? p 'keys) (hash-has-key? p 'parent_id) (hash-has-key? p 'draft) (hash-has-key? p 'deleted) (hash-has-key? p 'cubbed_by) (hash-has-key? p 'badged_kids) (hash-has-key? p 'saved_by) (hash-has-key? p 'community_tag) ; ? (hash-has-key? p 'mail) (hash-has-key? p 'cc) (hash-has-key? p 'date) (hash-has-key? p 'tag2) (hash-has-key? p 'badged_by) (hash-has-key? p 'votes) (publication-jsexpr-votes? (hash-ref p 'votes)) (hash-has-key? p 'id) (hash-has-key? p 'title) (hash-has-key? p 'text) (hash-has-key? p 'kids) (hash-has-key? p 'shared_by) (hash-has-key? p 'time) (hash-has-key? p 'type) (hash-has-key? p 'md) (hash-has-key? p 'url) (hash-has-key? p 'domain) (hash-has-key? p 'tag) (hash-has-key? p 'score) (hash-has-key? p 'user) (hash-has-key? p 'no_kill) (hash-has-key? p 'locked)))
null
https://raw.githubusercontent.com/hubski/hubski/97ddebb02ff404edcf8db6e1a7889cfdf43b367a/publications.rkt
racket
DO NOT change it from hub. Change in github.com/hubski/hubski, and update the versioned file. Contributors WILL update this file in hub without checking for changes. Whether the publication is publically viewable, or private to certain users. \todo add contract returns a list of the given value. Used because Arc pub lists are doubled for some reason. (define (list-add-hash-member-community-tags h l) (let* ([memb 'community_tags] [sexp-member 'ctags] [ctags (null->nil (hash-ref-or-nil h memb))]) ( write " lahmct " ) ( write ctags ) ( write newline ) (if (hash-empty? h) (cons (list sexp-member 'nil) l) (cons (list sexp-member (h->list (hash-ref h memb))) l)))) \todo write a pipeline macro? ptag? ptag? \todo validate the types of values (hash-has-key? p 'keys) ?
This file has been VERSIONED into the hub repo . #lang racket (require json) (require "arc-utils.rkt") (provide jsexpr->pub-sexp pub-sexp->jsexpr publication-jsexpr? try-string->jsexpr pub-sexp->pub-hash publication-is-public nil->null safe-unlist hash-ref-or-nil un-nil-list list-add-hash-member list-add-hash-member-bool list-add-hash-member-symbol list-add-hash-member-list list-add-hash-member-votes ) (define (publication-is-public p) (not (or (hash-ref p 'mail) (hash-ref p 'draft) (hash-ref p 'deleted)))) (define (try-string->jsexpr s) (with-handlers ([exn:fail:read? (lambda (e) 'nil)]) (string->jsexpr s))) (define (hash-ref-or-nil h memb) (if (hash-has-key? h memb) (hash-ref h memb) 'nil)) (define (null->nil v) (if (equal? v 'null) 'nil v)) (define (list-add-hash-member h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (if (equal? val '()) (cons (list sexp-memb 'nil) l) (cons (list sexp-memb val) l)))) (define (list-add-hash-member-symbol h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (cons (list sexp-memb (string->symbol val)) l))) (define (list-add-hash-member-bool h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (cons (list sexp-memb (bool->arc-bool val)) l))) (define (list-add-hash-member-list h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (if (or (equal? val 'nil) (equal? val '())) (cons (list sexp-memb 'nil) l) (cons (list sexp-memb (list (hash-ref h memb))) l)))) (define (list-add-hash-member-list-of-nil h memb sexp-memb l) (let ([val (null->nil (hash-ref-or-nil h memb))]) (if (or (equal? val 'nil) (equal? val '())) (cons (list sexp-memb '(nil)) l) (cons (list sexp-memb (list (hash-ref h memb))) l)))) (define (vote-hash->list h publication-id) (list (hash-ref h 'id) publication-id (hash-ref h 'user) (if (hash-ref h 'up) 'up 'down) (hash-ref h 'num))) (define (list-add-hash-member-votes h l) (let* ([id (hash-ref h 'id)] [memb 'votes] [sexp-memb 'votes] [votes (null->nil (hash-ref-or-nil h memb))] [votes-list (map (lambda (v) (vote-hash->list v id)) votes)]) (if (equal? votes-list '()) (cons (list sexp-memb 'nil) l) (cons (list sexp-memb votes-list) l)))) (define (ctags-hash->list h) (letrec ([ctags-iter (lambda (i l) (if (equal? i #f) l (let* ([user (symbol->string (hash-iterate-key h i))] [tag (hash-iterate-value h i)] [newl (list* (list tag user) l)]) (ctags-iter (hash-iterate-next h i) newl))))]) (ctags-iter (hash-iterate-first h) '()))) (define (jsexpr->pub-sexp-not-null j) (list-add-hash-member j 'keys 'keys (list-add-hash-member j 'parent_id 'parent (list-add-hash-member-bool j 'draft 'draft (list-add-hash-member-bool j 'deleted 'deleted (list-add-hash-member j 'cubbed_by 'cubbedby (list-add-hash-member j 'badged_kids 'badgedkids (list-add-hash-member j 'saved_by 'savedby (list-add-hash-member j 'community_tag 'ctag (list-add-hash-member-bool j 'mail 'mail (list-add-hash-member j 'cc 'cc (list-add-hash-member j 'date 'date (list-add-hash-member j 'tag2 'tag2 (list-add-hash-member j 'badged_by 'badgedby (list-add-hash-member-votes j (list-add-hash-member j 'id 'id (list-add-hash-member j 'title 'title (list-add-hash-member j 'text 'text (list-add-hash-member j 'kids 'kids (list-add-hash-member j 'shared_by 'sharedby (list-add-hash-member j 'time 'time (list-add-hash-member-symbol j 'type 'type (list-add-hash-member j 'md 'md (list-add-hash-member j 'url 'url (list-add-hash-member-list j 'domain 'domain (list-add-hash-member j 'tag 'tag (list-add-hash-member j 'score 'score (list-add-hash-member j 'user 'by (list-add-hash-member-bool j 'no_kill 'nokill (list-add-hash-member-bool j 'locked 'locked '() )))))))))))))))))))))))))))))) (define (pub-sexp->pub-hash s) (letrec ([acc (lambda (s h) (if (equal? s '()) h (let* ([head (first s)] [key (first head)] [value (second head)]) (hash-set! h key value) (acc (rest s) h))))]) (acc s (make-hasheq)))) (define (votes-list-list->votes-list-hash l) (if (list? l) (map (lambda (vote) (vote-list->hash vote)) l) l)) we ca n't just use hash->list because the hash has member hashes which must be converted (define (jsexpr->pub-sexp j) (if (equal? j 'null) 'null (jsexpr->pub-sexp-not-null j))) (define (safe-unlist l) (if (list? l) (car l) l)) (define (un-nil-list l) (if (and (list? l) (equal? (length l) 1) (equal? (car l) 'nil)) '() l)) (define (nil->null v) (if (equal? v 'nil) 'null v)) (define get-string (compose1 nil->null safe-unlist hash-ref-or-nil)) (define get-bool (compose1 arc-bool->bool safe-unlist hash-ref-or-nil)) (define get-list (compose1 nil->null un-nil-list hash-ref-or-nil)) (define (vote-list->hash vote) (let* ([vote-id (first vote)] sometimes vote has an IP in the middle , and is thus length 6 , with user , up , num one farther in the list . [username (if (equal? (length vote) 5) (third vote) (fourth vote))] [up-atom (if (equal? (length vote) 5) (fourth vote) (fifth vote))] [up (equal? up-atom 'up)] [num (if (equal? (length vote) 5) (fifth vote) (sixth vote))]) (hasheq 'id vote-id 'up up 'user username 'num num))) (define (community-tags-list->hash h ctags) (letrec ([acc (lambda (ctags chash) (if (empty? ctags) chash (let* ([ctag (first ctags)] [tag-str (first ctag)] [user-str (second ctag)] [newhash (hash-set chash (string->symbol user-str) tag-str)]) (acc (rest ctags) newhash))))]) (acc ctags (make-immutable-hash)))) (define (pub-sexp->jsexpr-not-null p) (let ([h (make-hash p)]) (hasheq 'keys (get-string h 'keys) 'parent_id (get-string h 'parent) 'draft (get-bool h 'draft) 'deleted (get-bool h 'deleted) 'cubbed_by (get-list h 'cubbedby) 'badged_kids (get-list h 'badgedkids) 'saved_by (get-list h 'savedby) 'community_tag (get-list h 'ctag) 'mail (get-bool h 'mail) 'cc (get-list h 'cc) 'date (get-string h 'date) 'tag2 (get-string h 'tag2) 'badged_by (get-list h 'badgedby) 'votes (votes-list-list->votes-list-hash (get-string h 'votes)) 'id (get-string h 'id) 'title (get-string h 'title) 'text (get-string h 'text) 'kids (get-list h 'kids) 'shared_by (get-list h 'sharedby) 'time (get-string h 'time) 'type (symbol->string (get-string h 'type)) 'md (get-string h 'mdn) 'url (get-string h 'url) 'domain (get-list h 'domain) 'tag (get-string h 'tag) 'score (get-string h 'score) 'user (get-string h 'by) 'no_kill (get-bool h 'nokill) 'locked (get-bool h 'locked) ))) (define (pub-sexp->jsexpr p) (if (or (equal? p 'null) (equal? p 'nil) (equal? p '())) 'null (pub-sexp->jsexpr-not-null p))) (define (publication-jsexpr-vote? v) (and (hash? v) (hash-has-key? v 'id) (number? (hash-ref v 'id)) (hash-has-key? v 'up) (boolean? (hash-ref v 'up)) (hash-has-key? v 'user) (string? (hash-ref v 'user)) (hash-has-key? v 'num) (number? (hash-ref v 'num)))) (define (publication-jsexpr-votes? l) (cond [(empty? l) #t] [(pair? l) (and (publication-jsexpr-vote? (first l)) (publication-jsexpr-votes? (rest l)))] [else #f])) (define (publication-jsexpr? p) (and (hash? p) (hash-has-key? p 'parent_id) (hash-has-key? p 'draft) (hash-has-key? p 'deleted) (hash-has-key? p 'cubbed_by) (hash-has-key? p 'badged_kids) (hash-has-key? p 'saved_by) (hash-has-key? p 'community_tag) (hash-has-key? p 'mail) (hash-has-key? p 'cc) (hash-has-key? p 'date) (hash-has-key? p 'tag2) (hash-has-key? p 'badged_by) (hash-has-key? p 'votes) (publication-jsexpr-votes? (hash-ref p 'votes)) (hash-has-key? p 'id) (hash-has-key? p 'title) (hash-has-key? p 'text) (hash-has-key? p 'kids) (hash-has-key? p 'shared_by) (hash-has-key? p 'time) (hash-has-key? p 'type) (hash-has-key? p 'md) (hash-has-key? p 'url) (hash-has-key? p 'domain) (hash-has-key? p 'tag) (hash-has-key? p 'score) (hash-has-key? p 'user) (hash-has-key? p 'no_kill) (hash-has-key? p 'locked)))
4c568bd5966e3da5953a45b1b31c69b1ade072010a62593345f440b2f06df520
geneweb/geneweb
hutil.mli
Copyright ( c ) 2007 INRIA open Config val header_without_http : config -> (bool -> unit) -> unit * [ header_without_http conf title ] prints HTML page header in the body of the current response on the socket . HTML page header consists of : - < ! DOCTYPE > Declaration - < head > tag where : - content of < title > tag is printed with [ title true ] - < meta > and < link > tags are filled due to [ conf ] - content of { i css.txt } template is evaluated and printed - content of { i hed.txt } template is evaluated and printed - Opening < body > tag with its attributes - If user is a wizard or a friend , then includes all messages send to him . HTML page header consists of : - <!DOCTYPE> Declaration - <head> tag where : - content of <title> tag is printed with [title true] - <meta> and <link> tags are filled due to [conf] - content of {i css.txt} template is evaluated and printed - content of {i hed.txt} template is evaluated and printed - Opening <body> tag with its attributes - If user is a wizard or a friend, then includes all messages send to him. *) val header_without_page_title : config -> (bool -> unit) -> unit (** Calls for [Util.html] to print HTTP header and for [header_without_http] to print HTML page header. Additionaly prints opening container <div> tag on the socket. *) val header : config -> (bool -> unit) -> unit (** [header conf title] calls for [header_without_page_title] to print HTTP header and HTML page header. Additionaly prints page title with [title true] (false to print browser tab title). *) val header_no_page_title : config -> (bool -> unit) -> unit (** Same as [header] but takes page title from [conf.env]. *) val header_fluid : config -> (bool -> unit) -> unit * Prints HTML page header ( without HTTP headers ) and opens fluid container < div > ( see ) . val header_link_welcome : config -> (bool -> unit) -> unit (** Same as [header] but insert links to previous and home pages (with [print_link_to_welcome]) before page title. *) val trailer : config -> unit (** [trailer conf] prints HTML page trailer in the body of the current response on the socket. HTML page trailer consists of : - Copyright message from template {i copyr.txt} with inserted logo - Scripts JS from template {i js.txt} - Closing <body> and <html> tags *) val rheader : config -> (bool -> unit) -> unit (** Same as [header] except page's title informs about an occured error (red title). *) val link_to_referer : config -> Adef.safe_string (** Returns the HTML link to the previous (referer) page *) val gen_print_link_to_welcome : (unit -> unit) -> config -> bool -> unit (** [gen_print_link_to_welcome f conf right_alined] prints links to previous and to home pages. [f] is used to print additional content before links. *) val print_link_to_welcome : config -> bool -> unit (** Calls [gen_print_link_to_welcome] with empty function [f]. *) val incorrect_request : config -> unit (** Sends [Bad Request] HTTP response (same as [GWPARAM.output_error conf Bad_Request]) *) TODOOCP val interp : config -> string -> ('a, 'b) Templ.interp_fun -> 'a Templ.env -> 'b -> unit val interp_no_header : config -> string -> ('a, 'b) Templ.interp_fun -> 'a Templ.env -> 'b -> unit val print_calendar : config -> unit * Displays the calendar ; if no key is set , it will use today 's date . Based on template file calendar.txt Based on template file calendar.txt *)
null
https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/hutil.mli
ocaml
* Calls for [Util.html] to print HTTP header and for [header_without_http] to print HTML page header. Additionaly prints opening container <div> tag on the socket. * [header conf title] calls for [header_without_page_title] to print HTTP header and HTML page header. Additionaly prints page title with [title true] (false to print browser tab title). * Same as [header] but takes page title from [conf.env]. * Same as [header] but insert links to previous and home pages (with [print_link_to_welcome]) before page title. * [trailer conf] prints HTML page trailer in the body of the current response on the socket. HTML page trailer consists of : - Copyright message from template {i copyr.txt} with inserted logo - Scripts JS from template {i js.txt} - Closing <body> and <html> tags * Same as [header] except page's title informs about an occured error (red title). * Returns the HTML link to the previous (referer) page * [gen_print_link_to_welcome f conf right_alined] prints links to previous and to home pages. [f] is used to print additional content before links. * Calls [gen_print_link_to_welcome] with empty function [f]. * Sends [Bad Request] HTTP response (same as [GWPARAM.output_error conf Bad_Request])
Copyright ( c ) 2007 INRIA open Config val header_without_http : config -> (bool -> unit) -> unit * [ header_without_http conf title ] prints HTML page header in the body of the current response on the socket . HTML page header consists of : - < ! DOCTYPE > Declaration - < head > tag where : - content of < title > tag is printed with [ title true ] - < meta > and < link > tags are filled due to [ conf ] - content of { i css.txt } template is evaluated and printed - content of { i hed.txt } template is evaluated and printed - Opening < body > tag with its attributes - If user is a wizard or a friend , then includes all messages send to him . HTML page header consists of : - <!DOCTYPE> Declaration - <head> tag where : - content of <title> tag is printed with [title true] - <meta> and <link> tags are filled due to [conf] - content of {i css.txt} template is evaluated and printed - content of {i hed.txt} template is evaluated and printed - Opening <body> tag with its attributes - If user is a wizard or a friend, then includes all messages send to him. *) val header_without_page_title : config -> (bool -> unit) -> unit val header : config -> (bool -> unit) -> unit val header_no_page_title : config -> (bool -> unit) -> unit val header_fluid : config -> (bool -> unit) -> unit * Prints HTML page header ( without HTTP headers ) and opens fluid container < div > ( see ) . val header_link_welcome : config -> (bool -> unit) -> unit val trailer : config -> unit val rheader : config -> (bool -> unit) -> unit val link_to_referer : config -> Adef.safe_string val gen_print_link_to_welcome : (unit -> unit) -> config -> bool -> unit val print_link_to_welcome : config -> bool -> unit val incorrect_request : config -> unit TODOOCP val interp : config -> string -> ('a, 'b) Templ.interp_fun -> 'a Templ.env -> 'b -> unit val interp_no_header : config -> string -> ('a, 'b) Templ.interp_fun -> 'a Templ.env -> 'b -> unit val print_calendar : config -> unit * Displays the calendar ; if no key is set , it will use today 's date . Based on template file calendar.txt Based on template file calendar.txt *)
e0eb89682303bde45afb3685f9aadec4051f335d42187e1c146e6f6eadd31b4e
kyleburton/sandbox
core.cljs
(ns web-app.core (:require )) (enable-console-print!) (println "This text is printed from src/web-app/core.cljs. Go ahead and edit it and see reloading in action.") ;; define your app data so that it doesn't get over-written on reload (defonce app-state (atom {:text "Hello world!"})) (defn on-js-reload [] ;; optionally touch your app-state to force rerendering depending on ;; your application ;; (swap! app-state update-in [:__figwheel_counter] inc) )
null
https://raw.githubusercontent.com/kyleburton/sandbox/cccbcc9a97026336691063a0a7eb59293a35c31a/examples/neo4j/web-app/src/web_app/core.cljs
clojure
define your app data so that it doesn't get over-written on reload optionally touch your app-state to force rerendering depending on your application (swap! app-state update-in [:__figwheel_counter] inc)
(ns web-app.core (:require )) (enable-console-print!) (println "This text is printed from src/web-app/core.cljs. Go ahead and edit it and see reloading in action.") (defonce app-state (atom {:text "Hello world!"})) (defn on-js-reload [] )
512291471747cf93e4a46b0c187fb5a15420dea6fb6ae2bd243160f4e1ed983f
RBornat/jape
usefile.ml
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . 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 ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape 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. Jape 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 jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) open Sml open UTF let bracketed_string_of_list = Listfuns.bracketed_string_of_list let consolereport = Miscellaneous.consolereport this is the Unix version ... Linux and MacOS X ok ; Windoze needs ' \\ ' so we stay in the world of unix filenames and normalize filenames according to OS just before opening Windoze needs '\\' so we stay in the world of unix filenames and normalize filenames according to OS just before opening *) let normalizePath filename = if Sys.os_type="Win32" then 0x2f = ' / ' = ' \\ ' 0x5c = '\\' *) let sloshify = function 0x2f->0x5c | c -> c in utf8_implode (List.map sloshify (utf8_explode filename)) else filename let pathStem path = (* Remove the stern of a path Path separator is immaterial so we can mix unix/windows-style paths in source files. *) 0x2f = ' / ' 0x5c = ' \\ ' 0x5c = '\\' *) let rec removestern = function | [] -> [Char.code '.'; Char.code '/'] | 0x2f :: xs -> 0x2f :: xs | 0x5c :: xs -> 0x5c :: xs | x :: xs -> removestern xs in utf8_implode (List.rev (removestern (List.rev (utf8_explode path)))) let list_of_Unixpath path = let rec ds pres path = match path with | "" -> pres | _ -> let dir = Filename.dirname path in if dir = path then path :: pres else ds (Filename.basename path :: pres) dir in ds [] path let warned = ref "" I changed this function to check if it is running on MacOS , and if so whether it is trying to read from one of the protected directories Desktop , Documents , Downloads and Library . Then I discovered that MacOS will let me read from one file at a time . So now it reads the entire input file into a buffer , closes the file , and gives you a UTF.ucode stream of its contents . Works in an a.out that I compiled ... but definitely does n't work in . So I left the check in place , but it now delivers a ( UTF.ucode stream ) option , because that seems to make more sense elsewhere . to read from one of the protected directories Desktop, Documents, Downloads and Library. Then I discovered that MacOS will let me read from one file at a time. So now it reads the entire input file into a buffer, closes the file, and gives you a UTF.ucode stream of its contents. Works in an a.out that I compiled ... but definitely doesn't work in Jape. So I left the check in place, but it now delivers a (UTF.ucode stream) option, because that seems to make more sense elsewhere. *) let open_input_file filename = let default () = Some (UTF.of_utfchannel (open_in (normalizePath filename))) in if Miscellaneous.onMacOS () then (let ss = list_of_Unixpath filename in (match ss with | "/" :: "Users" :: name :: place :: path when List.mem place ["Desktop"; "Documents"; "Downloads"; "Library"] && List.mem "examples" path && !warned <> place -> (let message = "It looks as if you have put your examples directory somewhere \ in your " ^ place ^ " folder. This doesn't work: because Jape is \ not notarised by Apple, it won't be able to read the examples files.\n \ \n\ The only thing to do is to move the examples folder somewhere outside \ the protected folders Desktop, Documents, Downloads and Library.\n \ \n\ Please press Cancel, move the folder, and Open the moved folder. \ If you press Proceed it really really really won't work." in match Alert.askCancel Alert.Warning message [("Proceed",0)] (-1) 1 with | 0 -> warned := place; default () | _ -> None ) | _ -> default () ) ) else default () let open_output_file filename = open_out (normalizePath filename) It 's not good enough ... we ought to parse the strings . RB 3 / i/2002 let usestack = ref (if Sys.os_type="Win32" then [] else ["./"]) let isabsolute path = if Sys.os_type="Win32" then ( try String.index path ':' < String.index path '\\' with Not_found -> false) else (try path.[0]='/' with _ -> false) let makerelative s = if isabsolute s then s else match !usestack with | [] -> s | top::_ -> top ^ s let rec startusing path = usestack := pathStem path :: !usestack exception Matchinstopusing (* spurious *) let rec stopusing () = match !usestack with | [path] -> () | path :: paths -> usestack := paths | _ -> raise Matchinstopusing
null
https://raw.githubusercontent.com/RBornat/jape/d2f507023c8a227e6862f9e5a16bb16ddeda692c/distrib/camlengine/usefile.ml
ocaml
Remove the stern of a path Path separator is immaterial so we can mix unix/windows-style paths in source files. spurious
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . 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 ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape 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. Jape 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 jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) open Sml open UTF let bracketed_string_of_list = Listfuns.bracketed_string_of_list let consolereport = Miscellaneous.consolereport this is the Unix version ... Linux and MacOS X ok ; Windoze needs ' \\ ' so we stay in the world of unix filenames and normalize filenames according to OS just before opening Windoze needs '\\' so we stay in the world of unix filenames and normalize filenames according to OS just before opening *) let normalizePath filename = if Sys.os_type="Win32" then 0x2f = ' / ' = ' \\ ' 0x5c = '\\' *) let sloshify = function 0x2f->0x5c | c -> c in utf8_implode (List.map sloshify (utf8_explode filename)) else filename let pathStem path = 0x2f = ' / ' 0x5c = ' \\ ' 0x5c = '\\' *) let rec removestern = function | [] -> [Char.code '.'; Char.code '/'] | 0x2f :: xs -> 0x2f :: xs | 0x5c :: xs -> 0x5c :: xs | x :: xs -> removestern xs in utf8_implode (List.rev (removestern (List.rev (utf8_explode path)))) let list_of_Unixpath path = let rec ds pres path = match path with | "" -> pres | _ -> let dir = Filename.dirname path in if dir = path then path :: pres else ds (Filename.basename path :: pres) dir in ds [] path let warned = ref "" I changed this function to check if it is running on MacOS , and if so whether it is trying to read from one of the protected directories Desktop , Documents , Downloads and Library . Then I discovered that MacOS will let me read from one file at a time . So now it reads the entire input file into a buffer , closes the file , and gives you a UTF.ucode stream of its contents . Works in an a.out that I compiled ... but definitely does n't work in . So I left the check in place , but it now delivers a ( UTF.ucode stream ) option , because that seems to make more sense elsewhere . to read from one of the protected directories Desktop, Documents, Downloads and Library. Then I discovered that MacOS will let me read from one file at a time. So now it reads the entire input file into a buffer, closes the file, and gives you a UTF.ucode stream of its contents. Works in an a.out that I compiled ... but definitely doesn't work in Jape. So I left the check in place, but it now delivers a (UTF.ucode stream) option, because that seems to make more sense elsewhere. *) let open_input_file filename = let default () = Some (UTF.of_utfchannel (open_in (normalizePath filename))) in if Miscellaneous.onMacOS () then (let ss = list_of_Unixpath filename in (match ss with | "/" :: "Users" :: name :: place :: path when List.mem place ["Desktop"; "Documents"; "Downloads"; "Library"] && List.mem "examples" path && !warned <> place -> (let message = "It looks as if you have put your examples directory somewhere \ in your " ^ place ^ " folder. This doesn't work: because Jape is \ not notarised by Apple, it won't be able to read the examples files.\n \ \n\ The only thing to do is to move the examples folder somewhere outside \ the protected folders Desktop, Documents, Downloads and Library.\n \ \n\ Please press Cancel, move the folder, and Open the moved folder. \ If you press Proceed it really really really won't work." in match Alert.askCancel Alert.Warning message [("Proceed",0)] (-1) 1 with | 0 -> warned := place; default () | _ -> None ) | _ -> default () ) ) else default () let open_output_file filename = open_out (normalizePath filename) It 's not good enough ... we ought to parse the strings . RB 3 / i/2002 let usestack = ref (if Sys.os_type="Win32" then [] else ["./"]) let isabsolute path = if Sys.os_type="Win32" then ( try String.index path ':' < String.index path '\\' with Not_found -> false) else (try path.[0]='/' with _ -> false) let makerelative s = if isabsolute s then s else match !usestack with | [] -> s | top::_ -> top ^ s let rec startusing path = usestack := pathStem path :: !usestack let rec stopusing () = match !usestack with | [path] -> () | path :: paths -> usestack := paths | _ -> raise Matchinstopusing
8bbbcfcdc2d3029ee59a6a6829d714a4f5cc93e514b4d451667c37675334a2b1
yesodweb/yesod
Media.hs
# LANGUAGE QuasiQuotes , TypeFamilies , TemplateHaskell , MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE FlexibleInstances , ViewPatterns # # OPTIONS_GHC -fno - warn - orphans # module YesodCoreTest.Media (mediaTest, Widget) where import Test.Hspec import Yesod.Core import Network.Wai import Network.Wai.Test import YesodCoreTest.MediaData mkYesodDispatch "Y" resourcesY instance Yesod Y where addStaticContent _ _ content = do route <- getCurrentRoute case route of Just StaticR -> return $ Just $ Left $ if content == "foo2{bar:baz}" then "screen.css" else "all.css" _ -> return Nothing getRootR :: Handler Html getRootR = defaultLayout $ do toWidget [lucius|foo1{bar:baz}|] toWidgetMedia "screen" [lucius|foo2{bar:baz}|] toWidget [lucius|foo3{bar:baz}|] getStaticR :: Handler Html getStaticR = getRootR runner :: Session () -> IO () runner f = toWaiApp Y >>= runSession f caseMedia :: IO () caseMedia = runner $ do res <- request defaultRequest assertStatus 200 res flip assertBody res "<!DOCTYPE html>\n<html><head><title></title><style>foo1{bar:baz}foo3{bar:baz}</style><style media=\"screen\">foo2{bar:baz}</style></head><body></body></html>" caseMediaLink :: IO () caseMediaLink = runner $ do res <- request defaultRequest { pathInfo = ["static"] } assertStatus 200 res flip assertBody res "<!DOCTYPE html>\n<html><head><title></title><link rel=\"stylesheet\" href=\"all.css\"><link rel=\"stylesheet\" media=\"screen\" href=\"screen.css\"></head><body></body></html>" mediaTest :: Spec mediaTest = describe "Test.Media" $ do it "media" caseMedia it "media link" caseMediaLink
null
https://raw.githubusercontent.com/yesodweb/yesod/c59993ff287b880abbf768f1e3f56ae9b19df51e/yesod-core/test/YesodCoreTest/Media.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes , TypeFamilies , TemplateHaskell , MultiParamTypeClasses # # LANGUAGE FlexibleInstances , ViewPatterns # # OPTIONS_GHC -fno - warn - orphans # module YesodCoreTest.Media (mediaTest, Widget) where import Test.Hspec import Yesod.Core import Network.Wai import Network.Wai.Test import YesodCoreTest.MediaData mkYesodDispatch "Y" resourcesY instance Yesod Y where addStaticContent _ _ content = do route <- getCurrentRoute case route of Just StaticR -> return $ Just $ Left $ if content == "foo2{bar:baz}" then "screen.css" else "all.css" _ -> return Nothing getRootR :: Handler Html getRootR = defaultLayout $ do toWidget [lucius|foo1{bar:baz}|] toWidgetMedia "screen" [lucius|foo2{bar:baz}|] toWidget [lucius|foo3{bar:baz}|] getStaticR :: Handler Html getStaticR = getRootR runner :: Session () -> IO () runner f = toWaiApp Y >>= runSession f caseMedia :: IO () caseMedia = runner $ do res <- request defaultRequest assertStatus 200 res flip assertBody res "<!DOCTYPE html>\n<html><head><title></title><style>foo1{bar:baz}foo3{bar:baz}</style><style media=\"screen\">foo2{bar:baz}</style></head><body></body></html>" caseMediaLink :: IO () caseMediaLink = runner $ do res <- request defaultRequest { pathInfo = ["static"] } assertStatus 200 res flip assertBody res "<!DOCTYPE html>\n<html><head><title></title><link rel=\"stylesheet\" href=\"all.css\"><link rel=\"stylesheet\" media=\"screen\" href=\"screen.css\"></head><body></body></html>" mediaTest :: Spec mediaTest = describe "Test.Media" $ do it "media" caseMedia it "media link" caseMediaLink
4a3edc74528e9d396ad044afe12b9a56e1be0764a6df2f9070c2313f1b5dfa74
haskellfoundation/error-message-index
NullaryClass.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DerivingStrategies # # LANGUAGE StandaloneDeriving # module NullaryClass where class ThisClassHasNoParameters deriving stock instance ThisClassHasNoParameters
null
https://raw.githubusercontent.com/haskellfoundation/error-message-index/6b80c2fe6d8d2941190bda587bcea6f775ded0a4/message-index/messages/GHC-04956/nullary-class/before/NullaryClass.hs
haskell
# LANGUAGE DeriveAnyClass #
# LANGUAGE DerivingStrategies # # LANGUAGE StandaloneDeriving # module NullaryClass where class ThisClassHasNoParameters deriving stock instance ThisClassHasNoParameters
783dde879ff338f7eeecad8ffc65e54c4faf7174bb10449995a8cf6666fca01a
ghc/ghc
T22645.hs
module T22645 where import Data.Coerce type T :: (* -> *) -> * -> * data T m a = MkT (m a) p :: Coercible a b => T Maybe a -> T Maybe b p = coerce
null
https://raw.githubusercontent.com/ghc/ghc/3d55d8ab51ece43c51055c43c9e7aba77cce46c0/testsuite/tests/typecheck/should_fail/T22645.hs
haskell
module T22645 where import Data.Coerce type T :: (* -> *) -> * -> * data T m a = MkT (m a) p :: Coercible a b => T Maybe a -> T Maybe b p = coerce
ce50e38c2c4a95ab2f09e85306a3c6592df180f5c9c5dfb6ac685cc06d3eec9b
fredrikt/yxa
event_handler.erl
%%%------------------------------------------------------------------- %%% File : event_handler.erl @author < > %%% @doc Event handler event manager. Receives all the events and %%% sends them on to all your configured event handlers. %%% @since 6 Dec 2004 by < > %%% @end %%%------------------------------------------------------------------- -module(event_handler). %%-compile(export_all). %%-------------------------------------------------------------------- %% External exports %%-------------------------------------------------------------------- -export([ start_link/1, stop/0, generic_event/4, generic_event/5, new_request/6, request_info/3, uas_result/5, uac_result/4 ]). %%-------------------------------------------------------------------- %% Include files %%-------------------------------------------------------------------- -include("siprecords.hrl"). %%-------------------------------------------------------------------- Macros %%-------------------------------------------------------------------- -define(SERVER, event_mgr). %%==================================================================== %% External functions %%==================================================================== %%-------------------------------------------------------------------- @spec ( AppName ) - > term ( ) " Result of gen_server : start_link/4 " %% AppName = string ( ) " name of YXA application " %% %% @doc start the server. %% @end %%-------------------------------------------------------------------- start_link(AppName) -> {ok, Handlers} = yxa_config:get_env(event_handler_handlers), case gen_event:start_link({local, ?SERVER}) of {ok, Pid} -> lists:map(fun(M) when is_atom(M) -> gen_event:add_handler(?SERVER, M, [AppName]); ({M, A}) when is_atom(M), is_list(A) -> gen_event:add_handler(?SERVER, M, [AppName] ++ A) end, Handlers), {ok, Pid}; Other -> Other end. stop() -> gen_event:stop(?SERVER). generic_event(Prio, Class, Id, L) when is_atom(Prio), is_atom(Class), is_list(Id) orelse is_list(L) -> gen_event:notify(?SERVER, {event, self(), Prio, Class, Id, L}). io_lib : format , then call generic_event(Prio, Class, Id, Format, Args) when is_atom(Prio), is_atom(Class), is_list(Format), is_list(Args) -> Str = io_lib:format(Format, Args), generic_event(Prio, Class, Id, [Str]). %% New request has arrived, log a bunch of parameters about it new_request(Method, URI, Branch, DialogId, From, To) when is_list(Method), is_record(URI, sipurl), is_list(Branch), is_list(DialogId), is_list(From), is_list(To) -> L = [{method, Method}, {uri, sipurl:print(URI)}, {dialogid, DialogId}, {from, From}, {to, To} ], gen_event:notify(?SERVER, {event, self(), normal, new_request, Branch, L}). %% More information gathered about request request_info(Prio, Branch, L) when is_atom(Prio), is_list(Branch), is_list(L) -> gen_event:notify(?SERVER, {event, self(), Prio, request_info, Branch, L}). UAS has sent a result , URI = string ( ) uas_result(Branch, Created, Status, Reason, L) when is_list(Branch), is_atom(Created), is_integer(Status), is_list(Reason), is_list(L) -> L2 = [{origin, Created}, {response, lists:concat([Status, " ", Reason])} | L], gen_event:notify(?SERVER, {event, self(), normal, uas_result, Branch, L2}). UAC has received a reply uac_result(Branch, Status, Reason, L) when is_list(Branch), is_integer(Status), is_list(Reason), is_list(L) -> L2 = [{response, lists:concat([Status, " ", Reason])} | L], gen_event:notify(?SERVER, {event, self(), debug, uac_result, Branch, L2}).
null
https://raw.githubusercontent.com/fredrikt/yxa/85da46a999d083e6f00b5f156a634ca9be65645b/src/event_handler/event_handler.erl
erlang
------------------------------------------------------------------- File : event_handler.erl @doc Event handler event manager. Receives all the events and sends them on to all your configured event handlers. @end ------------------------------------------------------------------- -compile(export_all). -------------------------------------------------------------------- External exports -------------------------------------------------------------------- -------------------------------------------------------------------- Include files -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- ==================================================================== External functions ==================================================================== -------------------------------------------------------------------- @doc start the server. @end -------------------------------------------------------------------- New request has arrived, log a bunch of parameters about it More information gathered about request
@author < > @since 6 Dec 2004 by < > -module(event_handler). -export([ start_link/1, stop/0, generic_event/4, generic_event/5, new_request/6, request_info/3, uas_result/5, uac_result/4 ]). -include("siprecords.hrl"). Macros -define(SERVER, event_mgr). @spec ( AppName ) - > term ( ) " Result of gen_server : start_link/4 " AppName = string ( ) " name of YXA application " start_link(AppName) -> {ok, Handlers} = yxa_config:get_env(event_handler_handlers), case gen_event:start_link({local, ?SERVER}) of {ok, Pid} -> lists:map(fun(M) when is_atom(M) -> gen_event:add_handler(?SERVER, M, [AppName]); ({M, A}) when is_atom(M), is_list(A) -> gen_event:add_handler(?SERVER, M, [AppName] ++ A) end, Handlers), {ok, Pid}; Other -> Other end. stop() -> gen_event:stop(?SERVER). generic_event(Prio, Class, Id, L) when is_atom(Prio), is_atom(Class), is_list(Id) orelse is_list(L) -> gen_event:notify(?SERVER, {event, self(), Prio, Class, Id, L}). io_lib : format , then call generic_event(Prio, Class, Id, Format, Args) when is_atom(Prio), is_atom(Class), is_list(Format), is_list(Args) -> Str = io_lib:format(Format, Args), generic_event(Prio, Class, Id, [Str]). new_request(Method, URI, Branch, DialogId, From, To) when is_list(Method), is_record(URI, sipurl), is_list(Branch), is_list(DialogId), is_list(From), is_list(To) -> L = [{method, Method}, {uri, sipurl:print(URI)}, {dialogid, DialogId}, {from, From}, {to, To} ], gen_event:notify(?SERVER, {event, self(), normal, new_request, Branch, L}). request_info(Prio, Branch, L) when is_atom(Prio), is_list(Branch), is_list(L) -> gen_event:notify(?SERVER, {event, self(), Prio, request_info, Branch, L}). UAS has sent a result , URI = string ( ) uas_result(Branch, Created, Status, Reason, L) when is_list(Branch), is_atom(Created), is_integer(Status), is_list(Reason), is_list(L) -> L2 = [{origin, Created}, {response, lists:concat([Status, " ", Reason])} | L], gen_event:notify(?SERVER, {event, self(), normal, uas_result, Branch, L2}). UAC has received a reply uac_result(Branch, Status, Reason, L) when is_list(Branch), is_integer(Status), is_list(Reason), is_list(L) -> L2 = [{response, lists:concat([Status, " ", Reason])} | L], gen_event:notify(?SERVER, {event, self(), debug, uac_result, Branch, L2}).
2cadd4731e8a2082fb8f77486b9f3b345ddf884bf68950623d15f74776731ba6
wdebeaum/step
walnut.lisp
;;;; W::WALNUT ;;;; (define-words :pos W::n :words ( (W::WALNUT (senses ((LF-PARENT ONT::NUTS-SEEDS) (TEMPL COUNT-PRED-TEMPL) ) ) ) ))
null
https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/walnut.lisp
lisp
W::WALNUT (define-words :pos W::n :words ( (W::WALNUT (senses ((LF-PARENT ONT::NUTS-SEEDS) (TEMPL COUNT-PRED-TEMPL) ) ) ) ))
0de5907db0a75f44995a1a90e53751900ecb5a2e5278df0519e8a20dfc7c3e58
ryszard/clsql
test-oodml.lisp
-*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Base : 10 -*- ;;;; ====================================================================== File : Author : < > ;;;; Created: 01/04/2004 ;;;; Updated: $Id$ ;;;; ;;;; Tests for the CLSQL Object Oriented Data Definition Language ;;;; (OODML). ;;;; This file is part of CLSQL . ;;;; CLSQL users are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License ;;;; (), also known as the LLGPL. ;;;; ====================================================================== (in-package #:clsql-tests) #.(clsql:locally-enable-sql-reader-syntax) (setq *rt-oodml* '( (deftest :oodml/select/1 (mapcar #'(lambda (e) (slot-value e 'last-name)) (clsql:select 'employee :order-by [last-name] :flatp t :caching nil)) ("Andropov" "Brezhnev" "Chernenko" "Gorbachev" "Kruschev" "Lenin" "Putin" "Stalin" "Trotsky" "Yeltsin")) (deftest :oodml/select/2 (mapcar #'(lambda (e) (slot-value e 'name)) (clsql:select 'company :flatp t :caching nil)) ("Widgets Inc.")) (deftest :oodml/select/3 (mapcar #'(lambda (e) (slot-value e 'ecompanyid)) (clsql:select 'employee :where [and [= [slot-value 'employee 'ecompanyid] [slot-value 'company 'companyid]] [= [slot-value 'company 'name] "Widgets Inc."]] :flatp t :caching nil)) (1 1 1 1 1 1 1 1 1 1)) (deftest :oodml/select/4 (mapcar #'(lambda (e) (concatenate 'string (slot-value e 'first-name) " " (slot-value e 'last-name))) (clsql:select 'employee :where [= [slot-value 'employee 'first-name] "Vladimir"] :flatp t :order-by [last-name] :caching nil)) ("Vladimir Lenin" "Vladimir Putin")) (deftest :oodml/select/5 (length (clsql:select 'employee :where [married] :flatp t :caching nil)) 3) (deftest :oodml/select/6 (let ((a (caar (clsql:select 'address :where [= 1 [addressid]] :caching nil)))) (values (slot-value a 'street-number) (slot-value a 'street-name) (slot-value a 'city) (slot-value a 'postal-code))) 10 "Park Place" "Leningrad" 123) (deftest :oodml/select/7 (let ((a (caar (clsql:select 'address :where [= 2 [addressid]] :caching nil)))) (values (slot-value a 'street-number) (slot-value a 'street-name) (slot-value a 'city) (slot-value a 'postal-code))) nil "" "no city" 0) (deftest :oodml/select/8 (mapcar #'(lambda (e) (slot-value e 'married)) (clsql:select 'employee :flatp t :order-by [emplid] :caching nil)) (t t t nil nil nil nil nil nil nil)) (deftest :oodml/select/9 (mapcar #'(lambda (pair) (list (typep (car pair) 'address) (typep (second pair) 'employee-address) (slot-value (car pair) 'addressid) (slot-value (second pair) 'aaddressid) (slot-value (second pair) 'aemplid))) (employee-addresses employee1)) ((t t 1 1 1) (t t 2 2 1))) (deftest :oodml/select/10 (mapcar #'(lambda (pair) (list (typep (car pair) 'address) (typep (second pair) 'employee-address) (slot-value (car pair) 'addressid) (slot-value (second pair) 'aaddressid) (slot-value (second pair) 'aemplid))) (employee-addresses employee2)) ((t t 2 2 2))) (deftest :oodml/select/11 (values (mapcar #'(lambda (x) (slot-value x 'emplid)) (clsql:select 'employee :order-by '(([emplid] :asc)) :flatp t)) (mapcar #'(lambda (x) (slot-value x 'emplid)) (clsql:select 'employee :order-by '(([emplid] :desc)) :flatp t))) (1 2 3 4 5 6 7 8 9 10) (10 9 8 7 6 5 4 3 2 1)) ;; test retrieval is deferred (deftest :oodm/retrieval/1 (every #'(lambda (e) (not (slot-boundp e 'company))) (select 'employee :flatp t :caching nil)) t) (deftest :oodm/retrieval/2 (every #'(lambda (e) (not (slot-boundp e 'address))) (select 'deferred-employee-address :flatp t :caching nil)) t) ;; :retrieval :immediate should be boundp before accessed (deftest :oodm/retrieval/3 (every #'(lambda (ea) (slot-boundp ea 'address)) (select 'employee-address :flatp t :caching nil)) t) (deftest :oodm/retrieval/4 (mapcar #'(lambda (ea) (typep (slot-value ea 'address) 'address)) (select 'employee-address :flatp t :caching nil)) (t t t t t)) (deftest :oodm/retrieval/5 (mapcar #'(lambda (ea) (typep (slot-value ea 'address) 'address)) (select 'deferred-employee-address :flatp t :caching nil)) (t t t t t)) (deftest :oodm/retrieval/6 (every #'(lambda (ea) (slot-boundp (slot-value ea 'address) 'addressid)) (select 'employee-address :flatp t :caching nil)) t) (deftest :oodm/retrieval/7 (every #'(lambda (ea) (slot-boundp (slot-value ea 'address) 'addressid)) (select 'deferred-employee-address :flatp t :caching nil)) t) (deftest :oodm/retrieval/8 (mapcar #'(lambda (ea) (slot-value (slot-value ea 'address) 'street-number)) (select 'employee-address :flatp t :order-by [aaddressid] :caching nil)) (10 10 nil nil nil)) (deftest :oodm/retrieval/9 (mapcar #'(lambda (ea) (slot-value (slot-value ea 'address) 'street-number)) (select 'deferred-employee-address :flatp t :order-by [aaddressid] :caching nil)) (10 10 nil nil nil)) ;; tests update-records-from-instance (deftest :oodml/update-records/1 (values (progn (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin)))) (progn (setf (slot-value employee1 'first-name) "Dimitriy" (slot-value employee1 'last-name) "Ivanovich" (slot-value employee1 'email) "") (clsql:update-records-from-instance employee1) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin)))) (progn (setf (slot-value employee1 'first-name) "Vladimir" (slot-value employee1 'last-name) "Lenin" (slot-value employee1 'email) "") (clsql:update-records-from-instance employee1) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin))))) "Vladimir Lenin: " "Dimitriy Ivanovich: " "Vladimir Lenin: ") ;; tests update-record-from-slot (deftest :oodml/update-records/2 (values (employee-email (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (progn (setf (slot-value employee1 'email) "") (clsql:update-record-from-slot employee1 'email) (employee-email (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (progn (setf (slot-value employee1 'email) "") (clsql:update-record-from-slot employee1 'email) (employee-email (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))))) "" "" "") ;; tests update-record-from-slots (deftest :oodml/update-records/3 (values (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin))) (progn (setf (slot-value employee1 'first-name) "Dimitriy" (slot-value employee1 'last-name) "Ivanovich" (slot-value employee1 'email) "") (clsql:update-record-from-slots employee1 '(first-name last-name email)) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin)))) (progn (setf (slot-value employee1 'first-name) "Vladimir" (slot-value employee1 'last-name) "Lenin" (slot-value employee1 'email) "") (clsql:update-record-from-slots employee1 '(first-name last-name email)) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin))))) "Vladimir Lenin: " "Dimitriy Ivanovich: " "Vladimir Lenin: ") ;; tests update-instance-from-records (deftest :oodml/update-instance/1 (values (concatenate 'string (slot-value employee1 'first-name) " " (slot-value employee1 'last-name) ": " (slot-value employee1 'email)) (progn (clsql:update-records [employee] :av-pairs '(([first-name] "Ivan") ([last-name] "Petrov") ([email] "")) :where [= [emplid] 1]) (clsql:update-instance-from-records employee1) (concatenate 'string (slot-value employee1 'first-name) " " (slot-value employee1 'last-name) ": " (slot-value employee1 'email))) (progn (clsql:update-records [employee] :av-pairs '(([first-name] "Vladimir") ([last-name] "Lenin") ([email] "")) :where [= [emplid] 1]) (clsql:update-instance-from-records employee1) (concatenate 'string (slot-value employee1 'first-name) " " (slot-value employee1 'last-name) ": " (slot-value employee1 'email)))) "Vladimir Lenin: " "Ivan Petrov: " "Vladimir Lenin: ") ;; tests update-slot-from-record (deftest :oodml/update-instance/2 (values (slot-value employee1 'email) (progn (clsql:update-records [employee] :av-pairs '(([email] "")) :where [= [emplid] 1]) (clsql:update-slot-from-record employee1 'email) (slot-value employee1 'email)) (progn (clsql:update-records [employee] :av-pairs '(([email] "")) :where [= [emplid] 1]) (clsql:update-slot-from-record employee1 'email) (slot-value employee1 'email))) "" "" "") (deftest :oodml/do-query/1 (let ((result '())) (clsql:do-query ((e) [select 'employee :order-by [emplid]]) (push (slot-value e 'last-name) result)) result) ("Putin" "Yeltsin" "Gorbachev" "Chernenko" "Andropov" "Brezhnev" "Kruschev" "Trotsky" "Stalin" "Lenin")) (deftest :oodml/do-query/2 (let ((result '())) (clsql:do-query ((e c) [select 'employee 'company :where [= [slot-value 'employee 'last-name] "Lenin"]]) (push (list (slot-value e 'last-name) (slot-value c 'name)) result)) result) (("Lenin" "Widgets Inc."))) (deftest :oodml/map-query/1 (clsql:map-query 'list #'last-name [select 'employee :order-by [emplid]]) ("Lenin" "Stalin" "Trotsky" "Kruschev" "Brezhnev" "Andropov" "Chernenko" "Gorbachev" "Yeltsin" "Putin")) (deftest :oodml/map-query/2 (clsql:map-query 'list #'(lambda (e c) (list (slot-value e 'last-name) (slot-value c 'name))) [select 'employee 'company :where [= [slot-value 'employee 'last-name] "Lenin"]]) (("Lenin" "Widgets Inc."))) (deftest :oodml/iteration/3 (loop for (e) being the records in [select 'employee :where [< [emplid] 4] :order-by [emplid]] collect (slot-value e 'last-name)) ("Lenin" "Stalin" "Trotsky")) (deftest :oodml/cache/1 (progn (setf (clsql-sys:record-caches *default-database*) nil) (let ((employees (select 'employee))) (every #'(lambda (a b) (eq a b)) employees (select 'employee)))) t) (deftest :oodml/cache/2 (let ((employees (select 'employee))) (equal employees (select 'employee :flatp t))) nil) (deftest :oodml/refresh/1 (let ((addresses (select 'address))) (equal addresses (select 'address :refresh t))) t) (deftest :oodml/refresh/2 (let* ((addresses (select 'address :order-by [addressid] :flatp t :refresh t)) (city (slot-value (car addresses) 'city))) (clsql:update-records [addr] :av-pairs '((city_field "A new city")) :where [= [addressid] (slot-value (car addresses) 'addressid)]) (let* ((new-addresses (select 'address :order-by [addressid] :refresh t :flatp t)) (new-city (slot-value (car addresses) 'city)) ) (clsql:update-records [addr] :av-pairs `((city_field ,city)) :where [= [addressid] (slot-value (car addresses) 'addressid)]) (values (equal addresses new-addresses) city new-city))) t "Leningrad" "A new city") (deftest :oodml/refresh/3 (let* ((addresses (select 'address :order-by [addressid] :flatp t))) (values (equal addresses (select 'address :refresh t :flatp t)) (equal addresses (select 'address :flatp t)))) nil nil) (deftest :oodml/refresh/4 (let* ((addresses (select 'address :order-by [addressid] :flatp t :refresh t)) (*db-auto-sync* t)) (make-instance 'address :addressid 1000 :city "A new address city") (let ((new-addresses (select 'address :order-by [addressid] :flatp t :refresh t))) (delete-records :from [addr] :where [= [addressid] 1000]) (values (length addresses) (length new-addresses) (eq (first addresses) (first new-addresses)) (eq (second addresses) (second new-addresses))))) 2 3 t t) (deftest :oodml/uoj/1 (progn (let* ((dea-list (select 'deferred-employee-address :caching nil :order-by ["ea_join" aaddressid] :flatp t)) (dea-list-copy (copy-seq dea-list)) (initially-unbound (every #'(lambda (dea) (not (slot-boundp dea 'address))) dea-list))) (update-objects-joins dea-list) (values initially-unbound (equal dea-list dea-list-copy) (every #'(lambda (dea) (slot-boundp dea 'address)) dea-list) (every #'(lambda (dea) (typep (slot-value dea 'address) 'address)) dea-list) (mapcar #'(lambda (dea) (slot-value (slot-value dea 'address) 'addressid)) dea-list)))) t t t t (1 1 2 2 2)) ;; update-object-joins needs to be fixed for multiple keys #+ignore (deftest :oodml/uoj/2 (progn (clsql:update-objects-joins (list company1)) (mapcar #'(lambda (e) (slot-value e 'ecompanyid)) (company-employees company1))) (1 1 1 1 1 1 1 1 1 1)) (deftest :oodml/big/1 (let ((objs (clsql:select 'big :order-by [i] :flatp t))) (values (length objs) (do ((i 0 (1+ i)) (max (expt 2 60)) (rest objs (cdr rest))) ((= i (length objs)) t) (let ((obj (car rest)) (index (1+ i))) (unless (and (eql (slot-value obj 'i) index) (eql (slot-value obj 'bi) (truncate max index))) (print index) (describe obj) (return nil)))))) 555 t) (deftest :oodml/db-auto-sync/1 (values (progn (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich") (select [last-name] :from [employee] :where [= [emplid] 20] :flatp t :field-names nil)) (let ((*db-auto-sync* t)) (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich") (prog1 (select [last-name] :from [employee] :flatp t :field-names nil :where [= [emplid] 20]) (delete-records :from [employee] :where [= [emplid] 20])))) nil ("Ivanovich")) (deftest :oodml/db-auto-sync/2 (values (let ((instance (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich"))) (setf (slot-value instance 'last-name) "Bulgakov") (select [last-name] :from [employee] :where [= [emplid] 20] :flatp t :field-names nil)) (let* ((*db-auto-sync* t) (instance (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich"))) (setf (slot-value instance 'last-name) "Bulgakov") (prog1 (select [last-name] :from [employee] :flatp t :field-names nil :where [= [emplid] 20]) (delete-records :from [employee] :where [= [emplid] 20])))) nil ("Bulgakov")) (deftest :oodml/setf-slot-value/1 (let* ((*db-auto-sync* t) (instance (make-instance 'employee :emplid 20 :groupid 1))) (prog1 (setf (slot-value instance 'first-name) "Mikhail" (slot-value instance 'last-name) "Bulgakov") (delete-records :from [employee] :where [= [emplid] 20]))) "Bulgakov") (deftest :oodml/float/1 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0E0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/2 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0S0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/3 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0F0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/4 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0D0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/5 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0L0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) )) #.(clsql:restore-sql-reader-syntax-state)
null
https://raw.githubusercontent.com/ryszard/clsql/9aafcb72bd7ca1d7e908938b6a5319753b3371d9/tests/test-oodml.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 -*- ====================================================================== Created: 01/04/2004 Updated: $Id$ Tests for the CLSQL Object Oriented Data Definition Language (OODML). (), also known as the LLGPL. ====================================================================== test retrieval is deferred :retrieval :immediate should be boundp before accessed tests update-records-from-instance tests update-record-from-slot tests update-record-from-slots tests update-instance-from-records tests update-slot-from-record update-object-joins needs to be fixed for multiple keys
File : Author : < > This file is part of CLSQL . CLSQL users are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License (in-package #:clsql-tests) #.(clsql:locally-enable-sql-reader-syntax) (setq *rt-oodml* '( (deftest :oodml/select/1 (mapcar #'(lambda (e) (slot-value e 'last-name)) (clsql:select 'employee :order-by [last-name] :flatp t :caching nil)) ("Andropov" "Brezhnev" "Chernenko" "Gorbachev" "Kruschev" "Lenin" "Putin" "Stalin" "Trotsky" "Yeltsin")) (deftest :oodml/select/2 (mapcar #'(lambda (e) (slot-value e 'name)) (clsql:select 'company :flatp t :caching nil)) ("Widgets Inc.")) (deftest :oodml/select/3 (mapcar #'(lambda (e) (slot-value e 'ecompanyid)) (clsql:select 'employee :where [and [= [slot-value 'employee 'ecompanyid] [slot-value 'company 'companyid]] [= [slot-value 'company 'name] "Widgets Inc."]] :flatp t :caching nil)) (1 1 1 1 1 1 1 1 1 1)) (deftest :oodml/select/4 (mapcar #'(lambda (e) (concatenate 'string (slot-value e 'first-name) " " (slot-value e 'last-name))) (clsql:select 'employee :where [= [slot-value 'employee 'first-name] "Vladimir"] :flatp t :order-by [last-name] :caching nil)) ("Vladimir Lenin" "Vladimir Putin")) (deftest :oodml/select/5 (length (clsql:select 'employee :where [married] :flatp t :caching nil)) 3) (deftest :oodml/select/6 (let ((a (caar (clsql:select 'address :where [= 1 [addressid]] :caching nil)))) (values (slot-value a 'street-number) (slot-value a 'street-name) (slot-value a 'city) (slot-value a 'postal-code))) 10 "Park Place" "Leningrad" 123) (deftest :oodml/select/7 (let ((a (caar (clsql:select 'address :where [= 2 [addressid]] :caching nil)))) (values (slot-value a 'street-number) (slot-value a 'street-name) (slot-value a 'city) (slot-value a 'postal-code))) nil "" "no city" 0) (deftest :oodml/select/8 (mapcar #'(lambda (e) (slot-value e 'married)) (clsql:select 'employee :flatp t :order-by [emplid] :caching nil)) (t t t nil nil nil nil nil nil nil)) (deftest :oodml/select/9 (mapcar #'(lambda (pair) (list (typep (car pair) 'address) (typep (second pair) 'employee-address) (slot-value (car pair) 'addressid) (slot-value (second pair) 'aaddressid) (slot-value (second pair) 'aemplid))) (employee-addresses employee1)) ((t t 1 1 1) (t t 2 2 1))) (deftest :oodml/select/10 (mapcar #'(lambda (pair) (list (typep (car pair) 'address) (typep (second pair) 'employee-address) (slot-value (car pair) 'addressid) (slot-value (second pair) 'aaddressid) (slot-value (second pair) 'aemplid))) (employee-addresses employee2)) ((t t 2 2 2))) (deftest :oodml/select/11 (values (mapcar #'(lambda (x) (slot-value x 'emplid)) (clsql:select 'employee :order-by '(([emplid] :asc)) :flatp t)) (mapcar #'(lambda (x) (slot-value x 'emplid)) (clsql:select 'employee :order-by '(([emplid] :desc)) :flatp t))) (1 2 3 4 5 6 7 8 9 10) (10 9 8 7 6 5 4 3 2 1)) (deftest :oodm/retrieval/1 (every #'(lambda (e) (not (slot-boundp e 'company))) (select 'employee :flatp t :caching nil)) t) (deftest :oodm/retrieval/2 (every #'(lambda (e) (not (slot-boundp e 'address))) (select 'deferred-employee-address :flatp t :caching nil)) t) (deftest :oodm/retrieval/3 (every #'(lambda (ea) (slot-boundp ea 'address)) (select 'employee-address :flatp t :caching nil)) t) (deftest :oodm/retrieval/4 (mapcar #'(lambda (ea) (typep (slot-value ea 'address) 'address)) (select 'employee-address :flatp t :caching nil)) (t t t t t)) (deftest :oodm/retrieval/5 (mapcar #'(lambda (ea) (typep (slot-value ea 'address) 'address)) (select 'deferred-employee-address :flatp t :caching nil)) (t t t t t)) (deftest :oodm/retrieval/6 (every #'(lambda (ea) (slot-boundp (slot-value ea 'address) 'addressid)) (select 'employee-address :flatp t :caching nil)) t) (deftest :oodm/retrieval/7 (every #'(lambda (ea) (slot-boundp (slot-value ea 'address) 'addressid)) (select 'deferred-employee-address :flatp t :caching nil)) t) (deftest :oodm/retrieval/8 (mapcar #'(lambda (ea) (slot-value (slot-value ea 'address) 'street-number)) (select 'employee-address :flatp t :order-by [aaddressid] :caching nil)) (10 10 nil nil nil)) (deftest :oodm/retrieval/9 (mapcar #'(lambda (ea) (slot-value (slot-value ea 'address) 'street-number)) (select 'deferred-employee-address :flatp t :order-by [aaddressid] :caching nil)) (10 10 nil nil nil)) (deftest :oodml/update-records/1 (values (progn (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin)))) (progn (setf (slot-value employee1 'first-name) "Dimitriy" (slot-value employee1 'last-name) "Ivanovich" (slot-value employee1 'email) "") (clsql:update-records-from-instance employee1) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin)))) (progn (setf (slot-value employee1 'first-name) "Vladimir" (slot-value employee1 'last-name) "Lenin" (slot-value employee1 'email) "") (clsql:update-records-from-instance employee1) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin))))) "Vladimir Lenin: " "Dimitriy Ivanovich: " "Vladimir Lenin: ") (deftest :oodml/update-records/2 (values (employee-email (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (progn (setf (slot-value employee1 'email) "") (clsql:update-record-from-slot employee1 'email) (employee-email (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (progn (setf (slot-value employee1 'email) "") (clsql:update-record-from-slot employee1 'email) (employee-email (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))))) "" "" "") (deftest :oodml/update-records/3 (values (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin))) (progn (setf (slot-value employee1 'first-name) "Dimitriy" (slot-value employee1 'last-name) "Ivanovich" (slot-value employee1 'email) "") (clsql:update-record-from-slots employee1 '(first-name last-name email)) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin)))) (progn (setf (slot-value employee1 'first-name) "Vladimir" (slot-value employee1 'last-name) "Lenin" (slot-value employee1 'email) "") (clsql:update-record-from-slots employee1 '(first-name last-name email)) (let ((lenin (car (clsql:select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil)))) (concatenate 'string (first-name lenin) " " (last-name lenin) ": " (employee-email lenin))))) "Vladimir Lenin: " "Dimitriy Ivanovich: " "Vladimir Lenin: ") (deftest :oodml/update-instance/1 (values (concatenate 'string (slot-value employee1 'first-name) " " (slot-value employee1 'last-name) ": " (slot-value employee1 'email)) (progn (clsql:update-records [employee] :av-pairs '(([first-name] "Ivan") ([last-name] "Petrov") ([email] "")) :where [= [emplid] 1]) (clsql:update-instance-from-records employee1) (concatenate 'string (slot-value employee1 'first-name) " " (slot-value employee1 'last-name) ": " (slot-value employee1 'email))) (progn (clsql:update-records [employee] :av-pairs '(([first-name] "Vladimir") ([last-name] "Lenin") ([email] "")) :where [= [emplid] 1]) (clsql:update-instance-from-records employee1) (concatenate 'string (slot-value employee1 'first-name) " " (slot-value employee1 'last-name) ": " (slot-value employee1 'email)))) "Vladimir Lenin: " "Ivan Petrov: " "Vladimir Lenin: ") (deftest :oodml/update-instance/2 (values (slot-value employee1 'email) (progn (clsql:update-records [employee] :av-pairs '(([email] "")) :where [= [emplid] 1]) (clsql:update-slot-from-record employee1 'email) (slot-value employee1 'email)) (progn (clsql:update-records [employee] :av-pairs '(([email] "")) :where [= [emplid] 1]) (clsql:update-slot-from-record employee1 'email) (slot-value employee1 'email))) "" "" "") (deftest :oodml/do-query/1 (let ((result '())) (clsql:do-query ((e) [select 'employee :order-by [emplid]]) (push (slot-value e 'last-name) result)) result) ("Putin" "Yeltsin" "Gorbachev" "Chernenko" "Andropov" "Brezhnev" "Kruschev" "Trotsky" "Stalin" "Lenin")) (deftest :oodml/do-query/2 (let ((result '())) (clsql:do-query ((e c) [select 'employee 'company :where [= [slot-value 'employee 'last-name] "Lenin"]]) (push (list (slot-value e 'last-name) (slot-value c 'name)) result)) result) (("Lenin" "Widgets Inc."))) (deftest :oodml/map-query/1 (clsql:map-query 'list #'last-name [select 'employee :order-by [emplid]]) ("Lenin" "Stalin" "Trotsky" "Kruschev" "Brezhnev" "Andropov" "Chernenko" "Gorbachev" "Yeltsin" "Putin")) (deftest :oodml/map-query/2 (clsql:map-query 'list #'(lambda (e c) (list (slot-value e 'last-name) (slot-value c 'name))) [select 'employee 'company :where [= [slot-value 'employee 'last-name] "Lenin"]]) (("Lenin" "Widgets Inc."))) (deftest :oodml/iteration/3 (loop for (e) being the records in [select 'employee :where [< [emplid] 4] :order-by [emplid]] collect (slot-value e 'last-name)) ("Lenin" "Stalin" "Trotsky")) (deftest :oodml/cache/1 (progn (setf (clsql-sys:record-caches *default-database*) nil) (let ((employees (select 'employee))) (every #'(lambda (a b) (eq a b)) employees (select 'employee)))) t) (deftest :oodml/cache/2 (let ((employees (select 'employee))) (equal employees (select 'employee :flatp t))) nil) (deftest :oodml/refresh/1 (let ((addresses (select 'address))) (equal addresses (select 'address :refresh t))) t) (deftest :oodml/refresh/2 (let* ((addresses (select 'address :order-by [addressid] :flatp t :refresh t)) (city (slot-value (car addresses) 'city))) (clsql:update-records [addr] :av-pairs '((city_field "A new city")) :where [= [addressid] (slot-value (car addresses) 'addressid)]) (let* ((new-addresses (select 'address :order-by [addressid] :refresh t :flatp t)) (new-city (slot-value (car addresses) 'city)) ) (clsql:update-records [addr] :av-pairs `((city_field ,city)) :where [= [addressid] (slot-value (car addresses) 'addressid)]) (values (equal addresses new-addresses) city new-city))) t "Leningrad" "A new city") (deftest :oodml/refresh/3 (let* ((addresses (select 'address :order-by [addressid] :flatp t))) (values (equal addresses (select 'address :refresh t :flatp t)) (equal addresses (select 'address :flatp t)))) nil nil) (deftest :oodml/refresh/4 (let* ((addresses (select 'address :order-by [addressid] :flatp t :refresh t)) (*db-auto-sync* t)) (make-instance 'address :addressid 1000 :city "A new address city") (let ((new-addresses (select 'address :order-by [addressid] :flatp t :refresh t))) (delete-records :from [addr] :where [= [addressid] 1000]) (values (length addresses) (length new-addresses) (eq (first addresses) (first new-addresses)) (eq (second addresses) (second new-addresses))))) 2 3 t t) (deftest :oodml/uoj/1 (progn (let* ((dea-list (select 'deferred-employee-address :caching nil :order-by ["ea_join" aaddressid] :flatp t)) (dea-list-copy (copy-seq dea-list)) (initially-unbound (every #'(lambda (dea) (not (slot-boundp dea 'address))) dea-list))) (update-objects-joins dea-list) (values initially-unbound (equal dea-list dea-list-copy) (every #'(lambda (dea) (slot-boundp dea 'address)) dea-list) (every #'(lambda (dea) (typep (slot-value dea 'address) 'address)) dea-list) (mapcar #'(lambda (dea) (slot-value (slot-value dea 'address) 'addressid)) dea-list)))) t t t t (1 1 2 2 2)) #+ignore (deftest :oodml/uoj/2 (progn (clsql:update-objects-joins (list company1)) (mapcar #'(lambda (e) (slot-value e 'ecompanyid)) (company-employees company1))) (1 1 1 1 1 1 1 1 1 1)) (deftest :oodml/big/1 (let ((objs (clsql:select 'big :order-by [i] :flatp t))) (values (length objs) (do ((i 0 (1+ i)) (max (expt 2 60)) (rest objs (cdr rest))) ((= i (length objs)) t) (let ((obj (car rest)) (index (1+ i))) (unless (and (eql (slot-value obj 'i) index) (eql (slot-value obj 'bi) (truncate max index))) (print index) (describe obj) (return nil)))))) 555 t) (deftest :oodml/db-auto-sync/1 (values (progn (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich") (select [last-name] :from [employee] :where [= [emplid] 20] :flatp t :field-names nil)) (let ((*db-auto-sync* t)) (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich") (prog1 (select [last-name] :from [employee] :flatp t :field-names nil :where [= [emplid] 20]) (delete-records :from [employee] :where [= [emplid] 20])))) nil ("Ivanovich")) (deftest :oodml/db-auto-sync/2 (values (let ((instance (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich"))) (setf (slot-value instance 'last-name) "Bulgakov") (select [last-name] :from [employee] :where [= [emplid] 20] :flatp t :field-names nil)) (let* ((*db-auto-sync* t) (instance (make-instance 'employee :emplid 20 :groupid 1 :last-name "Ivanovich"))) (setf (slot-value instance 'last-name) "Bulgakov") (prog1 (select [last-name] :from [employee] :flatp t :field-names nil :where [= [emplid] 20]) (delete-records :from [employee] :where [= [emplid] 20])))) nil ("Bulgakov")) (deftest :oodml/setf-slot-value/1 (let* ((*db-auto-sync* t) (instance (make-instance 'employee :emplid 20 :groupid 1))) (prog1 (setf (slot-value instance 'first-name) "Mikhail" (slot-value instance 'last-name) "Bulgakov") (delete-records :from [employee] :where [= [emplid] 20]))) "Bulgakov") (deftest :oodml/float/1 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0E0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/2 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0S0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/3 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0F0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/4 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0D0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) (deftest :oodml/float/5 (let* ((emp1 (car (select 'employee :where [= [slot-value 'employee 'emplid] 1] :flatp t :caching nil))) (height (slot-value emp1 'height))) (prog1 (progn (setf (slot-value emp1 'height) 1.0L0) (clsql:update-record-from-slot emp1 'height) (= (car (clsql:select [height] :from [employee] :where [= [emplid] 1] :flatp t :field-names nil)) 1)) (setf (slot-value emp1 'height) height) (clsql:update-record-from-slot emp1 'height))) t) )) #.(clsql:restore-sql-reader-syntax-state)
d90bc0cc1d85ee9e24b9fbb60de1b08c3f3b2d7db978feef7dd3cb3ab29e0df0
kana-sama/sicp
1.40 - cubic equation.scm
(load "1/1.35 - search golden ratio by fixed point.scm") (define dx 0.0001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (newton-transform g) (let ((g* (deriv g))) (lambda (x) (- x (/ (g x) (g* x)))))) (define (newtons-method g guess) (fixed-point (newton-transform g) guess)) y = ax^3 + bx^2 + cx + d (define (cubic a b c d) (lambda (x) (+ (* a (cube x)) (* b (square x)) (* c x) d))) (print (newtons-method (cubic 1 5 10 150) 1.0))
null
https://raw.githubusercontent.com/kana-sama/sicp/fc637d4b057cfcae1bae3d72ebc08e1af52e619d/1/1.40%20-%20cubic%20equation.scm
scheme
(load "1/1.35 - search golden ratio by fixed point.scm") (define dx 0.0001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (newton-transform g) (let ((g* (deriv g))) (lambda (x) (- x (/ (g x) (g* x)))))) (define (newtons-method g guess) (fixed-point (newton-transform g) guess)) y = ax^3 + bx^2 + cx + d (define (cubic a b c d) (lambda (x) (+ (* a (cube x)) (* b (square x)) (* c x) d))) (print (newtons-method (cubic 1 5 10 150) 1.0))
52a7b51f85cdfd98e418c08e4d7a8924a7d36062342a17175b36e06d1d9ae14f
MinaProtocol/mina
impls.mli
open Pickles_types module Wrap_impl : module type of Snarky_backendless.Snark.Run.Make (Backend.Tock) module Step : sig module Impl : module type of Snarky_backendless.Snark.Run.Make (Backend.Tick) include module type of Impl module Verification_key = Backend.Tick.Verification_key module Proving_key = Backend.Tick.Proving_key module Digest : module type of Import.Digest.Make (Impl) module Challenge : module type of Import.Challenge.Make (Impl) module Keypair : sig type t = { pk : Proving_key.t; vk : Verification_key.t } [@@deriving fields] val create : pk:Proving_key.t -> vk:Verification_key.t -> t val generate : prev_challenges:int -> Kimchi_pasta_constraint_system.Vesta_constraint_system.t -> t end module Other_field : sig type t = Field.t * Boolean.var module Constant = Backend.Tock.Field val typ_unchecked : (t, Constant.t) Typ.t val typ : (t, Constant.t, Internal_Basic.field) Snarky_backendless.Typ.t end val input : proofs_verified:'a Pickles_types.Nat.t -> wrap_rounds:'b Pickles_types.Nat.t -> feature_flags:Plonk_types.Opt.Flag.t Plonk_types.Features.t -> ( ( ( ( Impl.Field.t , Impl.Field.t Composition_types.Scalar_challenge.t , Other_field.t Pickles_types.Shifted_value.Type2.t , ( Other_field.t Pickles_types.Shifted_value.Type2.t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , ( Impl.Field.t Composition_types.Scalar_challenge.t Pickles_types.Hlist0.Id.t Composition_types.Step.Proof_state.Deferred_values.Plonk .In_circuit .Lookup .t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , ( Impl.field Snarky_backendless.Cvar.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , 'b ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , Impl.field Snarky_backendless.Cvar.t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Composition_types.Step.Proof_state.Per_proof.In_circuit.t , 'a ) Pickles_types.Vector.t , Impl.field Snarky_backendless.Cvar.t Pickles_types.Hlist0.Id.t , (Impl.field Snarky_backendless.Cvar.t, 'a) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t ) Import.Types.Step.Statement.t , ( ( ( Challenge.Constant.t , Challenge.Constant.t Composition_types.Scalar_challenge.t , Other_field.Constant.t Pickles_types.Shifted_value.Type2.t , Other_field.Constant.t Pickles_types.Shifted_value.Type2.t option , Challenge.Constant.t Composition_types.Scalar_challenge.t Composition_types.Step.Proof_state.Deferred_values.Plonk .In_circuit .Lookup .t option , ( Limb_vector.Challenge.Constant.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , 'b ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , bool ) Composition_types.Step.Proof_state.Per_proof.In_circuit.t , 'a ) Pickles_types.Vector.t , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec Pickles_types.Hlist0.Id.t , ( ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , 'a ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t ) Import.Types.Step.Statement.t , Impl.field ) Import.Spec.ETyp.t end module Wrap : sig module Impl : module type of Snarky_backendless.Snark.Run.Make (Backend.Tock) include module type of Impl module Challenge : module type of Import.Challenge.Make (Impl) module Digest : module type of Import.Digest.Make (Impl) module Wrap_field = Backend.Tock.Field module Step_field = Backend.Tick.Field module Verification_key = Backend.Tock.Verification_key module Proving_key = Backend.Tock.Proving_key module Keypair : sig type t = { pk : Proving_key.t; vk : Verification_key.t } [@@deriving fields] val create : pk:Proving_key.t -> vk:Verification_key.t -> t val generate : prev_challenges:int -> Kimchi_pasta_constraint_system.Pallas_constraint_system.t -> t end module Other_field : sig type t = Field.t module Constant = Backend.Tick.Field val typ_unchecked : (Impl.Field.t, Backend.Tick.Field.t) Impl.Typ.t val typ : ( Impl.Field.t , Backend.Tick.Field.t , Wrap_impl.Internal_Basic.Field.t ) Snarky_backendless.Typ.t end val input : unit -> ( ( Impl.Field.t , Impl.Field.t Composition_types.Scalar_challenge.t , Impl.Field.t Pickles_types.Shifted_value.Type1.t , ( Impl.Field.t Pickles_types.Shifted_value.Type1.t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , ( Impl.Field.t Composition_types.Scalar_challenge.t Composition_types.Wrap.Proof_state.Deferred_values.Plonk.In_circuit .Lookup .t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , Impl.Boolean.var , Impl.field Snarky_backendless.Cvar.t , Impl.field Snarky_backendless.Cvar.t , Impl.field Snarky_backendless.Cvar.t , ( Impl.field Snarky_backendless.Cvar.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , Pickles_types.Nat.z Backend.Tick.Rounds.plus_n ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , Impl.field Snarky_backendless.Cvar.t ) Import.Types.Wrap.Statement.In_circuit.t , ( Limb_vector.Challenge.Constant.t , Limb_vector.Challenge.Constant.t Composition_types.Scalar_challenge.t , Other_field.Constant.t Pickles_types.Shifted_value.Type1.t , Other_field.Constant.t Pickles_types.Shifted_value.Type1.t option , Limb_vector.Challenge.Constant.t Composition_types.Scalar_challenge.t Composition_types.Wrap.Proof_state.Deferred_values.Plonk.In_circuit .Lookup .t option , bool , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , ( Limb_vector.Challenge.Constant.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , Pickles_types.Nat.z Backend.Tick.Rounds.plus_n ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , Composition_types.Branch_data.t ) Import.Types.Wrap.Statement.In_circuit.t , Wrap_impl.field ) Import.Spec.ETyp.t end
null
https://raw.githubusercontent.com/MinaProtocol/mina/8403887a428f56e91bfdf4187c6b8dc260e5424a/src/lib/pickles/impls.mli
ocaml
open Pickles_types module Wrap_impl : module type of Snarky_backendless.Snark.Run.Make (Backend.Tock) module Step : sig module Impl : module type of Snarky_backendless.Snark.Run.Make (Backend.Tick) include module type of Impl module Verification_key = Backend.Tick.Verification_key module Proving_key = Backend.Tick.Proving_key module Digest : module type of Import.Digest.Make (Impl) module Challenge : module type of Import.Challenge.Make (Impl) module Keypair : sig type t = { pk : Proving_key.t; vk : Verification_key.t } [@@deriving fields] val create : pk:Proving_key.t -> vk:Verification_key.t -> t val generate : prev_challenges:int -> Kimchi_pasta_constraint_system.Vesta_constraint_system.t -> t end module Other_field : sig type t = Field.t * Boolean.var module Constant = Backend.Tock.Field val typ_unchecked : (t, Constant.t) Typ.t val typ : (t, Constant.t, Internal_Basic.field) Snarky_backendless.Typ.t end val input : proofs_verified:'a Pickles_types.Nat.t -> wrap_rounds:'b Pickles_types.Nat.t -> feature_flags:Plonk_types.Opt.Flag.t Plonk_types.Features.t -> ( ( ( ( Impl.Field.t , Impl.Field.t Composition_types.Scalar_challenge.t , Other_field.t Pickles_types.Shifted_value.Type2.t , ( Other_field.t Pickles_types.Shifted_value.Type2.t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , ( Impl.Field.t Composition_types.Scalar_challenge.t Pickles_types.Hlist0.Id.t Composition_types.Step.Proof_state.Deferred_values.Plonk .In_circuit .Lookup .t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , ( Impl.field Snarky_backendless.Cvar.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , 'b ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , Impl.field Snarky_backendless.Cvar.t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Composition_types.Step.Proof_state.Per_proof.In_circuit.t , 'a ) Pickles_types.Vector.t , Impl.field Snarky_backendless.Cvar.t Pickles_types.Hlist0.Id.t , (Impl.field Snarky_backendless.Cvar.t, 'a) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t ) Import.Types.Step.Statement.t , ( ( ( Challenge.Constant.t , Challenge.Constant.t Composition_types.Scalar_challenge.t , Other_field.Constant.t Pickles_types.Shifted_value.Type2.t , Other_field.Constant.t Pickles_types.Shifted_value.Type2.t option , Challenge.Constant.t Composition_types.Scalar_challenge.t Composition_types.Step.Proof_state.Deferred_values.Plonk .In_circuit .Lookup .t option , ( Limb_vector.Challenge.Constant.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , 'b ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , bool ) Composition_types.Step.Proof_state.Per_proof.In_circuit.t , 'a ) Pickles_types.Vector.t , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec Pickles_types.Hlist0.Id.t , ( ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , 'a ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t ) Import.Types.Step.Statement.t , Impl.field ) Import.Spec.ETyp.t end module Wrap : sig module Impl : module type of Snarky_backendless.Snark.Run.Make (Backend.Tock) include module type of Impl module Challenge : module type of Import.Challenge.Make (Impl) module Digest : module type of Import.Digest.Make (Impl) module Wrap_field = Backend.Tock.Field module Step_field = Backend.Tick.Field module Verification_key = Backend.Tock.Verification_key module Proving_key = Backend.Tock.Proving_key module Keypair : sig type t = { pk : Proving_key.t; vk : Verification_key.t } [@@deriving fields] val create : pk:Proving_key.t -> vk:Verification_key.t -> t val generate : prev_challenges:int -> Kimchi_pasta_constraint_system.Pallas_constraint_system.t -> t end module Other_field : sig type t = Field.t module Constant = Backend.Tick.Field val typ_unchecked : (Impl.Field.t, Backend.Tick.Field.t) Impl.Typ.t val typ : ( Impl.Field.t , Backend.Tick.Field.t , Wrap_impl.Internal_Basic.Field.t ) Snarky_backendless.Typ.t end val input : unit -> ( ( Impl.Field.t , Impl.Field.t Composition_types.Scalar_challenge.t , Impl.Field.t Pickles_types.Shifted_value.Type1.t , ( Impl.Field.t Pickles_types.Shifted_value.Type1.t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , ( Impl.Field.t Composition_types.Scalar_challenge.t Composition_types.Wrap.Proof_state.Deferred_values.Plonk.In_circuit .Lookup .t , Impl.field Snarky_backendless.Cvar.t Snarky_backendless.Snark_intf.Boolean0.t ) Pickles_types.Plonk_types.Opt.t , Impl.Boolean.var , Impl.field Snarky_backendless.Cvar.t , Impl.field Snarky_backendless.Cvar.t , Impl.field Snarky_backendless.Cvar.t , ( Impl.field Snarky_backendless.Cvar.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , Pickles_types.Nat.z Backend.Tick.Rounds.plus_n ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , Impl.field Snarky_backendless.Cvar.t ) Import.Types.Wrap.Statement.In_circuit.t , ( Limb_vector.Challenge.Constant.t , Limb_vector.Challenge.Constant.t Composition_types.Scalar_challenge.t , Other_field.Constant.t Pickles_types.Shifted_value.Type1.t , Other_field.Constant.t Pickles_types.Shifted_value.Type1.t option , Limb_vector.Challenge.Constant.t Composition_types.Scalar_challenge.t Composition_types.Wrap.Proof_state.Deferred_values.Plonk.In_circuit .Lookup .t option , bool , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , ( Limb_vector.Constant.Hex64.t , Composition_types.Digest.Limbs.n ) Pickles_types.Vector.vec , ( Limb_vector.Challenge.Constant.t Kimchi_backend_common.Scalar_challenge.t Composition_types.Bulletproof_challenge.t , Pickles_types.Nat.z Backend.Tick.Rounds.plus_n ) Pickles_types.Vector.t Pickles_types.Hlist0.Id.t , Composition_types.Branch_data.t ) Import.Types.Wrap.Statement.In_circuit.t , Wrap_impl.field ) Import.Spec.ETyp.t end
775ca1835e130f6186ee557408da419bc07f0d23fbaf13e482cdb484b83cc64e
klarna-incubator/system_monitor
system_monitor_sup.erl
%%-------------------------------------------------------------------------------- %% Copyright 2020 Klarna Bank AB %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------------------- -module(system_monitor_sup). TODO : does n't like this one : %-behaviour(supervisor3). %% External exports -export([start_link/0]). %% supervisor callbacks -export([init/1, post_init/1]). %%-------------------------------------------------------------------- Macros %%-------------------------------------------------------------------- -define(SERVER, ?MODULE). -define(SUP2, system_monitor2_sup). %%%---------------------------------------------------------------------- %%% API %%%---------------------------------------------------------------------- start_link() -> supervisor3:start_link({local, ?SERVER}, ?MODULE, ?SERVER). %%%---------------------------------------------------------------------- %%% Callback functions from supervisor %%%---------------------------------------------------------------------- server(Name, Type) -> server(Name, Type, 2000). server(Name, Type, Shutdown) -> {Name, {Name, start_link, []}, {permanent, 15}, Shutdown, Type, [Name]}. worker(Name) -> server(Name, worker). post_init(_) -> ignore. init(?SERVER) -> %% The top level supervisor *does not allow restarts*; if a component %% directly under this supervisor crashes, the entire node will shut %% down and restart. Thus, only those components that must never be %% unavailable should be directly under this supervisor. SecondSup = {?SUP2, {supervisor3, start_link, [{local, ?SUP2}, ?MODULE, ?SUP2]}, permanent, 2000, supervisor, [?MODULE]}, {ok, {{one_for_one,0,1}, % no restarts allowed! [SecondSup] }}; init(?SUP2) -> The second - level supervisor allows some restarts . This is where the %% normal services live. {ok, {{one_for_one, 10, 20}, [ worker(system_monitor_top) , worker(system_monitor_events) , worker(system_monitor) ] ++ producer_callback() }}. producer_callback() -> case system_monitor_callback:get_callback_mod() of undefined -> []; Mod -> [worker(Mod)] end.
null
https://raw.githubusercontent.com/klarna-incubator/system_monitor/8c323a005417159b124f462e8722a7ea664a3b18/src/system_monitor_sup.erl
erlang
-------------------------------------------------------------------------------- Copyright 2020 Klarna Bank AB 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. -------------------------------------------------------------------------------- -behaviour(supervisor3). External exports supervisor callbacks -------------------------------------------------------------------- -------------------------------------------------------------------- ---------------------------------------------------------------------- API ---------------------------------------------------------------------- ---------------------------------------------------------------------- Callback functions from supervisor ---------------------------------------------------------------------- The top level supervisor *does not allow restarts*; if a component directly under this supervisor crashes, the entire node will shut down and restart. Thus, only those components that must never be unavailable should be directly under this supervisor. no restarts allowed! normal services live.
Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(system_monitor_sup). TODO : does n't like this one : -export([start_link/0]). -export([init/1, post_init/1]). Macros -define(SERVER, ?MODULE). -define(SUP2, system_monitor2_sup). start_link() -> supervisor3:start_link({local, ?SERVER}, ?MODULE, ?SERVER). server(Name, Type) -> server(Name, Type, 2000). server(Name, Type, Shutdown) -> {Name, {Name, start_link, []}, {permanent, 15}, Shutdown, Type, [Name]}. worker(Name) -> server(Name, worker). post_init(_) -> ignore. init(?SERVER) -> SecondSup = {?SUP2, {supervisor3, start_link, [{local, ?SUP2}, ?MODULE, ?SUP2]}, permanent, 2000, supervisor, [?MODULE]}, [SecondSup] }}; init(?SUP2) -> The second - level supervisor allows some restarts . This is where the {ok, {{one_for_one, 10, 20}, [ worker(system_monitor_top) , worker(system_monitor_events) , worker(system_monitor) ] ++ producer_callback() }}. producer_callback() -> case system_monitor_callback:get_callback_mod() of undefined -> []; Mod -> [worker(Mod)] end.
0e3b04bec2386e369263b17bddb76cb9322e42a6cdeda04702f3d18bfb04e00e
clojureverse/clojurians-log-app
datomic.clj
(ns clojurians-log.datomic (:require [com.stuartsierra.component :as component] [datomic.client.api :as d])) (def cloud? true) (defrecord Datomic [config client conn] component/Lifecycle (start [component] (let [client (d/client config) db (d/create-database client {:db-name (:db-name config)}) conn (d/connect client {:db-name (:db-name config)})] (assoc component :conn conn))) (stop [component] (assoc component :conn nil :client nil))) (defn new-datomic-db [config] (map->Datomic {:config (:cloud config)})) (def create-database d/create-database) (def connect d/connect) (def db d/db) (def q d/q) (def transact (fn [conn data] (future (d/transact conn {:tx-data data})))) (def transact-async transact)
null
https://raw.githubusercontent.com/clojureverse/clojurians-log-app/d34c9bd715e492c8f1899653548716d32c623fad/profiles/datomic_cloud/clojurians_log/datomic.clj
clojure
(ns clojurians-log.datomic (:require [com.stuartsierra.component :as component] [datomic.client.api :as d])) (def cloud? true) (defrecord Datomic [config client conn] component/Lifecycle (start [component] (let [client (d/client config) db (d/create-database client {:db-name (:db-name config)}) conn (d/connect client {:db-name (:db-name config)})] (assoc component :conn conn))) (stop [component] (assoc component :conn nil :client nil))) (defn new-datomic-db [config] (map->Datomic {:config (:cloud config)})) (def create-database d/create-database) (def connect d/connect) (def db d/db) (def q d/q) (def transact (fn [conn data] (future (d/transact conn {:tx-data data})))) (def transact-async transact)
655614f57afe24a83ac6da8b36fa8cd987e0eee1e4939079367897ae39f13a64
bobot/FetedelascienceINRIAsaclay
movement.ml
File : movement.ml Copyright ( C ) 2008 < > < > WWW : / This library is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2.1 or later as published by the Free Software Foundation , with the special exception on linking described in the file LICENSE . This library 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 file LICENSE for more details . Copyright (C) 2008 Dany Maslowski <> Christophe Troestler <> WWW: / This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2.1 or later as published by the Free Software Foundation, with the special exception on linking described in the file LICENSE. This library 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 file LICENSE for more details. *) open Mindstorm open Random (** We parametrise the solver by the connections to the ports (so as to change them easily) *) module Make(C: sig val conn : Mindstorm.bluetooth Mindstorm.conn val motor_fighter : Motor.port val motor_hand : Motor.port val motor_pf : Motor.port val push_hand_port : Sensor.port val push_fighter_port : Sensor.port val cog_is_set_left : bool end) = struct open C open Printf type cont = unit -> unit let r = Robot.make() let execute() = Robot.run r let end_cont () = Robot.stop r State of the rubik robot let cube_is_held = ref true (** Indicates whether the cube is is not held by the "hand". *) let cog_is_left = ref (C.cog_is_set_left) * To know if cogs are placed to turn left or right . This variable is used because there is a large space between the teeth of cogs ( we lose about 30 degrees when we change the direction of rotations of the platform ) . variable is used because there is a large space between the teeth of cogs (we lose about 30 degrees when we change the direction of rotations of the platform). *) let speed motor ?tach_limit sp = Motor.set conn motor (Motor.speed ?tach_limit (sp)) let get_tc_pf () = let (x,_,_,_) = Motor.get C.conn motor_pf in x let motor_is motor state = Robot.meas r (fun () -> let (st,_,_,_) = Motor.get C.conn motor in st.Motor.run_state = state) let idle_hand = motor_is motor_hand `Idle let idle_fighter = motor_is motor_fighter `Idle let idle_pf = motor_is motor_pf `Idle let running_pf = motor_is motor_pf `Running let hand_push = Robot.touch C.conn push_hand_port r let fighter_push = Robot.touch C.conn push_fighter_port r * Give an appropriate position to the cogs to turn left if the boolean bool is true or to turn otherwise . boolean bool is true or to turn rigth otherwise. *) let set_cog turn_left k = if turn_left then if !cog_is_left then k() else (Robot.event_is idle_pf k; cog_is_left := true ; speed motor_pf ~tach_limit:38 (-3)) else if !cog_is_left then (Robot.event_is idle_pf k; cog_is_left := false; speed motor_pf ~tach_limit:38 3) else k() let hold_rubik k = if !cube_is_held then k() else (Robot.event_is idle_hand k; cube_is_held := true; speed motor_hand ~tach_limit:110 (-30)) let free_rubik k = if !cube_is_held then begin Robot.event_is hand_push (fun _ -> speed motor_hand 0; k()); cube_is_held := false; speed motor_hand 15 end else k() let usleep s = ignore(Unix.select [] [] [] s) let reset_fighter k = Robot.event_is fighter_push (fun _ -> speed motor_fighter 0; k()); speed motor_fighter (-5) (** Reset the position of the fighter after having kicked the cube *) let kick_back k = Robot.event_is fighter_push begin fun _ -> speed motor_fighter 0; usleep 0.3; (* let the bump happen before measuring again *) reset_fighter k end; speed motor_fighter (-25) let kick k = hold_rubik begin fun _ -> Robot.event_is idle_fighter (fun _ -> kick_back k); speed motor_fighter ~tach_limit:80 100 end (** Turn the platform slowly to adjust it with precision *) let turn_pf_slowly tach_limit v k = Robot.event_is idle_pf (fun _ -> speed motor_pf 0; k()); speed motor_pf ~tach_limit v How many degrees the motor must rotate for the cube platform to make the fourth of a turn . make the fourth of a turn. *) let degree_per_quarter = 300 let turn_pf qt k = let turn () = free_rubik begin fun _ -> let tl17 = qt*(-331) in if qt > 0 then ( Robot.event_is idle_pf (fun _ -> turn_pf_slowly (-tl17) (-8) k); speed motor_pf ~tach_limit:(qt * degree_per_quarter) (-100)) else ( Robot.event_is idle_pf (fun _ -> turn_pf_slowly tl17 8 k); speed motor_pf ~tach_limit:(-qt * degree_per_quarter) 90) end in set_cog (qt > 0) turn (** Rectify the platform after having turned the cube because there is a small error caused by a space between the cube and the "hand". *) let rectif_pf turn_left tl10 v10 k= set_cog (not turn_left) begin fun _ -> Robot.event_is idle_pf k; speed motor_pf ~tach_limit:tl10 v10 end (** Turn the platform slowly (the cube is held) to have a good precision *) let turn_rubik_slowly turn_left tl30 tl10 v30 v10 k = set_cog turn_left begin fun _ -> Robot.event_is idle_pf (fun _ -> rectif_pf turn_left tl10 v10 k); speed motor_pf ~tach_limit:tl30 v30 end (** Turn the platform (the cube is held) *) let turn_rubik turn_left tach_limit tl30 tl10 v100 v30 v10 k = hold_rubik begin fun _ -> Robot.event_is idle_pf (fun _ -> turn_rubik_slowly turn_left tl30 tl10 v30 v10 k); speed motor_pf ~tach_limit v100 end let turn_rubik_left ~cont = set_cog true (fun _ -> turn_rubik true 450 249 68 (-70) (-20) (10) cont) let turn_rubik_right ~cont = set_cog false (fun _ -> turn_rubik false 450 225 39 (70) 20 (-10) cont) Last values : turn_rubik false 450 235 54 ( 70 ) 20 ( -10 ) cont let turn_rubik_half ~cont = let left = Random.bool() in set_cog left (fun _ -> if left then turn_rubik true 900 426 64 (-70) (-20) (10) cont else turn_rubik false 900 419 57 70 20 (-10) cont ) let () = kick_back (fun _ -> free_rubik (end_cont)); execute() end (* Local Variables: *) compile - command : " make " (* End: *)
null
https://raw.githubusercontent.com/bobot/FetedelascienceINRIAsaclay/87765db9f9c7211a26a09eb93e9c92f99a49b0bc/2010/robot/examples_mindstorm_lab/rubik/movement.ml
ocaml
* We parametrise the solver by the connections to the ports (so as to change them easily) * Indicates whether the cube is is not held by the "hand". * Reset the position of the fighter after having kicked the cube let the bump happen before measuring again * Turn the platform slowly to adjust it with precision * Rectify the platform after having turned the cube because there is a small error caused by a space between the cube and the "hand". * Turn the platform slowly (the cube is held) to have a good precision * Turn the platform (the cube is held) Local Variables: End:
File : movement.ml Copyright ( C ) 2008 < > < > WWW : / This library is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2.1 or later as published by the Free Software Foundation , with the special exception on linking described in the file LICENSE . This library 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 file LICENSE for more details . Copyright (C) 2008 Dany Maslowski <> Christophe Troestler <> WWW: / This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2.1 or later as published by the Free Software Foundation, with the special exception on linking described in the file LICENSE. This library 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 file LICENSE for more details. *) open Mindstorm open Random module Make(C: sig val conn : Mindstorm.bluetooth Mindstorm.conn val motor_fighter : Motor.port val motor_hand : Motor.port val motor_pf : Motor.port val push_hand_port : Sensor.port val push_fighter_port : Sensor.port val cog_is_set_left : bool end) = struct open C open Printf type cont = unit -> unit let r = Robot.make() let execute() = Robot.run r let end_cont () = Robot.stop r State of the rubik robot let cube_is_held = ref true let cog_is_left = ref (C.cog_is_set_left) * To know if cogs are placed to turn left or right . This variable is used because there is a large space between the teeth of cogs ( we lose about 30 degrees when we change the direction of rotations of the platform ) . variable is used because there is a large space between the teeth of cogs (we lose about 30 degrees when we change the direction of rotations of the platform). *) let speed motor ?tach_limit sp = Motor.set conn motor (Motor.speed ?tach_limit (sp)) let get_tc_pf () = let (x,_,_,_) = Motor.get C.conn motor_pf in x let motor_is motor state = Robot.meas r (fun () -> let (st,_,_,_) = Motor.get C.conn motor in st.Motor.run_state = state) let idle_hand = motor_is motor_hand `Idle let idle_fighter = motor_is motor_fighter `Idle let idle_pf = motor_is motor_pf `Idle let running_pf = motor_is motor_pf `Running let hand_push = Robot.touch C.conn push_hand_port r let fighter_push = Robot.touch C.conn push_fighter_port r * Give an appropriate position to the cogs to turn left if the boolean bool is true or to turn otherwise . boolean bool is true or to turn rigth otherwise. *) let set_cog turn_left k = if turn_left then if !cog_is_left then k() else (Robot.event_is idle_pf k; cog_is_left := true ; speed motor_pf ~tach_limit:38 (-3)) else if !cog_is_left then (Robot.event_is idle_pf k; cog_is_left := false; speed motor_pf ~tach_limit:38 3) else k() let hold_rubik k = if !cube_is_held then k() else (Robot.event_is idle_hand k; cube_is_held := true; speed motor_hand ~tach_limit:110 (-30)) let free_rubik k = if !cube_is_held then begin Robot.event_is hand_push (fun _ -> speed motor_hand 0; k()); cube_is_held := false; speed motor_hand 15 end else k() let usleep s = ignore(Unix.select [] [] [] s) let reset_fighter k = Robot.event_is fighter_push (fun _ -> speed motor_fighter 0; k()); speed motor_fighter (-5) let kick_back k = Robot.event_is fighter_push begin fun _ -> speed motor_fighter 0; reset_fighter k end; speed motor_fighter (-25) let kick k = hold_rubik begin fun _ -> Robot.event_is idle_fighter (fun _ -> kick_back k); speed motor_fighter ~tach_limit:80 100 end let turn_pf_slowly tach_limit v k = Robot.event_is idle_pf (fun _ -> speed motor_pf 0; k()); speed motor_pf ~tach_limit v How many degrees the motor must rotate for the cube platform to make the fourth of a turn . make the fourth of a turn. *) let degree_per_quarter = 300 let turn_pf qt k = let turn () = free_rubik begin fun _ -> let tl17 = qt*(-331) in if qt > 0 then ( Robot.event_is idle_pf (fun _ -> turn_pf_slowly (-tl17) (-8) k); speed motor_pf ~tach_limit:(qt * degree_per_quarter) (-100)) else ( Robot.event_is idle_pf (fun _ -> turn_pf_slowly tl17 8 k); speed motor_pf ~tach_limit:(-qt * degree_per_quarter) 90) end in set_cog (qt > 0) turn let rectif_pf turn_left tl10 v10 k= set_cog (not turn_left) begin fun _ -> Robot.event_is idle_pf k; speed motor_pf ~tach_limit:tl10 v10 end let turn_rubik_slowly turn_left tl30 tl10 v30 v10 k = set_cog turn_left begin fun _ -> Robot.event_is idle_pf (fun _ -> rectif_pf turn_left tl10 v10 k); speed motor_pf ~tach_limit:tl30 v30 end let turn_rubik turn_left tach_limit tl30 tl10 v100 v30 v10 k = hold_rubik begin fun _ -> Robot.event_is idle_pf (fun _ -> turn_rubik_slowly turn_left tl30 tl10 v30 v10 k); speed motor_pf ~tach_limit v100 end let turn_rubik_left ~cont = set_cog true (fun _ -> turn_rubik true 450 249 68 (-70) (-20) (10) cont) let turn_rubik_right ~cont = set_cog false (fun _ -> turn_rubik false 450 225 39 (70) 20 (-10) cont) Last values : turn_rubik false 450 235 54 ( 70 ) 20 ( -10 ) cont let turn_rubik_half ~cont = let left = Random.bool() in set_cog left (fun _ -> if left then turn_rubik true 900 426 64 (-70) (-20) (10) cont else turn_rubik false 900 419 57 70 20 (-10) cont ) let () = kick_back (fun _ -> free_rubik (end_cont)); execute() end compile - command : " make "
17a93e06d510d95f627082b81a64335346bc914fec114b5b69cb111832c2dc1a
appleshan/cl-http
cl-http-70-65.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Package : USER ; Base : 10 ; Patch - File : T -*- Patch file for CL - HTTP version 70.65 ;;; Reason: I saw a case where the indices were in the right relationship but stream-input-buffer was NIL , so the call to % SETUP - NEXT - PHYSICAL - INPUT - BUFFER was being skipped when it ought not to be . -- ;;; ;;; Function (DEFUN-IN-FLAVOR TCP::%READ-BYTE TCP::CHUNK-TRANSFER-DECODING-INPUT-STREAM-MIXIN): include existence of si:stream-input-buffer in test ;;; Function (DEFUN-IN-FLAVOR TCP::%READ-CR TCP::CHUNK-TRANSFER-DECODING-INPUT-STREAM-MIXIN): ditto ;;; Function (DEFUN-IN-FLAVOR TCP::%READ-LF TCP::CHUNK-TRANSFER-DECODING-INPUT-STREAM-MIXIN): ditto Written by , 8/28/00 07:39:45 while running on from FUJI:/usr / users / reti / Genera-8 - 5 - MIT - all - who - calls - inc.vlod with Open Genera 2.0 , Genera 8.5 , Documentation Database 440.12 , Logical Pathnames Translation Files NEWEST , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.20 , 8 5 Support Patches 1.0 , Genera 8 5 Mailer Patches 1.1 , Genera 8 5 Domain Name Server Patches 1.1 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.0 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.0 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MacIvory Support 447.0 , Mailer 438.0 , Domain Name Server 436.0 , Metering 444.0 , Metering Substrate 444.1 , , Jericho 237.0 , Joshua Documentation 216.0 , 206.0 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Images 431.2 , Image Substrate 440.4 , Color Demo 422.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , C 440.0 , , 438.0 , Minimal Lexer Runtime 439.0 , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Pascal 433.0 , , Pascal Package 434.0 , , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , HTTP Server 70.64 , Showable Procedures 36.3 , Binary Tree 34.0 , W3 Presentation System 8.1 , HTTP Client 49.8 , HTTP Client Substrate 3.15 , Experimental Jpeg Lib 1.0 , HTML Parser 11.0 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.14 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1280x974 8 - bit PSEUDO - COLOR X Screen FUJI:0.0 with 224 Genera fonts ( DECWINDOWS Digital Equipment Corporation Digital UNIX V4.0 R1 ) , Machine serial number -2141189522 , Add clos to mx list methods ( from KRI : KRI;ADD - CLOS - TO - MX - LIST - METHODS.LISP.1 ) , Its end of line patch ( from KRI : KRI;ITS - END - OF - LINE - PATCH.LISP.3 ) , Unix inbox from spoofing patch ( from KRI : KRI;UNIX - INBOX - FROM - SPOOFING - PATCH.LISP.20 ) , ;;; hack to treat namespace as a partial cache of domain (from W:>hes>fixes>partial-namespace-domain.lisp.5), ;;; Popup patch (from KRI:KRI;POPUP-PATCH.LISP.1), ;;; Content type in forward patch (from KRI:KRI;CONTENT-TYPE-IN-FORWARD-PATCH.LISP.4), ;;; Attempt to fix recursive block transport (from KRI:KRI;RBT-PATCH.LISP.1), ;;; Directory attributes patch (from KRI:KRI;DIRECTORY-ATTRIBUTES-PATCH.LISP.6), ;;; Ansi common lisp as synonym patch (from KRI:KRI;ANSI-COMMON-LISP-AS-SYNONYM-PATCH.LISP.9), ;;; Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), Read ( from KRI : KRI;READ - JFIF - VOGT.LISP.3 ) , ;;; Domain try harder patch (from KRI:KRI;DOMAIN-TRY-HARDER-PATCH.LISP.6), ;;; Find free ephemeral space patch (from KRI:KRI;FIND-FREE-EPHEMERAL-SPACE-PATCH.LISP.3), ;;; Section name patch (from KRI:KRI;SECTION-NAME-PATCH.LISP.1), Tape spec patch ( from KRI : KRI;TAPE - SPEC - PATCH.LISP.10 ) , ;;; Set dump dates on compare patch (from KRI:KRI;SET-DUMP-DATES-ON-COMPARE-PATCH.LISP.73), Telnet naws patch ( from KRI : KRI;TELNET - NAWS - PATCH.LISP.9 ) , Load file only ( from KRI : KRI;LOAD - FILE - ONLY - BIN.LISP.1 ) , Show jpeg pathname ( from KRI : KRI;SHOW - JPEG - PATHNAME.LISP.1 ) , Bullet proof trampoline args ( from KRI : - PROOF - TRAMPOLINE - ARGS.LISP.1 ) , More y2k patches ( from KRI : KRI;MORE - Y2K - PATCHES.LISP.8 ) , Vlm disk save patch ( from KRI : KRI;VLM - DISK - SAVE - PATCH.LISP.5 ) . (SCT:FILES-PATCHED-IN-THIS-PATCH-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: lisp; Syntax: Common-Lisp; Package: TCP; Base: 10; Lowercase: preferably; Patch-File: Yes; -*-") (defun-in-flavor (%read-byte chunk-transfer-decoding-input-stream-mixin) () (unless (and si::stream-input-buffer (< si:stream-input-index si:stream-input-limit)) (%setup-next-physical-input-buffer nil t)) (prog1 (aref si:stream-input-buffer si:stream-input-index) (incf si:stream-input-index))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: lisp; Syntax: Common-Lisp; Package: TCP; Base: 10; Lowercase: preferably; Patch-File: Yes; -*-") (defun-in-flavor (%read-cr chunk-transfer-decoding-input-stream-mixin) () (with-chunk-transfer-decoding-traced (format *trace-output* "~&~'b~&Read:~ cr (~'BIndex:~ ~D)" si:stream-input-index)) (unless (and si::stream-input-buffer (< si:stream-input-index si:stream-input-limit)) (%setup-next-physical-input-buffer nil t)) (cond ((= (aref si:stream-input-buffer si:stream-input-index) #.(si:char-to-ascii #\return)) (incf si:stream-input-index) t) (t (error 'chunk-transfer-decoding-error :stream self :format-string "~@C was found when ~@C was expected in chunked transfer decoding." :format-args (list (ascii-to-char (aref si:stream-input-buffer si:stream-input-index)) #\return))))) ;======================== (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: lisp; Syntax: Common-Lisp; Package: TCP; Base: 10; Lowercase: preferably; Patch-File: Yes; -*-") (defun-in-flavor (%read-lf chunk-transfer-decoding-input-stream-mixin) () (with-chunk-transfer-decoding-traced (format *trace-output* "~&~'b~&Read:~ LF (~'BIndex:~ ~D)" si:stream-input-index)) (unless (and si::stream-input-buffer (< si:stream-input-index si:stream-input-limit)) (%setup-next-physical-input-buffer nil t)) (cond ((= (aref si:stream-input-buffer si:stream-input-index) #.(si:char-to-ascii #\linefeed)) (incf si:stream-input-index) t) (t (error 'chunk-transfer-decoding-error :stream self :format-string "~@C was found when ~@C was expected in chunked transfer decoding." :format-args (list (ascii-to-char (aref si:stream-input-buffer si:stream-input-index)) #\linefeed)))))
null
https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/lispm/server/patch/cl-http-70/cl-http-70-65.lisp
lisp
Syntax : Common - Lisp ; Package : USER ; Base : 10 ; Patch - File : T -*- Reason: I saw a case where the indices were in the right relationship but stream-input-buffer was Function (DEFUN-IN-FLAVOR TCP::%READ-BYTE TCP::CHUNK-TRANSFER-DECODING-INPUT-STREAM-MIXIN): include existence of si:stream-input-buffer in test Function (DEFUN-IN-FLAVOR TCP::%READ-CR TCP::CHUNK-TRANSFER-DECODING-INPUT-STREAM-MIXIN): ditto Function (DEFUN-IN-FLAVOR TCP::%READ-LF TCP::CHUNK-TRANSFER-DECODING-INPUT-STREAM-MIXIN): ditto ADD - CLOS - TO - MX - LIST - METHODS.LISP.1 ) , ITS - END - OF - LINE - PATCH.LISP.3 ) , UNIX - INBOX - FROM - SPOOFING - PATCH.LISP.20 ) , hack to treat namespace as a partial cache of domain (from W:>hes>fixes>partial-namespace-domain.lisp.5), Popup patch (from KRI:KRI;POPUP-PATCH.LISP.1), Content type in forward patch (from KRI:KRI;CONTENT-TYPE-IN-FORWARD-PATCH.LISP.4), Attempt to fix recursive block transport (from KRI:KRI;RBT-PATCH.LISP.1), Directory attributes patch (from KRI:KRI;DIRECTORY-ATTRIBUTES-PATCH.LISP.6), Ansi common lisp as synonym patch (from KRI:KRI;ANSI-COMMON-LISP-AS-SYNONYM-PATCH.LISP.9), Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10), READ - JFIF - VOGT.LISP.3 ) , Domain try harder patch (from KRI:KRI;DOMAIN-TRY-HARDER-PATCH.LISP.6), Find free ephemeral space patch (from KRI:KRI;FIND-FREE-EPHEMERAL-SPACE-PATCH.LISP.3), Section name patch (from KRI:KRI;SECTION-NAME-PATCH.LISP.1), TAPE - SPEC - PATCH.LISP.10 ) , Set dump dates on compare patch (from KRI:KRI;SET-DUMP-DATES-ON-COMPARE-PATCH.LISP.73), TELNET - NAWS - PATCH.LISP.9 ) , LOAD - FILE - ONLY - BIN.LISP.1 ) , SHOW - JPEG - PATHNAME.LISP.1 ) , MORE - Y2K - PATCHES.LISP.8 ) , VLM - DISK - SAVE - PATCH.LISP.5 ) . ======================== ======================== ========================
Patch file for CL - HTTP version 70.65 NIL , so the call to % SETUP - NEXT - PHYSICAL - INPUT - BUFFER was being skipped when it ought not to be . -- Written by , 8/28/00 07:39:45 while running on from FUJI:/usr / users / reti / Genera-8 - 5 - MIT - all - who - calls - inc.vlod with Open Genera 2.0 , Genera 8.5 , Documentation Database 440.12 , Logical Pathnames Translation Files NEWEST , Experimental Genera 8 5 Patches 1.0 , Genera 8 5 System Patches 1.20 , 8 5 Support Patches 1.0 , Genera 8 5 Mailer Patches 1.1 , Genera 8 5 Domain Name Server Patches 1.1 , Genera 8 5 Metering Patches 1.0 , 8 5 , Genera 8 5 Jericho Patches 1.0 , 8 5 , Genera 8 5 , 8 5 Statice Runtime Patches 1.0 , Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 , Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.0 , Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 , Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 , Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 , Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 , Genera 8 5 Concordia Patches 1.0 , 8 5 , Genera 8 5 C Patches 1.0 , 8 5 , Genera 8 5 Fortran Patches 1.0 , MacIvory Support 447.0 , Mailer 438.0 , Domain Name Server 436.0 , Metering 444.0 , Metering Substrate 444.1 , , Jericho 237.0 , Joshua Documentation 216.0 , 206.0 , Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 , CLIM 72.0 , Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 , CLIM Documentation 72.0 , Color 427.1 , Graphics Support 431.0 , Genera Extensions 16.0 , Essential Image Substrate 433.0 , Color System Documentation 10.0 , SGD Book Design 10.0 , Images 431.2 , Image Substrate 440.4 , Color Demo 422.0 , Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 , Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 , Concordia Documentation 432.0 , C 440.0 , , 438.0 , Minimal Lexer Runtime 439.0 , Lalr 1 434.0 , Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 , Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 , Syntax Editor Runtime 434.0 , C Library Headers 434 , Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 , C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 , Pascal 433.0 , , Pascal Package 434.0 , , Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , , HTTP Server 70.64 , Showable Procedures 36.3 , Binary Tree 34.0 , W3 Presentation System 8.1 , HTTP Client 49.8 , HTTP Client Substrate 3.15 , Experimental Jpeg Lib 1.0 , HTML Parser 11.0 , Ivory Revision 5 , VLM Debugger 329 , Genera program 8.14 , DEC OSF/1 V4.0 ( Rev. 110 ) , 1280x974 8 - bit PSEUDO - COLOR X Screen FUJI:0.0 with 224 Genera fonts ( DECWINDOWS Digital Equipment Corporation Digital UNIX V4.0 R1 ) , Machine serial number -2141189522 , Bullet proof trampoline args ( from KRI : - PROOF - TRAMPOLINE - ARGS.LISP.1 ) , (SCT:FILES-PATCHED-IN-THIS-PATCH-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: lisp; Syntax: Common-Lisp; Package: TCP; Base: 10; Lowercase: preferably; Patch-File: Yes; -*-") (defun-in-flavor (%read-byte chunk-transfer-decoding-input-stream-mixin) () (unless (and si::stream-input-buffer (< si:stream-input-index si:stream-input-limit)) (%setup-next-physical-input-buffer nil t)) (prog1 (aref si:stream-input-buffer si:stream-input-index) (incf si:stream-input-index))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: lisp; Syntax: Common-Lisp; Package: TCP; Base: 10; Lowercase: preferably; Patch-File: Yes; -*-") (defun-in-flavor (%read-cr chunk-transfer-decoding-input-stream-mixin) () (with-chunk-transfer-decoding-traced (format *trace-output* "~&~'b~&Read:~ cr (~'BIndex:~ ~D)" si:stream-input-index)) (unless (and si::stream-input-buffer (< si:stream-input-index si:stream-input-limit)) (%setup-next-physical-input-buffer nil t)) (cond ((= (aref si:stream-input-buffer si:stream-input-index) #.(si:char-to-ascii #\return)) (incf si:stream-input-index) t) (t (error 'chunk-transfer-decoding-error :stream self :format-string "~@C was found when ~@C was expected in chunked transfer decoding." :format-args (list (ascii-to-char (aref si:stream-input-buffer si:stream-input-index)) #\return))))) (SCT:BEGIN-PATCH-SECTION) (SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;TCP-LISPM-STREAM.LISP.172") (SCT:PATCH-SECTION-ATTRIBUTES "-*- Mode: lisp; Syntax: Common-Lisp; Package: TCP; Base: 10; Lowercase: preferably; Patch-File: Yes; -*-") (defun-in-flavor (%read-lf chunk-transfer-decoding-input-stream-mixin) () (with-chunk-transfer-decoding-traced (format *trace-output* "~&~'b~&Read:~ LF (~'BIndex:~ ~D)" si:stream-input-index)) (unless (and si::stream-input-buffer (< si:stream-input-index si:stream-input-limit)) (%setup-next-physical-input-buffer nil t)) (cond ((= (aref si:stream-input-buffer si:stream-input-index) #.(si:char-to-ascii #\linefeed)) (incf si:stream-input-index) t) (t (error 'chunk-transfer-decoding-error :stream self :format-string "~@C was found when ~@C was expected in chunked transfer decoding." :format-args (list (ascii-to-char (aref si:stream-input-buffer si:stream-input-index)) #\linefeed)))))
f4f1e1f54824064a2dcf1c999b5009ce1c907327ec1b23c7b2eeeb907a219e3c
SecPriv/webspec
config.ml
(********************************************************************************) Copyright ( c ) 2021 (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"), *) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included in *) (* all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (********************************************************************************) module Env = struct module type ARG = sig type t val name : string val doc : string val default : t val get : unit -> t end module type BOOL = ARG with type t = bool module type INT = ARG with type t = int module type FLOAT = ARG with type t = float module type STRING = ARG with type t = string module Generic (Arg : sig type t val name : string val doc : string val default : t val of_string : string -> t end) : ARG with type t = Arg.t = struct include Arg let name = name let get () = try of_string (Sys.getenv name) with _ -> default end module Bool (Arg : sig val name : string val doc : string val default : bool end) : BOOL = struct include Generic (struct include Arg type t = bool let of_string string = bool_of_string string end) end module Int (Arg : sig val name : string val doc : string val default : int end) : INT = struct include Generic (struct include Arg type t = int let of_string string = int_of_string string end) end module Float (Arg : sig val name : string val doc : string val default : float end) : FLOAT = struct include Generic (struct include Arg type t = float let of_string string = float_of_string string end) end module String (Arg : sig val name : string val doc : string val default : string end) : STRING = struct include Generic (struct include Arg type t = string let of_string string = string end) end end (********************************************************************************) module Coq = struct module type ARG = sig type t val default : t val set : t -> unit val get : unit -> t end module type BOOL = ARG with type t = bool module type INT = ARG with type t = int module type FLOAT = ARG with type t = float module type STRING = ARG with type t = string module Generic (Arg : sig type t val default : t end) : ARG with type t = Arg.t = struct include Arg let ref = ref default let set v = ref := v let get () = !ref end module Int (Arg : sig val default : int end) : INT = struct include Generic (struct include Arg type t = int end) end module Float (Arg : sig val default : float end) : FLOAT = struct include Generic (struct include Arg type t = float end) end module String (Arg : sig val default : string end) : STRING = struct include Generic (struct include Arg type t = string end) end module type SET = sig type elt val clear : unit -> unit val add : elt -> unit val mem : elt -> bool val remove : elt -> unit val elements : unit -> elt list end module Set (Ord : sig type t val compare : t -> t -> int end) = struct module S = Set.Make(Ord) type elt = S.elt let ref = ref S.empty let clear () = ref := S.empty let add v = ref := S.add v !ref let mem v = S.mem v !ref let remove v = ref := S.remove v !ref let elements () = S.elements !ref end module type MAP = sig type key type elt val clear : unit -> unit val add : key -> elt -> unit val find : key -> elt option val remove : key -> unit val bindings : unit -> (key * elt) list end module Map (Ord : sig type t val compare : t -> t -> int end) (Elt : sig type t end) = struct module M = Map.Make(Ord) type key = M.key type elt = Elt.t let ref : elt M.t ref = ref M.empty let clear () = ref := M.empty let add k v = ref := M.add k v !ref let find k = M.find_opt k !ref let remove k = ref := M.remove k !ref let bindings () = M.bindings !ref end end (********************************************************************************) module Info = Env.Bool (struct let name = "INFO" let doc = "Enable or disable infos" let default = false end) module Debug = Env.Bool (struct let name = "DEBUG" let doc = "Enable or disable debugs" let default = false end) module Warning = Env.Bool (struct let name = "WARNING" let doc = "Enable or disable warnings" let default = true end) module Error = Env.Bool (struct let name = "ERROR" let doc = "Enable or disable errors" let default = true end) module ArraySize = Coq.Int (struct let default = 16 end) module InlineDepth = Coq.Int (struct let default = 5 end) module InlinedConstants = Coq.Set(Names.KerName) module InlinedRelations = Coq.Map(String)(Int) module DestructRelations= Coq.Map(String)(Int)
null
https://raw.githubusercontent.com/SecPriv/webspec/9f500bd85400551d8bf0e117ac5aa57088f9bc20/compiler/src/config.ml
ocaml
****************************************************************************** Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************** ****************************************************************************** ******************************************************************************
Copyright ( c ) 2021 to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING module Env = struct module type ARG = sig type t val name : string val doc : string val default : t val get : unit -> t end module type BOOL = ARG with type t = bool module type INT = ARG with type t = int module type FLOAT = ARG with type t = float module type STRING = ARG with type t = string module Generic (Arg : sig type t val name : string val doc : string val default : t val of_string : string -> t end) : ARG with type t = Arg.t = struct include Arg let name = name let get () = try of_string (Sys.getenv name) with _ -> default end module Bool (Arg : sig val name : string val doc : string val default : bool end) : BOOL = struct include Generic (struct include Arg type t = bool let of_string string = bool_of_string string end) end module Int (Arg : sig val name : string val doc : string val default : int end) : INT = struct include Generic (struct include Arg type t = int let of_string string = int_of_string string end) end module Float (Arg : sig val name : string val doc : string val default : float end) : FLOAT = struct include Generic (struct include Arg type t = float let of_string string = float_of_string string end) end module String (Arg : sig val name : string val doc : string val default : string end) : STRING = struct include Generic (struct include Arg type t = string let of_string string = string end) end end module Coq = struct module type ARG = sig type t val default : t val set : t -> unit val get : unit -> t end module type BOOL = ARG with type t = bool module type INT = ARG with type t = int module type FLOAT = ARG with type t = float module type STRING = ARG with type t = string module Generic (Arg : sig type t val default : t end) : ARG with type t = Arg.t = struct include Arg let ref = ref default let set v = ref := v let get () = !ref end module Int (Arg : sig val default : int end) : INT = struct include Generic (struct include Arg type t = int end) end module Float (Arg : sig val default : float end) : FLOAT = struct include Generic (struct include Arg type t = float end) end module String (Arg : sig val default : string end) : STRING = struct include Generic (struct include Arg type t = string end) end module type SET = sig type elt val clear : unit -> unit val add : elt -> unit val mem : elt -> bool val remove : elt -> unit val elements : unit -> elt list end module Set (Ord : sig type t val compare : t -> t -> int end) = struct module S = Set.Make(Ord) type elt = S.elt let ref = ref S.empty let clear () = ref := S.empty let add v = ref := S.add v !ref let mem v = S.mem v !ref let remove v = ref := S.remove v !ref let elements () = S.elements !ref end module type MAP = sig type key type elt val clear : unit -> unit val add : key -> elt -> unit val find : key -> elt option val remove : key -> unit val bindings : unit -> (key * elt) list end module Map (Ord : sig type t val compare : t -> t -> int end) (Elt : sig type t end) = struct module M = Map.Make(Ord) type key = M.key type elt = Elt.t let ref : elt M.t ref = ref M.empty let clear () = ref := M.empty let add k v = ref := M.add k v !ref let find k = M.find_opt k !ref let remove k = ref := M.remove k !ref let bindings () = M.bindings !ref end end module Info = Env.Bool (struct let name = "INFO" let doc = "Enable or disable infos" let default = false end) module Debug = Env.Bool (struct let name = "DEBUG" let doc = "Enable or disable debugs" let default = false end) module Warning = Env.Bool (struct let name = "WARNING" let doc = "Enable or disable warnings" let default = true end) module Error = Env.Bool (struct let name = "ERROR" let doc = "Enable or disable errors" let default = true end) module ArraySize = Coq.Int (struct let default = 16 end) module InlineDepth = Coq.Int (struct let default = 5 end) module InlinedConstants = Coq.Set(Names.KerName) module InlinedRelations = Coq.Map(String)(Int) module DestructRelations= Coq.Map(String)(Int)
9744b6fc76863dbb188f289461b9f762cd3e555ee585d25f27ad261d3e14a571
yogthos/krueger
common.clj
(ns krueger.routes.services.common (:require [clojure.tools.logging :as log] [ring.util.http-response :refer [internal-server-error]] [schema.core :as s])) (s/defschema Success {:result s/Keyword}) (defn user-id [req] (get-in req [:session :identity :id])) (defmacro handler "wraps handler in a try-catch block with built in logging" {:style/indent :defn} [fn-name args & body] `(defn ~fn-name ~args (try ~@body (catch Throwable t# (log/error t# "error handling request") (internal-server-error {:error "error occured serving the request"})))))
null
https://raw.githubusercontent.com/yogthos/krueger/782e1f8ab358867102b907c5a80e56ee6bc6ff82/src/clj/krueger/routes/services/common.clj
clojure
(ns krueger.routes.services.common (:require [clojure.tools.logging :as log] [ring.util.http-response :refer [internal-server-error]] [schema.core :as s])) (s/defschema Success {:result s/Keyword}) (defn user-id [req] (get-in req [:session :identity :id])) (defmacro handler "wraps handler in a try-catch block with built in logging" {:style/indent :defn} [fn-name args & body] `(defn ~fn-name ~args (try ~@body (catch Throwable t# (log/error t# "error handling request") (internal-server-error {:error "error occured serving the request"})))))
608d7f7ec33d946cfb5c1a4e16b18e1473618348892ece2bc4559b80bf4d9929
locusmath/locus
object.clj
(ns locus.partial.copresheaf.object (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.sequence.object :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.mapping.function.image.image-function :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.quiver.relation.binary.sr :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.quiver.binary.core.morphism :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.algebra.category.core.object :refer :all] [locus.algebra.category.core.morphism :refer :all] [locus.set.copresheaf.topoi.copresheaf.object :refer :all] [locus.algebra.category.concrete.categories :refer :all] [locus.partial.mapping.function :refer :all] [locus.partial.quiver.object :refer :all]) (:import (locus.set.copresheaf.topoi.copresheaf.object Copresheaf) (locus.algebra.category.core.morphism Functor))) ; A functor F : C -> Sets[Part] is a functor from a category to the category of sets and partial ; functions. The category Sets[Part] of sets and partial functions is a concrete category, where each set is adjoined an extra zero element which is outputted when the values of a ; partial function don't exist. It follows therefore that as a functor to a concrete category, ; it is a structure copresheaf. So it will be handled as part of the presheaf theory framework which is the hallmark of Locus . (deftype PartialCopresheaf [category object-function morphism-function] AbstractMorphism (source-object [this] category) (target-object [this] partial-sets) StructuredDifunction (first-function [this] morphism-function) (second-function [this] object-function)) (derive PartialCopresheaf :locus.set.copresheaf.structure.core.protocols/structure-copresheaf) Implementing these multimethods integrates partial copresheaves into the structure presheaf framework (defmethod get-object PartialCopresheaf [functor x] ((second-function functor) x)) (defmethod get-morphism PartialCopresheaf [functor x] ((first-function functor) x)) (defmethod get-set PartialCopresheaf [functor x] (nullable-set (get-object functor x))) (defmethod get-function PartialCopresheaf [functor x] (nullable-function (get-morphism functor x))) Partial copresheaves are structure copresheaves over an index category (defmethod index PartialCopresheaf [^PartialCopresheaf functor] (.-category functor)) Generalized mechanisms for converting objects into partial copresheaves (defmulti to-partial-copresheaf type) (defmethod to-partial-copresheaf PartialCopresheaf [functor] functor) (defmethod to-partial-copresheaf :locus.set.logic.core.set/universal [coll] (PartialCopresheaf (thin-category (weak-order [#{0}])) (fn [obj] coll) (fn [arrow] (partial-identity-function coll)))) (defmethod to-partial-copresheaf :locus.partial.mapping.function/partial-function [func] (PartialCopresheaf. (thin-category (weak-order [#{0} #{1}])) (fn [obj] (case obj 0 (source-object func) 1 (target-object func))) (fn [[a b]] (case [a b] [0 0] (partial-identity-function (source-object func)) [1 1] (partial-identity-function (target-object func)) [0 1] func)))) (defmethod to-partial-copresheaf Copresheaf [copresheaf] (PartialCopresheaf. (index copresheaf) (partial get-set copresheaf) (fn [arrow] (to-partial-function (get-function copresheaf arrow))))) (defmethod to-partial-copresheaf :default [copresheaf] (to-partial-copresheaf (to-copresheaf copresheaf))) ; Conversion routines (defmethod to-functor PartialCopresheaf [functor] (Functor. (index functor) partial-sets (partial get-object functor) (partial get-morphism functor))) (defmethod to-copresheaf PartialCopresheaf [functor] (Copresheaf. (index functor) (partial get-set functor) (partial get-function functor))) Partial copresheaves produce partial actions (comment (defn get-pset-by-object [partial-functor object] (let [cat (index partial-functor)] (->PSet (endomorphism-monoid cat object) (get-object partial-functor object) (fn [arrow] (get-morphism partial-functor arrow)))))) ; A mechanism for automatically creating triangles in the category of sets and partial functions (defn partial-triangle [f g] (PartialCopresheaf. (thin-category (weak-order [#{0} #{1} #{2}])) (fn [obj] (case obj 0 (source-object g) 1 (target-object g) 2 (target-object f))) (fn [[a b]] (case [a b] [0 0] (partial-identity-function (source-object g)) [0 1] g [0 2] (compose f g) [1 1] (partial-identity-function (target-object g)) [1 2] f [2 2] (partial-identity-function (target-object f)))))) ; Ontology of partial functors (defn partial-copresheaf? [x] (= (type x) PartialCopresheaf)) (defn object-partial-copresheaf? [x] (and (partial-copresheaf? x) (let [cat (index x)] (= (count (objects cat)) (count (morphisms cat)) 1)))) (defn function-partial-copresheaf? [x] (and (partial-copresheaf? x) (let [cat (index x)] (and (= (count (objects cat)) 2) (total-order-category? cat))))) (defn partial-chain? [x] (and (partial-copresheaf? x) (total-order-category? (index x)))) (defn partial-triangle? [x] (and (partial-copresheaf? x) (total-order-category? (index x)) (= (count (objects (index x))) 3))) (defn partial-diamond? [x] (and (partial-copresheaf? x) (diamond-category? (index x)))) (defn partial-span? [x] (and (partial-copresheaf? x) (let [cat (index x)] (and (n-span-category? cat) (= (count (objects cat)) 3))))) (defn partial-cospan? [x] (and (partial-copresheaf? x) (let [cat (index x)] (and (n-cospan-category? cat) (= (count (objects cat)) 3)))))
null
https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/partial/copresheaf/object.clj
clojure
A functor F : C -> Sets[Part] is a functor from a category to the category of sets and partial functions. The category Sets[Part] of sets and partial functions is a concrete category, partial function don't exist. It follows therefore that as a functor to a concrete category, it is a structure copresheaf. So it will be handled as part of the presheaf theory framework Conversion routines A mechanism for automatically creating triangles in the category of sets and partial functions Ontology of partial functors
(ns locus.partial.copresheaf.object (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.sequence.object :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.mapping.function.image.image-function :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.quiver.relation.binary.sr :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.quiver.binary.core.morphism :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.algebra.category.core.object :refer :all] [locus.algebra.category.core.morphism :refer :all] [locus.set.copresheaf.topoi.copresheaf.object :refer :all] [locus.algebra.category.concrete.categories :refer :all] [locus.partial.mapping.function :refer :all] [locus.partial.quiver.object :refer :all]) (:import (locus.set.copresheaf.topoi.copresheaf.object Copresheaf) (locus.algebra.category.core.morphism Functor))) where each set is adjoined an extra zero element which is outputted when the values of a which is the hallmark of Locus . (deftype PartialCopresheaf [category object-function morphism-function] AbstractMorphism (source-object [this] category) (target-object [this] partial-sets) StructuredDifunction (first-function [this] morphism-function) (second-function [this] object-function)) (derive PartialCopresheaf :locus.set.copresheaf.structure.core.protocols/structure-copresheaf) Implementing these multimethods integrates partial copresheaves into the structure presheaf framework (defmethod get-object PartialCopresheaf [functor x] ((second-function functor) x)) (defmethod get-morphism PartialCopresheaf [functor x] ((first-function functor) x)) (defmethod get-set PartialCopresheaf [functor x] (nullable-set (get-object functor x))) (defmethod get-function PartialCopresheaf [functor x] (nullable-function (get-morphism functor x))) Partial copresheaves are structure copresheaves over an index category (defmethod index PartialCopresheaf [^PartialCopresheaf functor] (.-category functor)) Generalized mechanisms for converting objects into partial copresheaves (defmulti to-partial-copresheaf type) (defmethod to-partial-copresheaf PartialCopresheaf [functor] functor) (defmethod to-partial-copresheaf :locus.set.logic.core.set/universal [coll] (PartialCopresheaf (thin-category (weak-order [#{0}])) (fn [obj] coll) (fn [arrow] (partial-identity-function coll)))) (defmethod to-partial-copresheaf :locus.partial.mapping.function/partial-function [func] (PartialCopresheaf. (thin-category (weak-order [#{0} #{1}])) (fn [obj] (case obj 0 (source-object func) 1 (target-object func))) (fn [[a b]] (case [a b] [0 0] (partial-identity-function (source-object func)) [1 1] (partial-identity-function (target-object func)) [0 1] func)))) (defmethod to-partial-copresheaf Copresheaf [copresheaf] (PartialCopresheaf. (index copresheaf) (partial get-set copresheaf) (fn [arrow] (to-partial-function (get-function copresheaf arrow))))) (defmethod to-partial-copresheaf :default [copresheaf] (to-partial-copresheaf (to-copresheaf copresheaf))) (defmethod to-functor PartialCopresheaf [functor] (Functor. (index functor) partial-sets (partial get-object functor) (partial get-morphism functor))) (defmethod to-copresheaf PartialCopresheaf [functor] (Copresheaf. (index functor) (partial get-set functor) (partial get-function functor))) Partial copresheaves produce partial actions (comment (defn get-pset-by-object [partial-functor object] (let [cat (index partial-functor)] (->PSet (endomorphism-monoid cat object) (get-object partial-functor object) (fn [arrow] (get-morphism partial-functor arrow)))))) (defn partial-triangle [f g] (PartialCopresheaf. (thin-category (weak-order [#{0} #{1} #{2}])) (fn [obj] (case obj 0 (source-object g) 1 (target-object g) 2 (target-object f))) (fn [[a b]] (case [a b] [0 0] (partial-identity-function (source-object g)) [0 1] g [0 2] (compose f g) [1 1] (partial-identity-function (target-object g)) [1 2] f [2 2] (partial-identity-function (target-object f)))))) (defn partial-copresheaf? [x] (= (type x) PartialCopresheaf)) (defn object-partial-copresheaf? [x] (and (partial-copresheaf? x) (let [cat (index x)] (= (count (objects cat)) (count (morphisms cat)) 1)))) (defn function-partial-copresheaf? [x] (and (partial-copresheaf? x) (let [cat (index x)] (and (= (count (objects cat)) 2) (total-order-category? cat))))) (defn partial-chain? [x] (and (partial-copresheaf? x) (total-order-category? (index x)))) (defn partial-triangle? [x] (and (partial-copresheaf? x) (total-order-category? (index x)) (= (count (objects (index x))) 3))) (defn partial-diamond? [x] (and (partial-copresheaf? x) (diamond-category? (index x)))) (defn partial-span? [x] (and (partial-copresheaf? x) (let [cat (index x)] (and (n-span-category? cat) (= (count (objects cat)) 3))))) (defn partial-cospan? [x] (and (partial-copresheaf? x) (let [cat (index x)] (and (n-cospan-category? cat) (= (count (objects cat)) 3)))))
50ae1b8da88f40595f4e22b84ef7bd451718a05354718d9d46a3b5e5cc4f95f1
exoscale/clojure-kubernetes-client
extensions_v1beta1_pod_security_policy.clj
(ns clojure-kubernetes-client.specs.extensions-v1beta1-pod-security-policy (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] [clojure-kubernetes-client.specs.v1-object-meta :refer :all] [clojure-kubernetes-client.specs.extensions-v1beta1-pod-security-policy-spec :refer :all] ) (:import (java.io File))) (declare extensions-v1beta1-pod-security-policy-data extensions-v1beta1-pod-security-policy) (def extensions-v1beta1-pod-security-policy-data { (ds/opt :apiVersion) string? (ds/opt :kind) string? (ds/opt :metadata) v1-object-meta (ds/opt :spec) extensions-v1beta1-pod-security-policy-spec }) (def extensions-v1beta1-pod-security-policy (ds/spec {:name ::extensions-v1beta1-pod-security-policy :spec extensions-v1beta1-pod-security-policy-data}))
null
https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/extensions_v1beta1_pod_security_policy.clj
clojure
(ns clojure-kubernetes-client.specs.extensions-v1beta1-pod-security-policy (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] [clojure-kubernetes-client.specs.v1-object-meta :refer :all] [clojure-kubernetes-client.specs.extensions-v1beta1-pod-security-policy-spec :refer :all] ) (:import (java.io File))) (declare extensions-v1beta1-pod-security-policy-data extensions-v1beta1-pod-security-policy) (def extensions-v1beta1-pod-security-policy-data { (ds/opt :apiVersion) string? (ds/opt :kind) string? (ds/opt :metadata) v1-object-meta (ds/opt :spec) extensions-v1beta1-pod-security-policy-spec }) (def extensions-v1beta1-pod-security-policy (ds/spec {:name ::extensions-v1beta1-pod-security-policy :spec extensions-v1beta1-pod-security-policy-data}))
c0fc5b0b61ff1922067ece70c076986edfda5c7c00a7bd24eeec9977788ad07b
samply/blaze
app.clj
(ns blaze.handler.app (:require [blaze.handler.health.spec] [blaze.rest-api.spec] [clojure.spec.alpha :as s] [integrant.core :as ig] [reitit.ring] [ring.util.response :as ring] [taoensso.timbre :as log])) (defn- options-handler [_ respond _] (-> (ring/response nil) (ring/status 405) respond)) (defn- router [health-handler] (reitit.ring/router [["/health" {:head health-handler :get health-handler}]] {:syntax :bracket :reitit.ring/default-options-endpoint {:handler options-handler}})) (defn- handler "Whole app Ring handler." [rest-api health-handler] (reitit.ring/ring-handler (router health-handler) rest-api)) (defmethod ig/pre-init-spec :blaze.handler/app [_] (s/keys :req-un [:blaze/rest-api :blaze/health-handler])) (defmethod ig/init-key :blaze.handler/app [_ {:keys [rest-api health-handler]}] (log/info "Init app handler") (handler rest-api health-handler))
null
https://raw.githubusercontent.com/samply/blaze/a2cfdd8d37b92c7c454dc2322301b6a5188e578f/src/blaze/handler/app.clj
clojure
(ns blaze.handler.app (:require [blaze.handler.health.spec] [blaze.rest-api.spec] [clojure.spec.alpha :as s] [integrant.core :as ig] [reitit.ring] [ring.util.response :as ring] [taoensso.timbre :as log])) (defn- options-handler [_ respond _] (-> (ring/response nil) (ring/status 405) respond)) (defn- router [health-handler] (reitit.ring/router [["/health" {:head health-handler :get health-handler}]] {:syntax :bracket :reitit.ring/default-options-endpoint {:handler options-handler}})) (defn- handler "Whole app Ring handler." [rest-api health-handler] (reitit.ring/ring-handler (router health-handler) rest-api)) (defmethod ig/pre-init-spec :blaze.handler/app [_] (s/keys :req-un [:blaze/rest-api :blaze/health-handler])) (defmethod ig/init-key :blaze.handler/app [_ {:keys [rest-api health-handler]}] (log/info "Init app handler") (handler rest-api health-handler))
2f93d2fb560a7029501539579cf99ec9d505fdeb62058f126052da93a880c608
ralph-schleicher/read-number
tests.lisp
;;; tests.lisp --- test procedure Copyright ( C ) 2016 ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in ;; the documentation and/or other materials provided with the ;; distribution. ;; ;; * Neither the name of the copyright holder nor the names of its ;; contributors may be used to endorse or promote products derived ;; from this software without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT ;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ;; ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;; POSSIBILITY OF SUCH DAMAGE. ;;; Code: (in-package :common-lisp-user) (quicklisp:quickload :lisp-unit) (quicklisp:quickload :read-number) (defpackage :read-number-tests (:use :common-lisp :lisp-unit :read-number)) (in-package :read-number-tests) (defun try (fun spec &optional expected &key next-char) (multiple-value-bind (string arguments) (cond ((stringp spec) (values spec nil)) (t (values (first spec) (rest spec)))) (with-input-from-string (input-stream string) (let (value status) (handler-case (setf value (apply fun input-stream arguments) status (= value expected)) (parse-error () (setf status (if (eq expected 'parse-error) t "failure (parse-error)"))) (end-of-file () (setf status (if (eq expected 'end-of-file) t "failure (end-of-file)"))) (t () (setf status "failure"))) (values (and (eql status t) (eql (peek-char nil input-stream nil) next-char)) status value) )))) (define-test read-integer-test ;; Integers. (assert-true (try #'read-integer "0" 0)) (assert-true (try #'read-integer "1" 1)) (assert-true (try #'read-integer "42" 42)) (assert-true (try #'read-integer "4223" 4223)) ;; Different radix. (assert-true (try #'read-integer '("10" t nil nil :radix 2) #2r10)) (assert-true (try #'read-integer '("21" t nil nil :radix 3) #3r21)) (assert-true (try #'read-integer '("32" t nil nil :radix 4) #4r32)) (assert-true (try #'read-integer '("43" t nil nil :radix 5) #5r43)) (assert-true (try #'read-integer '("54" t nil nil :radix 6) #6r54)) (assert-true (try #'read-integer '("65" t nil nil :radix 7) #7r65)) (assert-true (try #'read-integer '("76" t nil nil :radix 8) #8r76)) (assert-true (try #'read-integer '("87" t nil nil :radix 9) #9r87)) (assert-true (try #'read-integer '("98" t nil nil :radix 10) #10r98)) (assert-true (try #'read-integer '("a9" t nil nil :radix 11) #11ra9)) (assert-true (try #'read-integer '("ba" t nil nil :radix 12) #12rba)) (assert-true (try #'read-integer '("cb" t nil nil :radix 13) #13rcb)) (assert-true (try #'read-integer '("dc" t nil nil :radix 14) #14rdc)) (assert-true (try #'read-integer '("ed" t nil nil :radix 15) #15red)) (assert-true (try #'read-integer '("fe" t nil nil :radix 16) #16rfe)) (assert-true (try #'read-integer '("gf" t nil nil :radix 17) #17rgf)) (assert-true (try #'read-integer '("hg" t nil nil :radix 18) #18rhg)) (assert-true (try #'read-integer '("ih" t nil nil :radix 19) #19rih)) (assert-true (try #'read-integer '("ji" t nil nil :radix 20) #20rji)) (assert-true (try #'read-integer '("kj" t nil nil :radix 21) #21rkj)) (assert-true (try #'read-integer '("lk" t nil nil :radix 22) #22rlk)) (assert-true (try #'read-integer '("ml" t nil nil :radix 23) #23rml)) (assert-true (try #'read-integer '("nm" t nil nil :radix 24) #24rnm)) (assert-true (try #'read-integer '("on" t nil nil :radix 25) #25ron)) (assert-true (try #'read-integer '("po" t nil nil :radix 26) #26rpo)) (assert-true (try #'read-integer '("qp" t nil nil :radix 27) #27rqp)) (assert-true (try #'read-integer '("rq" t nil nil :radix 28) #28rrq)) (assert-true (try #'read-integer '("sr" t nil nil :radix 29) #29rsr)) (assert-true (try #'read-integer '("ts" t nil nil :radix 30) #30rts)) (assert-true (try #'read-integer '("ut" t nil nil :radix 31) #31rut)) (assert-true (try #'read-integer '("vu" t nil nil :radix 32) #32rvu)) (assert-true (try #'read-integer '("wv" t nil nil :radix 33) #33rwv)) (assert-true (try #'read-integer '("xw" t nil nil :radix 34) #34rxw)) (assert-true (try #'read-integer '("yx" t nil nil :radix 35) #35ryx)) (assert-true (try #'read-integer '("zy" t nil nil :radix 36) #36rzy)) (assert-true (try #'read-integer '("ZY" t nil nil :radix 36) #36rzy)) Leading zeros . (assert-true (try #'read-integer "00" 0)) (assert-true (try #'read-integer "007" 7)) ;; Signed numbers. (assert-true (try #'read-integer "+0" 0)) (assert-true (try #'read-integer "-0" 0)) (assert-true (try #'read-integer "+42" 42)) (assert-true (try #'read-integer "-42" -42)) ;; Trailing characters. (assert-true (try #'read-integer "42 " 42 :next-char #\Space)) (assert-true (try #'read-integer "42|" 42 :next-char #\|)) ;; Errors. (assert-true (try #'read-integer "" 'end-of-file)) (assert-true (try #'read-integer "+" 'end-of-file)) (assert-true (try #'read-integer "-" 'end-of-file)) (assert-true (try #'read-integer "|" 'parse-error :next-char #\|)) (assert-true (try #'read-integer "+|" 'parse-error :next-char #\|)) (assert-true (try #'read-integer "-|" 'parse-error :next-char #\|)) (assert-true (try #'read-integer " 42" 'parse-error :next-char #\Space)) (assert-true (try #'read-integer '("+42" t nil nil :unsigned-number t) 'parse-error :next-char #\+)) (assert-true (try #'read-integer '("-42" t nil nil :unsigned-number t) 'parse-error :next-char #\-)) (assert-true (try #'read-integer '("+42" t nil nil :unsigned-number :plus) 'parse-error :next-char #\+)) (assert-true (try #'read-integer '("-42" t nil nil :unsigned-number :plus) -42)) ;; Digit groups. (assert-true (try #'read-integer '("100_000" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-integer '("10_00_00" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-integer '("1_0_0_0_0_0" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-integer '("100_000_" t nil nil :group-separator "_") 'end-of-file)) (assert-true (try #'read-integer '("100_000_|" t nil nil :group-separator "_") 'parse-error :next-char #\|)) (assert-true (try #'read-integer '("100__000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("_100_000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("+_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("-_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("10'00_00" t nil nil :group-separator "_'") 1000 :next-char #\_)) (values)) (define-test read-float-test ;; Integers. (assert-true (try #'read-float "0" 0)) (assert-true (try #'read-float "1" 1)) (assert-true (try #'read-float "42" 42)) (assert-true (try #'read-float "4223" 4223)) Leading zeros . (assert-true (try #'read-float "00" 0)) (assert-true (try #'read-float "007" 7)) ;; Signed numbers. (assert-true (try #'read-float "+0" 0)) (assert-true (try #'read-float "-0" 0)) (assert-true (try #'read-float "+42" 42)) (assert-true (try #'read-float "-42" -42)) ;; Decimal numbers. (assert-true (try #'read-float "42." 42.0)) (assert-true (try #'read-float "42.0" 42.0)) (assert-true (try #'read-float "42.00" 42.0)) (assert-true (try #'read-float "42.23" 42.23)) (assert-true (try #'read-float "42.230" 42.23)) (assert-true (try #'read-float "42.2300" 42.23)) (assert-true (try #'read-float ".23" 0.23)) (assert-true (try #'read-float "+.23" 0.23)) (assert-true (try #'read-float "-.23" -0.23)) ;; Exponential notation. (assert-true (try #'read-float "1E1" 1E1)) (assert-true (try #'read-float "+1E1" 1E1)) (assert-true (try #'read-float "-1E1" -1E1)) (assert-true (try #'read-float "1.E1" 1E1)) (assert-true (try #'read-float "1.0E1" 1E1)) (assert-true (try #'read-float ".1E2" 0.1E2)) (assert-true (try #'read-float "1E+5" 1E+5)) (assert-true (try #'read-float "1E-5" 1E-5)) (assert-true (try #'read-float "1E00" 1E0)) (assert-true (try #'read-float "1E01" 1E1)) (assert-true (try #'read-float "1E+01" 1E+1)) (assert-true (try #'read-float "1E-01" 1E-1)) ;; Trailing characters. (assert-true (try #'read-float "42 " 42 :next-char #\Space)) (assert-true (try #'read-float "42|" 42 :next-char #\|)) ;; Errors. (assert-true (try #'read-float "" 'end-of-file)) (assert-true (try #'read-float "+" 'end-of-file)) (assert-true (try #'read-float "-" 'end-of-file)) (assert-true (try #'read-float "." 'end-of-file)) (assert-true (try #'read-float "1E" 'end-of-file)) (assert-true (try #'read-float "1E+" 'end-of-file)) (assert-true (try #'read-float "1E-" 'end-of-file)) (assert-true (try #'read-float "E" 'parse-error :next-char #\E)) (assert-true (try #'read-float "+E" 'parse-error :next-char #\E)) (assert-true (try #'read-float "-E" 'parse-error :next-char #\E)) (assert-true (try #'read-float ".E" 'parse-error :next-char #\E)) (assert-true (try #'read-float "|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "+|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "-|" 'parse-error :next-char #\|)) (assert-true (try #'read-float ".|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "1E|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "1E+|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "1E-|" 'parse-error :next-char #\|)) (assert-true (try #'read-float " 42" 'parse-error :next-char #\Space)) (assert-true (try #'read-float '("+42" t nil nil :unsigned-number t) 'parse-error :next-char #\+)) (assert-true (try #'read-float '("-42" t nil nil :unsigned-number t) 'parse-error :next-char #\-)) (assert-true (try #'read-float '("+42" t nil nil :unsigned-number :plus) 'parse-error :next-char #\+)) (assert-true (try #'read-float '("-42" t nil nil :unsigned-number :plus) -42)) ;; Digit groups. (assert-true (try #'read-float '("100_000" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-float '("10_00_00" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-float '("1_0_0_0_0_0" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-float '("100_000_" t nil nil :group-separator "_") 'end-of-file)) (assert-true (try #'read-float '("100_000_|" t nil nil :group-separator "_") 'parse-error :next-char #\|)) (assert-true (try #'read-float '("100__000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("_100_000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("+_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("-_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("10'00_00" t nil nil :group-separator "_'") 1000 :next-char #\_)) (assert-true (try #'read-float '("0.000_005" t nil nil :group-separator "_") 0.000005)) (assert-true (try #'read-float '("0.00_00_05" t nil nil :group-separator "_") 0.000005)) (assert-true (try #'read-float '("0.0_0_0_0_0_5" t nil nil :group-separator "_") 0.000005)) (assert-true (try #'read-float '("0.000_005_" t nil nil :group-separator "_") 'end-of-file)) (assert-true (try #'read-float '("0.000_005_|" t nil nil :group-separator "_") 'parse-error :next-char #\|)) (assert-true (try #'read-float '("0.000__005|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("0._000_005|" t nil nil :group-separator "_") 0 :next-char #\_)) (assert-true (try #'read-float '("10_00.00_05" t nil nil :group-separator "_") 1000.0005)) (assert-true (try #'read-float '("10_00_.00_05" t nil nil :group-separator "_") 'parse-error :next-char #\.)) (assert-true (try #'read-float '("10_00._00_05" t nil nil :group-separator "_") 1000 :next-char #\_)) (values)) (run-tests) ;;; tests.lisp ends here
null
https://raw.githubusercontent.com/ralph-schleicher/read-number/79fba40febd77b7793c42b5c5aa2bfdc5dfe80a2/tests.lisp
lisp
tests.lisp --- test procedure Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OR BUSINESS INTERRUPTION ) HOWEVER 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. Code: Integers. Different radix. Signed numbers. Trailing characters. Errors. Digit groups. Integers. Signed numbers. Decimal numbers. Exponential notation. Trailing characters. Errors. Digit groups. tests.lisp ends here
Copyright ( C ) 2016 " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT (in-package :common-lisp-user) (quicklisp:quickload :lisp-unit) (quicklisp:quickload :read-number) (defpackage :read-number-tests (:use :common-lisp :lisp-unit :read-number)) (in-package :read-number-tests) (defun try (fun spec &optional expected &key next-char) (multiple-value-bind (string arguments) (cond ((stringp spec) (values spec nil)) (t (values (first spec) (rest spec)))) (with-input-from-string (input-stream string) (let (value status) (handler-case (setf value (apply fun input-stream arguments) status (= value expected)) (parse-error () (setf status (if (eq expected 'parse-error) t "failure (parse-error)"))) (end-of-file () (setf status (if (eq expected 'end-of-file) t "failure (end-of-file)"))) (t () (setf status "failure"))) (values (and (eql status t) (eql (peek-char nil input-stream nil) next-char)) status value) )))) (define-test read-integer-test (assert-true (try #'read-integer "0" 0)) (assert-true (try #'read-integer "1" 1)) (assert-true (try #'read-integer "42" 42)) (assert-true (try #'read-integer "4223" 4223)) (assert-true (try #'read-integer '("10" t nil nil :radix 2) #2r10)) (assert-true (try #'read-integer '("21" t nil nil :radix 3) #3r21)) (assert-true (try #'read-integer '("32" t nil nil :radix 4) #4r32)) (assert-true (try #'read-integer '("43" t nil nil :radix 5) #5r43)) (assert-true (try #'read-integer '("54" t nil nil :radix 6) #6r54)) (assert-true (try #'read-integer '("65" t nil nil :radix 7) #7r65)) (assert-true (try #'read-integer '("76" t nil nil :radix 8) #8r76)) (assert-true (try #'read-integer '("87" t nil nil :radix 9) #9r87)) (assert-true (try #'read-integer '("98" t nil nil :radix 10) #10r98)) (assert-true (try #'read-integer '("a9" t nil nil :radix 11) #11ra9)) (assert-true (try #'read-integer '("ba" t nil nil :radix 12) #12rba)) (assert-true (try #'read-integer '("cb" t nil nil :radix 13) #13rcb)) (assert-true (try #'read-integer '("dc" t nil nil :radix 14) #14rdc)) (assert-true (try #'read-integer '("ed" t nil nil :radix 15) #15red)) (assert-true (try #'read-integer '("fe" t nil nil :radix 16) #16rfe)) (assert-true (try #'read-integer '("gf" t nil nil :radix 17) #17rgf)) (assert-true (try #'read-integer '("hg" t nil nil :radix 18) #18rhg)) (assert-true (try #'read-integer '("ih" t nil nil :radix 19) #19rih)) (assert-true (try #'read-integer '("ji" t nil nil :radix 20) #20rji)) (assert-true (try #'read-integer '("kj" t nil nil :radix 21) #21rkj)) (assert-true (try #'read-integer '("lk" t nil nil :radix 22) #22rlk)) (assert-true (try #'read-integer '("ml" t nil nil :radix 23) #23rml)) (assert-true (try #'read-integer '("nm" t nil nil :radix 24) #24rnm)) (assert-true (try #'read-integer '("on" t nil nil :radix 25) #25ron)) (assert-true (try #'read-integer '("po" t nil nil :radix 26) #26rpo)) (assert-true (try #'read-integer '("qp" t nil nil :radix 27) #27rqp)) (assert-true (try #'read-integer '("rq" t nil nil :radix 28) #28rrq)) (assert-true (try #'read-integer '("sr" t nil nil :radix 29) #29rsr)) (assert-true (try #'read-integer '("ts" t nil nil :radix 30) #30rts)) (assert-true (try #'read-integer '("ut" t nil nil :radix 31) #31rut)) (assert-true (try #'read-integer '("vu" t nil nil :radix 32) #32rvu)) (assert-true (try #'read-integer '("wv" t nil nil :radix 33) #33rwv)) (assert-true (try #'read-integer '("xw" t nil nil :radix 34) #34rxw)) (assert-true (try #'read-integer '("yx" t nil nil :radix 35) #35ryx)) (assert-true (try #'read-integer '("zy" t nil nil :radix 36) #36rzy)) (assert-true (try #'read-integer '("ZY" t nil nil :radix 36) #36rzy)) Leading zeros . (assert-true (try #'read-integer "00" 0)) (assert-true (try #'read-integer "007" 7)) (assert-true (try #'read-integer "+0" 0)) (assert-true (try #'read-integer "-0" 0)) (assert-true (try #'read-integer "+42" 42)) (assert-true (try #'read-integer "-42" -42)) (assert-true (try #'read-integer "42 " 42 :next-char #\Space)) (assert-true (try #'read-integer "42|" 42 :next-char #\|)) (assert-true (try #'read-integer "" 'end-of-file)) (assert-true (try #'read-integer "+" 'end-of-file)) (assert-true (try #'read-integer "-" 'end-of-file)) (assert-true (try #'read-integer "|" 'parse-error :next-char #\|)) (assert-true (try #'read-integer "+|" 'parse-error :next-char #\|)) (assert-true (try #'read-integer "-|" 'parse-error :next-char #\|)) (assert-true (try #'read-integer " 42" 'parse-error :next-char #\Space)) (assert-true (try #'read-integer '("+42" t nil nil :unsigned-number t) 'parse-error :next-char #\+)) (assert-true (try #'read-integer '("-42" t nil nil :unsigned-number t) 'parse-error :next-char #\-)) (assert-true (try #'read-integer '("+42" t nil nil :unsigned-number :plus) 'parse-error :next-char #\+)) (assert-true (try #'read-integer '("-42" t nil nil :unsigned-number :plus) -42)) (assert-true (try #'read-integer '("100_000" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-integer '("10_00_00" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-integer '("1_0_0_0_0_0" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-integer '("100_000_" t nil nil :group-separator "_") 'end-of-file)) (assert-true (try #'read-integer '("100_000_|" t nil nil :group-separator "_") 'parse-error :next-char #\|)) (assert-true (try #'read-integer '("100__000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("_100_000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("+_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("-_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-integer '("10'00_00" t nil nil :group-separator "_'") 1000 :next-char #\_)) (values)) (define-test read-float-test (assert-true (try #'read-float "0" 0)) (assert-true (try #'read-float "1" 1)) (assert-true (try #'read-float "42" 42)) (assert-true (try #'read-float "4223" 4223)) Leading zeros . (assert-true (try #'read-float "00" 0)) (assert-true (try #'read-float "007" 7)) (assert-true (try #'read-float "+0" 0)) (assert-true (try #'read-float "-0" 0)) (assert-true (try #'read-float "+42" 42)) (assert-true (try #'read-float "-42" -42)) (assert-true (try #'read-float "42." 42.0)) (assert-true (try #'read-float "42.0" 42.0)) (assert-true (try #'read-float "42.00" 42.0)) (assert-true (try #'read-float "42.23" 42.23)) (assert-true (try #'read-float "42.230" 42.23)) (assert-true (try #'read-float "42.2300" 42.23)) (assert-true (try #'read-float ".23" 0.23)) (assert-true (try #'read-float "+.23" 0.23)) (assert-true (try #'read-float "-.23" -0.23)) (assert-true (try #'read-float "1E1" 1E1)) (assert-true (try #'read-float "+1E1" 1E1)) (assert-true (try #'read-float "-1E1" -1E1)) (assert-true (try #'read-float "1.E1" 1E1)) (assert-true (try #'read-float "1.0E1" 1E1)) (assert-true (try #'read-float ".1E2" 0.1E2)) (assert-true (try #'read-float "1E+5" 1E+5)) (assert-true (try #'read-float "1E-5" 1E-5)) (assert-true (try #'read-float "1E00" 1E0)) (assert-true (try #'read-float "1E01" 1E1)) (assert-true (try #'read-float "1E+01" 1E+1)) (assert-true (try #'read-float "1E-01" 1E-1)) (assert-true (try #'read-float "42 " 42 :next-char #\Space)) (assert-true (try #'read-float "42|" 42 :next-char #\|)) (assert-true (try #'read-float "" 'end-of-file)) (assert-true (try #'read-float "+" 'end-of-file)) (assert-true (try #'read-float "-" 'end-of-file)) (assert-true (try #'read-float "." 'end-of-file)) (assert-true (try #'read-float "1E" 'end-of-file)) (assert-true (try #'read-float "1E+" 'end-of-file)) (assert-true (try #'read-float "1E-" 'end-of-file)) (assert-true (try #'read-float "E" 'parse-error :next-char #\E)) (assert-true (try #'read-float "+E" 'parse-error :next-char #\E)) (assert-true (try #'read-float "-E" 'parse-error :next-char #\E)) (assert-true (try #'read-float ".E" 'parse-error :next-char #\E)) (assert-true (try #'read-float "|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "+|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "-|" 'parse-error :next-char #\|)) (assert-true (try #'read-float ".|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "1E|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "1E+|" 'parse-error :next-char #\|)) (assert-true (try #'read-float "1E-|" 'parse-error :next-char #\|)) (assert-true (try #'read-float " 42" 'parse-error :next-char #\Space)) (assert-true (try #'read-float '("+42" t nil nil :unsigned-number t) 'parse-error :next-char #\+)) (assert-true (try #'read-float '("-42" t nil nil :unsigned-number t) 'parse-error :next-char #\-)) (assert-true (try #'read-float '("+42" t nil nil :unsigned-number :plus) 'parse-error :next-char #\+)) (assert-true (try #'read-float '("-42" t nil nil :unsigned-number :plus) -42)) (assert-true (try #'read-float '("100_000" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-float '("10_00_00" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-float '("1_0_0_0_0_0" t nil nil :group-separator "_") 100000)) (assert-true (try #'read-float '("100_000_" t nil nil :group-separator "_") 'end-of-file)) (assert-true (try #'read-float '("100_000_|" t nil nil :group-separator "_") 'parse-error :next-char #\|)) (assert-true (try #'read-float '("100__000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("_100_000|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("+_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("-_100_000" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("10'00_00" t nil nil :group-separator "_'") 1000 :next-char #\_)) (assert-true (try #'read-float '("0.000_005" t nil nil :group-separator "_") 0.000005)) (assert-true (try #'read-float '("0.00_00_05" t nil nil :group-separator "_") 0.000005)) (assert-true (try #'read-float '("0.0_0_0_0_0_5" t nil nil :group-separator "_") 0.000005)) (assert-true (try #'read-float '("0.000_005_" t nil nil :group-separator "_") 'end-of-file)) (assert-true (try #'read-float '("0.000_005_|" t nil nil :group-separator "_") 'parse-error :next-char #\|)) (assert-true (try #'read-float '("0.000__005|" t nil nil :group-separator "_") 'parse-error :next-char #\_)) (assert-true (try #'read-float '("0._000_005|" t nil nil :group-separator "_") 0 :next-char #\_)) (assert-true (try #'read-float '("10_00.00_05" t nil nil :group-separator "_") 1000.0005)) (assert-true (try #'read-float '("10_00_.00_05" t nil nil :group-separator "_") 'parse-error :next-char #\.)) (assert-true (try #'read-float '("10_00._00_05" t nil nil :group-separator "_") 1000 :next-char #\_)) (values)) (run-tests)