id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
42,902 | byte-vector.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/src/byte-vector.lisp | (in-package :cl-user)
(defpackage fast-http.byte-vector
(:use :cl)
(:import-from :alexandria
:define-constant)
(:export :+cr+
:+lf+
:+space+
:+tab+
:+page+
:+dash+
:+crlf+
:simple-byte-vector
:make-byte-vector
:digit-byte-char-p
:digit-byte-char-to-integer
:alpha-byte-char-p
:alpha-byte-char-to-lower-char
:alphanumeric-byte-char-p
:mark-byte-char-p
:ascii-octets-to-string
:ascii-octets-to-lower-string
:append-byte-vectors))
(in-package :fast-http.byte-vector)
(defconstant +cr+ (char-code #\Return))
(defconstant +lf+ (char-code #\Newline))
(defconstant +space+ (char-code #\Space))
(defconstant +tab+ (char-code #\Tab))
(defconstant +page+ (char-code #\Page))
(defconstant +dash+ #.(char-code #\-))
(define-constant +crlf+
(make-array 2 :element-type '(unsigned-byte 8)
:initial-contents (list +cr+ +lf+))
:test 'equalp)
(deftype simple-byte-vector (&optional (len '*))
`(simple-array (unsigned-byte 8) (,len)))
(declaim (inline digit-byte-char-p
digit-byte-char-to-integer
alpha-byte-char-p
alpha-byte-char-to-lower-char
alphanumeric-byte-char-p
mark-byte-char-p))
(defun digit-byte-char-p (byte)
(declare (type (unsigned-byte 8) byte)
(optimize (speed 3) (safety 0)))
(<= #.(char-code #\0) byte #.(char-code #\9)))
(declaim (ftype (function ((unsigned-byte 8)) fixnum) digit-byte-char-to-integer))
(defun digit-byte-char-to-integer (byte)
(declare (type (unsigned-byte 8) byte)
(optimize (speed 3) (safety 0)))
(the fixnum (- byte #.(char-code #\0))))
(defun alpha-byte-char-p (byte)
(declare (type (unsigned-byte 8) byte)
(optimize (speed 3) (safety 0)))
(or (<= #.(char-code #\A) byte #.(char-code #\Z))
(<= #.(char-code #\a) byte #.(char-code #\z))))
(defun alpha-byte-char-to-lower-char (byte)
(declare (type (unsigned-byte 8) byte)
(optimize (speed 3) (safety 0)))
(the character
(cond
((<= #.(char-code #\A) byte #.(char-code #\Z))
(code-char (+ byte #x20)))
(T #+nil(<= #.(char-code #\a) byte #.(char-code #\z))
(code-char byte)))))
(defun alphanumeric-byte-char-p (byte)
(declare (type (unsigned-byte 8) byte))
(or (alpha-byte-char-p byte)
(digit-byte-char-p byte)))
(defun mark-byte-char-p (byte)
(declare (type (unsigned-byte 8) byte)
(optimize (speed 3) (safety 0)))
(or (= byte #.(char-code #\-))
(= byte #.(char-code #\_))
(= byte #.(char-code #\.))
(= byte #.(char-code #\!))
(= byte #.(char-code #\~))
(= byte #.(char-code #\*))
(= byte #.(char-code #\'))
(= byte #.(char-code #\())
(= byte #.(char-code #\)))))
(declaim (ftype (function ((unsigned-byte 8)) (unsigned-byte 8)) byte-to-ascii-lower)
(inline byte-to-ascii-lower))
(defun byte-to-ascii-lower (x)
(declare (type (unsigned-byte 8) x)
(optimize (speed 3) (safety 0)))
(if (<= #.(char-code #\A) x #.(char-code #\Z))
(- x #.(- (char-code #\A) (char-code #\a)))
x))
(declaim (inline ascii-octets-to-string))
(defun ascii-octets-to-string (octets &key (start 0) (end (length octets)))
(declare (type simple-byte-vector octets)
(type (unsigned-byte 64) start end)
(optimize (speed 3) (safety 0)))
(let* ((len (the (unsigned-byte 64) (- end start)))
(string (make-string len :element-type 'character)))
(declare (type (unsigned-byte 64) len)
(type simple-string string))
(do ((i 0 (1+ i))
(j start (1+ j)))
((= j end) string)
(setf (aref string i)
(code-char (aref octets j))))))
(declaim (inline ascii-octets-to-lower-string))
(defun ascii-octets-to-lower-string (octets &key (start 0) (end (length octets)))
(declare (type simple-byte-vector octets)
(type (unsigned-byte 64) start end)
(optimize (speed 3) (safety 0)))
(let* ((len (the (unsigned-byte 64) (- end start)))
(string (make-string len :element-type 'character)))
(declare (type (unsigned-byte 64) len)
(type simple-string string))
(do ((i 0 (1+ i))
(j start (1+ j)))
((= j end) string)
(setf (aref string i)
(code-char (byte-to-ascii-lower (aref octets j)))))))
(defun append-byte-vectors (vec1 vec2)
(declare (type simple-byte-vector vec1 vec2)
(optimize (speed 3) (safety 0)))
(let* ((vec1-len (length vec1))
(vec2-len (length vec2))
(result (make-array (+ vec1-len vec2-len)
:element-type '(unsigned-byte 8))))
(declare (type simple-byte-vector result))
(replace result vec1 :start1 0)
(replace result vec2 :start1 vec1-len)
result))
| 4,989 | Common Lisp | .lisp | 128 | 31.625 | 85 | 0.570367 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | a526e7d41d2c36ca7606e68b63333abbc86741257c79d049fa51ef428a742040 | 42,902 | [
399456
] |
42,903 | parser.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/src/parser.lisp | (in-package :cl-user)
(defpackage fast-http.parser
(:use :cl
:fast-http.http
:fast-http.error
:proc-parse)
(:import-from :fast-http.byte-vector
:+space+
:+tab+
:+cr+
:+lf+
:simple-byte-vector
:digit-byte-char-p
:digit-byte-char-to-integer)
(:import-from :fast-http.util
:defun-insane
:defun-speedy)
(:import-from :alexandria
:format-symbol
:with-gensyms
:define-constant
:when-let)
(:export :callbacks
:make-callbacks
:parse-request
:parse-response
;; Conditions
:eof
;; Types
:pointer))
(in-package :fast-http.parser)
;;
;; Variables
(declaim (type fixnum +max-header-line+))
(defconstant +max-header-line+ 1024
"Maximum number of header lines allowed.
This restriction is for protecting users' application
against denial-of-service attacks where the attacker feeds
us a never-ending header that the application keeps buffering.")
;;
;; Types
(deftype pointer () 'integer)
;;
;; Callbacks
(defstruct callbacks
(message-begin nil :type (or null function)) ;; 1 arg
(url nil :type (or null function))
(first-line nil :type (or null function))
(status nil :type (or null function))
(header-field nil :type (or null function))
(header-value nil :type (or null function))
(headers-complete nil :type (or null function)) ;; 1 arg
(body nil :type (or null function))
(message-complete nil :type (or null function)))
(defmacro callback-data (name http callbacks data start end)
(with-gensyms (callback e)
`(when-let (,callback (,(format-symbol t "~A-~A" :callbacks name) ,callbacks))
(handler-bind ((error
(lambda (,e)
(unless (typep ,e 'fast-http-error)
(error ',(format-symbol t "~A-~A" :cb name)
:error ,e)
(abort ,e)))))
(funcall ,callback ,http ,data ,start ,end)))))
(defmacro callback-notify (name http callbacks)
(with-gensyms (callback e)
`(when-let (,callback (,(format-symbol t "~A-~A" :callbacks name) ,callbacks))
(handler-bind ((error
(lambda (,e)
(unless (typep ,e 'fast-http-error)
(error ',(format-symbol t "~A-~A" :cb name)
:error ,e)
(abort ,e)))))
(funcall ,callback ,http)))))
;;
;; Parser utilities
(define-condition eof () ())
(define-condition expect-failed (parsing-error)
((fast-http.error::description :initform "expect failed")))
;;
;; Tokens
(declaim (type (simple-array character (128)) +tokens+))
(define-constant +tokens+
(make-array 128
:element-type 'character
:initial-contents
'( #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul
#\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul
#\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul
#\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul
#\Nul #\! #\Nul #\# #\$ #\% #\& #\'
#\Nul #\Nul #\* #\+ #\Nul #\- #\. #\Nul
#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7
#\8 #\9 #\Nul #\Nul #\Nul #\Nul #\Nul #\Nul
#\Nul #\a #\b #\c #\d #\e #\f #\g
#\h #\i #\j #\k #\l #\m #\n #\o
#\p #\q #\r #\s #\t #\u #\v #\w
#\x #\y #\z #\Nul #\Nul #\Nul #\^ #\_
#\` #\a #\b #\c #\d #\e #\f #\g
#\h #\i #\j #\k #\l #\m #\n #\o
#\p #\q #\r #\s #\t #\u #\v #\w
#\x #\y #\z #\Nul #\| #\Nul #\~ #\Nul ))
:test 'equalp)
(declaim (type (simple-array fixnum (128)) +unhex+))
(define-constant +unhex+
(make-array 128 :element-type 'fixnum :initial-contents
'(-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
0 1 2 3 4 5 6 7 8 9 -1 -1 -1 -1 -1 -1
-1 10 11 12 13 14 15 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 10 11 12 13 14 15 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1))
:test 'equalp)
(defun-insane unhex-byte (byte)
(aref +unhex+ byte))
;;
;; Main
(defun-insane parse-method (data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(with-octets-parsing (data :start start :end end)
(return-from parse-method
(values
(prog1
(match-case
("CONNECT" :CONNECT)
("COPY" :COPY)
("CHECKOUT" :CHECKOUT)
("DELETE" :DELETE)
("GET" :GET)
("HEAD" :HEAD)
("LOCK" :LOCK)
("MKCOL" :MKCOL)
("MKCALENDAR" :MKCALENDAR)
("MKACTIVITY" :MKACTIVITY)
("MOVE" :MOVE)
("MERGE" :MERGE)
("M-SEARCH" :M-SEARCH)
("NOTIFY" :NOTIFY)
("OPTIONS" :OPTIONS)
("POST" :POST)
("PROPFIND" :PROPFIND)
("PROPPATCH" :PROPPATCH)
("PUT" :PUT)
("PURGE" :PURGE)
("PATCH" :PATCH)
("REPORT" :REPORT)
("SEARCH" :SEARCH)
("SUBSCRIBE" :SUBSCRIBE)
("TRACE" :TRACE)
("UNLOCK" :UNLOCK)
("UNSUBSCRIBE" :UNSUBSCRIBE)
(otherwise (error 'invalid-method)))
(unless (= (current) +space+)
(error 'invalid-method)))
(pos))))
(error 'eof))
(defun-insane parse-url (data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(flet ((url-char-byte-p (byte)
(or (<= (char-code #\!) byte (char-code #\~))
(<= 128 byte))))
(with-octets-parsing (data :start start :end end)
(skip-while url-char-byte-p)
(return-from parse-url (pos)))
(error 'eof)))
(defun-insane parse-http-version (data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(let (major minor)
(with-octets-parsing (data :start start :end end)
(or (match? "HTTP/")
(return-from parse-http-version (values nil nil (pos))))
(if (digit-byte-char-p (current))
(setq major (digit-byte-char-to-integer (current)))
(return-from parse-http-version (values nil nil (pos))))
(advance)
(or (skip? #\.) (return-from parse-http-version (values nil nil (pos))))
(if (digit-byte-char-p (current))
(setq minor (digit-byte-char-to-integer (current)))
(return-from parse-http-version (values nil nil (pos))))
(advance)
(return-from parse-http-version
(values major minor (pos))))
(error 'eof)))
(defun-insane parse-status-code (http callbacks data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(or (with-octets-parsing (data :start start :end end)
(if (digit-byte-char-p (current))
(setf (http-status http) (digit-byte-char-to-integer (current)))
(error 'invalid-status))
(loop
(advance)
(cond
((digit-byte-char-p (current))
(setf (http-status http)
(+ (the fixnum (* 10 (http-status http)))
(digit-byte-char-to-integer (current))))
(when (< 999 (http-status http))
(error 'invalid-status :status-code (http-status http))))
((= (current) +space+)
;; Reading the status text
(advance)
(let ((status-text-start (pos)))
(skip* (not #\Return))
(advance)
(skip #\Newline)
(callback-data :status http callbacks data status-text-start (- (pos) 1)))
(return))
((= (current) +cr+)
;; No status text
(advance)
(skip #\Newline)
(return))
(T (error 'invalid-status))))
(pos))
(error 'eof)))
(defun-speedy parse-header-field-and-value (http callbacks data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(or
(with-octets-parsing (data :start start :end end)
(let ((field-start (pos))
field-end)
(macrolet ((skip-until-value-start-and (&body body)
`(progn
;; skip #\: and leading spaces
(skip #\:)
(skip* #\Space #\Tab)
(cond
((= (current) +cr+)
;; continue to the next line
(advance)
(skip #\Newline)
(cond
((or (= (current) +space+)
(= (current) +tab+))
(skip* #\Space #\Tab)
(if (= (current) +cr+)
;; empty body
(progn
(advance)
(skip #\Newline)
(callback-data :header-field http callbacks data field-start field-end)
(callback-data :header-value http callbacks data (pos) (pos)))
(progn ,@body)))
;; empty body
(t
(callback-data :header-field http callbacks data field-start field-end)
(callback-data :header-value http callbacks data (pos) (pos)))))
(t ,@body))))
(handle-otherwise ()
`(progn
;; skip until field end
(do ((char (aref +tokens+ (current))
(aref +tokens+ (current))))
((= (current) (char-code #\:)))
(declare (type character char))
(when (char= char #\Nul)
(error 'invalid-header-token))
(advance))
(setq field-end (pos))
(skip-until-value-start-and
(advance-to*
(parse-header-value http callbacks data (pos) end field-start field-end)))))
(expect-field-end (&body body)
`(if (= (current) #.(char-code #\:))
(progn
(setq field-end (pos))
,@body)
(handle-otherwise))))
(match-i-case
("content-length"
(expect-field-end
(skip-until-value-start-and
(multiple-value-bind (value-start value-end next content-length)
(parse-header-value-content-length data (pos) end)
(declare (type pointer next))
(setf (http-content-length http) content-length)
(advance-to* next)
(callback-data :header-field http callbacks data field-start field-end)
(callback-data :header-value http callbacks data value-start value-end)))))
("transfer-encoding"
(expect-field-end
(skip-until-value-start-and
(multiple-value-bind (value-start value-end next chunkedp)
(parse-header-value-transfer-encoding data (pos) end)
(declare (type pointer next))
(setf (http-chunked-p http) chunkedp)
(advance-to* next)
(callback-data :header-field http callbacks data field-start field-end)
(callback-data :header-value http callbacks data value-start value-end)))))
("upgrade"
(expect-field-end
(skip-until-value-start-and
(setf (http-upgrade-p http) T)
(let ((value-start (pos)))
(skip* (not #\Return))
(advance)
(skip #\Newline)
(callback-data :header-field http callbacks data field-start field-end)
(callback-data :header-value http callbacks data value-start (- (pos) 2))))))
(otherwise (handle-otherwise)))))
(pos))
(error 'eof)))
(defun-speedy parse-header-value (http callbacks data start end &optional field-start field-end)
(or (with-octets-parsing (data :start start :end end)
(skip* (not #\Return))
(advance)
(skip #\Newline)
(when field-start
(callback-data :header-field http callbacks data field-start field-end))
(callback-data :header-value http callbacks data start (- (pos) 2))
(pos))
(error 'eof)))
(defun-speedy parse-header-value-transfer-encoding (data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(with-octets-parsing (data :start start :end end)
(match-i-case
("chunked"
(if (= (current) +cr+)
(progn
(advance)
(skip #\Newline)
(return-from parse-header-value-transfer-encoding
(values start (- (pos) 2) (pos) t)))
(progn
(skip+ (not #\Return))
(advance)
(skip #\Newline)
(return-from parse-header-value-transfer-encoding
(values start (- (pos) 2) (pos) nil)))))
(otherwise
(skip* (not #\Return))
(advance)
(skip #\Newline)
(return-from parse-header-value-transfer-encoding
(values start (- (pos) 2) (pos) nil)))))
(error 'eof))
(defun-speedy parse-header-value-content-length (data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(let ((content-length 0))
(declare (type integer content-length))
(with-octets-parsing (data :start start :end end)
(if (digit-byte-char-p (current))
(setq content-length (digit-byte-char-to-integer (current)))
(error 'invalid-content-length))
(loop
(advance)
(cond
((digit-byte-char-p (current))
(setq content-length
(+ (* 10 content-length)
(digit-byte-char-to-integer (current)))))
((= (current) +cr+)
(advance)
(skip #\Newline)
(return-from parse-header-value-content-length
(values start (- (pos) 2) (pos) content-length)))
((= (current) +space+)
;; Discard spaces
)
(t (error 'invalid-content-length)))))
(error 'eof)))
(defun-speedy parse-header-line (http callbacks data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(when (<= end start)
(error 'eof))
(let ((current (aref data start)))
(declare (type (unsigned-byte 8) current))
(cond
((or (= current +tab+)
(= current +space+))
(parse-header-value http callbacks data start end))
((/= current +cr+)
(parse-header-field-and-value http callbacks data start end))
(t
(incf start)
(when (= start end)
(error 'eof))
(setq current (aref data start))
(unless (= current +lf+)
(error 'expect-failed))
(values (1+ start) t)))))
(defun-speedy parse-headers (http callbacks data start end)
(declare (type http http)
(type simple-byte-vector data)
(type pointer start end))
(or (with-octets-parsing (data :start start :end end)
;; empty headers
(when (= (current) +cr+)
(advance)
(if (= (current) +lf+)
(return-from parse-headers (1+ (pos)))
(error 'expect-failed)))
(advance-to* (parse-header-field-and-value http callbacks data start end))
(setf (http-mark http) (pos))
(loop
(when (= +max-header-line+ (the fixnum (incf (http-header-read http))))
(error 'header-overflow))
(multiple-value-bind (next endp)
(parse-header-line http callbacks data (pos) end)
(advance-to* next)
(when endp
(return)))
(setf (http-mark http) (pos)))
(setf (http-mark http) (pos))
(setf (http-state http) +state-body+)
(pos))
(error 'eof)))
(defun-speedy read-body-data (http callbacks data start end)
(declare (type http http)
(type simple-byte-vector data)
(type pointer start end))
(let ((readable-count (the pointer (- end start))))
(declare (dynamic-extent readable-count)
(type pointer readable-count))
(if (<= (http-content-length http) readable-count)
(let ((body-end (+ start (http-content-length http))))
(declare (dynamic-extent body-end))
(setf (http-content-length http) 0)
(callback-data :body http callbacks data start body-end)
(setf (http-mark http) body-end)
(values body-end t))
;; still needs to read
(progn
(decf (http-content-length http) readable-count)
(callback-data :body http callbacks data start end)
(setf (http-mark http) end)
(values end nil)))))
(defun-speedy http-message-needs-eof-p (http)
(let ((status-code (http-status http)))
(declare (type status-code status-code))
(when (= status-code 0) ;; probably request
(return-from http-message-needs-eof-p nil))
(when (or (< 99 status-code 200) ;; 1xx e.g. Continue
(= status-code 204) ;; No Content
(= status-code 304)) ;; Not Modified
(return-from http-message-needs-eof-p nil))
(when (or (http-chunked-p http)
(http-content-length http))
(return-from http-message-needs-eof-p nil))
T))
(defun-speedy parse-body (http callbacks data start end requestp)
(declare (type http http)
(type simple-byte-vector data)
(type pointer start end))
(macrolet ((message-complete ()
`(progn
(callback-notify :message-complete http callbacks)
(setf (http-state http) +state-first-line+))))
(case (http-content-length http)
(0
;; Content-Length header given but zero: Content-Length: 0\r\n
(message-complete)
start)
('nil
(if (or requestp
(not (http-message-needs-eof-p http)))
;; Assume content-length 0 - read the next
(progn
(message-complete)
end)
;; read until EOF
(progn
(callback-data :body http callbacks data start end)
(setf (http-mark http) end)
end)))
(otherwise
;; Content-Length header given and non-zero
(multiple-value-bind (next completedp)
(read-body-data http callbacks data start end)
(when completedp
(message-complete))
next)))))
(defun-speedy parse-chunked-body (http callbacks data start end)
(declare (type http http)
(type simple-byte-vector data)
(type pointer start end))
(when (= start end)
(return-from parse-chunked-body start))
(or (with-octets-parsing (data :start start :end end)
(tagbody
(cond
((= (http-state http) +state-chunk-size+)
(go chunk-size))
((= (http-state http) +state-body+)
(go body))
((= (http-state http) +state-chunk-body-end-crlf+)
(go body-end-crlf))
((= (http-state http) +state-trailing-headers+)
(go trailing-headers))
(T (error 'invalid-internal-state :code (http-state http))))
chunk-size
(let ((unhex-val (unhex-byte (current))))
(declare (type fixnum unhex-val)
(dynamic-extent unhex-val))
(when (= unhex-val -1)
(error 'invalid-chunk-size))
(setf (http-content-length http) unhex-val)
(loop
(advance)
(if (= (current) +cr+)
(progn
(advance)
(tagbody
(skip #\Newline)
:eof
(return)))
(progn
(setq unhex-val (unhex-byte (current)))
(cond
((= unhex-val -1)
(cond
((or (= (current) (char-code #\;))
(= (current) (char-code #\Space)))
(skip* (not #\Return))
(advance)
(tagbody
(skip #\Newline)
:eof
(return)))
(t (error 'invalid-chunk-size))))
(t (setf (http-content-length http)
(+ (* 16 (http-content-length http)) unhex-val)))))))
(setf (http-state http) +state-body+)
(if (eofp)
(return-from parse-chunked-body (pos))
(setf (http-mark http) (pos))))
body
(cond
((zerop (http-content-length http))
;; trailing headers
(setf (http-state http) +state-trailing-headers+)
(go trailing-headers))
(T
(multiple-value-bind (next completedp)
(read-body-data http callbacks data (pos) end)
(declare (type pointer next))
(unless completedp
(return-from parse-chunked-body (pos)))
(setf (http-state http) +state-chunk-body-end-crlf+)
(advance-to next))))
body-end-crlf
(skip #\Return)
(tagbody
(skip #\Newline)
:eof
(setf (http-state http) +state-chunk-size+)
(when (eofp)
(return-from parse-chunked-body (pos))))
(setf (http-mark http) (pos))
(go chunk-size)
trailing-headers
(return-from parse-chunked-body
(prog1 (parse-headers http callbacks data (pos) end)
(callback-notify :message-complete http callbacks)))))
(error 'eof)))
(defun-speedy parse-request (http callbacks data &key (start 0) end)
(declare (type http http)
(type simple-byte-vector data))
(let ((end (or end (length data))))
(declare (type pointer start end))
(handler-bind ((match-failed
(lambda (c)
(declare (ignore c))
(error 'expect-failed))))
(with-octets-parsing (data :start start :end end)
(setf (http-mark http) start)
(tagbody
(let ((state (http-state http)))
(declare (type fixnum state))
(cond
((= +state-first-line+ state)
(go first-line))
((= +state-headers+ state)
(go headers))
((<= +state-chunk-size+ state +state-trailing-headers+)
(go body))
(T (error 'invalid-internal-state :code state))))
first-line
;; skip first empty line (some clients add CRLF after POST content)
(when (= (current) +cr+)
(advance)
(tagbody
(skip #\Newline)
:eof
(when (eofp)
(return-from parse-request (pos)))))
(setf (http-mark http) (pos))
(callback-notify :message-begin http callbacks)
(multiple-value-bind (method next)
(parse-method data (pos) end)
(declare (type pointer next))
(setf (http-method http) method)
(advance-to* next))
(skip* #\Space)
(let ((url-start-mark (pos))
(url-end-mark (parse-url data (pos) end)))
(declare (type pointer url-start-mark url-end-mark))
(tagbody retry-url-parse
(advance-to* url-end-mark)
(skip* #\Space)
(cond
;; No HTTP version
((= (current) +cr+)
(callback-data :url http callbacks data url-start-mark url-end-mark)
(advance)
(skip #\Newline))
(T (multiple-value-bind (major minor next)
(parse-http-version data (pos) end)
(declare (type pointer next))
(unless major
;; Invalid HTTP version.
;; Assuming it's also a part of URI.
(setq url-end-mark (parse-url data next end))
(go retry-url-parse))
(callback-data :url http callbacks data url-start-mark url-end-mark)
(setf (http-major-version http) major
(http-minor-version http) minor)
(advance-to* next))
(skip #\Return)
(skip #\Newline)))))
(setf (http-mark http) (pos))
(setf (http-state http) +state-headers+)
(callback-notify :first-line http callbacks)
headers
(advance-to* (parse-headers http callbacks data (pos) end))
(callback-notify :headers-complete http callbacks)
(setf (http-header-read http) 0)
;; Exit, the rest of the connect is in a different protocol.
(when (http-upgrade-p http)
(setf (http-state http) +state-first-line+)
(callback-notify :message-complete http callbacks)
(return-from parse-request (pos)))
(setf (http-state http)
(if (http-chunked-p http)
+state-chunk-size+
+state-body+))
body
(if (http-chunked-p http)
(advance-to* (parse-chunked-body http callbacks data (pos) end))
(progn
(and (advance-to* (parse-body http callbacks data (pos) end t))
(go first-line))))
(return-from parse-request (pos)))))
(error 'eof)))
(defun-speedy parse-response (http callbacks data &key (start 0) end)
(declare (type http http)
(type simple-byte-vector data))
(let ((end (or end
(length data))))
(declare (type pointer start end))
(handler-bind ((match-failed
(lambda (c)
(declare (ignore c))
(error 'expect-failed))))
(with-octets-parsing (data :start start :end end)
(setf (http-mark http) start)
(tagbody
(let ((state (http-state http)))
(declare (type fixnum state))
(cond
((= +state-first-line+ state)
(go first-line))
((= +state-headers+ state)
(go headers))
((<= +state-chunk-size+ state +state-trailing-headers+)
(go body))
(T (error 'invalid-internal-state :code state))))
first-line
(setf (http-mark http) (pos))
(callback-notify :message-begin http callbacks)
(multiple-value-bind (major minor next)
(parse-http-version data (pos) end)
(declare (type pointer next))
(setf (http-major-version http) major
(http-minor-version http) minor)
(advance-to* next))
(cond
((= (current) +space+)
(advance)
(advance-to (parse-status-code http callbacks data (pos) end)))
((= (current) +cr+)
(skip #\Newline))
(T (error 'invalid-version)))
(setf (http-mark http) (pos))
(setf (http-state http) +state-headers+)
(callback-notify :first-line http callbacks)
headers
(advance-to* (parse-headers http callbacks data (pos) end))
(callback-notify :headers-complete http callbacks)
(setf (http-header-read http) 0)
(setf (http-state http)
(if (http-chunked-p http)
+state-chunk-size+
+state-body+))
body
(if (http-chunked-p http)
(advance-to* (parse-chunked-body http callbacks data (pos) end))
(progn
(advance-to* (parse-body http callbacks data (pos) end nil))
(unless (eofp)
(go first-line))))
(return-from parse-response (pos)))))
(error 'eof)))
(defun parse-header-value-parameters (data &key
header-value-callback
header-parameter-key-callback
header-parameter-value-callback)
(declare (type simple-string data)
(optimize (speed 3) (safety 2)))
(let* ((header-name-mark 0)
parameter-key-mark
parameter-value-mark
parsing-quoted-string-p
(p 0)
(end (length data))
(char (aref data p)))
(declare (type character char))
(when (= end 0)
(return-from parse-header-value-parameters 0))
(macrolet ((go-state (state &optional (advance 1))
`(locally (declare (optimize (speed 3) (safety 0)))
(incf p ,advance)
(when (= p end)
(go eof))
(setq char (aref data p))
(go ,state))))
(flet ((tokenp (char)
(declare (optimize (speed 3) (safety 0)))
(let ((byte (char-code char)))
(and (< byte 128)
(not (char= (the character (aref +tokens+ byte)) #\Nul))))))
(tagbody
parsing-header-value-start
(case char
((#\Space #\Tab)
(go-state parsing-header-value))
(otherwise
(unless (tokenp char)
(error 'invalid-header-value))
(setq header-name-mark p)
(go-state parsing-header-value 0)))
parsing-header-value
(case char
(#\;
(when header-value-callback
(funcall (the function header-value-callback)
data header-name-mark p))
(setq header-name-mark nil)
(go-state looking-for-parameter-key))
(otherwise (go-state parsing-header-value)))
looking-for-parameter-key
(case char
((#\Space #\Tab #\; #\Newline #\Return)
(go-state looking-for-parameter-key))
(otherwise
(unless (tokenp char)
(error 'invalid-parameter-key))
(setq parameter-key-mark p)
(go-state parsing-parameter-key)))
parsing-parameter-key
(case char
(#\=
(assert parameter-key-mark)
(when header-parameter-key-callback
(funcall (the function header-parameter-key-callback)
data parameter-key-mark p))
(setq parameter-key-mark nil)
(go-state parsing-parameter-value-start))
(otherwise
(unless (tokenp char)
(error 'invalid-parameter-key))
(go-state parsing-parameter-key)))
parsing-parameter-value-start
(case char
(#\"
;; quoted-string
(setq parameter-value-mark (1+ p))
(setq parsing-quoted-string-p t)
(go-state parsing-parameter-quoted-value))
((#.+space+ #.+tab+)
(go-state parsing-parameter-value-start))
(otherwise
(setq parameter-value-mark p)
(go-state parsing-parameter-value 0)))
parsing-parameter-quoted-value
(if (char= char #\")
(progn
(assert parameter-value-mark)
(setq parsing-quoted-string-p nil)
(when header-parameter-value-callback
(funcall (the function header-parameter-value-callback)
data parameter-value-mark p))
(setq parameter-value-mark nil)
(go-state looking-for-parameter-key))
(go-state parsing-parameter-quoted-value))
parsing-parameter-value
(case char
(#\;
(assert parameter-value-mark)
(when header-parameter-value-callback
(funcall (the function header-parameter-value-callback)
data parameter-value-mark p))
(setq parameter-value-mark nil)
(go-state looking-for-parameter-key))
(otherwise
(go-state parsing-parameter-value)))
eof
(when header-name-mark
(when header-value-callback
(funcall (the function header-value-callback)
data header-name-mark p)))
(when parameter-key-mark
(error 'invalid-eof-state))
(when parameter-value-mark
(when parsing-quoted-string-p
(error 'invalid-eof-state))
(when header-parameter-value-callback
(funcall (the function header-parameter-value-callback)
data parameter-value-mark p))))))
p))
| 34,777 | Common Lisp | .lisp | 830 | 28.424096 | 106 | 0.493385 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 43c0014483ba9b2dc41dd7b238585dd03ab0c8be31070a2e5e28f69569055d80 | 42,903 | [
227526
] |
42,904 | fast-http.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/src/fast-http.lisp | (in-package :cl-user)
(defpackage fast-http
(:use :cl
:fast-http.http
:fast-http.parser
:fast-http.multipart-parser
:fast-http.byte-vector
:fast-http.error
:xsubseq)
(:import-from :fast-http.http
:+state-body+)
(:import-from :fast-http.parser
:parse-header-value-parameters)
(:import-from :fast-http.multipart-parser
:+body-done+)
(:import-from :fast-http.util
:defun-careful)
(:import-from :smart-buffer
:make-smart-buffer
:write-to-buffer
:finalize-buffer)
(:export :make-parser
:http-request
:http-response
:make-http-request
:make-http-response
:http-request-p
:http-response-p
:make-callbacks
:http-version
:http-major-version
:http-minor-version
:http-method
:http-resource
:http-status
:http-status-text
:http-content-length
:http-chunked-p
:http-upgrade-p
:http-headers
;; multipart parser
:make-multipart-parser
;; Low-level parser API
:http
:http-p
:make-http
:parse-request
:parse-response
:http-multipart-parse
:ll-multipart-parser
:make-ll-multipart-parser
;; Error
:fast-http-error
:callback-error
:cb-message-begin
:cb-url
:cb-first-line
:cb-header-field
:cb-header-value
:cb-headers-complete
:cb-body
:cb-message-complete
:cb-status
:parsing-error
:invalid-eof-state
:header-overflow
:closed-connection
:invalid-version
:invalid-status
:invalid-method
:invalid-url
:invalid-host
:invalid-port
:invalid-path
:invalid-query-string
:invalid-fragment
:lf-expected
:invalid-header-token
:invalid-content-length
:invalid-chunk-size
:invalid-constant
:invalid-internal-state
:strict-error
:paused-error
:unknown-error
:multipart-parsing-error
:invalid-multipart-body
:invalid-boundary
:header-value-parsing-error
:invalid-header-value
:invalid-parameter-key
:invalid-parameter-value))
(in-package :fast-http)
(defun-careful make-parser (http &key first-line-callback header-callback body-callback finish-callback)
(declare (type http http))
(let (callbacks
(parse-fn (etypecase http
(http-request #'parse-request)
(http-response #'parse-response)))
(headers nil)
(header-value-buffer nil)
parsing-header-field
data-buffer
header-complete-p
completedp)
(flet ((collect-prev-header-value ()
(when header-value-buffer
(let ((header-value
(locally (declare (optimize (speed 3) (safety 0)))
(coerce-to-string
(the (or octets-concatenated-xsubseqs
octets-xsubseq)
header-value-buffer)))))
(if (string= parsing-header-field "set-cookie")
(push header-value (gethash "set-cookie" headers))
(multiple-value-bind (previous-value existp)
(gethash (the simple-string parsing-header-field) headers)
(setf (gethash (the simple-string parsing-header-field) headers)
(if existp
(if (simple-string-p previous-value)
(concatenate 'string (the simple-string previous-value) ", " header-value)
(format nil "~A, ~A" previous-value header-value))
header-value))))))))
(setq callbacks
(make-callbacks
:message-begin (lambda (http)
(declare (ignore http))
(setq headers (make-hash-table :test 'equal)
header-complete-p nil
completedp nil))
:url (lambda (http data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(setf (http-resource http)
(ascii-octets-to-string data :start start :end end)))
:status (lambda (http data start end)
(declare (type simple-byte-vector data)
(type pointer start end))
(setf (http-status-text http)
(ascii-octets-to-string data :start start :end end)))
:first-line (and first-line-callback
(lambda (http)
(declare (ignore http))
(funcall (the function first-line-callback))))
:header-field (lambda (http data start end)
(declare (ignore http)
(type simple-byte-vector data)
(type pointer start end))
(collect-prev-header-value)
(setq header-value-buffer (make-concatenated-xsubseqs))
(setq parsing-header-field
(ascii-octets-to-lower-string data :start start :end end)))
:header-value (lambda (http data start end)
(declare (ignore http)
(type simple-byte-vector data)
(type pointer start end))
(xnconcf header-value-buffer
(xsubseq (subseq (the simple-byte-vector data) start end) 0)))
:headers-complete (lambda (http)
(collect-prev-header-value)
(setq header-value-buffer nil)
(when (gethash "set-cookie" headers)
(setf (gethash "set-cookie" headers)
(nreverse (gethash "set-cookie" headers))))
(setf (http-headers http) headers)
(when header-callback
(funcall (the function header-callback) headers))
(when (and (not (http-chunked-p http))
(not (numberp (http-content-length http))))
(setq completedp t))
(setq header-complete-p t))
:body (and body-callback
(lambda (http data start end)
(declare (ignore http)
(type simple-byte-vector data)
(type pointer start end))
(funcall (the function body-callback)
data start end)))
:message-complete (lambda (http)
(declare (ignore http))
(collect-prev-header-value)
(when finish-callback
(funcall (the function finish-callback)))
(setq completedp t)))))
(lambda (data &key (start 0) end)
(declare (optimize (speed 3) (safety 2)))
(cond
((eql data :eof)
(setq completedp t)
(when finish-callback
(funcall (the function finish-callback))))
(T
(locally (declare (type simple-byte-vector data)
(type pointer start))
(check-type end (or null pointer))
(when data-buffer
(setq data
(coerce-to-sequence
(xnconc (xsubseq data-buffer 0)
(xsubseq (the simple-byte-vector data) start (or end (length data))))))
(setq data-buffer nil
start 0
end nil))
(setf (http-mark http) start)
(handler-case
(funcall parse-fn http callbacks (the simple-byte-vector data) :start start :end end)
(eof ()
(setq data-buffer
(subseq data (http-mark http) (or end (length data)))))))))
(values http header-complete-p completedp))))
(defun find-boundary (content-type)
(declare (type string content-type))
(let ((parsing-boundary nil))
(parse-header-value-parameters content-type
:header-value-callback
(lambda (data start end)
(unless (string= data "multipart/form-data"
:start1 start :end1 end)
(return-from find-boundary nil)))
:header-parameter-key-callback
(lambda (data start end)
(when (string= data "boundary"
:start1 start :end1 end)
(setq parsing-boundary t)))
:header-parameter-value-callback
(lambda (data start end)
(when parsing-boundary
(return-from find-boundary (subseq data start end)))))))
(defun make-multipart-parser (content-type callback)
(check-type content-type string)
(let ((boundary (find-boundary content-type)))
(unless boundary
(return-from make-multipart-parser nil))
(let ((parser (make-ll-multipart-parser :boundary boundary))
(headers (make-hash-table :test 'equal))
parsing-content-disposition
parsing-header-field
field-meta
header-value-buffer
(body-buffer (make-smart-buffer))
callbacks)
(flet ((collect-prev-header-value ()
(when header-value-buffer
(let ((header-value
(babel:octets-to-string
(coerce-to-sequence header-value-buffer))))
(when parsing-content-disposition
(setq field-meta
(let (parsing-key
(field-meta (make-hash-table :test 'equal)))
(parse-header-value-parameters header-value
:header-parameter-key-callback
(lambda (data start end)
(setq parsing-key
(string-downcase (subseq data start end))))
:header-parameter-value-callback
(lambda (data start end)
(setf (gethash parsing-key field-meta)
(subseq data start end))))
field-meta)))
(setf (gethash parsing-header-field headers)
header-value)))))
(setq callbacks
(make-callbacks
:header-field (lambda (parser data start end)
(declare (ignore parser))
(collect-prev-header-value)
(setq header-value-buffer (make-concatenated-xsubseqs))
(let ((header-name
(ascii-octets-to-lower-string data :start start :end end)))
(setq parsing-content-disposition
(string= header-name "content-disposition"))
(setq parsing-header-field header-name)))
:header-value (lambda (parser data start end)
(declare (ignore parser))
(xnconcf header-value-buffer
(xsubseq (subseq data start end) 0)))
:headers-complete (lambda (parser)
(declare (ignore parser))
(collect-prev-header-value))
:message-complete (lambda (parser)
(declare (ignore parser))
(funcall callback
(gethash "name" field-meta)
headers
field-meta
(finalize-buffer body-buffer))
(setq headers (make-hash-table :test 'equal)
body-buffer (make-smart-buffer)
header-value-buffer nil))
:body (lambda (parser data start end)
(declare (ignore parser))
(write-to-buffer body-buffer data start end)))))
(lambda (data)
(http-multipart-parse parser callbacks data)
(= (ll-multipart-parser-state parser) +body-done+)))))
| 14,199 | Common Lisp | .lisp | 296 | 26.760135 | 111 | 0.447677 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 03e9e9910ef3422929d71664eb0742ea81849308f87ff26f1c64c69124d00cc2 | 42,904 | [
-1
] |
42,905 | multipart-parser.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/src/multipart-parser.lisp | (in-package :cl-user)
(defpackage fast-http.multipart-parser
(:use :cl
:fast-http.byte-vector
:fast-http.error)
(:import-from :fast-http.parser
:callbacks-body
:callbacks-headers-complete
:callbacks-message-begin
:callbacks-message-complete
:make-callbacks
:parse-headers)
(:import-from :fast-http.http
:http-state
:make-http
:+state-headers+
:+state-body+)
(:import-from :fast-http.util
:tagcasev
:casev)
(:import-from :alexandria
:format-symbol
:when-let)
(:export :ll-multipart-parser
:ll-multipart-parser-state
:make-ll-multipart-parser
:http-multipart-parse))
(in-package :fast-http.multipart-parser)
(defstruct (ll-multipart-parser (:constructor make-ll-multipart-parser
(&key boundary
&aux (header-parser
(let ((parser (make-http)))
(setf (http-state parser) +state-headers+)
parser)))))
(state 0 :type fixnum)
(header-parser)
boundary
body-mark
body-buffer
boundary-mark
boundary-buffer)
#.`(eval-when (:compile-toplevel :load-toplevel :execute)
,@(loop for i from 0
for state in '(parsing-delimiter-dash-start
parsing-delimiter-dash
parsing-delimiter
parsing-delimiter-end
parsing-delimiter-almost-done
parsing-delimiter-done
header-field-start
body-start
looking-for-delimiter
maybe-delimiter-start
maybe-delimiter-first-dash
maybe-delimiter-second-dash
body-almost-done
body-done)
collect `(defconstant ,(format-symbol t "+~A+" state) ,i)))
(defun http-multipart-parse (parser callbacks data &key (start 0) end)
(declare (type simple-byte-vector data))
(let* ((end (or end (length data)))
(boundary (map '(simple-array (unsigned-byte 8) (*)) #'char-code (ll-multipart-parser-boundary parser)))
(boundary-length (length boundary))
(header-parser (ll-multipart-parser-header-parser parser)))
(declare (type simple-byte-vector boundary))
(when (= start end)
(return-from http-multipart-parse start))
(macrolet ((with-body-cb (callback &body body)
`(handler-case (when-let (,callback (callbacks-body callbacks))
,@body)
(error (e)
(error 'cb-body :error e))))
(call-body-cb (&optional (end '(ll-multipart-parser-boundary-mark parser)))
(let ((g-end (gensym "END")))
`(with-body-cb callback
(when (ll-multipart-parser-body-buffer parser)
(funcall callback parser
(ll-multipart-parser-body-buffer parser)
0 (length (ll-multipart-parser-body-buffer parser)))
(setf (ll-multipart-parser-body-buffer parser) nil))
(when-let (,g-end ,end)
(funcall callback parser data
(ll-multipart-parser-body-mark parser)
,g-end)))))
(flush-boundary-buffer ()
`(with-body-cb callback
(when (ll-multipart-parser-boundary-buffer parser)
(funcall callback parser
(ll-multipart-parser-boundary-buffer parser)
0 (length (ll-multipart-parser-boundary-buffer parser)))
(setf (ll-multipart-parser-boundary-buffer parser) nil)))))
(let* ((p start)
(byte (aref data p)))
#+fast-http-debug
(log:debug (code-char byte))
(tagbody
(macrolet ((go-state (tag &optional (advance 1))
`(progn
,(case advance
(0 ())
(1 '(incf p))
(otherwise `(incf p ,advance)))
(setf (ll-multipart-parser-state parser) ,tag)
#+fast-http-debug
(log:debug ,(princ-to-string tag))
,@(and (not (eql advance 0))
`((when (= p end)
(go exit-loop))
(setq byte (aref data p))
#+fast-http-debug
(log:debug (code-char byte))))
(go ,tag))))
(tagcasev (ll-multipart-parser-state parser)
(+parsing-delimiter-dash-start+
(unless (= byte +dash+)
(go-state +header-field-start+ 0))
(go-state +parsing-delimiter-dash+))
(+parsing-delimiter-dash+
(unless (= byte +dash+)
(error 'invalid-multipart-body))
(go-state +parsing-delimiter+))
(+parsing-delimiter+
(let ((end2 (+ p boundary-length)))
(cond
((ll-multipart-parser-boundary-buffer parser)
(when (< (+ end (length (ll-multipart-parser-boundary-buffer parser)) -3) end2)
(setf (ll-multipart-parser-boundary-buffer parser)
(concatenate 'simple-byte-vector
(ll-multipart-parser-boundary-buffer parser)
data))
(go exit-loop))
(let ((data2 (make-array boundary-length :element-type '(unsigned-byte 8)))
(boundary-buffer-length (length (ll-multipart-parser-boundary-buffer parser))))
(replace data2 (ll-multipart-parser-boundary-buffer parser)
:start2 2)
(replace data2 data
:start1 (- boundary-buffer-length 2))
(unless (search boundary data2)
;; Still in the body
(when (ll-multipart-parser-body-mark parser)
(call-body-cb nil)
(flush-boundary-buffer)
(go-state +looking-for-delimiter+))
(error 'invalid-boundary))
(go-state +parsing-delimiter-end+ (- boundary-length boundary-buffer-length -2))))
((< (1- end) end2)
;; EOF
(setf (ll-multipart-parser-boundary-buffer parser)
(if (ll-multipart-parser-boundary-buffer parser)
(concatenate 'simple-byte-vector
(ll-multipart-parser-boundary-buffer parser)
(subseq data (max 0 (- p 2))))
(subseq data (max 0 (- p 2)))))
(go exit-loop))
(T
(unless (search boundary data :start2 p :end2 end2)
;; Still in the body
(when (ll-multipart-parser-body-mark parser)
(go-state +looking-for-delimiter+))
(error 'invalid-boundary))
(go-state +parsing-delimiter-end+ boundary-length)))))
(+parsing-delimiter-end+
(casev byte
(+cr+ (go-state +parsing-delimiter-almost-done+))
(+lf+ (go-state +parsing-delimiter-almost-done+ 0))
(+dash+ (go-state +body-almost-done+))
(otherwise
;; Still in the body
(when (ll-multipart-parser-body-mark parser)
(call-body-cb nil)
(flush-boundary-buffer)
(go-state +looking-for-delimiter+))
(error 'invalid-boundary))))
(+parsing-delimiter-almost-done+
(unless (= byte +lf+)
(error 'invalid-boundary))
(when (ll-multipart-parser-body-mark parser)
;; got a part
(when (ll-multipart-parser-boundary-mark parser)
(call-body-cb))
(when-let (callback (callbacks-message-complete callbacks))
(handler-case (funcall callback parser)
(error (e)
(error 'cb-message-complete :error e)))))
(go-state +parsing-delimiter-done+))
(+parsing-delimiter-done+
(when-let (callback (callbacks-message-begin callbacks))
(handler-case (funcall callback parser)
(error (e)
(error 'cb-message-begin :error e))))
(setf (ll-multipart-parser-body-mark parser) p)
(go-state +header-field-start+ 0))
(+header-field-start+
(let ((next (parse-headers header-parser callbacks data p end)))
(setq p (1- next)) ;; XXX
;; parsing headers done
(when (= (http-state header-parser) +state-body+)
(when-let (callback (callbacks-headers-complete callbacks))
(handler-case (funcall callback parser)
(error (e)
(error 'cb-headers-complete :error e))))
(setf (http-state header-parser) +state-headers+))
(go-state +body-start+ 0)))
(+body-start+
(setf (ll-multipart-parser-body-mark parser) (1+ p))
(go-state +looking-for-delimiter+))
(+looking-for-delimiter+
(setf (ll-multipart-parser-boundary-mark parser) nil)
(casev byte
(+cr+ (setf (ll-multipart-parser-boundary-mark parser) p)
(go-state +maybe-delimiter-start+))
(otherwise (go-state +looking-for-delimiter+))))
(+maybe-delimiter-start+
(unless (= byte +lf+)
(go-state +looking-for-delimiter+ 0))
(go-state +maybe-delimiter-first-dash+))
(+maybe-delimiter-first-dash+
(if (= byte +dash+)
(go-state +maybe-delimiter-second-dash+)
(if (= byte +cr+)
(progn
(setf (ll-multipart-parser-boundary-mark parser) p)
(go-state +maybe-delimiter-start+))
(go-state +looking-for-delimiter+))))
(+maybe-delimiter-second-dash+
(if (= byte +dash+)
(go-state +parsing-delimiter+)
(go-state +looking-for-delimiter+)))
(+body-almost-done+
(casev byte
(+dash+ (go-state +body-done+ 0))
(otherwise (error 'invalid-multipart-body))))
(+body-done+
(when (ll-multipart-parser-body-mark parser)
;; got a part
(setf (ll-multipart-parser-body-buffer parser) nil)
(call-body-cb)
(when-let (callback (callbacks-message-complete callbacks))
(handler-case (funcall callback parser)
(error (e)
(error 'cb-message-complete :error e))))
(setf (ll-multipart-parser-body-mark parser) nil))
(go exit-loop))))
exit-loop)
(when (ll-multipart-parser-body-mark parser)
(when (<= +looking-for-delimiter+
(ll-multipart-parser-state parser)
+maybe-delimiter-second-dash+)
(call-body-cb (or (ll-multipart-parser-boundary-mark parser) p)))
;; buffer the last part
(when (ll-multipart-parser-boundary-mark parser)
(setf (ll-multipart-parser-body-buffer parser)
(if (ll-multipart-parser-body-buffer parser)
(concatenate 'simple-byte-vector
(ll-multipart-parser-body-buffer parser)
(subseq data (ll-multipart-parser-boundary-mark parser)))
(subseq data (ll-multipart-parser-boundary-mark parser)))))
(setf (ll-multipart-parser-body-mark parser) 0
(ll-multipart-parser-boundary-mark parser) nil))
p))))
| 13,212 | Common Lisp | .lisp | 260 | 30.969231 | 113 | 0.471007 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 655a524d38617c970797353958bd2b2cbe978ee026bca619c9140e4880d8412a | 42,905 | [
3126
] |
42,906 | util.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/t/util.lisp | (in-package :cl-user)
(defpackage fast-http-test.util
(:use :cl
:fast-http.util
:prove))
(in-package :fast-http-test.util)
(plan nil)
(defun is-number (string expected)
(etypecase expected
(number
(ok (number-string-p string) (format nil "~S is a number" string))
(is (read-from-string string) expected (format nil "~S is ~S" string expected)))
(null
(ok (not (number-string-p string)) (format nil "~S is not a number" string)))))
(subtest "number-string-p"
(is-number "100" 100)
(is-number " 200" 200)
(is-number (format nil "~C250" #\Tab) 250)
(is-number " 300 " 300)
(is-number "10." 10)
(is-number "" nil)
(is-number " " nil)
(is-number (format nil "~C" #\Tab) nil)
(is-number "10a" nil)
(is-number "b20" nil)
(is-number "127.0.0.1" nil)
(is-number "1 2 3 4" nil))
(finalize)
| 853 | Common Lisp | .lisp | 28 | 26.928571 | 85 | 0.632156 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b30d63131ce0821b468d32650e9e105e6543c1ac1f69e5d9e29d9d84e7cf9fa8 | 42,906 | [
192686
] |
42,907 | test-utils.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/t/test-utils.lisp | (in-package :cl-user)
(defpackage fast-http-test.test-utils
(:use :cl)
(:export :str
:bv))
(in-package :fast-http-test.test-utils)
(defun str (&rest strings)
(apply #'concatenate 'string strings))
(defun bv (object &key length)
(flet ((to-bv (object)
(etypecase object
((simple-array (unsigned-byte 8) (*)) object)
(string (babel:string-to-octets object))
(vector (make-array (length object)
:element-type '(unsigned-byte 8)
:initial-contents object)))))
(if length
(let ((buf (make-array length :element-type '(unsigned-byte 8))))
(loop for i from 0
for el across (to-bv object)
do (setf (aref buf i) el))
buf)
(to-bv object))))
| 839 | Common Lisp | .lisp | 23 | 26.391304 | 73 | 0.540541 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | d6b1ecaa4ce45a3ea1235aed9fb2d7fd3becb1785674e9ab2a7c9e15c6ddddae | 42,907 | [
456053
] |
42,908 | benchmark.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/t/benchmark.lisp | (in-package :cl-user)
(defpackage fast-http-test.benchmark
(:use :cl
:fast-http)
(:export :run-ll-benchmark
:run-benchmark
:run-ll-profile
:run-profile))
(in-package :fast-http-test.benchmark)
(syntax:use-syntax :interpol)
(defun run-ll-benchmark ()
(let ((http (make-http-request))
(callbacks (make-callbacks))
(data (babel:string-to-octets #?"GET /cookies HTTP/1.1\r\nHost: 127.0.0.1:8090\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\nCookie: name=wookie\r\n\r\n")))
#+sbcl (sb-ext:gc :full t)
(time
(loop repeat 100000 do
(parse-request http callbacks data)))))
(defun run-benchmark ()
(let ((data (babel:string-to-octets #?"GET /cookies HTTP/1.1\r\nHost: 127.0.0.1:8090\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\nCookie: name=wookie\r\n\r\n"))
(http (make-http-request)))
#+sbcl (sb-ext:gc :full t)
(time
(loop repeat 100000 do
(let ((parser (make-parser http)))
(funcall parser data))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *profile-packages*
'("FAST-HTTP" "FAST-HTTP.PARSER" "FAST-HTTP.BYTE-VECTOR" "FAST-HTTP.ERROR" "FAST-HTTP.UTIL")))
#+sbcl
(defun run-ll-profile ()
#.`(sb-profile:profile ,@*profile-packages*)
(run-ll-benchmark)
(sb-profile:report)
#.`(sb-profile:unprofile ,@*profile-packages*))
#+sbcl
(defun run-profile ()
#.`(sb-profile:profile ,@*profile-packages*)
(run-benchmark)
(sb-profile:report)
#.`(sb-profile:unprofile ,@*profile-packages*))
| 2,218 | Common Lisp | .lisp | 41 | 49.439024 | 497 | 0.682174 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b9f36fb7c9ff4dbeec54a5438f27987fc9d4c5699720960f80350ecca4a6123b | 42,908 | [
184000
] |
42,909 | body-buffer.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/t/body-buffer.lisp | (in-package :cl-user)
(defpackage fast-http-test.body-buffer
(:use :cl
:fast-http.body-buffer
:fast-http-test.test-utils
:prove))
(in-package :fast-http-test.body-buffer)
(plan nil)
(subtest "swithcing buffer"
(let ((buffer (make-body-buffer :memory-limit 10 :disk-limit 15)))
(is (buffer-on-memory-p buffer) t "on memory")
(write-to-buffer buffer (bv "Hello"))
(is (buffer-on-memory-p buffer) t "still on memory")
(write-to-buffer buffer (bv "World!"))
(is (buffer-on-memory-p buffer) nil "on disk")
(is-error (write-to-buffer buffer (bv "Hello!"))
'body-buffer-limit-exceeded
"body buffer limit exceeded")))
(subtest "finalize-buffer"
(let ((buffer (make-body-buffer :memory-limit 10 :disk-limit 15)))
(write-to-buffer buffer (bv "Hello!"))
(let ((read-buf (make-array 6 :element-type '(unsigned-byte 8))))
(read-sequence read-buf (finalize-buffer buffer))
(is read-buf (bv "Hello!") :test #'equalp "on memory")))
(let ((buffer (make-body-buffer :memory-limit 10 :disk-limit 15)))
(write-to-buffer buffer (bv "Hello, World!"))
(let ((read-buf (make-array 13 :element-type '(unsigned-byte 8))))
(read-sequence read-buf (finalize-buffer buffer))
(is read-buf (bv "Hello, World!") :test #'equalp "on disk"))))
(finalize)
| 1,349 | Common Lisp | .lisp | 30 | 39.666667 | 70 | 0.649163 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | c3ed841bfe912042a2074edea819c3dc81ccf04dde81a9dfa529c5e411c34e9e | 42,909 | [
474008
] |
42,910 | parser.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/t/parser.lisp | (in-package :cl-user)
(defpackage fast-http-test.parser
(:use :cl
:fast-http.http
:fast-http.parser
:fast-http.error
:fast-http-test.test-utils
:prove
:babel))
(in-package :fast-http-test.parser)
(syntax:use-syntax :interpol)
(plan nil)
(defun test-simple (&rest objects)
(let ((http (make-http)))
(parse-request http (make-callbacks)
(bv (apply #'concatenate 'string objects)))
http))
(defun test-parser (type &rest objects)
(let ((http (make-http))
(headers '())
url
(body ""))
(funcall (ecase type
(:request #'parse-request)
(:response #'parse-response))
http
(make-callbacks
:header-field (lambda (http data start end)
(declare (ignore http))
(push (cons (babel:octets-to-string data :start start :end end)
nil)
headers))
:header-value (lambda (http data start end)
(declare (ignore http))
(setf (cdr (car headers))
(append (cdr (car headers))
(list (babel:octets-to-string data :start start :end end)))))
:body (lambda (http data start end)
(declare (ignore http))
(setq body
(concatenate 'string
body
(babel:octets-to-string data :start start :end end))))
:url (lambda (http data start end)
(declare (ignore http))
(setq url (babel:octets-to-string data :start start :end end))))
(bv (apply #'concatenate 'string objects)))
(list :method (http-method http)
:status-code (if (eql (http-status http) 0)
nil
(http-status http))
:http-major (http-major-version http)
:http-minor (http-minor-version http)
:url url
:headers (loop for (field . values) in (nreverse headers)
append (list field (apply #'concatenate 'string values)))
:body body)))
(subtest "HTTP methods"
(dolist (method '("DELETE"
"GET"
"HEAD"
"POST"
"PUT"
"OPTIONS"
"TRACE"
"COPY"
"LOCK"
"MKCOL"
"MOVE"
"PROPFIND"
"PROPPATCH"
"UNLOCK"
"REPORT"
"MKACTIVITY"
"CHECKOUT"
"MERGE"
"M-SEARCH"
"NOTIFY"
"SUBSCRIBE"
"UNSUBSCRIBE"
"PATCH"))
(ok (test-simple (concatenate 'string method #?" / HTTP/1.1\r\n\r\n"))
method)))
(subtest "HTTP bad methods"
(dolist (method '("ASDF"
"C******"
"COLA"
"GEM"
"GETA"
"M****"
"MKCOLA"
"PROPPATCHA"
"PUN"
"PX"
"SA"
"hello world"
"0"))
(is-error (test-simple (concatenate 'string method #?" / HTTP/1.1\r\n\r\n"))
'invalid-method
(format nil "~A" method))))
(is-error (test-simple #?"GET / HTTP/1.1\r\n"
#?"name\r\n"
#?" : value\r\n"
#?"\r\n")
'invalid-header-token
"illegal header field name line folding")
(ok (test-simple #?"GET / HTTP/1.1\r\n"
#?"X-SSL-Bullshit: -----BEGIN CERTIFICATE-----\r\n"
#?"\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\r\n"
#?"\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\r\n"
#?"\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\r\n"
#?"\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\r\n"
#?"\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\r\n"
#?"\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\r\n"
#?"\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC/1R64fAcEF\r\n"
#?"\tW51rEyFYiIeZGx/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\r\n"
#?"\tgW7cMA/s/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi/F1SiFlPDxuDfmdiNzL31+sL\r\n"
#?"\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW/iaLB0/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\r\n"
#?"\tu2MSpFyf+9BbC/aXgaZuiCvSR+8Snv3xApQY+fULK/xY8h8Ua51iXoQ5jrgu2SqR\r\n"
#?"\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\r\n"
#?"\tA1UdEwEB/wQCMAAwEQYJYIZIAYb4QgHTTPAQDAgWgMA4GA1UdDwEB/wQEAwID6DAs\r\n"
#?"\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\r\n"
#?"\tVR0OBBYEFDTt/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\r\n"
#?"\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\r\n"
#?"\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\r\n"
#?"\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\r\n"
#?"\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\r\n"
#?"\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\r\n"
#?"\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\r\n"
#?"\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\r\n"
#?"\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\r\n"
#?"\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS/U4iiooBENGW/Hwmmd3\r\n"
#?"\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv/hmi0qlnlHs+k/3Iobc3LjS5AMYr5L8\r\n"
#?"\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\r\n"
#?"\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\r\n"
#?"\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7/ZhW6DqT8UFvsAdjvQbXyhV8Eu\r\n"
#?"\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0/ES5gDGsABo4fqovUKlgop3\r\n"
#?"\tRA==\r\n"
#?"\t-----END CERTIFICATE-----\r\n"
#?"\r\n"))
(is (test-parser :request
#?"GET /test HTTP/1.1\r\n"
#?"User-Agent: curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n"
#?"Host: 0.0.0.0=5000\r\n"
#?"Accept: */*\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/test"
:headers ("User-Agent" "curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1"
"Host" "0.0.0.0=5000"
"Accept" "*/*")
:body "")
"curl GET")
(is (test-parser :request
#?"GET /favicon.ico HTTP/1.1\r\n"
#?"Host: 0.0.0.0=5000\r\n"
#?"User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0\r\n"
#?"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
#?"Accept-Language: en-us,en;q=0.5\r\n"
#?"Accept-Encoding: gzip,deflate\r\n"
#?"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
#?"Keep-Alive: 300\r\n"
#?"Connection: keep-alive\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/favicon.ico"
:headers ("Host" "0.0.0.0=5000"
"User-Agent" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0"
"Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"Accept-Language" "en-us,en;q=0.5"
"Accept-Encoding" "gzip,deflate"
"Accept-Charset" "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
"Keep-Alive" "300"
"Connection" "keep-alive")
:body "")
"Firefox GET")
(is (test-parser :request
#?"GET /dumbfuck HTTP/1.1\r\n"
#?"aaaaaaaaaaaaa:++++++++++\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/dumbfuck"
:headers ("aaaaaaaaaaaaa" "++++++++++")
:body "")
"dumbfuck")
(is (test-parser :request
#?"GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/forums/1/topics/2375?page=1#posts-17408"
:headers ()
:body "")
"fragment in URL")
(is (test-parser :request
#?"GET /get_no_headers_no_body/world HTTP/1.1\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/get_no_headers_no_body/world"
:headers ()
:body "")
"get no headers no body")
(is (test-parser :request
#?"GET /get_one_header_no_body HTTP/1.1\r\n"
#?"Accept: */*\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/get_one_header_no_body"
:headers ("Accept" "*/*")
:body "")
"get one header no body")
(is (test-parser :request
#?"GET /get_funky_content_length_body_hello HTTP/1.0\r\n"
#?"conTENT-Length: 5\r\n"
#?"\r\n"
"HELLO")
'(:method :get
:status-code nil
:http-major 1
:http-minor 0
:url "/get_funky_content_length_body_hello"
:headers ("conTENT-Length" "5")
:body "HELLO")
"get funky content length body hello")
(is (test-parser :request
#?"POST /post_identity_body_world?q=search#hey HTTP/1.1\r\n"
#?"Accept: */*\r\n"
#?"Transfer-Encoding: identity\r\n"
#?"Content-Length: 5\r\n"
#?"\r\n"
"World")
'(:method :post
:status-code nil
:http-major 1
:http-minor 1
:url "/post_identity_body_world?q=search#hey"
:headers ("Accept" "*/*"
"Transfer-Encoding" "identity"
"Content-Length" "5")
:body "World")
"post identity body world")
(is (test-parser :request
#?"POST /post_chunked_all_your_base HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"1e\r\nall your base are belong to us\r\n"
#?"0\r\n"
#?"\r\n")
'(:method :post
:status-code nil
:http-major 1
:http-minor 1
:url "/post_chunked_all_your_base"
:headers ("Transfer-Encoding" "chunked")
:body "all your base are belong to us")
"post - chunked body: all your base are belong to us")
(is (test-parser :request
#?"POST /two_chunks_mult_zero_end HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"5\r\nhello\r\n"
#?"6\r\n world\r\n"
#?"000\r\n"
#?"\r\n")
'(:method :post
:status-code nil
:http-major 1
:http-minor 1
:url "/two_chunks_mult_zero_end"
:headers ("Transfer-Encoding" "chunked")
:body "hello world")
"two chunks ; triple zero ending")
(is (test-parser :request
#?"POST /chunked_w_trailing_headers HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"5\r\nhello\r\n"
#?"6\r\n world\r\n"
#?"0\r\n"
#?"Vary: *\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n")
'(:method :post
:status-code nil
:http-major 1
:http-minor 1
:url "/chunked_w_trailing_headers"
:headers ("Transfer-Encoding" "chunked"
"Vary" "*"
"Content-Type" "text/plain")
:body "hello world")
"chunked with trailing headers. blech.")
(is (test-parser :request
#?"POST /chunked_w_bullshit_after_length HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"5; ihatew3;whatthefuck=aretheseparametersfor\r\nhello\r\n"
#?"6; blahblah; blah\r\n world\r\n"
#?"0\r\n"
#?"\r\n")
'(:method :post
:status-code nil
:http-major 1
:http-minor 1
:url "/chunked_w_bullshit_after_length"
:headers ("Transfer-Encoding" "chunked")
:body "hello world")
"with bullshit after the length")
(is (test-parser :request
#?"GET /with_\"stupid\"_quotes?foo=\"bar\" HTTP/1.1\r\n\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/with_\"stupid\"_quotes?foo=\"bar\""
:headers ()
:body "")
"with quotes")
(is (test-parser :request
#?"GET /test HTTP/1.0\r\n"
#?"Host: 0.0.0.0:5000\r\n"
#?"User-Agent: ApacheBench/2.3\r\n"
#?"Accept: */*\r\n\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 0
:url "/test"
:headers ("Host" "0.0.0.0:5000"
"User-Agent" "ApacheBench/2.3"
"Accept" "*/*")
:body "")
"ApacheBench GET")
(is (test-parser :request
#?"GET /test.cgi?foo=bar?baz HTTP/1.1\r\n\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/test.cgi?foo=bar?baz"
:headers ()
:body "")
"Query URL with question mark")
(is (test-parser :request
#?"\r\nGET /test HTTP/1.1\r\n\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/test"
:headers ()
:body "")
"Newline prefix GET")
(is (test-parser :request
#?"GET /demo HTTP/1.1\r\n"
#?"Host: example.com\r\n"
#?"Connection: Upgrade\r\n"
#?"Sec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\n"
#?"Sec-WebSocket-Protocol: sample\r\n"
#?"Upgrade-Insecure-Requests: 1\r\n"
#?"Upgrade: WebSocket\r\n"
#?"Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5\r\n"
#?"Origin: http://example.com\r\n"
#?"\r\n"
"Hot diggity dogg")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/demo"
:headers ("Host" "example.com"
"Connection" "Upgrade"
"Sec-WebSocket-Key2" "12998 5 Y3 1 .P00"
"Sec-WebSocket-Protocol" "sample"
"Upgrade-Insecure-Requests" "1"
"Upgrade" "WebSocket"
"Sec-WebSocket-Key1" "4 @1 46546xW%0l 1 5"
"Origin" "http://example.com")
:body "")
"Upgrade request")
(is (test-parser :request
#?"CONNECT 0-home0.netscape.com:443 HTTP/1.0\r\n"
#?"User-agent: Mozilla/1.1N\r\n"
#?"Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
#?"\r\n"
#?"some data\r\n"
"and yet even more data")
'(:method :connect
:status-code nil
:http-major 1
:http-minor 0
:url "0-home0.netscape.com:443"
:headers ("User-agent" "Mozilla/1.1N"
"Proxy-authorization" "basic aGVsbG86d29ybGQ=")
:body "")
"CONNECT request")
(is (test-parser :request
#?"REPORT /test HTTP/1.1\r\n"
#?"\r\n")
'(:method :report
:status-code nil
:http-major 1
:http-minor 1
:url "/test"
:headers ()
:body "")
"REPORT request")
(is (test-parser :request
#?"GET /\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 0
:http-minor 9
:url "/"
:headers ()
:body "")
"request with no HTTP version")
(is (test-parser :request
#?"M-SEARCH * HTTP/1.1\r\n"
#?"HOST: 239.255.255.250:1900\r\n"
#?"MAN: \"ssdp:discover\"\r\n"
#?"ST: \"ssdp:all\"\r\n"
#?"\r\n")
'(:method :m-search
:status-code nil
:http-major 1
:http-minor 1
:url "*"
:headers ("HOST" "239.255.255.250:1900"
"MAN" "\"ssdp:discover\""
"ST" "\"ssdp:all\"")
:body "")
"M-SEARCH request")
(is (test-parser :request
#?"GET / HTTP/1.1\r\n"
#?"Line1: abc\r\n"
#?"\tdef\r\n"
#?" ghi\r\n"
#?"\t\tjkl\r\n"
#?" mno \r\n"
#?"\t \tqrs\r\n"
#?"Line2: \t line2\t\r\n"
#?"Line3:\r\n"
#?" line3\r\n"
#?"Line4: \r\n"
#?" \r\n"
#?"Connection:\r\n"
#?" close\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/"
:headers ("Line1" #?"abc\tdef ghi\t\tjkl mno \t \tqrs"
"Line2" #?"line2\t"
"Line3" "line3"
"Line4" ""
"Connection" "close")
:body "")
"line folding in header value")
(is (test-parser :request
#?"GET http://hypnotoad.org?hail=all HTTP/1.1\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "http://hypnotoad.org?hail=all"
:headers ()
:body "")
"host terminated by a query string")
(is (test-parser :request
#?"GET http://hypnotoad.org:1234?hail=all HTTP/1.1\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "http://hypnotoad.org:1234?hail=all"
:headers ()
:body "")
"host:port terminated by a query string")
(is (test-parser :request
#?"GET http://hypnotoad.org:1234 HTTP/1.1\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "http://hypnotoad.org:1234"
:headers ()
:body "")
"host:port terminated by a space")
(is (test-parser :request
#?"PATCH /file.txt HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"Content-Type: application/example\r\n"
#?"If-Match: \"e0023aa4e\"\r\n"
#?"Content-Length: 10\r\n"
#?"\r\n"
"cccccccccc")
'(:method :patch
:status-code nil
:http-major 1
:http-minor 1
:url "/file.txt"
:headers ("Host" "www.example.com"
"Content-Type" "application/example"
"If-Match" "\"e0023aa4e\""
"Content-Length" "10")
:body "cccccccccc")
"PATCH request")
(is (test-parser :request
#?"CONNECT HOME0.NETSCAPE.COM:443 HTTP/1.0\r\n"
#?"User-agent: Mozilla/1.1N\r\n"
#?"Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
#?"\r\n")
'(:method :connect
:status-code nil
:http-major 1
:http-minor 0
:url "HOME0.NETSCAPE.COM:443"
:headers ("User-agent" "Mozilla/1.1N"
"Proxy-authorization" "basic aGVsbG86d29ybGQ=")
:body "")
"CONNECT caps request")
(is (test-parser :request
#?"GET /δ¶/δt/pope?q=1#narf HTTP/1.1\r\n"
#?"Host: github.com\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/δ¶/δt/pope?q=1#narf"
:headers ("Host" "github.com")
:body "")
"utf-8 path request")
(is (test-parser :request
#?"CONNECT home_0.netscape.com:443 HTTP/1.0\r\n"
#?"User-agent: Mozilla/1.1N\r\n"
#?"Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
#?"\r\n")
'(:method :connect
:status-code nil
:http-major 1
:http-minor 0
:url "home_0.netscape.com:443"
:headers ("User-agent" "Mozilla/1.1N"
"Proxy-authorization" "basic aGVsbG86d29ybGQ=")
:body "")
"underscore in hostname")
(is (test-parser :request
#?"POST / HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"Content-Type: application/x-www-form-urlencoded\r\n"
#?"Content-Length: 4\r\n"
#?"\r\n"
#?"q=42\r\n")
'(:method :post
:status-code nil
:http-major 1
:http-minor 1
:url "/"
:headers ("Host" "www.example.com"
"Content-Type" "application/x-www-form-urlencoded"
"Content-Length" "4")
:body "q=42")
"eat CRLF between requests, no \"Connection: close\" header")
(is (test-parser :request
#?"POST / HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"Content-Type: application/x-www-form-urlencoded\r\n"
#?"Content-Length: 4\r\n"
#?"Connection: close\r\n"
#?"\r\n"
#?"q=42\r\n")
'(:method :post
:status-code nil
:http-major 1
:http-minor 1
:url "/"
:headers ("Host" "www.example.com"
"Content-Type" "application/x-www-form-urlencoded"
"Content-Length" "4"
"Connection" "close")
:body "q=42")
"eat CRLF between requests even if \"Connection: close\" is set")
(is (test-parser :request
#?"PURGE /file.txt HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"\r\n")
'(:method :purge
:status-code nil
:http-major 1
:http-minor 1
:url "/file.txt"
:headers ("Host" "www.example.com")
:body "")
"PURGE request")
(is (test-parser :request
#?"SEARCH / HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"\r\n")
'(:method :search
:status-code nil
:http-major 1
:http-minor 1
:url "/"
:headers ("Host" "www.example.com")
:body "")
"SEARCH request")
(is (test-parser :request
#?"GET http://a%12:b!&*[email protected]:1234/toto HTTP/1.1\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "http://a%12:b!&*[email protected]:1234/toto"
:headers ()
:body "")
"host:port and basic_auth")
#+nil
(is (test-parser #?"GET / HTTP/1.1\n"
#?"Line1: abc\n"
#?"\tdef\n"
#?" ghi\n"
#?"\t\tjkl\n"
#?" mno \n"
#?"\t \tqrs\n"
#?"Line2: \t line2\t\n"
#?"Line3:\n"
#?" line3\n"
#?"Line4: \n"
#?" \n"
#?"Connection:\n"
#?" close\n"
#?"\n")
'(:method :get
:http-major 1
:http-minor 1
:url "/"
:headers ("Line1" #?"abc\tdef ghi\t\tjkl mno \t \tqrs"
"Line2" #?"line2\t"
"Line3" "line3"
"Line4" ""
"Connection" "close")
:body "")
"line folding in header value")
(let ((http (make-http)))
(parse-request http (make-callbacks)
(bv (str #?"POST / HTTP/1.1\r\n"
#?"Host: localhost:4242\r\n"
#?"User-Agent: Drakma/1.3.9 (SBCL 1.2.5; Darwin; 13.4.0; http://weitz.de/drakma/)\r\n"
#?"Accept: */*\r\n"
#?"Connection: close\r\n"
#?"Content-Type: multipart/form-data; boundary=----------6K3VbKXWtcya1TvQGlecdvbuB2x32I2jeasiKt8u7reHBln6i0\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n")))
(parse-request http (make-callbacks)
(bv (str #?"FB\r\n"
#?"------------6K3VbKXWtcya1TvQGlecdvbuB2x32I2jeasiKt8u7reHBln6i0\r\n"
#?"Content-Disposition: form-data; name=\"file\"; filename=\"file.txt\"\r\n"
#?"Content-Type: plain/text\r\n"
#?"\r\n"
#?"This is a text for test.\n"
#?"\r\n"
#?"------------6K3VbKXWtcya1TvQGlecdvbuB2x32I2jeasiKt8u7reHBln6i0--\r\n"
#?"\r\n"
#?"0\r\n"
#?"\r\n")))
(is (list :method (http-method http)
:http-major (http-major-version http)
:http-minor (http-minor-version http))
(list :method :post
:http-major 1
:http-minor 1)
"Divide into two"))
(is (test-parser :request
#?"GET /test\r\n"
#?"Host: 0.0.0.0=5000\r\n"
#?"Accept: */*\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 0
:http-minor 9
:url "/test"
:headers ("Host" "0.0.0.0=5000"
"Accept" "*/*")
:body "")
"GET (HTTP/0.9)")
(is (test-parser :request
#?"GET /test?name=my name\r\n"
#?"Host: 0.0.0.0=5000\r\n"
#?"Accept: */*\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 0
:http-minor 9
:url "/test?name=my name"
:headers ("Host" "0.0.0.0=5000"
"Accept" "*/*")
:body "")
"Space in URI (HTTP/0.9)")
(is (test-parser :request
#?"GET /test?name=my name HTTP/1.1\r\n"
#?"Host: 0.0.0.0=5000\r\n"
#?"Accept: */*\r\n"
#?"\r\n")
'(:method :get
:status-code nil
:http-major 1
:http-minor 1
:url "/test?name=my name"
:headers ("Host" "0.0.0.0=5000"
"Accept" "*/*")
:body "")
"Space in URI (HTTP/1.1)")
;;
;; Response
(is (test-parser :response
#?"HTTP/1.1 301 Moved Permanently\r\n"
#?"Location: http://www.google.com/\r\n"
#?"Content-Type: text/html; charset=UTF-8\r\n"
#?"Date: Sun, 26 Apr 2009 11:11:49 GMT\r\n"
#?"Expires: Tue, 26 May 2009 11:11:49 GMT\r\n"
#?"X-$PrototypeBI-Version: 1.6.0.3\r\n"
#?"Cache-Control: public, max-age=2592000\r\n"
#?"Server: gws\r\n"
#?"Content-Length: 219 \r\n"
#?"\r\n"
#?"<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"
#?"<TITLE>301 Moved</TITLE></HEAD><BODY>\n"
#?"<H1>301 Moved</H1>\n"
#?"The document has moved\n"
#?"<A HREF=\"http://www.google.com/\">here</A>.\r\n"
#?"</BODY></HTML>\r\n")
`(:method nil
:status-code 301
:http-major 1
:http-minor 1
:url nil
:headers ("Location" "http://www.google.com/"
"Content-Type" "text/html; charset=UTF-8"
"Date" "Sun, 26 Apr 2009 11:11:49 GMT"
"Expires" "Tue, 26 May 2009 11:11:49 GMT"
"X-$PrototypeBI-Version" "1.6.0.3"
"Cache-Control" "public, max-age=2592000"
"Server" "gws"
"Content-Length" "219 ")
:body ,(concatenate 'string
#?"<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"
#?"<TITLE>301 Moved</TITLE></HEAD><BODY>\n"
#?"<H1>301 Moved</H1>\n"
#?"The document has moved\n"
#?"<A HREF=\"http://www.google.com/\">here</A>.\r\n"
#?"</BODY></HTML>\r\n"))
"Google 301")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"Date: Tue, 04 Aug 2009 07:59:32 GMT\r\n"
#?"Server: Apache\r\n"
#?"X-Powered-By: Servlet/2.5 JSP/2.1\r\n"
#?"Content-Type: text/xml; charset=utf-8\r\n"
#?"Connection: close\r\n"
#?"\r\n"
#?"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
#?"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
#?" <SOAP-ENV:Body>\n"
#?" <SOAP-ENV:Fault>\n"
#?" <faultcode>SOAP-ENV:Client</faultcode>\n"
#?" <faultstring>Client Error</faultstring>\n"
#?" </SOAP-ENV:Fault>\n"
#?" </SOAP-ENV:Body>\n"
#?"</SOAP-ENV:Envelope>")
`(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Date" "Tue, 04 Aug 2009 07:59:32 GMT"
"Server" "Apache"
"X-Powered-By" "Servlet/2.5 JSP/2.1"
"Content-Type" "text/xml; charset=utf-8"
"Connection" "close")
:body ,(concatenate 'string
#?"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
#?"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
#?" <SOAP-ENV:Body>\n"
#?" <SOAP-ENV:Fault>\n"
#?" <faultcode>SOAP-ENV:Client</faultcode>\n"
#?" <faultstring>Client Error</faultstring>\n"
#?" </SOAP-ENV:Fault>\n"
#?" </SOAP-ENV:Body>\n"
#?"</SOAP-ENV:Envelope>"))
"no Content-Length response")
(is (test-parser :response
#?"HTTP/1.1 404 Not Found\r\n\r\n")
'(:method nil
:status-code 404
:http-major 1
:http-minor 1
:url nil
:headers ()
:body "")
"404 no headers and no body")
(is (test-parser :response
#?"HTTP/1.1 301\r\n\r\n")
'(:method nil
:status-code 301
:http-major 1
:http-minor 1
:url nil
:headers ()
:body "")
"301 no response phase")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"Content-Type: text/plain\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"25 \r\n"
#?"This is the data in the first chunk\r\n"
#?"\r\n"
#?"1C\r\n"
#?"and this is the second one\r\n"
#?"\r\n"
#?"0 \r\n"
#?"\r\n")
`(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Content-Type" "text/plain"
"Transfer-Encoding" "chunked")
:body ,(concatenate 'string
#?"This is the data in the first chunk\r\n"
#?"and this is the second one\r\n"))
"200 trailing space on chunked body")
#+todo
(is (test-parser :response
#?"HTTP/1.1 200 OK\n"
#?"Content-Type: text/html; charset=utf-8\n"
#?"Connection: close\n"
#?"\n"
#?"these headers are from http://news.ycombinator.com/")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Content-Type" "text/html; charset=utf-8"
"Connection" "close")
:body "these headers are from http://news.ycombinator.com/")
"no carriage ret")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"Content-Type: text/html; charset=UTF-8\r\n"
#?"Content-Length: 11\r\n"
#?"Proxy-Connection: close\r\n"
#?"Date: Thu, 31 Dec 2009 20:55:48 +0000\r\n"
#?"\r\n"
"hello world")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Content-Type" "text/html; charset=UTF-8"
"Content-Length" "11"
"Proxy-Connection" "close"
"Date" "Thu, 31 Dec 2009 20:55:48 +0000")
:body "hello world")
"proxy connection")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"Server: DCLK-AdSvr\r\n"
#?"Content-Type: text/xml\r\n"
#?"Content-Length: 0\r\n"
#?"DCLK_imp: v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~~okv=;dcmt=text/xml;;~~cs=o\r\n\r\n")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Server" "DCLK-AdSvr"
"Content-Type" "text/xml"
"Content-Length" "0"
"DCLK_imp" "v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~~okv=;dcmt=text/xml;;~~cs=o")
:body "")
"underscore header key")
(is (test-parser :response
#?"HTTP/1.0 301 Moved Permanently\r\n"
#?"Date: Thu, 03 Jun 2010 09:56:32 GMT\r\n"
#?"Server: Apache/2.2.3 (Red Hat)\r\n"
#?"Cache-Control: public\r\n"
#?"Pragma: \r\n"
#?"Location: http://www.bonjourmadame.fr/\r\n"
#?"Vary: Accept-Encoding\r\n"
#?"Content-Length: 0\r\n"
#?"Content-Type: text/html; charset=UTF-8\r\n"
#?"Connection: keep-alive\r\n"
#?"\r\n")
'(:method nil
:status-code 301
:http-major 1
:http-minor 0
:url nil
:headers ("Date" "Thu, 03 Jun 2010 09:56:32 GMT"
"Server" "Apache/2.2.3 (Red Hat)"
"Cache-Control" "public"
"Pragma" ""
"Location" "http://www.bonjourmadame.fr/"
"Vary" "Accept-Encoding"
"Content-Length" "0"
"Content-Type" "text/html; charset=UTF-8"
"Connection" "keep-alive")
:body "")
"bonjourmadame.fr")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"Date: Tue, 28 Sep 2010 01:14:13 GMT\r\n"
#?"Server: Apache\r\n"
#?"Cache-Control: no-cache, must-revalidate\r\n"
#?"Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n"
#?".et-Cookie: PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com\r\n"
#?"Vary: Accept-Encoding\r\n"
#?"_eep-Alive: timeout=45\r\n"
#?"_onnection: Keep-Alive\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"Content-Type: text/html\r\n"
#?"Connection: close\r\n"
#?"\r\n"
#?"0\r\n\r\n")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Date" "Tue, 28 Sep 2010 01:14:13 GMT"
"Server" "Apache"
"Cache-Control" "no-cache, must-revalidate"
"Expires" "Mon, 26 Jul 1997 05:00:00 GMT"
".et-Cookie" "PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com"
"Vary" "Accept-Encoding"
"_eep-Alive" "timeout=45"
"_onnection" "Keep-Alive"
"Transfer-Encoding" "chunked"
"Content-Type" "text/html"
"Connection" "close")
:body "")
"field underscore")
(is (test-parser :response
#?"HTTP/1.1 500 Oriëntatieprobleem\r\n"
#?"Date: Fri, 5 Nov 2010 23:07:12 GMT+2\r\n"
#?"Content-Length: 0\r\n"
#?"Connection: close\r\n"
#?"\r\n")
'(:method nil
:status-code 500
:http-major 1
:http-minor 1
:url nil
:headers ("Date" "Fri, 5 Nov 2010 23:07:12 GMT+2"
"Content-Length" "0"
"Connection" "close")
:body "")
"non-ASCII in status line")
(is (test-parser :response
#?"HTTP/0.9 200 OK\r\n"
#?"\r\n")
'(:method nil
:status-code 200
:http-major 0
:http-minor 9
:url nil
:headers ()
:body "")
"HTTP version 0.9")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n"
"hello world")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Content-Type" "text/plain")
:body "hello world")
"neither Content-Length nor Transfer-Encoding response")
(is (test-parser :response
#?"HTTP/1.0 200 OK\r\n"
#?"Connection: keep-alive\r\n"
#?"\r\n")
'(:method nil
:status-code 200
:http-major 1
:http-minor 0
:url nil
:headers ("Connection" "keep-alive")
:body "")
"HTTP/1.0 with keep-alive and EOF-terminated 200 status")
(is (test-parser :response
#?"HTTP/1.0 204 No content\r\n"
#?"Connection: keep-alive\r\n"
#?"\r\n")
'(:method nil
:status-code 204
:http-major 1
:http-minor 0
:url nil
:headers ("Connection" "keep-alive")
:body "")
"HTTP/1.0 with keep-alive and a 204 status")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"\r\n")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ()
:body "")
"HTTP/1.1 with an EOF-terminated 200 status")
(is (test-parser :response
#?"HTTP/1.1 204 No content\r\n"
#?"\r\n")
'(:method nil
:status-code 204
:http-major 1
:http-minor 1
:url nil
:headers ()
:body "")
"HTTP/1.1 with a 204 status")
(is (test-parser :response
#?"HTTP/1.1 204 No content\r\n"
#?"Connection: close\r\n"
#?"\r\n")
'(:method nil
:status-code 204
:http-major 1
:http-minor 1
:url nil
:headers ("Connection" "close")
:body "")
"HTTP/1.1 with a 204 status and keep-alive disabled")
(is (test-parser :response
#?"HTTP/1.1 200 OK\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"0\r\n"
#?"\r\n")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ("Transfer-Encoding" "chunked")
:body "")
"HTTP/1.1 with chunked endocing and a 200 response")
(is (test-parser :response
#?"HTTP/1.1 301 MovedPermanently\r\n"
#?"Date: Wed, 15 May 2013 17:06:33 GMT\r\n"
#?"Server: Server\r\n"
#?"x-amz-id-1: 0GPHKXSJQ826RK7GZEB2\r\n"
#?"p3p: policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \"\r\n"
#?"x-amz-id-2: STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD\r\n"
#?"Location: http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846\r\n"
#?"Vary: Accept-Encoding,User-Agent\r\n"
#?"Content-Type: text/html; charset=ISO-8859-1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"1\r\n"
#?"\n\r\n"
#?"0\r\n"
#?"\r\n")
'(:method nil
:status-code 301
:http-major 1
:http-minor 1
:url nil
:headers ("Date" "Wed, 15 May 2013 17:06:33 GMT"
"Server" "Server"
"x-amz-id-1" "0GPHKXSJQ826RK7GZEB2"
"p3p" "policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \""
"x-amz-id-2" "STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD"
"Location" "http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846"
"Vary" "Accept-Encoding,User-Agent"
"Content-Type" "text/html; charset=ISO-8859-1"
"Transfer-Encoding" "chunked")
:body #?"\n")
"amazon.com")
(is (test-parser :response
#?"HTTP/1.1 200 \r\n"
#?"\r\n")
'(:method nil
:status-code 200
:http-major 1
:http-minor 1
:url nil
:headers ()
:body "")
"empty reason phrase after space")
(finalize)
| 42,263 | Common Lisp | .lisp | 1,131 | 25.265252 | 249 | 0.484703 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 7e9bb6c6a04584a860fa676fc85799249e5099992b8875b3511bcc6ed805e7ab | 42,910 | [
410673
] |
42,911 | fast-http.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/t/fast-http.lisp | (in-package :cl-user)
(defpackage fast-http-test
(:use :cl
:fast-http
:fast-http-test.test-utils
:prove
:babel
:xsubseq)
(:import-from :alexandria
:ensure-list))
(in-package :fast-http-test)
(syntax:use-syntax :interpol)
(plan nil)
(defun is-request-or-response (type chunks headers body description)
(let* (got-headers
(got-body nil)
finishedp
headers-test-done-p body-test-done-p
(chunks (ensure-list chunks))
(length (length chunks))
(parser (make-parser (ecase type
(:request (make-http-request))
(:response (make-http-response)))
:header-callback (lambda (h) (setf got-headers h))
:body-callback (lambda (b start end)
(push (subseq b start end) got-body))
:finish-callback (lambda () (setf finishedp t)))))
(subtest description
(loop for i from 1
for chunk in chunks
do (multiple-value-bind (http header-complete-p completedp)
(funcall parser (babel:string-to-octets chunk))
(declare (ignore http))
(is completedp (= i length)
(format nil "is~:[ not~;~] completed: ~D / ~D" (= i length) i length))
(when (and header-complete-p
(not headers-test-done-p))
(subtest "headers"
(loop for (k v) on headers by #'cddr
do (is (gethash (string-downcase k) got-headers)
v))
(is (hash-table-count got-headers) (/ (length headers) 2)))
(setf headers-test-done-p t))
(when (and completedp
(not body-test-done-p))
(is (and got-body
(apply #'concatenate '(simple-array (unsigned-byte 8) (*))
(nreverse got-body))) body "body" :test #'equalp)
(setf body-test-done-p t)))))))
(defun is-request (chunks headers body description)
(is-request-or-response :request chunks headers body description))
(defun is-response (chunks headers body description)
(is-request-or-response :response chunks headers body description))
;;
;; Requests
(is-request (str #?"GET /test HTTP/1.1\r\n"
#?"User-Agent: curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n"
#?"Host: 0.0.0.0=5000\r\n"
#?"Accept: */*\r\n"
#?"\r\n")
'(:user-agent "curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1"
:host "0.0.0.0=5000"
:accept "*/*")
nil
"curl GET")
(is-request (str #?"GET /favicon.ico HTTP/1.1\r\n"
#?"Host: 0.0.0.0=5000\r\n"
#?"User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0\r\n"
#?"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
#?"Accept-Language: en-us,en;q=0.5\r\n"
#?"Accept-Encoding: gzip,deflate\r\n"
#?"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
#?"Keep-Alive: 300\r\n"
#?"Connection: keep-alive\r\n"
#?"\r\n")
'(:host "0.0.0.0=5000"
:user-agent "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0"
:accept "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
:accept-language "en-us,en;q=0.5"
:accept-encoding "gzip,deflate"
:accept-charset "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
:keep-alive "300"
:connection "keep-alive")
nil
"Firefox GET")
(is-request (str #?"GET /dumbfuck HTTP/1.1\r\n"
#?"aaaaaaaaaaaaa:++++++++++\r\n"
#?"\r\n")
'(:aaaaaaaaaaaaa "++++++++++")
nil
"dumbfuck")
(is-request (str #?"GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n"
#?"\r\n")
'()
nil
"fragment in URL")
(is-request (str #?"GET /get_no_headers_no_body/world HTTP/1.1\r\n"
#?"\r\n")
'()
nil
"get no headers no body")
(is-request (str #?"GET /get_one_header_no_body HTTP/1.1\r\n"
#?"Accept: */*\r\n"
#?"\r\n")
'(:accept "*/*")
nil
"get one headers no body")
(is-request (str #?"GET /get_funky_content_length_body_hello HTTP/1.0\r\n"
#?"conTENT-Length: 5\r\n"
#?"\r\n"
#?"HELLO")
'(:content-length "5")
(bv "HELLO")
"get funky content length body HELLO")
(is-request (str #?"POST /post_identity_body_world?q=search#hey HTTP/1.1\r\n"
#?"Accept: */*\r\n"
#?"Transfer-Encoding: identity\r\n"
#?"Content-Length: 5\r\n"
#?"\r\n"
#?"World")
'(:accept "*/*"
:transfer-encoding "identity"
:content-length "5")
(bv "World")
"post identity body world")
(is-request (str #?"POST /post_chunked_all_your_base HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"1e\r\nall your base are belong to us\r\n"
#?"0\r\n"
#?"\r\n")
'(:transfer-encoding "chunked")
(bv "all your base are belong to us")
"post - chunked body: all your base are belong to us")
(is-request (str #?"POST /two_chunks_mult_zero_end HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"5\r\nhello\r\n"
#?"6\r\n world\r\n"
#?"000\r\n"
#?"\r\n")
'(:transfer-encoding "chunked")
(bv "hello world")
"two chunks ; triple zero ending")
(is-request (str #?"POST /chunked_w_trailing_headers HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"5\r\nhello\r\n"
#?"6\r\n world\r\n"
#?"0\r\n"
#?"Vary: *\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n")
'(:transfer-encoding "chunked"
:vary "*"
:content-type "text/plain")
(bv "hello world")
"chunked with trailing headers. blech.")
(is-request (str #?"POST /chunked_w_bullshit_after_length HTTP/1.1\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"\r\n"
#?"5; ihatew3;whatthefuck=aretheseparametersfor\r\nhello\r\n"
#?"6; blahblah; blah\r\n world\r\n"
#?"0\r\n"
#?"\r\n")
'(:transfer-encoding "chunked")
(bv "hello world")
"with bullshit after the length")
(is-request #?"GET /with_\"stupid\"_quotes?foo=\"bar\" HTTP/1.1\r\n\r\n"
'()
nil
"with quotes")
(is-request (str #?"GET /test HTTP/1.0\r\n"
#?"Host: 0.0.0.0:5000\r\n"
#?"User-Agent: ApacheBench/2.3\r\n"
#?"Accept: */*\r\n\r\n")
'(:host "0.0.0.0:5000"
:user-agent "ApacheBench/2.3"
:accept "*/*")
nil
"ApacheBench GET")
(is-request #?"GET /test.cgi?foo=bar?baz HTTP/1.1\r\n\r\n"
'()
nil
"Query URL with question mark")
(is-request #?"\r\nGET /test HTTP/1.1\r\n\r\n"
'()
nil
"Newline prefix GET")
(is-request (str #?"GET /demo HTTP/1.1\r\n"
#?"Host: example.com\r\n"
#?"Connection: Upgrade\r\n"
#?"Sec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\n"
#?"Sec-WebSocket-Protocol: sample\r\n"
#?"Upgrade: WebSocket\r\n"
#?"Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5\r\n"
#?"Origin: http://example.com\r\n"
#?"\r\n"
#?"Hot diggity dogg")
'(:host "example.com"
:connection "Upgrade"
:sec-websocket-key2 "12998 5 Y3 1 .P00"
:sec-websocket-protocol "sample"
:upgrade "WebSocket"
:sec-websocket-key1 "4 @1 46546xW%0l 1 5"
:origin "http://example.com")
nil
"Upgrade request")
(is-request (str #?"CONNECT 0-home0.netscape.com:443 HTTP/1.0\r\n"
#?"User-agent: Mozilla/1.1N\r\n"
#?"Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
#?"\r\n"
#?"some data\r\n"
#?"and yet even more data")
'(:user-agent "Mozilla/1.1N"
:proxy-authorization "basic aGVsbG86d29ybGQ=")
nil
"CONNECT request")
(is-request (str #?"REPORT /test HTTP/1.1\r\n"
#?"\r\n")
'()
nil
"REPORT request")
(is-request (str #?"GET /\r\n"
#?"\r\n")
'()
nil
"request with no HTTP version")
(is-request (str #?"M-SEARCH * HTTP/1.1\r\n"
#?"HOST: 239.255.255.250:1900\r\n"
#?"MAN: \"ssdp:discover\"\r\n"
#?"ST: \"ssdp:all\"\r\n"
#?"\r\n")
'(:host "239.255.255.250:1900"
:man "\"ssdp:discover\""
:st "\"ssdp:all\"")
nil
"M-SEARCH request")
(is-request (str #?"GET / HTTP/1.1\r\n"
#?"Line1: abc\r\n"
#?"\tdef\r\n"
#?" ghi\r\n"
#?"\t\tjkl\r\n"
#?" mno \r\n"
#?"\t \tqrs\r\n"
#?"Line2: \t line2\t\r\n"
#?"Line3:\r\n"
#?" line3\r\n"
#?"Line4: \r\n"
#?" \r\n"
#?"Connection:\r\n"
#?" close\r\n"
#?"\r\n")
'(:line1 #?"abc\tdef ghi\t\tjkl mno \t \tqrs"
:line2 #?"line2\t"
:line3 "line3"
:line4 ""
:connection "close")
nil
"line folding in header value")
(is-request (str #?"GET http://hypnotoad.org?hail=all HTTP/1.1\r\n"
#?"\r\n")
'()
nil
"host terminated by a query string")
(is-request (str #?"GET http://hypnotoad.org:1234?hail=all HTTP/1.1\r\n"
#?"\r\n")
'()
nil
"host:port terminated by a query string")
(is-request (str #?"GET http://hypnotoad.org:1234 HTTP/1.1\r\n"
#?"\r\n")
'()
nil
"host:port terminated by a space")
(is-request (str #?"PATCH /file.txt HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"Content-Type: application/example\r\n"
#?"If-Match: \"e0023aa4e\"\r\n"
#?"Content-Length: 10\r\n"
#?"\r\n"
#?"cccccccccc")
'(:host "www.example.com"
:content-type "application/example"
:if-match "\"e0023aa4e\""
:content-length "10")
(bv "cccccccccc")
"PATCH request")
(is-request (str #?"CONNECT HOME0.NETSCAPE.COM:443 HTTP/1.0\r\n"
#?"User-agent: Mozilla/1.1N\r\n"
#?"Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
#?"\r\n")
'(:user-agent "Mozilla/1.1N"
:proxy-authorization "basic aGVsbG86d29ybGQ=")
nil
"CONNECT caps request")
(is-request (str #?"GET /δ¶/δt/pope?q=1#narf HTTP/1.1\r\n"
#?"Host: github.com\r\n"
#?"\r\n")
'(:host "github.com")
nil
"utf-8 path request")
(is-request (str #?"CONNECT home_0.netscape.com:443 HTTP/1.0\r\n"
#?"User-agent: Mozilla/1.1N\r\n"
#?"Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
#?"\r\n")
'(:user-agent "Mozilla/1.1N"
:proxy-authorization "basic aGVsbG86d29ybGQ=")
nil
"underscore in hostname")
(is-request (str #?"POST / HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"Content-Type: application/x-www-form-urlencoded\r\n"
#?"Content-Length: 4\r\n"
#?"\r\n"
#?"q=42\r\n")
'(:host "www.example.com"
:content-type "application/x-www-form-urlencoded"
:content-length "4")
(bv "q=42")
"eat CRLF between requests, no \"Connection: close\" header")
(is-request (str #?"POST / HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"Content-Type: application/x-www-form-urlencoded\r\n"
#?"Content-Length: 4\r\n"
#?"Connection: close\r\n"
#?"\r\n"
#?"q=42\r\n")
'(:host "www.example.com"
:content-type "application/x-www-form-urlencoded"
:content-length "4"
:connection "close")
(bv "q=42")
"eat CRLF between requests even if \"Connection: close\" is set")
(is-request (str #?"PURGE /file.txt HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"\r\n")
'(:host "www.example.com")
nil
"PURGE request")
(is-request (str #?"SEARCH / HTTP/1.1\r\n"
#?"Host: www.example.com\r\n"
#?"\r\n")
'(:host "www.example.com")
nil
"SEARCH request")
(is-request (str #?"GET http://a%12:b!&*[email protected]:1234/toto HTTP/1.1\r\n"
#?"\r\n")
'()
nil
"host:port and basic_auth")
#+nil
(is-request (str #?"GET / HTTP/1.1\n"
#?"Line1: abc\n"
#?"\tdef\n"
#?" ghi\n"
#?"\t\tjkl\n"
#?" mno \n"
#?"\t \tqrs\n"
#?"Line2: \t line2\t\n"
#?"Line3:\n"
#?" line3\n"
#?"Line4: \n"
#?" \n"
#?"Connection:\n"
#?" close\n"
#?"\n")
'(:line1 #?"abc\tdef ghi\t\tjkl mno \t \tqrs"
:line2 #?"line2\t"
:line3 "line3"
:line4 ""
:connection "close")
nil
"line folding in header value")
;;
;; Responses
(is-response (str #?"HTTP/1.1 301 Moved Permanently\r\n"
#?"Location: http://www.google.com/\r\n"
#?"Content-Type: text/html; charset=UTF-8\r\n"
#?"Date: Sun, 26 Apr 2009 11:11:49 GMT\r\n"
#?"Expires: Tue, 26 May 2009 11:11:49 GMT\r\n"
#?"X-$PrototypeBI-Version: 1.6.0.3\r\n"
#?"Cache-Control: public, max-age=2592000\r\n"
#?"Server: gws\r\n"
#?"Content-Length: 219 \r\n"
#?"\r\n"
#?"<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"
#?"<TITLE>301 Moved</TITLE></HEAD><BODY>\n"
#?"<H1>301 Moved</H1>\n"
#?"The document has moved\n"
#?"<A HREF=\"http://www.google.com/\">here</A>.\r\n"
#?"</BODY></HTML>\r\n")
'(:location "http://www.google.com/"
:content-type "text/html; charset=UTF-8"
:date "Sun, 26 Apr 2009 11:11:49 GMT"
:expires "Tue, 26 May 2009 11:11:49 GMT"
:x-$prototypebi-version "1.6.0.3"
:cache-control "public, max-age=2592000"
:server "gws"
:content-length "219 ")
(bv (str #?"<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"
#?"<TITLE>301 Moved</TITLE></HEAD><BODY>\n"
#?"<H1>301 Moved</H1>\n"
#?"The document has moved\n"
#?"<A HREF=\"http://www.google.com/\">here</A>.\r\n"
#?"</BODY></HTML>\r\n"))
"Google 301")
(is-response (str #?"HTTP/1.1 200 OK\r\n"
#?"Date: Tue, 04 Aug 2009 07:59:32 GMT\r\n"
#?"Server: Apache\r\n"
#?"X-Powered-By: Servlet/2.5 JSP/2.1\r\n"
#?"Content-Type: text/xml; charset=utf-8\r\n"
#?"Connection: close\r\n"
#?"\r\n"
#?"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
#?"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
#?" <SOAP-ENV:Body>\n"
#?" <SOAP-ENV:Fault>\n"
#?" <faultcode>SOAP-ENV:Client</faultcode>\n"
#?" <faultstring>Client Error</faultstring>\n"
#?" </SOAP-ENV:Fault>\n"
#?" </SOAP-ENV:Body>\n"
#?"</SOAP-ENV:Envelope>")
'(:date "Tue, 04 Aug 2009 07:59:32 GMT"
:server "Apache"
:x-powered-by "Servlet/2.5 JSP/2.1"
:content-type "text/xml; charset=utf-8"
:connection "close")
(bv (str #?"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
#?"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
#?" <SOAP-ENV:Body>\n"
#?" <SOAP-ENV:Fault>\n"
#?" <faultcode>SOAP-ENV:Client</faultcode>\n"
#?" <faultstring>Client Error</faultstring>\n"
#?" </SOAP-ENV:Fault>\n"
#?" </SOAP-ENV:Body>\n"
#?"</SOAP-ENV:Envelope>"))
"no Content-Length response")
(defparameter *response*
#?"HTTP/1.1 200 OK\r
Server: Wookie (0.3.11)\r
Transfer-Encoding: chunked\r
\r
7\r
hello, \r
4\r
how \r
4\r
are \r
4\r
you?\r
0\r
\r
")
(subtest "chunk body"
(let* ((http (fast-http:make-http-response))
(parser (fast-http:make-parser http
:body-callback
(lambda (chunk start end)
(format t "chunk: ~a~%" (babel:octets-to-string (subseq chunk start end))))
:finish-callback
(lambda ()
(format t "finish.~%"))))
(header-chunk1 (subseq *response* 0 1)) ; <headers>
(header-chunk2 (subseq *response* 1 72)) ; <headers>
(chunk1 (subseq *response* 72 84)) ; "hello, "
(chunk2 (subseq *response* 84 102)) ; "how are "
(chunk3 (subseq *response* 102)) ; "you?"
(do-parse (lambda (chunk)
(funcall parser (babel:string-to-octets chunk)))))
(funcall do-parse header-chunk1)
(funcall do-parse header-chunk2)
(is-print (funcall do-parse chunk1) #?"chunk: hello, \n" "chunk1")
(is-print (funcall do-parse chunk2) #?"chunk: how \nchunk: are \n" "chunk2")
(is-print (funcall do-parse chunk3) #?"chunk: you?\nfinish.\n" "chunk3 and finish")))
(subtest "chunk body"
(let* ((http (fast-http:make-http-response))
(parser (fast-http:make-parser http
:body-callback
(lambda (chunk start end)
(format t "chunk: ~a~%" (babel:octets-to-string (subseq chunk start end))))
:finish-callback
(lambda ()
(format t "finish.~%"))))
(chunk01 (subseq *response* 0 17))
(chunk02 (subseq *response* 17 72))
(chunk03 (subseq *response* 72 73))
(chunk04 (subseq *response* 73 84))
(chunk05 (subseq *response* 84 85))
(chunk06 (subseq *response* 85 87))
(chunk07 (subseq *response* 87 91))
(chunk08 (subseq *response* 91 93))
(chunk09 (subseq *response* 93 101))
(chunk10 (subseq *response* 101 103))
(chunk11 (subseq *response* 103))
(do-parse (lambda (chunk)
(funcall parser (babel:string-to-octets chunk)))))
;; first line
(funcall do-parse chunk01)
;; headers
(funcall do-parse chunk02)
(is-print (funcall do-parse chunk03) "")
(is-print (funcall do-parse chunk04) #?"chunk: hello, \n")
(is-print (funcall do-parse chunk05) "")
(is-print (funcall do-parse chunk06) "")
(is-print (funcall do-parse chunk07) #?"chunk: how \n")
(is-print (funcall do-parse chunk08) "")
(is-print (funcall do-parse chunk09) #?"chunk: are \n")
(is-print (funcall do-parse chunk10) "")
(is-print (funcall do-parse chunk11) #?"chunk: you?\nfinish.\n")))
;; Take from http://www.sonosite.com/
;; https://github.com/fukamachi/fast-http/pull/15
(is-response (str #?"HTTP/1.1 200 OK\r\n"
#?"Set-Cookie: SESS99110bddbcd18a012d19509db399dc05=9hubdaihrslaka5ci69novcl55; expires=Fri, 30-Jan-2015 08:43:59 GMT; path=/; domain=.sonosite.com\r\n"
#?"Last-Modified: Fri, 30 Jan 2015 05:35:20 GMT\r\n"
#?"ETag: \"d7b7d261ac63a34d416e6cbefc5b6e3f\"\r\n"
#?"Expires: Sun, 19 Nov 1978 05:00:00 GMT\r\n"
#?"Content-Type: text/html; charset=utf-8\r\n"
#?"Server: Go Away\r\n"
#?"Age: 0\r\n"
#?"Cache-Control: must-revalidate\r\n"
#?"X-Yottaa-Optimizations: ob/0 si/1215743397 tts/1416857618979 ti/52d77c618b5f02370e0119d9 ai/50e5c1b84707e60c8000021f\r\n"
#?"Transfer-Encoding: chunked\r\n"
#?"Date: Fri, 30 Jan 2015 05:43:59 GMT\r\n"
#?"Age: 0\r\n"
#?"Connection: keep-alive\r\n"
#?"X-Yottaa-Metrics: 042136fb801b/[427,231,-] 041136fba428/[-,429.246]\r\n"
#?"\r\n"
#?"0\r\n\r\n")
'(:set-cookie ("SESS99110bddbcd18a012d19509db399dc05=9hubdaihrslaka5ci69novcl55; expires=Fri, 30-Jan-2015 08:43:59 GMT; path=/; domain=.sonosite.com")
:last-modified "Fri, 30 Jan 2015 05:35:20 GMT"
:etag "\"d7b7d261ac63a34d416e6cbefc5b6e3f\""
:expires "Sun, 19 Nov 1978 05:00:00 GMT"
:content-type "text/html; charset=utf-8"
:server "Go Away"
:age "0, 0"
:cache-control "must-revalidate"
:x-yottaa-optimizations "ob/0 si/1215743397 tts/1416857618979 ti/52d77c618b5f02370e0119d9 ai/50e5c1b84707e60c8000021f"
:transfer-encoding "chunked"
:date "Fri, 30 Jan 2015 05:43:59 GMT"
:connection "keep-alive"
:x-yottaa-metrics "042136fb801b/[427,231,-] 041136fba428/[-,429.246]")
nil
"multiple number headers")
(finalize)
| 23,886 | Common Lisp | .lisp | 545 | 29.392661 | 169 | 0.465516 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 0da2a13acf8190ff97975837c2070d1a51a7364ae4a590757213d7fdff274c34 | 42,911 | [
-1
] |
42,912 | multipart-parser.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/fast-http-20191007-git/t/multipart-parser.lisp | (in-package :cl-user)
(defpackage fast-http-test.multipart-parser
(:use :cl
:fast-http
:fast-http.multipart-parser
:fast-http.parser
:fast-http-test.test-utils
:xsubseq
:prove)
(:import-from :cl-utilities
:collecting
:collect))
(in-package :fast-http-test.multipart-parser)
(syntax:use-syntax :interpol)
(plan nil)
(defun test-ll-parser (boundary body expected &optional description)
(let ((parser (make-ll-multipart-parser :boundary boundary))
results
headers)
(http-multipart-parse parser
(make-callbacks
:header-field (lambda (parser data start end)
(declare (ignore parser))
(push (cons (babel:octets-to-string data :start start :end end)
nil)
headers))
:header-value (lambda (parser data start end)
(declare (ignore parser))
(setf (cdr (car headers))
(append (cdr (car headers))
(list (babel:octets-to-string data :start start :end end)))))
:body (lambda (parser data start end)
(declare (ignore parser))
(push
(list :headers
(loop for (key . values) in (nreverse headers)
append (list key (apply #'concatenate 'string values)))
:body
(babel:octets-to-string data :start start :end end))
results)
(setf headers nil)))
body)
(is (nreverse results) expected description)))
(test-ll-parser "AaB03x"
(bv (str #?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"field1\"\r\n"
#?"\r\n"
#?"Joe Blow\r\nalmost tricked you!\r\n"
#?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"pics\"; filename=\"file1.txt\"\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n"
#?"... contents of file1.txt ...\r\r\n"
#?"--AaB03x--\r\n"))
'((:headers ("Content-Disposition" "form-data; name=\"field1\"")
:body #?"Joe Blow\r\nalmost tricked you!")
(:headers ("Content-Disposition" "form-data; name=\"pics\"; filename=\"file1.txt\""
"Content-Type" "text/plain")
:body #?"... contents of file1.txt ...\r"))
"rfc1867")
(let ((big-content (make-string (* 1024 3) :initial-element #\a)))
(test-ll-parser "---------------------------186454651713519341951581030105"
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"file1\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
big-content #?"\r\n"
#?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"file2\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
big-content big-content #?"\r\n"
#?"-----------------------------186454651713519341951581030105--\r\n"))
`((:headers ("Content-Disposition" "form-data; name=\"file1\"; filename=\"random.png\""
"Content-Type" "image/png")
:body ,big-content)
(:headers ("Content-Disposition" "form-data; name=\"file2\"; filename=\"random.png\""
"Content-Type" "image/png")
:body ,(concatenate 'string big-content big-content)))
"big file"))
(test-ll-parser "---------------------------186454651713519341951581030105"
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"name\"\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n"
#?"深町英太郎\r\n"
#?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"introduce\"\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n"
#?"Common Lispが好きです。好きな関数はconsです。\r\n"
#?"-----------------------------186454651713519341951581030105--\r\n"))
'((:headers ("Content-Disposition" "form-data; name=\"name\""
"Content-Type" "text/plain")
:body "深町英太郎")
(:headers ("Content-Disposition" "form-data; name=\"introduce\""
"Content-Type" "text/plain")
:body "Common Lispが好きです。好きな関数はconsです。"))
"UTF-8")
(test-ll-parser "---------------------------186454651713519341951581030105"
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data;\r\n"
#?"\tname=\"file1\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
#?"abc\r\n"
#?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data;\r\n"
#?" name=\"text\"\r\n"
#?"\r\n"
#?"Test text\n with\r\n ümläuts!\r\n"
#?"-----------------------------186454651713519341951581030105--\r\n"))
'((:headers ("Content-Disposition" #?"form-data;\tname=\"file1\"; filename=\"random.png\""
"Content-Type" "image/png")
:body "abc")
(:headers ("Content-Disposition" "form-data; name=\"text\"")
:body #?"Test text\n with\r\n ümläuts!"))
"multiline header value")
(let ((parser (make-ll-multipart-parser :boundary "AaB03x"))
(callbacks (make-callbacks
:body (lambda (parser data start end)
(declare (ignore parser))
(princ (babel:octets-to-string data :start start :end end))))))
(flet ((parse (body)
(http-multipart-parse parser callbacks body)))
(is-print (parse (bv (str #?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"field1\"\r\n"
#?"\r\n"
#?"Joe Blow\r\nalmost tricked you!\r\n")))
#?"Joe Blow\r\nalmost tricked you!")
(is-print (parse (bv #?"--AaB03x\r\n")) "")))
(let ((parser (make-ll-multipart-parser :boundary "AaB03x"))
(callbacks (make-callbacks
:body (lambda (parser data start end)
(declare (ignore parser))
(princ (babel:octets-to-string data :start start :end end))))))
(flet ((parse (body)
(http-multipart-parse parser callbacks body)))
(is-print (parse (bv (str #?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"field1\"\r\n"
#?"\r\n"
#?"Joe Blow\r\nalmost tricked you!\r\n")))
#?"Joe Blow\r\nalmost tricked you!")
(is-print (parse (bv #?"--Aa")) "")
(is-print (parse (bv #?"B03x\r\n"))
#?"")))
(let ((parser (make-ll-multipart-parser :boundary "AaB03x"))
(callbacks (make-callbacks
:body (lambda (parser data start end)
(declare (ignore parser))
(princ (babel:octets-to-string data :start start :end end))))))
(flet ((parse (body)
(http-multipart-parse parser callbacks body)))
(is-print (parse (bv (str #?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"field1\"\r\n"
#?"\r\n"
#?"Joe Blow\r\nalmost tricked you!\r\n")))
#?"Joe Blow\r\nalmost tricked you!")
(is-print (parse (bv #?"--Aa")) "")
(is-print (parse (bv #?"BbCc\r\n"))
#?"\r\n--AaBbCc")))
(let ((parser (make-ll-multipart-parser :boundary "AaB03x"))
(callbacks (make-callbacks
:body (lambda (parser data start end)
(declare (ignore parser))
(princ (babel:octets-to-string data :start start :end end))))))
(flet ((parse (body)
(http-multipart-parse parser callbacks body)))
(is-print (parse (bv (str #?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"field1\"\r\n"
#?"\r\n"
#?"Joe Blow\r\nalmost tricked you!\r\n")))
#?"Joe Blow\r\nalmost tricked you!")
(is-print (parse (bv "--Aa")) "")
(is-print (parse (bv "B03x")) "")
(is-print (parse (bv "C")) #?"\r\n--AaB03xC")))
(defun slurp-stream (stream)
(with-xsubseqs (xsub)
(let ((buffer (make-array 1024 :element-type '(unsigned-byte 8))))
(loop for bytes-read = (read-sequence buffer stream)
do (xnconcf xsub (xsubseq buffer 0 bytes-read))
while (= bytes-read 1024)))))
(defun test-parser (content-type data expected &optional description)
(let ((got (collecting
(let ((parser
(make-multipart-parser content-type
(lambda (field-name headers field-meta body)
(setf body (slurp-stream body))
(collect (list field-name
headers
field-meta
(babel:octets-to-string body)))))))
(funcall parser data)))))
(flet ((hash-table-equal (hash plist desc)
(subtest desc
(maphash (lambda (k v)
(is v (getf plist (intern (string-upcase k) :keyword)) k))
hash))))
(subtest (or description "")
(loop for got in got
for expected in expected
do (is (first got) (first expected) "field-name")
(hash-table-equal (second got) (second expected) "headers")
(hash-table-equal (third got) (third expected) "field-meta")
(is (fourth got) (fourth expected) "body"))))))
(test-parser "multipart/form-data; boundary=AaB03x"
(bv (str #?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"field1\"\r\n"
#?"\r\n"
#?"Joe Blow\r\nalmost tricked you!\r\n"
#?"--AaB03x\r\n"
#?"Content-Disposition: form-data; name=\"pics\"; filename=\"file1.txt\"\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n"
#?"... contents of file1.txt ...\r\r\n"
#?"--AaB03x--\r\n"))
'(("field1"
(:content-disposition "form-data; name=\"field1\"")
(:name "field1")
#?"Joe Blow\r\nalmost tricked you!")
("pics"
(:content-disposition "form-data; name=\"pics\"; filename=\"file1.txt\""
:content-type "text/plain")
(:name "pics"
:filename "file1.txt")
#?"... contents of file1.txt ...\r"))
"rfc1867")
(let ((big-content (make-string (* 1024 3) :initial-element #\a)))
(test-parser "multipart/form-data; boundary=\"---------------------------186454651713519341951581030105\""
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"file1\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
big-content #?"\r\n"
#?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"file2\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
big-content big-content #?"\r\n"
#?"-----------------------------186454651713519341951581030105--\r\n"))
`(("file1"
(:content-disposition "form-data; name=\"file1\"; filename=\"random.png\""
:content-type "image/png")
(:name "file1" :filename "random.png")
,big-content)
("file2"
(:content-disposition "form-data; name=\"file2\"; filename=\"random.png\""
:content-type "image/png")
(:name "file2" :filename "random.png")
,(concatenate 'string big-content big-content)))
"big file"))
(test-parser "multipart/form-data; boundary=\"---------------------------186454651713519341951581030105\""
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"name\"\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n"
#?"深町英太郎\r\n"
#?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"introduce\"\r\n"
#?"Content-Type: text/plain\r\n"
#?"\r\n"
#?"Common Lispが好きです。好きな関数はconsです。\r\n"
#?"-----------------------------186454651713519341951581030105--\r\n"))
'(("name"
(:content-disposition "form-data; name=\"name\""
:content-type "text/plain")
(:name "name")
"深町英太郎")
("introduce"
(:content-disposition "form-data; name=\"introduce\""
:content-type "text/plain")
(:name "introduce")
"Common Lispが好きです。好きな関数はconsです。"))
"UTF-8")
(test-parser "multipart/form-data; boundary=\"---------------------------186454651713519341951581030105\""
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data;\r\n"
#?"\tname=\"file1\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
#?"abc\r\n"
#?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data;\r\n"
#?" name=\"text\"\r\n"
#?"\r\n"
#?"Test text\n with\r\n ümläuts!\r\n"
#?"-----------------------------186454651713519341951581030105--\r\n"))
'(("file1"
(:content-disposition #?"form-data;\tname=\"file1\"; filename=\"random.png\""
:content-type "image/png")
(:name "file1" :filename "random.png")
"abc")
("text"
(:content-disposition "form-data; name=\"text\"")
(:name "text")
#?"Test text\n with\r\n ümläuts!"))
"multiline header value")
;;
;; Continuous calling
(let* ((got-body nil)
(parser (make-multipart-parser
"multipart/form-data; boundary=\"---------------------------186454651713519341951581030105\""
(lambda (field-name headers field-meta body)
(declare (ignore field-name headers field-meta))
(setf got-body (slurp-stream body))))))
(is (funcall parser
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data;\r\n"
#?"\tname=\"file1\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
#?"abc\r\n")))
nil)
(is got-body nil)
(is (funcall parser
(bv #?"-----------------------------186454651713519341951581030105\r\n"))
nil)
(is got-body (bv "abc") :test #'equalp))
(let* ((got-body nil)
(parser (make-multipart-parser
"multipart/form-data; boundary=\"---------------------------186454651713519341951581030105\""
(lambda (field-name headers field-meta body)
(declare (ignore field-name headers field-meta))
(setf got-body (slurp-stream body))))))
(is (funcall parser
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data;\r\n"
#?"\tname=\"file1\"; filename=\"random.png\"\r\n"
#?"Content-Type: image/png\r\n"
#?"\r\n"
#?"abc\r\n")))
nil)
(is got-body nil)
(is (funcall parser
(bv #?"-----------------------------186454651713519341951581030105abc\r\n"))
nil)
(is got-body nil)
(is (funcall parser
(bv #?"-----------------------------186454651713519341951581030105--"))
t)
(is got-body (bv (str #?"abc\r\n"
#?"-----------------------------186454651713519341951581030105abc"))
:test #'equalp))
(let* ((got-body nil)
(got-headers nil)
(got-field-meta nil)
(parser (make-multipart-parser
"multipart/form-data; boundary=\"---------------------------186454651713519341951581030105\""
(lambda (field-name headers field-meta body)
(declare (ignore field-name))
(setf got-headers headers)
(setf got-field-meta field-meta)
(setf got-body (slurp-stream body))))))
(is (funcall parser
(bv (str #?"-----------------------------186454651713519341951581030105\r\n"
#?"Content-Disposition: form-data; name=\"file\"; filename=\"黑客与画家(中文版).pdf\"\r\n"
#?"Content-Type: application/octet-stream\r\n"
#?"\r\n"
#?"abc\r\n")))
nil)
(is got-headers nil)
(is got-field-meta nil)
(is got-body nil)
(is (funcall parser
(bv #?"-----------------------------186454651713519341951581030105\r\n"))
nil)
(is (gethash "content-disposition" got-headers)
"form-data; name=\"file\"; filename=\"黑客与画家(中文版).pdf\"")
(is (gethash "filename" got-field-meta)
"黑客与画家(中文版).pdf")
(is got-body (bv "abc") :test #'equalp))
(finalize)
| 20,501 | Common Lisp | .lisp | 372 | 35.787634 | 118 | 0.437126 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | df4b44354c858af4660738df9d610cd8663b4cd5880f5ef01848cebafcd229b1 | 42,912 | [
413482
] |
42,913 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/test/package.lisp | (cl:in-package :cl-user)
(defpackage :local-time.test
(:use :alexandria
:common-lisp
:hu.dwim.stefil
:local-time))
(in-package :local-time.test)
(defsuite* (test :in root-suite) ()
(local-time::reread-timezone-repository)
(run-child-tests))
| 274 | Common Lisp | .lisp | 10 | 23.1 | 42 | 0.670498 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | d9e19ab0d07de79c7d7e99abdd09518b97430c22f7054cba6739887e0af6643e | 42,913 | [
-1
] |
42,914 | comparison.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/test/comparison.lisp | (in-package #:local-time.test)
(defsuite* (comparison :in simple))
(defmacro defcmptest (comparator-name &body args)
`(deftest ,(symbolicate 'test/simple/comparison/ comparator-name) ()
(flet ((make (day &optional (sec 0) (nsec 0))
(make-timestamp :day day :sec sec :nsec nsec)))
,@(loop
:for entry :in args
:when (= (length entry) 1)
:do (push 'is entry)
:else
:do (if (member (car entry) '(t true is) :test #'eq)
'is
'is)
collect (let ((body `(,comparator-name (make ,@(second entry))
(make ,@(third entry)))))
(cond
((eq (car entry) 'true)
`(is ,body))
((eq (car entry) 'false)
`(is (not ,body)))
(t (error "Don't know how to interpret ~S" entry))))))))
(defcmptest timestamp<
(true (1 0 0)
(2 0 0))
(true (0 1 0)
(0 2 0))
(true (0 0 1)
(0 0 2))
(false (2 0 0)
(1 0 0))
(false (0 2 0)
(0 1 0))
(false (0 0 2)
(0 0 1)))
(defcmptest timestamp<=
(true (1 0 0)
(2 0 0))
(true (0 1 0)
(0 2 0))
(true (0 0 1)
(0 0 2))
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (2 0 0)
(1 0 0))
(false (0 2 0)
(0 1 0))
(false (0 0 2)
(0 0 1)))
(defcmptest timestamp>
(true (2 0 0)
(1 0 0))
(true (0 2 0)
(0 1 0))
(true (0 0 2)
(0 0 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(defcmptest timestamp>=
(true (2 0 0)
(1 0 0))
(true (0 2 0)
(0 1 0))
(true (0 0 2)
(0 0 1))
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(defcmptest timestamp=
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(deftest test/simple/comparison/timestamp=/2 ()
(is (timestamp= (make-timestamp) (make-timestamp)))
(is (not (timestamp= (make-timestamp) (make-timestamp :nsec 1)))))
(deftest test/simple/comparison/timestamp=/3 ()
(is (eql (handler-case
(timestamp= (make-timestamp) nil)
(type-error ()
:correct-error))
:correct-error)))
(deftest test/simple/comparison/timestamp/= ()
(is (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2)))
(is (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2) (make-timestamp :nsec 3)))
(is (not (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2) (make-timestamp :nsec 1))))
(is (not (timestamp/= (make-timestamp) (make-timestamp)))))
| 3,082 | Common Lisp | .lisp | 113 | 19.477876 | 101 | 0.46784 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | afea2d971234462d5ff1659296b043a243b73013ba01b62cd5220ec10d05ce6e | 42,914 | [
410878
] |
42,915 | parsing.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/test/parsing.lisp | (in-package #:local-time.test)
(defsuite* (parsing :in test))
(deftest test/parsing/parse-format-consistency/range (&key (start-day -100000) (end-day 100000))
(declare (optimize debug))
(without-test-progress-printing
(loop
:with time = (make-timestamp)
:for day :from start-day :upto end-day
:for index :upfrom 0 :do
(setf (day-of time) day)
(when (zerop (mod index 10000))
(print time))
(let ((parsed (parse-timestring (format-timestring nil time))))
(is (timestamp= parsed time))))))
(deftest test/parsing/parse-format-consistency ()
(flet ((compare (nsec sec min hour day mon year str
&key start end offset
(allow-missing-elements t))
(let* ((timestamp-a (encode-timestamp nsec sec min hour
day mon year :offset offset))
(used-offset (or offset
(local-time::%guess-offset (sec-of timestamp-a)
(day-of timestamp-a))))
(timestamp-b (parse-timestring str
:start start
:end end
:allow-missing-elements
allow-missing-elements
:offset used-offset)))
(is (timestamp= timestamp-a timestamp-b)))))
(let ((timestamp (now)))
(is (timestamp= timestamp
(parse-timestring
(format-timestring nil timestamp)))))
(let* ((*default-timezone* (find-timezone-by-location-name "Europe/Budapest")))
(compare 0 0 0 0 1 1 1 "0001-01-01T00:00:00,0"))
(compare 0 0 0 0 1 1 1 "0001-01-01T00:00:00Z" :offset 0)
(compare 0 0 0 0 1 1 2006 "2006-01-01T00:00:00,0")
(compare 0 0 0 0 1 1 2006 "xxxx 2006-01-01T00:00:00,0 xxxx"
:start 5
:end 15)
(is (eql (day-of (parse-timestring "2006-06-06TZ")) 2288))
(compare 20000000 3 4 5 6 7 2008 "2008-07-06T05:04:03,02")
(compare 0 2 0 0 23 3 2000 "--23T::02" :allow-missing-elements t)
(compare 80000000 7 6 5 1 3 2000 "T05:06:07,08" :allow-missing-elements t)
(compare 940703000 28 56 16 20 2 2008 "2008-02-20T16:56:28.940703Z"
:offset 0)))
(deftest test/parsing/split ()
(is (equal (local-time::%split-timestring "2006-01-02T03:04:05,6-05")
'(2006 1 2 3 4 5 600000000 -5 0)))
(is (equal (local-time::%split-timestring "2006-01-02T03:04:05,6-0515")
'(2006 1 2 3 4 5 600000000 -5 -15)))
(is (equal (local-time::%split-timestring "2006-01-02T03:04:05,6-05:15")
'(2006 1 2 3 4 5 600000000 -5 -15))))
(deftest test/parsing/reader ()
(let ((now (now)))
(setf (nsec-of now) 123456000)
(is (timestamp= now
(with-input-from-string (ins (format-timestring nil now))
(local-time::%read-timestring ins #\@))))))
(deftest test/parsing/read-universal-time ()
(let ((now (now)))
(setf (nsec-of now) 0)
(is (timestamp= now
(with-input-from-string (ins (princ-to-string (timestamp-to-universal now)))
(local-time::%read-universal-time ins #\@ nil))))))
(deftest test/parsing/error ()
(signals invalid-timestring (parse-timestring "2019-w2-20")))
(deftest test/parsing/parse-rfc3339 ()
(let ((local-time:*default-timezone* local-time:+utc-zone+))
(is (equal (multiple-value-list (decode-timestamp (local-time::parse-rfc3339-timestring "2006-01-02T03:04:05.6-05")))
'(600000000 5 4 8 2 1 2006 1 NIL 0 "UTC")))
;; rfc3339 only supports . for fractional seconds
(signals local-time::invalid-timestring (local-time::parse-rfc3339-timestring "2006-01-02T03:04:05,6-05"))))
| 3,970 | Common Lisp | .lisp | 74 | 40.418919 | 121 | 0.558217 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 1738aa8ae483f0aa52c93e75ee570567e29ee84afd75efff78a964308787b858 | 42,915 | [
-1
] |
42,916 | formatting.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/test/formatting.lisp | (in-package #:local-time.test)
(defsuite* (formatting :in test))
(deftest test/formatting/format-timestring/1 ()
(let ((*default-timezone* local-time:+utc-zone+)
(test-timestamp (encode-timestamp 1000 2 3 4 5 6 2008 :offset 0)))
(macrolet ((frob (&rest args)
`(progn
,@(loop
:for (a b) :on args :by #'cddr
:collect `(is (string= ,a ,b))))))
(frob
"2008-06-05T04:03:02.000001Z"
(format-timestring nil test-timestamp)
"2008-06-05T04:03:02.000001-05:00"
(let ((utc-5 (local-time::%make-simple-timezone "UTC-5" "UTC-5" -18000)))
(format-timestring nil (encode-timestamp 1000 2 3 4 5 6 2008
:offset (* 3600 -5))
:timezone utc-5))
"Thu Jun 5 04:03:02 2008"
(format-timestring nil test-timestamp :format +asctime-format+)
"Thu, 05 Jun 2008 04:03:02 +0000"
(format-timestring nil test-timestamp :format +rfc-1123-format+)
""
(format-timestring nil test-timestamp
:format nil)
"04"
(format-timestring nil test-timestamp
:format '((:hour 2)))
"04:03"
(format-timestring nil test-timestamp
:format '((:hour 2) #\: (:min 2)))
"5th"
(format-timestring nil test-timestamp
:format '(:ordinal-day))
"2004-W53-6"
(format-timestring nil (encode-timestamp 0 0 0 0 1 1 2005)
:format +iso-week-date-format+)
"2004-W53-7"
(format-timestring nil (encode-timestamp 0 0 0 0 2 1 2005)
:format +iso-week-date-format+)
"2005-W52-6"
(format-timestring nil (encode-timestamp 0 0 0 0 31 12 2005)
:format +iso-week-date-format+)
"2007-W01-1"
(format-timestring nil (encode-timestamp 0 0 0 0 1 1 2007)
:format +iso-week-date-format+)
"2007-W52-7"
(format-timestring nil (encode-timestamp 0 0 0 0 30 12 2007)
:format +iso-week-date-format+)
"2008-W01-1"
(format-timestring nil (encode-timestamp 0 0 0 0 31 12 2007)
:format +iso-week-date-format+)
"2009-W53-5"
(format-timestring nil (encode-timestamp 0 0 0 0 1 1 2010)
:format +iso-week-date-format+)
"2009-W01-3"
(format-timestring nil (encode-timestamp 0 0 0 0 31 12 2008)
:format +iso-week-date-format+)))))
(deftest test/formatting/format-timestring/2 ()
(with-output-to-string (*standard-output*)
(let ((*default-timezone* (find-timezone-by-location-name "UTC")))
(finishes (print (now))))))
(deftest test/formatting/ordinals ()
(flet ((format-ordinal (day)
(format-timestring nil (encode-timestamp 0 0 0 0 day 1 2008)
:format '(:ordinal-day))))
(string= "31st" (format-ordinal 31))
(string= "11th" (format-ordinal 11))
(string= "22nd" (format-ordinal 22))
(string= "3rd" (format-ordinal 3))))
(deftest test/formatting/bug/1 ()
(let ((*default-timezone* (find-timezone-by-location-name "Pacific/Auckland")))
(finishes (format-timestring nil (now)))))
(deftest test/formatting/leap-year ()
(let ((timestamp (parse-timestring "2004-02-29")))
(is (timestamp= timestamp (parse-timestring (format-timestring nil timestamp))))))
| 3,578 | Common Lisp | .lisp | 76 | 35.131579 | 86 | 0.559897 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 9e0dd97a43916b81f5eff6611ba7102dd0b09e40f03c254d7cbb8a173fa5d98f | 42,916 | [
26615,
371622
] |
42,917 | simple.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/test/simple.lisp | (in-package #:local-time.test)
(defsuite* (simple :in test))
(eval-when (:compile-toplevel :load-toplevel :execute)
(local-time::define-timezone eastern-tz
(merge-pathnames #p"US/Eastern" local-time::*default-timezone-repository-path*))
(local-time::define-timezone amsterdam-tz
(merge-pathnames #p"Europe/Amsterdam" local-time::*default-timezone-repository-path*)))
(deftest test/simple/make-timestamp ()
(let ((timestamp (make-timestamp :nsec 1 :sec 2 :day 3)))
(is (= (nsec-of timestamp) 1))
(is (= (sec-of timestamp) 2))
(is (= (day-of timestamp) 3))))
(deftest test/simple/read-binary-integer ()
(let ((tmp-file-path (merge-pathnames (uiop:temporary-directory) "local-time-test")))
(with-open-file (ouf tmp-file-path
:direction :output
:element-type 'unsigned-byte
:if-exists :supersede)
(dotimes (i 14)
(write-byte 200 ouf)))
(with-open-file (inf tmp-file-path :element-type 'unsigned-byte)
(is (eql (local-time::%read-binary-integer inf 1) 200))
(is (eql (local-time::%read-binary-integer inf 1 t) -56))
(is (eql (local-time::%read-binary-integer inf 2) 51400))
(is (eql (local-time::%read-binary-integer inf 2 t) -14136))
(is (eql (local-time::%read-binary-integer inf 4) 3368601800))
(is (eql (local-time::%read-binary-integer inf 4 t) -926365496)))))
(deftest test/simple/encode-timestamp ()
(macrolet ((entry ((&rest encode-timestamp-args)
day sec nsec)
`(let ((timestamp (encode-timestamp ,@encode-timestamp-args)))
(is (= (day-of timestamp) ,day))
(is (= (sec-of timestamp) ,sec))
(is (= (nsec-of timestamp) ,nsec)))))
(entry (0 0 0 0 1 3 2000 :offset 0)
0 0 0)
(entry (0 0 0 0 29 2 2000 :offset 0)
-1 0 0)
(entry (0 0 0 0 2 3 2000 :offset 0)
1 0 0)
(entry (0 0 0 0 1 1 2000 :offset 0)
-60 0 0)
(entry (0 0 0 0 1 3 2001 :offset 0)
365 0 0)))
(defmacro encode-decode-test (args &body body)
`(let ((timestamp (encode-timestamp ,@(subseq args 0 7) :offset 0)))
(is (equal '(,@args ,@(let ((stars nil))
(dotimes (n (- 7 (length args)))
(push '* stars))
stars))
(multiple-value-list
(decode-timestamp timestamp :timezone local-time:+utc-zone+))))
,@body))
(deftest test/simple/encode-decode-consistency/1 ()
(encode-decode-test (5 5 5 5 5 5 1990 6 nil 0 "UTC"))
(encode-decode-test (0 0 0 0 1 3 2001 4 nil 0 "UTC"))
(encode-decode-test (0 0 0 0 1 3 1998 0 nil 0 "UTC"))
(encode-decode-test (1 2 3 4 5 6 2008 4 nil 0 "UTC"))
(encode-decode-test (0 0 0 0 1 1 1 1 nil 0 "UTC")))
(deftest test/simple/encode-decode-consistency/random ()
(loop :repeat 1000 :do
(let ((timestamp (make-timestamp :day (- (random 65535) 36767)
:sec (random 86400)
:nsec (random 1000000000))))
(multiple-value-bind (ns ss mm hh day month year)
(decode-timestamp timestamp :timezone local-time:+utc-zone+)
(is (timestamp= timestamp
(encode-timestamp ns ss mm hh day month year :offset 0)))))))
;;;;;;
;;; TODO the rest is uncategorized, just simply converted from the old 5am suite
(deftest test/timestamp-conversions ()
(is (eql 0 (timestamp-to-unix
(encode-timestamp 0 0 0 0 1 1 1970 :offset 0))))
(is (equal (values 2 3 4 5 6 2008 3 * *)
(decode-universal-time
(timestamp-to-universal
(encode-timestamp 1 2 3 4 5 6 2008 :offset 0)) 0)))
(let ((now (now)))
(setf (nsec-of now) 0)
(is (timestamp= now
(unix-to-timestamp (timestamp-to-unix now)))))
(let ((now (get-universal-time)))
(is (equal now
(timestamp-to-universal (universal-to-timestamp now))))))
(deftest test/year-difference ()
(let ((a (parse-timestring "2006-01-01T00:00:00"))
(b (parse-timestring "2001-01-01T00:00:00")))
(is (= 5 (timestamp-whole-year-difference a b))))
(let ((a (parse-timestring "2006-01-01T00:00:00"))
(b (parse-timestring "2001-01-02T00:00:00")))
(is (= 4 (timestamp-whole-year-difference a b))))
(let* ((local-time::*default-timezone* amsterdam-tz)
(a (parse-timestring "1978-10-01")))
(is (= 0 (timestamp-whole-year-difference a a)))))
(deftest test/adjust-timestamp/day-of-week/basic ()
(let ((sunday (parse-timestring "2020-09-13T00:00:00"))
(saturday (parse-timestring "2020-09-19T00:00:00"))
(base (parse-timestring "2020-09-15T00:00:00")))
(loop for dow in '(:sunday :monday :tuesday)
do (let ((modified (adjust-timestamp base (timezone +utc-zone+) (offset :day-of-week dow))))
(is (and (timestamp>= modified sunday) (timestamp<= modified base)))))
(loop for dow in '(:wednesday :thursday :friday :saturday)
do (let ((modified (adjust-timestamp base (timezone +utc-zone+) (offset :day-of-week dow))))
(is (and (timestamp> modified base) (timestamp<= modified saturday)))))))
(deftest test/adjust-timestamp/bug1 ()
(let* ((timestamp (parse-timestring "2006-01-01T00:00:00Z"))
(modified-timestamp (adjust-timestamp timestamp (timezone +utc-zone+) (offset :year 1))))
(is (timestamp= (parse-timestring "2007-01-01T00:00:00Z") modified-timestamp))))
(deftest test/adjust-timestamp/bug2 ()
(let* ((timestamp (parse-timestring "2009-03-01T01:00:00.000000+00:00"))
(modified-timestamp (adjust-timestamp timestamp (timezone +utc-zone+) (offset :month 1))))
(is (timestamp= (parse-timestring "2009-04-01T01:00:00.000000+00:00") modified-timestamp))))
(deftest test/adjust-timestamp/bug3 ()
(let* ((timestamp (parse-timestring "2009-03-01T01:00:00.000000+00:00"))
(modified-timestamp (adjust-timestamp timestamp (timezone +utc-zone+) (offset :day-of-week :monday))))
(is (timestamp= (parse-timestring "2009-02-23T01:00:00.000000+00:00") modified-timestamp)))
(let* ((timestamp (parse-timestring "2009-03-04T01:00:00.000000+00:00"))
(modified-timestamp (adjust-timestamp timestamp (timezone +utc-zone+) (offset :day-of-week :monday))))
(is (timestamp= (parse-timestring "2009-03-02T01:00:00.000000+00:00") modified-timestamp))))
(deftest test/adjust-timestamp/bug4 ()
(let* ((timestamp (parse-timestring "2013-04-30T00:00:00.000000+00:00"))
(modified-timestamp (adjust-timestamp timestamp (timezone +utc-zone+) (offset :day-of-week :wednesday))))
(is (timestamp= (parse-timestring "2013-05-01T00:00:00.000000+00:00") modified-timestamp)))
(let* ((timestamp (parse-timestring "2013-12-31T00:00:00.000000+00:00"))
(modified-timestamp (adjust-timestamp timestamp (timezone +utc-zone+) (offset :day-of-week :wednesday))))
(is (timestamp= (parse-timestring "2014-01-01T00:00:00.000000+00:00") modified-timestamp))))
#+nil
(deftest test/adjust-days ()
(let ((sunday (parse-timestring "2006-12-17T01:02:03Z")))
(is (timestamp= (parse-timestring "2006-12-11T01:02:03Z")
(adjust-timestamp sunday (offset :day-of-week :monday))))
(is (timestamp= (parse-timestring "2006-12-20T01:02:03Z")
(adjust-timestamp sunday (offset :day 3))))))
(deftest test/decode-date ()
(loop
:for (total-day year month day) :in '((-1 2000 02 29)
(0 2000 03 01)
(1 2000 03 02)
(364 2001 02 28)
(365 2001 03 01)
(366 2001 03 02)
(#.(* 2 365) 2002 03 01)
(#.(* 4 365) 2004 02 29)
(#.(1+ (* 4 365)) 2004 03 01))
:do (multiple-value-bind (year* month* day*)
(local-time::%timestamp-decode-date total-day)
(is (= year year*))
(is (= month month*))
(is (= day day*)))))
(deftest test/timestamp-decoding-readers ()
(let ((*default-timezone* +utc-zone+))
(dolist (year '(1900 1975 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010))
(dolist (month '(1 2 3 4 5 6 7 8 9 10 11 12))
(dolist (day '(1 2 3 27 28 29 30 31))
(when (valid-date-tuple? year month day)
(let ((hour (random 24))
(min (random 60))
(sec (random 60))
(nsec (random 1000000000)))
(let ((time (encode-timestamp nsec sec min hour day month year :offset 0)))
(is (= (floor year 10) (timestamp-decade time)))
(is (= year (timestamp-year time)))
(is (= month (timestamp-month time)))
(is (= day (timestamp-day time)))
(is (= hour (timestamp-hour time)))
(is (= min (timestamp-minute time)))
(is (= sec (timestamp-second time)))
(is (= (floor nsec 1000000)
(timestamp-millisecond time)))
(is (= (floor nsec 1000)
(timestamp-microsecond time)))))))))))
(deftest test/timestamp-century ()
(let ((*default-timezone* +utc-zone+))
(dolist (year-data '((-101 -2)
(-100 -1)
(-1 -1)
(1 1)
(100 1)
(101 2)
(1999 20)
(2000 20)
(2001 21)))
(let ((time (encode-timestamp 0 0 0 0 1 1 (first year-data) :offset 0)))
(is (= (second year-data) (timestamp-century time)))))))
(deftest test/timestamp-millennium ()
(let ((*default-timezone* +utc-zone+))
(dolist (year-data '((-101 -1)
(-100 -1)
(-1 -1)
(1 1)
(100 1)
(101 1)
(1001 2)
(1999 2)
(2000 2)
(2001 3)))
(let ((time (encode-timestamp 0 0 0 0 1 1 (first year-data) :offset 0)))
(is (= (second year-data) (timestamp-millennium time)))))))
(defun valid-date-tuple? (year month day)
;; it works only on the gregorian calendar
(let ((month-days #(31 28 31 30 31 30 31 31 30 31 30 31)))
(and (<= 1 month 12)
(<= 1 day (+ (aref month-days (1- month))
(if (and (= month 2)
(zerop (mod year 4))
(not (zerop (mod year 100)))
(zerop (mod year 400)))
1
0))))))
(deftest test/encode-decode-timestamp ()
(let ((*default-timezone* +utc-zone+))
(loop for year :in '(1900 1975 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010) do
(loop for month :from 1 :to 12 do
(loop for day :in '(1 2 3 27 28 29 30 31) do
(when (valid-date-tuple? year month day)
(multiple-value-bind (nsec sec minute hour day* month* year* day-of-week)
(decode-timestamp (encode-timestamp 0 0 0 0 day month year :offset 0))
(declare (ignore nsec sec minute day-of-week))
(is (= hour 0))
(is (= year year*))
(is (= month month*))
(is (= day day*)))))))))
(deftest test/timestamp-maximize-part ()
(timestamp= (timestamp-maximize-part
(encode-timestamp 0 49 26 13 9 12 2010 :offset -18000)
:min)
(encode-timestamp 999999999 59 59 13 9 12 2010 :offset -18000)))
(deftest test/timestamp-minimize-part ()
(timestamp= (timestamp-minimize-part
(encode-timestamp 0 49 26 13 9 12 2010 :offset -18000)
:min)
(encode-timestamp 0 0 0 13 9 12 2010 :offset -18000)))
(deftest test/decode-iso-week ()
(dolist (*default-timezone* (list eastern-tz +utc-zone+ amsterdam-tz))
(dolist (testcase '((2005 01 01 2004 53 6)
(2005 01 02 2004 53 7)
(2005 12 31 2005 52 6)
(2007 01 01 2007 1 1)
(2007 12 30 2007 52 7)
(2007 12 31 2008 1 1)
(2008 01 01 2008 1 2)
(2008 12 28 2008 52 7)
(2008 12 29 2009 1 1)
(2008 12 30 2009 1 2)
(2008 12 31 2009 1 3)
(2009 01 01 2009 1 4)
(2009 12 31 2009 53 4)
(2010 01 01 2009 53 5)
(2010 01 02 2009 53 6)
(2010 01 03 2009 53 7)
(2016 01 04 2016 1 1)))
(destructuring-bind (year month day iso-year iso-week iso-dow)
testcase
(let ((ts (encode-timestamp 0 0 0 12 day month year)))
(is (equal (list iso-year iso-week iso-dow)
(multiple-value-list (local-time::%timestamp-decode-iso-week ts)))))))))
| 13,496 | Common Lisp | .lisp | 256 | 39.636719 | 114 | 0.541105 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | d6cca114154febbe40ff9b2a6fc34afdf5e138c0bd69ea51428b8e60dcb5f01d | 42,917 | [
-1
] |
42,918 | timezone.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/test/timezone.lisp | (in-package #:local-time.test)
(defsuite* (timezone :in test))
(eval-when (:compile-toplevel :load-toplevel :execute)
(local-time::define-timezone eastern-tz
(merge-pathnames #p"EST5EDT" local-time::*default-timezone-repository-path*))
(local-time::define-timezone utc-leaps
(merge-pathnames #p"right/UTC" local-time::*default-timezone-repository-path*)))
(deftest transition-position/correct-position ()
(let ((cases '((0 #(1 2 3 4 5) 0)
(1 #(1 2 3 4 5) 0)
(2 #(1 2 3 4 5) 1)
(3 #(1 2 3 4 5) 2)
(4 #(1 2 3 4 5) 3)
(5 #(1 2 3 4 5) 4)
(1 #(1 3 5) 0)
(2 #(1 3 5) 0)
(3 #(1 3 5) 1)
(4 #(1 3 5) 1)
(5 #(1 3 5) 2)
(6 #(1 3 5) 2)
(1 #(1 3 5 7) 0)
(2 #(1 3 5 7) 0)
(3 #(1 3 5 7) 1)
(4 #(1 3 5 7) 1)
(5 #(1 3 5 7) 2)
(6 #(1 3 5 7) 2)
(7 #(1 3 5 7) 3)
(8 #(1 3 5 7) 3)
)))
(dolist (case cases)
(destructuring-bind (needle haystack want)
case
(let ((got (local-time::transition-position needle haystack)))
(is (= got want)
"(transition-position ~a ~a) got ~a, want ~a"
needle haystack got want))))))
(deftest test/timezone/decode-timestamp-dst ()
;; Testing DST calculation with a known timezone
(let ((test-cases '(
;; Spring forward
((2008 3 9 6 58) (2008 3 9 1 58))
((2008 3 9 6 59) (2008 3 9 1 59))
((2008 3 9 7 0) (2008 3 9 3 0))
((2008 3 9 7 1) (2008 3 9 3 1))
;; Fall back
((2008 11 2 5 59) (2008 11 2 1 59))
((2008 11 2 6 0) (2008 11 2 1 0))
((2008 11 2 6 1) (2008 11 2 1 1)))))
(dolist (test-case test-cases)
(is (equal
(let ((timestamp
(apply 'local-time:encode-timestamp
`(0 0 ,@(reverse (first test-case)) :offset 0))))
(local-time:decode-timestamp timestamp :timezone eastern-tz))
(apply 'values `(0 0 ,@(reverse (second test-case)))))))))
(deftest test/timezone/adjust-across-dst-by-days ()
(let* ((old (parse-timestring "2014-03-09T01:00:00.000000-05:00"))
(new (timestamp+ old 1 :day eastern-tz)))
(is (= (* 23 60 60) (timestamp-difference new old)))))
(deftest test/timezone/adjust-across-dst-by-hours ()
(let* ((old (parse-timestring "2014-03-09T01:00:00.000000-05:00"))
(new (timestamp+ old 24 :hour eastern-tz)))
(is (= (* 24 60 60) (timestamp-difference new old)))))
(deftest test/timezone/timestamp-minimize-part ()
(is (timestamp=
(timestamp-minimize-part
(encode-timestamp 999999999 59 59 1 14 3 2010 :timezone eastern-tz)
:month
:timezone eastern-tz)
(encode-timestamp 0 0 0 0 1 1 2010 :timezone eastern-tz)))
(is (timestamp=
(timestamp-minimize-part
(encode-timestamp 0 0 0 2 14 3 2010 :timezone eastern-tz)
:month
:timezone eastern-tz)
(encode-timestamp 0 0 0 0 1 1 2010 :timezone eastern-tz))))
(deftest test/timezone/timestamp-maximize-part ()
(is (timestamp=
(timestamp-maximize-part
(encode-timestamp 999999999 59 59 1 7 11 2010 :timezone eastern-tz)
:month
:timezone eastern-tz)
(encode-timestamp 999999999 59 59 23 31 12 2010 :timezone eastern-tz)))
(is (timestamp=
(timestamp-maximize-part
(encode-timestamp 0 0 0 2 7 11 2010 :timezone eastern-tz)
:month
:timezone eastern-tz)
(encode-timestamp 999999999 59 59 23 31 12 2010 :timezone eastern-tz))))
(deftest test/leaps/tai-to-utc ()
(let ((*default-timezone* utc-leaps))
(is (= 1435708799
(local-time::%adjust-sec-for-leap-seconds 1435708824)
(local-time::%adjust-sec-for-leap-seconds 1435708825)))
(is (= 1435708800
(local-time::%adjust-sec-for-leap-seconds 1435708826)))))
(deftest test/abbrev-subzone/not-found ()
(is (null (local-time:all-timezones-matching-subzone "FOO"))))
(deftest test/abbrev-subzone/find-bst ()
(is (member
"Europe/London"
(local-time:timezones-matching-subzone "BST" (unix-to-timestamp 1585906626))
:key (lambda (x) (local-time:zone-name (car x)))
:test #'string=))
;; Some historical timezone
(is (member
"America/Atka"
(local-time:all-timezones-matching-subzone "BST")
:key (lambda (x) (local-time:zone-name (car x)))
:test #'string=)))
(deftest test/abbrev-subzone/find-gmt ()
;; As of 2020-04-03
(is (equal
"Etc/Greenwich"
(local-time:zone-name
(caar (local-time:timezones-matching-subzone "GMT" (unix-to-timestamp 1585906626)))))))
| 4,916 | Common Lisp | .lisp | 116 | 33.025862 | 95 | 0.561847 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 78775731a886faa46a01bb8c667c801581ddb968146e11c148e44623d70e3f13 | 42,918 | [
-1
] |
42,919 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/src/package.lisp | (defpackage #:local-time
(:use #:cl)
(:export #:timestamp
#:date
#:time-of-day
#:make-timestamp
#:clone-timestamp
#:day-of
#:sec-of
#:nsec-of
#:timestamp<
#:timestamp<=
#:timestamp>
#:timestamp>=
#:timestamp=
#:timestamp/=
#:timestamp-maximum
#:timestamp-minimum
#:adjust-timestamp
#:adjust-timestamp!
#:timestamp-whole-year-difference
#:days-in-month
#:timestamp-
#:timestamp+
#:timestamp-difference
#:timestamp-minimize-part
#:timestamp-maximize-part
#:with-decoded-timestamp
#:decode-timestamp
#:timestamp-century
#:timestamp-day
#:timestamp-day-of-week
#:timestamp-decade
#:timestamp-hour
#:timestamp-microsecond
#:timestamp-millennium
#:timestamp-millisecond
#:timestamp-minute
#:timestamp-month
#:timestamp-second
#:timestamp-week
#:timestamp-year
#:parse-timestring
#:invalid-timestring
#:format-timestring
#:format-rfc1123-timestring
#:to-rfc1123-timestring
#:format-rfc3339-timestring
#:to-rfc3339-timestring
#:encode-timestamp
#:parse-rfc3339-timestring
#:universal-to-timestamp
#:timestamp-to-universal
#:unix-to-timestamp
#:timestamp-to-unix
#:timestamp-subtimezone
#:define-timezone
#:*default-timezone*
#:*clock*
#:leap-second-adjusted
#:clock-now
#:clock-today
#:find-timezone-by-location-name
#:timezones-matching-subzone
#:all-timezones-matching-subzone
#:reread-timezone-repository
#:now
#:today
#:enable-read-macros
#:+utc-zone+
#:+gmt-zone+
#:+month-names+
#:+short-month-names+
#:+day-names+
#:+short-day-names+
#:+seconds-per-day+
#:+seconds-per-hour+
#:+seconds-per-minute+
#:+minutes-per-day+
#:+minutes-per-hour+
#:+hours-per-day+
#:+days-per-week+
#:+months-per-year+
#:+iso-8601-format+
#:+iso-8601-date-format+
#:+iso-8601-time-format+
#:+rfc3339-format+
#:+rfc3339-format/date-only+
#:+asctime-format+
#:+rfc-1123-format+
#:+iso-week-date-format+
#:astronomical-julian-date
#:modified-julian-date
#:astronomical-modified-julian-date
#:zone-name))
| 2,892 | Common Lisp | .lisp | 95 | 18.747368 | 46 | 0.496246 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | f81f4acb3f7dd4b8935c1a67cdf4cc7595147185a5b6e09b8565d654633438d8 | 42,919 | [
-1
] |
42,920 | cl-postgres.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/local-time-20220707-git/src/integration/cl-postgres.lisp | (in-package :local-time)
(export 'set-local-time-cl-postgres-readers :local-time)
;; Postgresql days are measured from 2000-01-01, whereas local-time
;; uses 2000-03-01. We expect the database server to be in the UTC timezone.
(defconstant +postgres-day-offset-to-local-time+ -60)
(defun set-local-time-cl-postgres-readers (&optional (table cl-postgres:*sql-readtable*))
(flet ((timestamp-reader (usecs)
(multiple-value-bind (days usecs)
(floor usecs +usecs-per-day+)
(multiple-value-bind (secs usecs)
(floor usecs 1000000)
(local-time:make-timestamp :nsec (* usecs 1000)
:sec secs
:day (+ days +postgres-day-offset-to-local-time+))))))
(cl-postgres:set-sql-datetime-readers
:table table
:date (lambda (days)
(local-time:make-timestamp
:nsec 0 :sec 0
:day (+ days +postgres-day-offset-to-local-time+)))
:timestamp #'timestamp-reader
:timestamp-with-timezone #'timestamp-reader
:interval
(lambda (months days usecs)
(declare (ignore months days usecs))
(error "Intervals are not yet supported"))
:time
(lambda (usecs)
(multiple-value-bind (days usecs)
(floor usecs +usecs-per-day+)
(assert (= days 0))
(multiple-value-bind (secs usecs)
(floor usecs 1000000)
(let ((time-of-day (local-time:make-timestamp
:nsec (* usecs 1000)
:sec secs
:day 0)))
(check-type time-of-day time-of-day)
time-of-day)))))))
(defmethod cl-postgres:to-sql-string ((arg local-time:timestamp))
(format nil "'~a'"
(local-time:format-rfc3339-timestring nil arg :timezone +utc-zone+)))
| 1,906 | Common Lisp | .lisp | 42 | 33.642857 | 96 | 0.573656 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 9c5775af2262d5944ae6d54accd584f221bb1270f7f69886c168f9d2cb60ad94 | 42,920 | [
112037,
262256
] |
42,921 | api.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/api.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/api.lisp,v 1.85 2009/09/17 19:17:30 edi Exp $
;;; The external API for creating and using scanners.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defvar *look-ahead-for-suffix* t
"Controls whether scanners will optimistically look ahead for a
constant suffix of a regular expression, if there is one.")
(defgeneric create-scanner (regex &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(:documentation "Accepts a regular expression - either as a
parse-tree or as a string - and returns a scan closure which will scan
strings for this regular expression and a list mapping registers to
their names \(NIL stands for unnamed ones). The \"mode\" keyword
arguments are equivalent to the imsx modifiers in Perl. If
DESTRUCTIVE is not NIL, the function is allowed to destructively
modify its first argument \(but only if it's a parse tree)."))
#-:use-acl-regexp2-engine
(defmethod create-scanner ((regex-string string) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
;; parse the string into a parse-tree and then call CREATE-SCANNER
;; again
(let* ((*extended-mode-p* extended-mode)
(quoted-regex-string (if *allow-quoting*
(quote-sections (clean-comments regex-string extended-mode))
regex-string))
(*syntax-error-string* (copy-seq quoted-regex-string)))
;; wrap the result with :GROUP to avoid infinite loops for
;; constant strings
(create-scanner (cons :group (list (parse-string quoted-regex-string)))
:case-insensitive-mode case-insensitive-mode
:multi-line-mode multi-line-mode
:single-line-mode single-line-mode
:destructive t)))
#-:use-acl-regexp2-engine
(defmethod create-scanner ((scanner function) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
(when (or case-insensitive-mode multi-line-mode single-line-mode extended-mode)
(signal-invocation-error "You can't use the keyword arguments to modify an existing scanner."))
scanner)
#-:use-acl-regexp2-engine
(defmethod create-scanner ((parse-tree t) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(when extended-mode
(signal-invocation-error "Extended mode doesn't make sense in parse trees."))
;; convert parse-tree into internal representation REGEX and at the
;; same time compute the number of registers and the constant string
;; (or anchor) the regex starts with (if any)
(unless destructive
(setq parse-tree (copy-tree parse-tree)))
(let (flags)
(if single-line-mode
(push :single-line-mode-p flags))
(if multi-line-mode
(push :multi-line-mode-p flags))
(if case-insensitive-mode
(push :case-insensitive-p flags))
(when flags
(setq parse-tree (list :group (cons :flags flags) parse-tree))))
(let ((*syntax-error-string* nil))
(multiple-value-bind (regex reg-num starts-with reg-names)
(convert parse-tree)
;; simplify REGEX by flattening nested SEQ and ALTERNATION
;; constructs and gathering STR objects
(let ((regex (gather-strings (flatten regex))))
;; set the MIN-REST slots of the REPETITION objects
(compute-min-rest regex 0)
;; set the OFFSET slots of the STR objects
(compute-offsets regex 0)
(let* (end-string-offset
end-anchored-p
;; compute the constant string the regex ends with (if
;; any) and at the same time set the special variables
;; END-STRING-OFFSET and END-ANCHORED-P
(end-string (end-string regex))
;; if we found a non-zero-length end-string we create an
;; efficient search function for it
(end-string-test (and *look-ahead-for-suffix*
end-string
(plusp (len end-string))
(if (= 1 (len end-string))
(create-char-searcher
(schar (str end-string) 0)
(case-insensitive-p end-string))
(create-bmh-matcher
(str end-string)
(case-insensitive-p end-string)))))
;; initialize the counters for CREATE-MATCHER-AUX
(*rep-num* 0)
(*zero-length-num* 0)
;; create the actual matcher function (which does all the
;; work of matching the regular expression) corresponding
;; to REGEX and at the same time set the special
;; variables *REP-NUM* and *ZERO-LENGTH-NUM*
(match-fn (create-matcher-aux regex #'identity))
;; if the regex starts with a string we create an
;; efficient search function for it
(start-string-test (and (typep starts-with 'str)
(plusp (len starts-with))
(if (= 1 (len starts-with))
(create-char-searcher
(schar (str starts-with) 0)
(case-insensitive-p starts-with))
(create-bmh-matcher
(str starts-with)
(case-insensitive-p starts-with))))))
(declare (special end-string-offset end-anchored-p end-string))
;; now create the scanner and return it
(values (create-scanner-aux match-fn
(regex-min-length regex)
(or (start-anchored-p regex)
;; a dot in single-line-mode also
;; implicitly anchors the regex at
;; the start, i.e. if we can't match
;; from the first position we won't
;; match at all
(and (typep starts-with 'everything)
(single-line-p starts-with)))
starts-with
start-string-test
;; only mark regex as end-anchored if we
;; found a non-zero-length string before
;; the anchor
(and end-string-test end-anchored-p)
end-string-test
(if end-string-test
(len end-string)
nil)
end-string-offset
*rep-num*
*zero-length-num*
reg-num)
reg-names))))))
#+:use-acl-regexp2-engine
(declaim (inline create-scanner))
#+:use-acl-regexp2-engine
(defmethod create-scanner ((scanner regexp::regular-expression) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
(when (or case-insensitive-mode multi-line-mode single-line-mode extended-mode)
(signal-invocation-error "You can't use the keyword arguments to modify an existing scanner."))
scanner)
#+:use-acl-regexp2-engine
(defmethod create-scanner ((parse-tree t) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
(excl:compile-re parse-tree
:case-fold case-insensitive-mode
:ignore-whitespace extended-mode
:multiple-lines multi-line-mode
:single-line single-line-mode
:return :index))
(defgeneric scan (regex target-string &key start end real-start-pos)
(:documentation "Searches TARGET-STRING from START to END and tries
to match REGEX. On success returns four values - the start of the
match, the end of the match, and two arrays denoting the beginnings
and ends of register matches. On failure returns NIL. REGEX can be a
string which will be parsed according to Perl syntax, a parse tree, or
a pre-compiled scanner created by CREATE-SCANNER. TARGET-STRING will
be coerced to a simple string if it isn't one already. The
REAL-START-POS parameter should be ignored - it exists only for
internal purposes."))
#-:use-acl-regexp2-engine
(defmethod scan ((regex-string string) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
;; note that the scanners are optimized for simple strings so we
;; have to coerce TARGET-STRING into one if it isn't already
(funcall (create-scanner regex-string)
(maybe-coerce-to-simple-string target-string)
start end))
#-:use-acl-regexp2-engine
(defmethod scan ((scanner function) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
(funcall scanner
(maybe-coerce-to-simple-string target-string)
start end))
#-:use-acl-regexp2-engine
(defmethod scan ((parse-tree t) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
(funcall (create-scanner parse-tree)
(maybe-coerce-to-simple-string target-string)
start end))
#+:use-acl-regexp2-engine
(declaim (inline scan))
#+:use-acl-regexp2-engine
(defmethod scan ((parse-tree t) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
(when (< end start)
(return-from scan nil))
(let ((results (multiple-value-list (excl:match-re parse-tree target-string
:start start
:end end
:return :index))))
(declare (dynamic-extent results))
(cond ((null (first results)) nil)
(t (let* ((no-of-regs (- (length results) 2))
(reg-starts (make-array no-of-regs
:element-type '(or null fixnum)))
(reg-ends (make-array no-of-regs
:element-type '(or null fixnum)))
(match (second results)))
(loop for (start . end) in (cddr results)
for i from 0
do (setf (aref reg-starts i) start
(aref reg-ends i) end))
(values (car match) (cdr match) reg-starts reg-ends))))))
#-:cormanlisp
(define-compiler-macro scan (&whole form regex target-string &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
;; Don't pass &environment to CONSTANTP, it may not be digestable by
;; LOAD-TIME-VALUE, e.g., MACROLETs.
(cond ((constantp regex)
`(scan (load-time-value (create-scanner ,regex))
,target-string ,@rest))
(t form)))
(defun scan-to-strings (regex target-string &key (start 0)
(end (length target-string))
sharedp)
"Like SCAN but returns substrings of TARGET-STRING instead of
positions, i.e. this function returns two values on success: the whole
match as a string plus an array of substrings (or NILs) corresponding
to the matched registers. If SHAREDP is true, the substrings may
share structure with TARGET-STRING."
(declare #.*standard-optimize-settings*)
(multiple-value-bind (match-start match-end reg-starts reg-ends)
(scan regex target-string :start start :end end)
(unless match-start
(return-from scan-to-strings nil))
(let ((substr-fn (if sharedp #'nsubseq #'subseq)))
(values (funcall substr-fn
target-string match-start match-end)
(map 'vector
(lambda (reg-start reg-end)
(if reg-start
(funcall substr-fn
target-string reg-start reg-end)
nil))
reg-starts
reg-ends)))))
#-:cormanlisp
(define-compiler-macro scan-to-strings
(&whole form regex target-string &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex)
`(scan-to-strings (load-time-value (create-scanner ,regex))
,target-string ,@rest))
(t form)))
(defmacro register-groups-bind (var-list (regex target-string
&key start end sharedp)
&body body)
"Executes BODY with the variables in VAR-LIST bound to the
corresponding register groups after TARGET-STRING has been matched
against REGEX, i.e. each variable is either bound to a string or to
NIL. If there is no match, BODY is _not_ executed. For each element
of VAR-LIST which is NIL there's no binding to the corresponding
register group. The number of variables in VAR-LIST must not be
greater than the number of register groups. If SHAREDP is true, the
substrings may share structure with TARGET-STRING."
(with-rebinding (target-string)
(with-unique-names (match-start match-end reg-starts reg-ends
start-index substr-fn)
(let ((var-bindings
(loop for (function var) in (normalize-var-list var-list)
for counter from 0
when var
collect `(,var (let ((,start-index
(aref ,reg-starts ,counter)))
(if ,start-index
(funcall ,function
(funcall ,substr-fn
,target-string
,start-index
(aref ,reg-ends ,counter)))
nil))))))
`(multiple-value-bind (,match-start ,match-end ,reg-starts ,reg-ends)
(scan ,regex ,target-string :start (or ,start 0)
:end (or ,end (length ,target-string)))
(declare (ignore ,match-end))
,@(unless var-bindings
`((declare (ignore ,reg-starts ,reg-ends))))
(when ,match-start
,@(if var-bindings
`((let* ,(list*
`(,substr-fn (if ,sharedp #'nsubseq #'subseq))
var-bindings)
,@body))
body)))))))
(defmacro do-scans ((match-start match-end reg-starts reg-ends regex
target-string
&optional result-form
&key start end)
&body body
&environment env)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with MATCH-START, MATCH-END, REG-STARTS, and
REG-ENDS bound to the four return values of each match in turn. After
the last match, returns RESULT-FORM if provided or NIL otherwise. An
implicit block named NIL surrounds DO-SCANS; RETURN may be used to
terminate the loop immediately. If REGEX matches an empty string the
scan is continued one position behind this match. BODY may start with
declarations."
(with-rebinding (target-string)
(with-unique-names (%start %end %regex scanner)
(declare (ignorable %regex scanner))
;; the NIL BLOCK to enable exits via (RETURN ...)
`(block nil
(let* ((,%start (or ,start 0))
(,%end (or ,end (length ,target-string)))
,@(unless (constantp regex env)
;; leave constant regular expressions as they are -
;; SCAN's compiler macro will take care of them;
;; otherwise create a scanner unless the regex is
;; already a function (otherwise SCAN will do this
;; on each iteration)
`((,%regex ,regex)
(,scanner (typecase ,%regex
(function ,%regex)
(t (create-scanner ,%regex)))))))
;; coerce TARGET-STRING to a simple string unless it is one
;; already (otherwise SCAN will do this on each iteration)
(setq ,target-string
(maybe-coerce-to-simple-string ,target-string))
(loop
;; invoke SCAN and bind the returned values to the
;; provided variables
(multiple-value-bind
(,match-start ,match-end ,reg-starts ,reg-ends)
(scan ,(cond ((constantp regex env) regex)
(t scanner))
,target-string :start ,%start :end ,%end
:real-start-pos (or ,start 0))
;; declare the variables to be IGNORABLE to prevent the
;; compiler from issuing warnings
(declare
(ignorable ,match-start ,match-end ,reg-starts ,reg-ends))
(unless ,match-start
;; stop iteration on first failure
(return ,result-form))
;; execute BODY (wrapped in LOCALLY so it can start with
;; declarations)
(locally
,@body)
;; advance by one position if we had a zero-length match
(setq ,%start (if (= ,match-start ,match-end)
(1+ ,match-end)
,match-end)))))))))
(defmacro do-matches ((match-start match-end regex
target-string
&optional result-form
&key start end)
&body body)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with MATCH-START and MATCH-END bound to the
start/end positions of each match in turn. After the last match,
returns RESULT-FORM if provided or NIL otherwise. An implicit block
named NIL surrounds DO-MATCHES; RETURN may be used to terminate the
loop immediately. If REGEX matches an empty string the scan is
continued one position behind this match. BODY may start with
declarations."
;; this is a simplified form of DO-SCANS - we just provide two dummy
;; vars and ignore them
(with-unique-names (reg-starts reg-ends)
`(do-scans (,match-start ,match-end
,reg-starts ,reg-ends
,regex ,target-string
,result-form
:start ,start :end ,end)
,@body)))
(defmacro do-matches-as-strings ((match-var regex
target-string
&optional result-form
&key start end sharedp)
&body body)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with MATCH-VAR bound to the substring of
TARGET-STRING corresponding to each match in turn. After the last
match, returns RESULT-FORM if provided or NIL otherwise. An implicit
block named NIL surrounds DO-MATCHES-AS-STRINGS; RETURN may be used to
terminate the loop immediately. If REGEX matches an empty string the
scan is continued one position behind this match. If SHAREDP is true,
the substrings may share structure with TARGET-STRING. BODY may start
with declarations."
(with-rebinding (target-string)
(with-unique-names (match-start match-end substr-fn)
`(let ((,substr-fn (if ,sharedp #'nsubseq #'subseq)))
;; simple use DO-MATCHES to extract the substrings
(do-matches (,match-start ,match-end ,regex ,target-string
,result-form :start ,start :end ,end)
(let ((,match-var
(funcall ,substr-fn
,target-string ,match-start ,match-end)))
,@body))))))
(defmacro do-register-groups (var-list (regex target-string
&optional result-form
&key start end sharedp)
&body body)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with the variables in VAR-LIST bound to the
corresponding register groups for each match in turn, i.e. each
variable is either bound to a string or to NIL. For each element of
VAR-LIST which is NIL there's no binding to the corresponding register
group. The number of variables in VAR-LIST must not be greater than
the number of register groups. After the last match, returns
RESULT-FORM if provided or NIL otherwise. An implicit block named NIL
surrounds DO-REGISTER-GROUPS; RETURN may be used to terminate the loop
immediately. If REGEX matches an empty string the scan is continued
one position behind this match. If SHAREDP is true, the substrings
may share structure with TARGET-STRING. BODY may start with
declarations."
(with-rebinding (target-string)
(with-unique-names (substr-fn match-start match-end
reg-starts reg-ends start-index)
`(let ((,substr-fn (if ,sharedp
#'nsubseq
#'subseq)))
(do-scans (,match-start ,match-end ,reg-starts ,reg-ends
,regex ,target-string
,result-form :start ,start :end ,end)
(let ,(loop for (function var) in (normalize-var-list var-list)
for counter from 0
when var
collect `(,var (let ((,start-index
(aref ,reg-starts ,counter)))
(if ,start-index
(funcall ,function
(funcall ,substr-fn
,target-string
,start-index
(aref ,reg-ends ,counter)))
nil))))
,@body))))))
(defun count-matches (regex target-string
&key (start 0)
(end (length target-string)))
"Returns a count of all substrings of TARGET-STRING which match REGEX."
(declare #.*standard-optimize-settings*)
(let ((count 0))
(do-matches (s e regex target-string count
:start start :end end)
(incf count))))
#-:cormanlisp
(define-compiler-macro count-matches (&whole form regex &rest rest)
"Make sure that constant forms are compiled into scanners at
compile time."
(cond ((constantp regex)
`(count-matches (load-time-value (create-scanner ,regex))
,@rest))
(t form)))
(defun all-matches (regex target-string
&key (start 0)
(end (length target-string)))
"Returns a list containing the start and end positions of all
matches of REGEX against TARGET-STRING, i.e. if there are N matches
the list contains (* 2 N) elements. If REGEX matches an empty string
the scan is continued one position behind this match."
(declare #.*standard-optimize-settings*)
(let (result-list)
(do-matches (match-start match-end
regex target-string
(nreverse result-list)
:start start :end end)
(push match-start result-list)
(push match-end result-list))))
#-:cormanlisp
(define-compiler-macro all-matches (&whole form regex &rest rest)
"Make sure that constant forms are compiled into scanners at
compile time."
(cond ((constantp regex)
`(all-matches (load-time-value (create-scanner ,regex))
,@rest))
(t form)))
(defun all-matches-as-strings (regex target-string
&key (start 0)
(end (length target-string))
sharedp)
"Returns a list containing all substrings of TARGET-STRING which
match REGEX. If REGEX matches an empty string the scan is continued
one position behind this match. If SHAREDP is true, the substrings may
share structure with TARGET-STRING."
(declare #.*standard-optimize-settings*)
(let (result-list)
(do-matches-as-strings (match regex target-string (nreverse result-list)
:start start :end end :sharedp sharedp)
(push match result-list))))
#-:cormanlisp
(define-compiler-macro all-matches-as-strings (&whole form regex &rest rest)
"Make sure that constant forms are compiled into scanners at
compile time."
(cond ((constantp regex)
`(all-matches-as-strings
(load-time-value (create-scanner ,regex))
,@rest))
(t form)))
(defun split (regex target-string
&key (start 0)
(end (length target-string))
limit
with-registers-p
omit-unmatched-p
sharedp)
"Matches REGEX against TARGET-STRING as often as possible and
returns a list of the substrings between the matches. If
WITH-REGISTERS-P is true, substrings corresponding to matched
registers are inserted into the list as well. If OMIT-UNMATCHED-P is
true, unmatched registers will simply be left out, otherwise they will
show up as NIL. LIMIT limits the number of elements returned -
registers aren't counted. If LIMIT is NIL \(or 0 which is
equivalent), trailing empty strings are removed from the result list.
If REGEX matches an empty string the scan is continued one position
behind this match. If SHAREDP is true, the substrings may share
structure with TARGET-STRING."
(declare #.*standard-optimize-settings*)
;; initialize list of positions POS-LIST to extract substrings with
;; START so that the start of the next match will mark the end of
;; the first substring
(let ((pos-list (list start))
(counter 0))
;; how would Larry Wall do it?
(when (eql limit 0)
(setq limit nil))
(do-scans (match-start match-end
reg-starts reg-ends
regex target-string nil
:start start :end end)
(unless (and (= match-start match-end)
(= match-start (car pos-list)))
;; push start of match on list unless this would be an empty
;; string adjacent to the last element pushed onto the list
(when (and limit
;; perlfunc(1) says
;; If LIMIT is negative, it is treated as if
;; it were instead arbitrarily large;
;; as many fields as possible are produced.
(plusp limit)
(>= (incf counter) limit))
(return))
(push match-start pos-list)
(when with-registers-p
;; optionally insert matched registers
(loop for reg-start across reg-starts
for reg-end across reg-ends
if reg-start
;; but only if they've matched
do (push reg-start pos-list)
(push reg-end pos-list)
else unless omit-unmatched-p
;; or if we're allowed to insert NIL instead
do (push nil pos-list)
(push nil pos-list)))
;; now end of match
(push match-end pos-list)))
;; end of whole string
(push end pos-list)
;; now collect substrings
(nreverse
(loop with substr-fn = (if sharedp #'nsubseq #'subseq)
with string-seen = nil
for (this-end this-start) on pos-list by #'cddr
;; skip empty strings from end of list
if (or limit
(setq string-seen
(or string-seen
(and this-start
(> this-end this-start)))))
collect (if this-start
(funcall substr-fn
target-string this-start this-end)
nil)))))
#-:cormanlisp
(define-compiler-macro split (&whole form regex target-string &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex)
`(split (load-time-value (create-scanner ,regex))
,target-string ,@rest))
(t form)))
(defun string-case-modifier (str from to start end)
(declare #.*standard-optimize-settings*)
(declare (fixnum from to start end))
"Checks whether all words in STR between FROM and TO are upcased,
downcased or capitalized and returns a function which applies a
corresponding case modification to strings. Returns #'IDENTITY
otherwise, especially if words in the target area extend beyond FROM
or TO. STR is supposed to be bounded by START and END. It is assumed
that \(<= START FROM TO END)."
(case
(if (or (<= to from)
(and (< start from)
(alphanumericp (char str (1- from)))
(alphanumericp (char str from)))
(and (< to end)
(alphanumericp (char str to))
(alphanumericp (char str (1- to)))))
;; if it's a zero-length string or if words extend beyond FROM
;; or TO we return NIL, i.e. #'IDENTITY
nil
;; otherwise we loop through STR from FROM to TO
(loop with last-char-both-case
with current-result
for index of-type fixnum from from below to
for chr = (char str index)
do (cond ((not #-:cormanlisp (both-case-p chr)
#+:cormanlisp (or (upper-case-p chr)
(lower-case-p chr)))
;; this character doesn't have a case so we
;; consider it as a word boundary (note that
;; this differs from how \b works in Perl)
(setq last-char-both-case nil))
((upper-case-p chr)
;; an uppercase character
(setq current-result
(if last-char-both-case
;; not the first character in a
(case current-result
((:undecided) :upcase)
((:downcase :capitalize) (return nil))
((:upcase) current-result))
(case current-result
((nil) :undecided)
((:downcase) (return nil))
((:capitalize :upcase) current-result)))
last-char-both-case t))
(t
;; a lowercase character
(setq current-result
(case current-result
((nil) :downcase)
((:undecided) :capitalize)
((:downcase) current-result)
((:capitalize) (if last-char-both-case
current-result
(return nil)))
((:upcase) (return nil)))
last-char-both-case t)))
finally (return current-result)))
((nil) #'identity)
((:undecided :upcase) #'string-upcase)
((:downcase) #'string-downcase)
((:capitalize) #'string-capitalize)))
;; first create a scanner to identify the special parts of the
;; replacement string (eat your own dog food...)
(defgeneric build-replacement-template (replacement-string)
(declare #.*standard-optimize-settings*)
(:documentation "Converts a replacement string for REGEX-REPLACE or
REGEX-REPLACE-ALL into a replacement template which is an
S-expression."))
#-:cormanlisp
(let* ((*use-bmh-matchers* nil)
(reg-scanner (create-scanner "\\\\(?:\\\\|\\{\\d+\\}|\\d+|&|`|')")))
(defmethod build-replacement-template ((replacement-string string))
(declare #.*standard-optimize-settings*)
(let ((from 0)
;; COLLECTOR will hold the (reversed) template
(collector '()))
;; scan through all special parts of the replacement string
(do-matches (match-start match-end reg-scanner replacement-string)
(when (< from match-start)
;; strings between matches are copied verbatim
(push (subseq replacement-string from match-start) collector))
;; PARSE-START is true if the pattern matched a number which
;; refers to a register
(let* ((parse-start (position-if #'digit-char-p
replacement-string
:start match-start
:end match-end))
(token (if parse-start
(1- (parse-integer replacement-string
:start parse-start
:junk-allowed t))
;; if we didn't match a number we convert the
;; character to a symbol
(case (char replacement-string (1+ match-start))
((#\&) :match)
((#\`) :before-match)
((#\') :after-match)
((#\\) :backslash)))))
(when (and (numberp token) (< token 0))
;; make sure we don't accept something like "\\0"
(signal-invocation-error "Illegal substring ~S in replacement string."
(subseq replacement-string match-start match-end)))
(push token collector))
;; remember where the match ended
(setq from match-end))
(when (< from (length replacement-string))
;; push the rest of the replacement string onto the list
(push (subseq replacement-string from) collector))
(nreverse collector))))
#-:cormanlisp
(defmethod build-replacement-template ((replacement-function function))
(declare #.*standard-optimize-settings*)
(list replacement-function))
#-:cormanlisp
(defmethod build-replacement-template ((replacement-function-symbol symbol))
(declare #.*standard-optimize-settings*)
(list replacement-function-symbol))
#-:cormanlisp
(defmethod build-replacement-template ((replacement-list list))
(declare #.*standard-optimize-settings*)
replacement-list)
;;; Corman Lisp's methods can't be closures... :(
#+:cormanlisp
(let* ((*use-bmh-matchers* nil)
(reg-scanner (create-scanner "\\\\(?:\\\\|\\{\\d+\\}|\\d+|&|`|')")))
(defun build-replacement-template (replacement)
(declare #.*standard-optimize-settings*)
(typecase replacement
(string
(let ((from 0)
;; COLLECTOR will hold the (reversed) template
(collector '()))
;; scan through all special parts of the replacement string
(do-matches (match-start match-end reg-scanner replacement)
(when (< from match-start)
;; strings between matches are copied verbatim
(push (subseq replacement from match-start) collector))
;; PARSE-START is true if the pattern matched a number which
;; refers to a register
(let* ((parse-start (position-if #'digit-char-p
replacement
:start match-start
:end match-end))
(token (if parse-start
(1- (parse-integer replacement
:start parse-start
:junk-allowed t))
;; if we didn't match a number we convert the
;; character to a symbol
(case (char replacement (1+ match-start))
((#\&) :match)
((#\`) :before-match)
((#\') :after-match)
((#\\) :backslash)))))
(when (and (numberp token) (< token 0))
;; make sure we don't accept something like "\\0"
(signal-invocation-error "Illegal substring ~S in replacement string."
(subseq replacement match-start match-end)))
(push token collector))
;; remember where the match ended
(setq from match-end))
(when (< from (length replacement))
;; push the rest of the replacement string onto the list
(push (nsubseq replacement from) collector))
(nreverse collector)))
(list
replacement)
(t
(list replacement)))))
(defun build-replacement (replacement-template
target-string
start end
match-start match-end
reg-starts reg-ends
simple-calls
element-type)
(declare #.*standard-optimize-settings*)
"Accepts a replacement template and the current values from the
matching process in REGEX-REPLACE or REGEX-REPLACE-ALL and returns the
corresponding string."
;; the upper exclusive bound of the register numbers in the regular
;; expression
(let ((reg-bound (if reg-starts
(array-dimension reg-starts 0)
0)))
(with-output-to-string (s nil :element-type element-type)
(loop for token in replacement-template
do (typecase token
(string
;; transfer string parts verbatim
(write-string token s))
(integer
;; replace numbers with the corresponding registers
(when (>= token reg-bound)
;; but only if the register was referenced in the
;; regular expression
(signal-invocation-error "Reference to non-existent register ~A in replacement string."
(1+ token)))
(when (svref reg-starts token)
;; and only if it matched, i.e. no match results
;; in an empty string
(write-string target-string s
:start (svref reg-starts token)
:end (svref reg-ends token))))
(function
(write-string
(cond (simple-calls
(apply token
(nsubseq target-string match-start match-end)
(map 'list
(lambda (reg-start reg-end)
(and reg-start
(nsubseq target-string reg-start reg-end)))
reg-starts reg-ends)))
(t
(funcall token
target-string
start end
match-start match-end
reg-starts reg-ends)))
s))
(symbol
(case token
((:backslash)
;; just a backslash
(write-char #\\ s))
((:match)
;; the whole match
(write-string target-string s
:start match-start
:end match-end))
((:before-match)
;; the part of the target string before the match
(write-string target-string s
:start start
:end match-start))
((:after-match)
;; the part of the target string after the match
(write-string target-string s
:start match-end
:end end))
(otherwise
(write-string
(cond (simple-calls
(apply token
(nsubseq target-string match-start match-end)
(map 'list
(lambda (reg-start reg-end)
(and reg-start
(nsubseq target-string reg-start reg-end)))
reg-starts reg-ends)))
(t
(funcall token
target-string
start end
match-start match-end
reg-starts reg-ends)))
s)))))))))
(defun replace-aux (target-string replacement pos-list reg-list start end
preserve-case simple-calls element-type)
"Auxiliary function used by REGEX-REPLACE and REGEX-REPLACE-ALL.
POS-LIST contains a list with the start and end positions of all
matches while REG-LIST contains a list of arrays representing the
corresponding register start and end positions."
(declare #.*standard-optimize-settings*)
;; build the template once before we start the loop
(let ((replacement-template (build-replacement-template replacement)))
(with-output-to-string (s nil :element-type element-type)
;; loop through all matches and take the start and end of the
;; whole string into account
(loop for (from to) on (append (list start) pos-list (list end))
;; alternate between replacement and no replacement
for replace = nil then (and (not replace) to)
for reg-starts = (if replace (pop reg-list) nil)
for reg-ends = (if replace (pop reg-list) nil)
for curr-replacement = (if replace
;; build the replacement string
(build-replacement replacement-template
target-string
start end
from to
reg-starts reg-ends
simple-calls
element-type)
nil)
while to
if replace
do (write-string (if preserve-case
;; modify the case of the replacement
;; string if necessary
(funcall (string-case-modifier target-string
from to
start end)
curr-replacement)
curr-replacement)
s)
else
;; no replacement
do (write-string target-string s :start from :end to)))))
(defun regex-replace (regex target-string replacement &key
(start 0)
(end (length target-string))
preserve-case
simple-calls
(element-type #+:lispworks 'lw:simple-char #-:lispworks 'character))
"Try to match TARGET-STRING between START and END against REGEX and
replace the first match with REPLACEMENT. Two values are returned;
the modified string, and T if REGEX matched or NIL otherwise.
REPLACEMENT can be a string which may contain the special substrings
\"\\&\" for the whole match, \"\\`\" for the part of TARGET-STRING
before the match, \"\\'\" for the part of TARGET-STRING after the
match, \"\\N\" or \"\\{N}\" for the Nth register where N is a positive
integer.
REPLACEMENT can also be a function designator in which case the
match will be replaced with the result of calling the function
designated by REPLACEMENT with the arguments TARGET-STRING, START,
END, MATCH-START, MATCH-END, REG-STARTS, and REG-ENDS. (REG-STARTS and
REG-ENDS are arrays holding the start and end positions of matched
registers or NIL - the meaning of the other arguments should be
obvious.)
Finally, REPLACEMENT can be a list where each element is a string,
one of the symbols :MATCH, :BEFORE-MATCH, or :AFTER-MATCH -
corresponding to \"\\&\", \"\\`\", and \"\\'\" above -, an integer N -
representing register (1+ N) -, or a function designator.
If PRESERVE-CASE is true, the replacement will try to preserve the
case (all upper case, all lower case, or capitalized) of the
match. The result will always be a fresh string, even if REGEX doesn't
match.
ELEMENT-TYPE is the element type of the resulting string."
(declare #.*standard-optimize-settings*)
(multiple-value-bind (match-start match-end reg-starts reg-ends)
(scan regex target-string :start start :end end)
(if match-start
(values (replace-aux target-string replacement
(list match-start match-end)
(list reg-starts reg-ends)
start end preserve-case
simple-calls element-type)
t)
(values (subseq target-string start end)
nil))))
#-:cormanlisp
(define-compiler-macro regex-replace
(&whole form regex target-string replacement &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex)
`(regex-replace (load-time-value (create-scanner ,regex))
,target-string ,replacement ,@rest))
(t form)))
(defun regex-replace-all (regex target-string replacement &key
(start 0)
(end (length target-string))
preserve-case
simple-calls
(element-type #+:lispworks 'lw:simple-char #-:lispworks 'character))
"Try to match TARGET-STRING between START and END against REGEX and
replace all matches with REPLACEMENT. Two values are returned; the
modified string, and T if REGEX matched or NIL otherwise.
REPLACEMENT can be a string which may contain the special substrings
\"\\&\" for the whole match, \"\\`\" for the part of TARGET-STRING
before the match, \"\\'\" for the part of TARGET-STRING after the
match, \"\\N\" or \"\\{N}\" for the Nth register where N is a positive
integer.
REPLACEMENT can also be a function designator in which case the
match will be replaced with the result of calling the function
designated by REPLACEMENT with the arguments TARGET-STRING, START,
END, MATCH-START, MATCH-END, REG-STARTS, and REG-ENDS. (REG-STARTS and
REG-ENDS are arrays holding the start and end positions of matched
registers or NIL - the meaning of the other arguments should be
obvious.)
Finally, REPLACEMENT can be a list where each element is a string,
one of the symbols :MATCH, :BEFORE-MATCH, or :AFTER-MATCH -
corresponding to \"\\&\", \"\\`\", and \"\\'\" above -, an integer N -
representing register (1+ N) -, or a function designator.
If PRESERVE-CASE is true, the replacement will try to preserve the
case (all upper case, all lower case, or capitalized) of the
match. The result will always be a fresh string, even if REGEX doesn't
match.
ELEMENT-TYPE is the element type of the resulting string."
(declare #.*standard-optimize-settings*)
(let ((pos-list '())
(reg-list '()))
(do-scans (match-start match-end reg-starts reg-ends regex target-string
nil
:start start :end end)
(push match-start pos-list)
(push match-end pos-list)
(push reg-starts reg-list)
(push reg-ends reg-list))
(if pos-list
(values (replace-aux target-string replacement
(nreverse pos-list)
(nreverse reg-list)
start end preserve-case
simple-calls element-type)
t)
(values (subseq target-string start end)
nil))))
#-:cormanlisp
(define-compiler-macro regex-replace-all
(&whole form regex target-string replacement &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex)
`(regex-replace-all (load-time-value (create-scanner ,regex))
,target-string ,replacement ,@rest))
(t form)))
#-:cormanlisp
(defmacro regex-apropos-aux ((regex packages case-insensitive &optional return-form)
&body body)
"Auxiliary macro used by REGEX-APROPOS and REGEX-APROPOS-LIST. Loops
through PACKAGES and executes BODY with SYMBOL bound to each symbol
which matches REGEX. Optionally evaluates and returns RETURN-FORM at
the end. If CASE-INSENSITIVE is true and REGEX isn't already a
scanner, a case-insensitive scanner is used."
(with-rebinding (regex)
(with-unique-names (scanner %packages next morep hash)
`(let* ((,scanner (create-scanner ,regex
:case-insensitive-mode
(and ,case-insensitive
(not (functionp ,regex)))))
(,%packages (or ,packages
(list-all-packages)))
(,hash (make-hash-table :test #'eq)))
(with-package-iterator (,next ,%packages :external :internal :inherited)
(loop
(multiple-value-bind (,morep symbol)
(,next)
(unless ,morep
(return ,return-form))
(unless (gethash symbol ,hash)
(when (scan ,scanner (symbol-name symbol))
(setf (gethash symbol ,hash) t)
,@body)))))))))
;;; The following two functions were provided by Karsten Poeck
#+:cormanlisp
(defmacro do-with-all-symbols ((variable package-or-packagelist) &body body)
"Executes BODY with VARIABLE bound to each symbol in
PACKAGE-OR-PACKAGELIST \(a designator for a list of packages) in
turn."
(with-unique-names (pack-var)
`(if (listp ,package-or-packagelist)
(dolist (,pack-var ,package-or-packagelist)
(do-symbols (,variable ,pack-var)
,@body))
(do-symbols (,variable ,package-or-packagelist)
,@body))))
#+:cormanlisp
(defmacro regex-apropos-aux ((regex packages case-insensitive &optional return-form)
&body body)
"Auxiliary macro used by REGEX-APROPOS and REGEX-APROPOS-LIST.
Loops through PACKAGES and executes BODY with SYMBOL bound to each
symbol which matches REGEX. Optionally evaluates and returns
RETURN-FORM at the end. If CASE-INSENSITIVE is true and REGEX isn't
already a scanner, a case-insensitive scanner is used."
(with-rebinding (regex)
(with-unique-names (scanner %packages hash)
`(let* ((,scanner (create-scanner ,regex
:case-insensitive-mode
(and ,case-insensitive
(not (functionp ,regex)))))
(,%packages (or ,packages
(list-all-packages)))
(,hash (make-hash-table :test #'eq)))
(do-with-all-symbols (symbol ,%packages)
(unless (gethash symbol ,hash)
(when (scan ,scanner (symbol-name symbol))
(setf (gethash symbol ,hash) t)
,@body)))
,return-form))))
(defun regex-apropos-list (regex &optional packages &key (case-insensitive t))
(declare #.*standard-optimize-settings*)
"Similar to the standard function APROPOS-LIST but returns a list of
all symbols which match the regular expression REGEX. If
CASE-INSENSITIVE is true and REGEX isn't already a scanner, a
case-insensitive scanner is used."
(let ((collector '()))
(regex-apropos-aux (regex packages case-insensitive collector)
(push symbol collector))))
(defun print-symbol-info (symbol)
"Auxiliary function used by REGEX-APROPOS. Tries to print some
meaningful information about a symbol."
(declare #.*standard-optimize-settings*)
(handler-case
(let ((output-list '()))
(cond ((special-operator-p symbol)
(push "[special operator]" output-list))
((macro-function symbol)
(push "[macro]" output-list))
((fboundp symbol)
(let* ((function (symbol-function symbol))
(compiledp (compiled-function-p function)))
(multiple-value-bind (lambda-expr closurep)
(function-lambda-expression function)
(push
(format nil
"[~:[~;compiled ~]~:[function~;closure~]]~:[~; ~A~]"
compiledp closurep lambda-expr (cadr lambda-expr))
output-list)))))
(let ((class (find-class symbol nil)))
(when class
(push (format nil "[class] ~S" class) output-list)))
(cond ((keywordp symbol)
(push "[keyword]" output-list))
((constantp symbol)
(push (format nil "[constant]~:[~; value: ~S~]"
(boundp symbol) (symbol-value symbol)) output-list))
((boundp symbol)
(push #+(or :lispworks :clisp) "[variable]"
#-(or :lispworks :clisp) (format nil "[variable] value: ~S"
(symbol-value symbol))
output-list)))
#-(or :cormanlisp :clisp)
(format t "~&~S ~<~;~^~A~@{~:@_~A~}~;~:>" symbol output-list)
#+(or :cormanlisp :clisp)
(loop for line in output-list
do (format t "~&~S ~A" symbol line)))
(condition ()
;; this seems to be necessary due to some errors I encountered
;; with LispWorks
(format t "~&~S [an error occurred while trying to print more info]" symbol))))
(defun regex-apropos (regex &optional packages &key (case-insensitive t))
"Similar to the standard function APROPOS but returns a list of all
symbols which match the regular expression REGEX. If CASE-INSENSITIVE
is true and REGEX isn't already a scanner, a case-insensitive scanner
is used."
(declare #.*standard-optimize-settings*)
(regex-apropos-aux (regex packages case-insensitive)
(print-symbol-info symbol))
(values))
(let* ((*use-bmh-matchers* nil)
(non-word-char-scanner (create-scanner "[^a-zA-Z_0-9]")))
(defun quote-meta-chars (string &key (start 0) (end (length string)))
"Quote, i.e. prefix with #\\\\, all non-word characters in STRING."
(regex-replace-all non-word-char-scanner string "\\\\\\&"
:start start :end end)))
(let* ((*use-bmh-matchers* nil)
(*allow-quoting* nil)
(quote-char-scanner (create-scanner "\\\\Q"))
(section-scanner (create-scanner "\\\\Q((?:[^\\\\]|\\\\(?!Q))*?)(?:\\\\E|$)")))
(defun quote-sections (string)
"Replace sections inside of STRING which are enclosed by \\Q and
\\E with the quoted equivalent of these sections \(see
QUOTE-META-CHARS). Repeat this as long as there are such
sections. These sections may nest."
(flet ((quote-substring (target-string start end match-start
match-end reg-starts reg-ends)
(declare (ignore start end match-start match-end))
(quote-meta-chars target-string
:start (svref reg-starts 0)
:end (svref reg-ends 0))))
(loop for result = string then (regex-replace-all section-scanner
result
#'quote-substring)
while (scan quote-char-scanner result)
finally (return result)))))
(let* ((*use-bmh-matchers* nil)
(comment-scanner (create-scanner "(?s)\\(\\?#.*?\\)"))
(extended-comment-scanner (create-scanner "(?m:#.*?$)|(?s:\\(\\?#.*?\\))"))
(quote-token-scanner (create-scanner "\\\\[QE]"))
(quote-token-replace-scanner (create-scanner "\\\\([QE])")))
(defun clean-comments (string &optional extended-mode)
"Clean \(?#...) comments within STRING for quoting, i.e. convert
\\Q to Q and \\E to E. If EXTENDED-MODE is true, also clean
end-of-line comments, i.e. those starting with #\\# and ending with
#\\Newline."
(flet ((remove-tokens (target-string start end match-start
match-end reg-starts reg-ends)
(declare (ignore start end reg-starts reg-ends))
(loop for result = (nsubseq target-string match-start match-end)
then (regex-replace-all quote-token-replace-scanner result "\\1")
;; we must probably repeat this because the comment
;; can contain substrings like \\Q
while (scan quote-token-scanner result)
finally (return result))))
(regex-replace-all (if extended-mode
extended-comment-scanner
comment-scanner)
string
#'remove-tokens))))
(defun parse-tree-synonym (symbol)
"Returns the parse tree the SYMBOL symbol is a synonym for. Returns
NIL is SYMBOL wasn't yet defined to be a synonym."
(get symbol 'parse-tree-synonym))
(defun (setf parse-tree-synonym) (new-parse-tree symbol)
"Defines SYMBOL to be a synonm for the parse tree NEW-PARSE-TREE."
(setf (get symbol 'parse-tree-synonym) new-parse-tree))
(defmacro define-parse-tree-synonym (name parse-tree)
"Defines the symbol NAME to be a synonym for the parse tree
PARSE-TREE. Both arguments are quoted."
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (parse-tree-synonym ',name) ',parse-tree)))
| 63,735 | Common Lisp | .lisp | 1,225 | 36.097143 | 108 | 0.542677 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 8dbc67f86988c74cb70e2b0fcad38268339cabc5b2c666912fd8fdb7b3588aaf | 42,921 | [
164787
] |
42,922 | lexer.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/lexer.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/lexer.lisp,v 1.35 2009/09/17 19:17:31 edi Exp $
;;; The lexer's responsibility is to convert the regex string into a
;;; sequence of tokens which are in turn consumed by the parser.
;;;
;;; The lexer is aware of Perl's 'extended mode' and it also 'knows'
;;; (with a little help from the parser) how many register groups it
;;; has opened so far. (The latter is necessary for interpreting
;;; strings like "\\10" correctly.)
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(declaim (inline map-char-to-special-class))
(defun map-char-to-special-char-class (chr)
(declare #.*standard-optimize-settings*)
"Maps escaped characters like \"\\d\" to the tokens which represent
their associated character classes."
(case chr
((#\d)
:digit-class)
((#\D)
:non-digit-class)
((#\w)
:word-char-class)
((#\W)
:non-word-char-class)
((#\s)
:whitespace-char-class)
((#\S)
:non-whitespace-char-class)))
(declaim (inline make-lexer-internal))
(defstruct (lexer (:constructor make-lexer-internal))
"LEXER structures are used to hold the regex string which is
currently lexed and to keep track of the lexer's state."
(str "" :type string :read-only t)
(len 0 :type fixnum :read-only t)
(reg 0 :type fixnum)
(pos 0 :type fixnum)
(last-pos nil :type list))
(defun make-lexer (string)
(declare #-:genera (string string))
(make-lexer-internal :str (maybe-coerce-to-simple-string string)
:len (length string)))
(declaim (inline end-of-string-p))
(defun end-of-string-p (lexer)
(declare #.*standard-optimize-settings*)
"Tests whether we're at the end of the regex string."
(<= (lexer-len lexer)
(lexer-pos lexer)))
(declaim (inline looking-at-p))
(defun looking-at-p (lexer chr)
(declare #.*standard-optimize-settings*)
"Tests whether the next character the lexer would see is CHR.
Does not respect extended mode."
(and (not (end-of-string-p lexer))
(char= (schar (lexer-str lexer) (lexer-pos lexer))
chr)))
(declaim (inline next-char-non-extended))
(defun next-char-non-extended (lexer)
(declare #.*standard-optimize-settings*)
"Returns the next character which is to be examined and updates the
POS slot. Does not respect extended mode."
(cond ((end-of-string-p lexer) nil)
(t (prog1
(schar (lexer-str lexer) (lexer-pos lexer))
(incf (lexer-pos lexer))))))
(defun next-char (lexer)
(declare #.*standard-optimize-settings*)
"Returns the next character which is to be examined and updates the
POS slot. Respects extended mode, i.e. whitespace, comments, and also
nested comments are skipped if applicable."
(let ((next-char (next-char-non-extended lexer))
last-loop-pos)
(loop
;; remember where we started
(setq last-loop-pos (lexer-pos lexer))
;; first we look for nested comments like (?#foo)
(when (and next-char
(char= next-char #\()
(looking-at-p lexer #\?))
(incf (lexer-pos lexer))
(cond ((looking-at-p lexer #\#)
;; must be a nested comment - so we have to search for
;; the closing parenthesis
(let ((error-pos (- (lexer-pos lexer) 2)))
(unless
;; loop 'til ')' or end of regex string and
;; return NIL if ')' wasn't encountered
(loop for skip-char = next-char
then (next-char-non-extended lexer)
while (and skip-char
(char/= skip-char #\)))
finally (return skip-char))
(signal-syntax-error* error-pos "Comment group not closed.")))
(setq next-char (next-char-non-extended lexer)))
(t
;; undo effect of previous INCF if we didn't see a #
(decf (lexer-pos lexer)))))
(when *extended-mode-p*
;; now - if we're in extended mode - we skip whitespace and
;; comments; repeat the following loop while we look at
;; whitespace or #\#
(loop while (and next-char
(or (char= next-char #\#)
(whitespacep next-char)))
do (setq next-char
(if (char= next-char #\#)
;; if we saw a comment marker skip until
;; we're behind #\Newline...
(loop for skip-char = next-char
then (next-char-non-extended lexer)
while (and skip-char
(char/= skip-char #\Newline))
finally (return (next-char-non-extended lexer)))
;; ...otherwise (whitespace) skip until we
;; see the next non-whitespace character
(loop for skip-char = next-char
then (next-char-non-extended lexer)
while (and skip-char
(whitespacep skip-char))
finally (return skip-char))))))
;; if the position has moved we have to repeat our tests
;; because of cases like /^a (?#xxx) (?#yyy) {3}c/x which
;; would be equivalent to /^a{3}c/ in Perl
(unless (> (lexer-pos lexer) last-loop-pos)
(return next-char)))))
(declaim (inline fail))
(defun fail (lexer)
(declare #.*standard-optimize-settings*)
"Moves (LEXER-POS LEXER) back to the last position stored in
\(LEXER-LAST-POS LEXER) and pops the LAST-POS stack."
(unless (lexer-last-pos lexer)
(signal-syntax-error "LAST-POS stack of LEXER ~A is empty." lexer))
(setf (lexer-pos lexer) (pop (lexer-last-pos lexer)))
nil)
(defun get-number (lexer &key (radix 10) max-length no-whitespace-p)
(declare #.*standard-optimize-settings*)
"Read and consume the number the lexer is currently looking at and
return it. Returns NIL if no number could be identified.
RADIX is used as in PARSE-INTEGER. If MAX-LENGTH is not NIL we'll read
at most the next MAX-LENGTH characters. If NO-WHITESPACE-P is not NIL
we don't tolerate whitespace in front of the number."
(when (or (end-of-string-p lexer)
(and no-whitespace-p
(whitespacep (schar (lexer-str lexer) (lexer-pos lexer)))))
(return-from get-number nil))
(multiple-value-bind (integer new-pos)
(parse-integer (lexer-str lexer)
:start (lexer-pos lexer)
:end (if max-length
(let ((end-pos (+ (lexer-pos lexer)
(the fixnum max-length)))
(lexer-len (lexer-len lexer)))
(if (< end-pos lexer-len)
end-pos
lexer-len))
(lexer-len lexer))
:radix radix
:junk-allowed t)
(cond ((and integer (>= (the fixnum integer) 0))
(setf (lexer-pos lexer) new-pos)
integer)
(t nil))))
(declaim (inline try-number))
(defun try-number (lexer &key (radix 10) max-length no-whitespace-p)
(declare #.*standard-optimize-settings*)
"Like GET-NUMBER but won't consume anything if no number is seen."
;; remember current position
(push (lexer-pos lexer) (lexer-last-pos lexer))
(let ((number (get-number lexer
:radix radix
:max-length max-length
:no-whitespace-p no-whitespace-p)))
(or number (fail lexer))))
(declaim (inline make-char-from-code))
(defun make-char-from-code (number error-pos)
(declare #.*standard-optimize-settings*)
"Create character from char-code NUMBER. NUMBER can be NIL
which is interpreted as 0. ERROR-POS is the position where
the corresponding number started within the regex string."
;; only look at rightmost eight bits in compliance with Perl
(let ((code (logand #o377 (the fixnum (or number 0)))))
(or (and (< code char-code-limit)
(code-char code))
(signal-syntax-error* error-pos "No character for hex-code ~X." number))))
(defun unescape-char (lexer)
(declare #.*standard-optimize-settings*)
"Convert the characters\(s) following a backslash into a token
which is returned. This function is to be called when the backslash
has already been consumed. Special character classes like \\W are
handled elsewhere."
(when (end-of-string-p lexer)
(signal-syntax-error "String ends with backslash."))
(let ((chr (next-char-non-extended lexer)))
(case chr
((#\E)
;; if \Q quoting is on this is ignored, otherwise it's just an
;; #\E
(if *allow-quoting*
:void
#\E))
((#\c)
;; \cx means control-x in Perl
(let ((next-char (next-char-non-extended lexer)))
(unless next-char
(signal-syntax-error* (lexer-pos lexer) "Character missing after '\\c'"))
(code-char (logxor #x40 (char-code (char-upcase next-char))))))
((#\x)
;; \x should be followed by a hexadecimal char code,
;; two digits or less
(let* ((error-pos (lexer-pos lexer))
(number (get-number lexer :radix 16 :max-length 2 :no-whitespace-p t)))
;; note that it is OK if \x is followed by zero digits
(make-char-from-code number error-pos)))
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
;; \x should be followed by an octal char code,
;; three digits or less
(let* ((error-pos (decf (lexer-pos lexer)))
(number (get-number lexer :radix 8 :max-length 3)))
(make-char-from-code number error-pos)))
;; the following five character names are 'semi-standard'
;; according to the CLHS but I'm not aware of any implementation
;; that doesn't implement them
((#\t)
#\Tab)
((#\n)
#\Newline)
((#\r)
#\Return)
((#\f)
#\Page)
((#\b)
#\Backspace)
((#\a)
(code-char 7)) ; ASCII bell
((#\e)
(code-char 27)) ; ASCII escape
(otherwise
;; all other characters aren't affected by a backslash
chr))))
(defun read-char-property (lexer first-char)
(declare #.*standard-optimize-settings*)
(unless (eql (next-char-non-extended lexer) #\{)
(signal-syntax-error* (lexer-pos lexer) "Expected left brace after \\~A." first-char))
(let ((name (with-output-to-string (out nil :element-type
#+:lispworks 'lw:simple-char #-:lispworks 'character)
(loop
(let ((char (or (next-char-non-extended lexer)
(signal-syntax-error "Unexpected EOF after \\~A{." first-char))))
(when (char= char #\})
(return))
(write-char char out))))))
(list (if (char= first-char #\p) :property :inverted-property)
name)))
(defun collect-char-class (lexer)
"Reads and consumes characters from regex string until a right
bracket is seen. Assembles them into a list \(which is returned) of
characters, character ranges, like \(:RANGE #\\A #\\E) for a-e, and
tokens representing special character classes."
(declare #.*standard-optimize-settings*)
(let ((start-pos (lexer-pos lexer)) ; remember start for error message
hyphen-seen
last-char
list)
(flet ((handle-char (c)
"Do the right thing with character C depending on whether
we're inside a range or not."
(cond ((and hyphen-seen last-char)
(setf (car list) (list :range last-char c)
last-char nil))
(t
(push c list)
(setq last-char c)))
(setq hyphen-seen nil)))
(loop for first = t then nil
for c = (next-char-non-extended lexer)
;; leave loop if at end of string
while c
do (cond
((char= c #\\)
;; we've seen a backslash
(let ((next-char (next-char-non-extended lexer)))
(case next-char
((#\d #\D #\w #\W #\s #\S)
;; a special character class
(push (map-char-to-special-char-class next-char) list)
;; if the last character was a hyphen
;; just collect it literally
(when hyphen-seen
(push #\- list))
;; if the next character is a hyphen do the same
(when (looking-at-p lexer #\-)
(push #\- list)
(incf (lexer-pos lexer)))
(setq hyphen-seen nil))
((#\P #\p)
;; maybe a character property
(cond ((null *property-resolver*)
(handle-char next-char))
(t
(push (read-char-property lexer next-char) list)
;; if the last character was a hyphen
;; just collect it literally
(when hyphen-seen
(push #\- list))
;; if the next character is a hyphen do the same
(when (looking-at-p lexer #\-)
(push #\- list)
(incf (lexer-pos lexer)))
(setq hyphen-seen nil))))
((#\E)
;; if \Q quoting is on we ignore \E,
;; otherwise it's just a plain #\E
(unless *allow-quoting*
(handle-char #\E)))
(otherwise
;; otherwise unescape the following character(s)
(decf (lexer-pos lexer))
(handle-char (unescape-char lexer))))))
(first
;; the first character must not be a right bracket
;; and isn't treated specially if it's a hyphen
(handle-char c))
((char= c #\])
;; end of character class
;; make sure we collect a pending hyphen
(when hyphen-seen
(setq hyphen-seen nil)
(handle-char #\-))
;; reverse the list to preserve the order intended
;; by the author of the regex string
(return-from collect-char-class (nreverse list)))
((and (char= c #\-)
last-char
(not hyphen-seen))
;; if the last character was 'just a character'
;; we expect to be in the middle of a range
(setq hyphen-seen t))
((char= c #\-)
;; otherwise this is just an ordinary hyphen
(handle-char #\-))
(t
;; default case - just collect the character
(handle-char c))))
;; we can only exit the loop normally if we've reached the end
;; of the regex string without seeing a right bracket
(signal-syntax-error* start-pos "Missing right bracket to close character class."))))
(defun maybe-parse-flags (lexer)
(declare #.*standard-optimize-settings*)
"Reads a sequence of modifiers \(including #\\- to reverse their
meaning) and returns a corresponding list of \"flag\" tokens. The
\"x\" modifier is treated specially in that it dynamically modifies
the behaviour of the lexer itself via the special variable
*EXTENDED-MODE-P*."
(prog1
(loop with set = t
for chr = (next-char-non-extended lexer)
unless chr
do (signal-syntax-error "Unexpected end of string.")
while (find chr "-imsx" :test #'char=)
;; the first #\- will invert the meaning of all modifiers
;; following it
if (char= chr #\-)
do (setq set nil)
else if (char= chr #\x)
do (setq *extended-mode-p* set)
else collect (if set
(case chr
((#\i)
:case-insensitive-p)
((#\m)
:multi-line-mode-p)
((#\s)
:single-line-mode-p))
(case chr
((#\i)
:case-sensitive-p)
((#\m)
:not-multi-line-mode-p)
((#\s)
:not-single-line-mode-p))))
(decf (lexer-pos lexer))))
(defun get-quantifier (lexer)
(declare #.*standard-optimize-settings*)
"Returns a list of two values (min max) if what the lexer is looking
at can be interpreted as a quantifier. Otherwise returns NIL and
resets the lexer to its old position."
;; remember starting position for FAIL and UNGET-TOKEN functions
(push (lexer-pos lexer) (lexer-last-pos lexer))
(let ((next-char (next-char lexer)))
(case next-char
((#\*)
;; * (Kleene star): match 0 or more times
'(0 nil))
((#\+)
;; +: match 1 or more times
'(1 nil))
((#\?)
;; ?: match 0 or 1 times
'(0 1))
((#\{)
;; one of
;; {n}: match exactly n times
;; {n,}: match at least n times
;; {n,m}: match at least n but not more than m times
;; note that anything not matching one of these patterns will
;; be interpreted literally - even whitespace isn't allowed
(let ((num1 (get-number lexer :no-whitespace-p t)))
(if num1
(let ((next-char (next-char-non-extended lexer)))
(case next-char
((#\,)
(let* ((num2 (get-number lexer :no-whitespace-p t))
(next-char (next-char-non-extended lexer)))
(case next-char
((#\})
;; this is the case {n,} (NUM2 is NIL) or {n,m}
(list num1 num2))
(otherwise
(fail lexer)))))
((#\})
;; this is the case {n}
(list num1 num1))
(otherwise
(fail lexer))))
;; no number following left curly brace, so we treat it
;; like a normal character
(fail lexer))))
;; cannot be a quantifier
(otherwise
(fail lexer)))))
(defun parse-register-name-aux (lexer)
"Reads and returns the name in a named register group. It is
assumed that the starting #\< character has already been read. The
closing #\> will also be consumed."
;; we have to look for an ending > character now
(let ((end-name (position #\>
(lexer-str lexer)
:start (lexer-pos lexer)
:test #'char=)))
(unless end-name
;; there has to be > somewhere, syntax error otherwise
(signal-syntax-error* (1- (lexer-pos lexer)) "Opening #\< in named group has no closing #\>."))
(let ((name (subseq (lexer-str lexer)
(lexer-pos lexer)
end-name)))
(unless (every #'(lambda (char)
(or (alphanumericp char)
(char= #\- char)))
name)
;; register name can contain only alphanumeric characters or #\-
(signal-syntax-error* (lexer-pos lexer) "Invalid character in named register group."))
;; advance lexer beyond "<name>" part
(setf (lexer-pos lexer) (1+ end-name))
name)))
(declaim (inline unget-token))
(defun unget-token (lexer)
(declare #.*standard-optimize-settings*)
"Moves the lexer back to the last position stored in the LAST-POS stack."
(if (lexer-last-pos lexer)
(setf (lexer-pos lexer)
(pop (lexer-last-pos lexer)))
(error "No token to unget \(this should not happen)")))
(defun get-token (lexer)
(declare #.*standard-optimize-settings*)
"Returns and consumes the next token from the regex string \(or NIL)."
;; remember starting position for UNGET-TOKEN function
(push (lexer-pos lexer)
(lexer-last-pos lexer))
(let ((next-char (next-char lexer)))
(cond (next-char
(case next-char
;; the easy cases first - the following six characters
;; always have a special meaning and get translated
;; into tokens immediately
((#\))
:close-paren)
((#\|)
:vertical-bar)
((#\?)
:question-mark)
((#\.)
:everything)
((#\^)
:start-anchor)
((#\$)
:end-anchor)
((#\+ #\*)
;; quantifiers will always be consumend by
;; GET-QUANTIFIER, they must not appear here
(signal-syntax-error* (1- (lexer-pos lexer)) "Quantifier '~A' not allowed." next-char))
((#\{)
;; left brace isn't a special character in it's own
;; right but we must check if what follows might
;; look like a quantifier
(let ((this-pos (lexer-pos lexer))
(this-last-pos (lexer-last-pos lexer)))
(unget-token lexer)
(when (get-quantifier lexer)
(signal-syntax-error* (car this-last-pos)
"Quantifier '~A' not allowed."
(subseq (lexer-str lexer)
(car this-last-pos)
(lexer-pos lexer))))
(setf (lexer-pos lexer) this-pos
(lexer-last-pos lexer) this-last-pos)
next-char))
((#\[)
;; left bracket always starts a character class
(cons (cond ((looking-at-p lexer #\^)
(incf (lexer-pos lexer))
:inverted-char-class)
(t
:char-class))
(collect-char-class lexer)))
((#\\)
;; backslash might mean different things so we have
;; to peek one char ahead:
(let ((next-char (next-char-non-extended lexer)))
(case next-char
((#\A)
:modeless-start-anchor)
((#\Z)
:modeless-end-anchor)
((#\z)
:modeless-end-anchor-no-newline)
((#\b)
:word-boundary)
((#\B)
:non-word-boundary)
((#\k)
(cond ((and *allow-named-registers*
(looking-at-p lexer #\<))
;; back-referencing a named register
(incf (lexer-pos lexer))
(list :back-reference
(parse-register-name-aux lexer)))
(t
;; false alarm, just unescape \k
#\k)))
((#\d #\D #\w #\W #\s #\S)
;; these will be treated like character classes
(map-char-to-special-char-class next-char))
((#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
;; uh, a digit...
(let* ((old-pos (decf (lexer-pos lexer)))
;; ...so let's get the whole number first
(backref-number (get-number lexer)))
(declare (fixnum backref-number))
(cond ((and (> backref-number (lexer-reg lexer))
(<= 10 backref-number))
;; \10 and higher are treated as octal
;; character codes if we haven't
;; opened that much register groups
;; yet
(setf (lexer-pos lexer) old-pos)
;; re-read the number from the old
;; position and convert it to its
;; corresponding character
(make-char-from-code (get-number lexer :radix 8 :max-length 3)
old-pos))
(t
;; otherwise this must refer to a
;; backreference
(list :back-reference backref-number)))))
((#\0)
;; this always means an octal character code
;; (at most three digits)
(let ((old-pos (decf (lexer-pos lexer))))
(make-char-from-code (get-number lexer :radix 8 :max-length 3)
old-pos)))
((#\P #\p)
;; might be a named property
(cond (*property-resolver* (read-char-property lexer next-char))
(t next-char)))
(otherwise
;; in all other cases just unescape the
;; character
(decf (lexer-pos lexer))
(unescape-char lexer)))))
((#\()
;; an open parenthesis might mean different things
;; depending on what follows...
(cond ((looking-at-p lexer #\?)
;; this is the case '(?' (and probably more behind)
(incf (lexer-pos lexer))
;; we have to check for modifiers first
;; because a colon might follow
(let* ((flags (maybe-parse-flags lexer))
(next-char (next-char-non-extended lexer)))
;; modifiers are only allowed if a colon
;; or a closing parenthesis are following
(when (and flags
(not (find next-char ":)" :test #'char=)))
(signal-syntax-error* (car (lexer-last-pos lexer))
"Sequence '~A' not recognized."
(subseq (lexer-str lexer)
(car (lexer-last-pos lexer))
(lexer-pos lexer))))
(case next-char
((nil)
;; syntax error
(signal-syntax-error "End of string following '(?'."))
((#\))
;; an empty group except for the flags
;; (if there are any)
(or (and flags
(cons :flags flags))
:void))
((#\()
;; branch
:open-paren-paren)
((#\>)
;; standalone
:open-paren-greater)
((#\=)
;; positive look-ahead
:open-paren-equal)
((#\!)
;; negative look-ahead
:open-paren-exclamation)
((#\:)
;; non-capturing group - return flags as
;; second value
(values :open-paren-colon flags))
((#\<)
;; might be a look-behind assertion or a named group, so
;; check next character
(let ((next-char (next-char-non-extended lexer)))
(cond ((and next-char
(alpha-char-p next-char))
;; we have encountered a named group
;; are we supporting register naming?
(unless *allow-named-registers*
(signal-syntax-error* (1- (lexer-pos lexer))
"Character '~A' may not follow '(?<' (because ~a = NIL)"
next-char
'*allow-named-registers*))
;; put the letter back
(decf (lexer-pos lexer))
;; named group
:open-paren-less-letter)
(t
(case next-char
((#\=)
;; positive look-behind
:open-paren-less-equal)
((#\!)
;; negative look-behind
:open-paren-less-exclamation)
((#\))
;; Perl allows "(?<)" and treats
;; it like a null string
:void)
((nil)
;; syntax error
(signal-syntax-error "End of string following '(?<'."))
(t
;; also syntax error
(signal-syntax-error* (1- (lexer-pos lexer))
"Character '~A' may not follow '(?<'."
next-char )))))))
(otherwise
(signal-syntax-error* (1- (lexer-pos lexer))
"Character '~A' may not follow '(?'."
next-char)))))
(t
;; if next-char was not #\? (this is within
;; the first COND), we've just seen an opening
;; parenthesis and leave it like that
:open-paren)))
(otherwise
;; all other characters are their own tokens
next-char)))
;; we didn't get a character (this if the "else" branch from
;; the first IF), so we don't return a token but NIL
(t
(pop (lexer-last-pos lexer))
nil))))
(declaim (inline start-of-subexpr-p))
(defun start-of-subexpr-p (lexer)
(declare #.*standard-optimize-settings*)
"Tests whether the next token can start a valid sub-expression, i.e.
a stand-alone regex."
(let* ((pos (lexer-pos lexer))
(next-char (next-char lexer)))
(not (or (null next-char)
(prog1
(member (the character next-char)
'(#\) #\|)
:test #'char=)
(setf (lexer-pos lexer) pos))))))
| 33,648 | Common Lisp | .lisp | 711 | 31.240506 | 115 | 0.486022 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 3e07f939174a624911e3736e93019b7e910d305fb7a1684dcf8fa10de85e070d | 42,922 | [
172642
] |
42,923 | util.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/util.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/util.lisp,v 1.48 2009/10/28 07:36:15 edi Exp $
;;; Utility functions and constants dealing with the character sets we
;;; use to encode character classes
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defmacro defconstant (name value &optional doc)
"Make sure VALUE is evaluated only once \(to appease SBCL)."
`(cl:defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
,@(when doc (list doc))))
#+:lispworks
(eval-when (:compile-toplevel :load-toplevel :execute)
(import 'lw:with-unique-names))
#-:lispworks
(defmacro with-unique-names ((&rest bindings) &body body)
"Syntax: WITH-UNIQUE-NAMES ( { var | (var x) }* ) declaration* form*
Executes a series of forms with each VAR bound to a fresh,
uninterned symbol. The uninterned symbol is as if returned by a call
to GENSYM with the string denoted by X - or, if X is not supplied, the
string denoted by VAR - as argument.
The variable bindings created are lexical unless special declarations
are specified. The scopes of the name bindings and declarations do not
include the Xs.
The forms are evaluated in order, and the values of all but the last
are discarded \(that is, the body is an implicit PROGN)."
;; reference implementation posted to comp.lang.lisp as
;; <[email protected]> by Vebjorn Ljosa - see also
;; <http://www.cliki.net/Common%20Lisp%20Utilities>
`(let ,(mapcar #'(lambda (binding)
(check-type binding (or cons symbol))
(if (consp binding)
(destructuring-bind (var x) binding
(check-type var symbol)
`(,var (gensym ,(etypecase x
(symbol (symbol-name x))
(character (string x))
(string x)))))
`(,binding (gensym ,(symbol-name binding)))))
bindings)
,@body))
#+:lispworks
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (macro-function 'with-rebinding)
(macro-function 'lw:rebinding)))
#-:lispworks
(defmacro with-rebinding (bindings &body body)
"WITH-REBINDING ( { var | (var prefix) }* ) form*
Evaluates a series of forms in the lexical environment that is
formed by adding the binding of each VAR to a fresh, uninterned
symbol, and the binding of that fresh, uninterned symbol to VAR's
original value, i.e., its value in the current lexical environment.
The uninterned symbol is created as if by a call to GENSYM with the
string denoted by PREFIX - or, if PREFIX is not supplied, the string
denoted by VAR - as argument.
The forms are evaluated in order, and the values of all but the last
are discarded \(that is, the body is an implicit PROGN)."
;; reference implementation posted to comp.lang.lisp as
;; <[email protected]> by Vebjorn Ljosa - see also
;; <http://www.cliki.net/Common%20Lisp%20Utilities>
(loop for binding in bindings
for var = (if (consp binding) (car binding) binding)
for name = (gensym)
collect `(,name ,var) into renames
collect ``(,,var ,,name) into temps
finally (return `(let ,renames
(with-unique-names ,bindings
`(let (,,@temps)
,,@body))))))
(declaim (inline digit-char-p))
(defun digit-char-p (chr)
(declare #.*standard-optimize-settings*)
"Tests whether a character is a decimal digit, i.e. the same as
Perl's [\\d]. Note that this function shadows the standard Common
Lisp function CL:DIGIT-CHAR-P."
(char<= #\0 chr #\9))
(declaim (inline word-char-p))
(defun word-char-p (chr)
(declare #.*standard-optimize-settings*)
"Tests whether a character is a \"word\" character. In the ASCII
charset this is equivalent to a-z, A-Z, 0-9, or _, i.e. the same as
Perl's [\\w]."
(or (alphanumericp chr)
(char= chr #\_)))
(defconstant +whitespace-char-string+
(coerce '(#\Space #\Tab #\Linefeed #\Return #\Page) 'string)
"A string of all characters which are considered to be whitespace.
Same as Perl's [\\s].")
(defun whitespacep (chr)
(declare #.*special-optimize-settings*)
"Tests whether a character is whitespace, i.e. whether it would
match [\\s] in Perl."
(find chr +whitespace-char-string+ :test #'char=))
(defmacro maybe-coerce-to-simple-string (string)
"Coerces STRING to a simple STRING unless it already is one."
(with-unique-names (=string=)
`(let ((,=string= ,string))
(cond (#+:lispworks
(lw:simple-text-string-p ,=string=)
#-:lispworks
(simple-string-p ,=string=)
,=string=)
(t
(coerce ,=string=
#+:lispworks 'lw:simple-text-string
#-:lispworks 'simple-string))))))
(declaim (inline nsubseq))
(defun nsubseq (sequence start &optional (end (length sequence)))
"Returns a subsequence by pointing to location in original sequence."
(make-array (- end start)
:element-type (array-element-type sequence)
:displaced-to sequence
:displaced-index-offset start))
(defun normalize-var-list (var-list)
"Utility function for REGISTER-GROUPS-BIND and DO-REGISTER-GROUPS.
Creates the long form \(a list of \(FUNCTION VAR) entries) out of the
short form of VAR-LIST."
(loop for element in var-list
if (consp element)
nconc (loop for var in (rest element)
collect (list (first element) var))
else
collect (list '(function identity) element)))
(defun string-list-to-simple-string (string-list)
"Concatenates a list of strings to one simple-string."
(declare #.*standard-optimize-settings*)
;; this function provided by JP Massar; note that we can't use APPLY
;; with CONCATENATE here because of CALL-ARGUMENTS-LIMIT
(let ((total-size 0))
(declare (fixnum total-size))
(dolist (string string-list)
#-:genera (declare (string string))
(incf total-size (length string)))
(let ((result-string (make-sequence #-:lispworks 'simple-string
#+:lispworks 'lw:simple-text-string
total-size))
(curr-pos 0))
(declare (fixnum curr-pos))
(dolist (string string-list)
#-:genera (declare (string string))
(replace result-string string :start1 curr-pos)
(incf curr-pos (length string)))
result-string)))
(defun complement* (test-function)
"Like COMPLEMENT but optimized for unary functions."
(declare #.*standard-optimize-settings*)
(typecase test-function
(function
(lambda (char)
(declare (character char))
(not (funcall (the function test-function) char))))
(otherwise
(lambda (char)
(declare (character char))
(not (funcall test-function char)))))) | 8,380 | Common Lisp | .lisp | 174 | 41.557471 | 86 | 0.665526 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 49b6f8d0879e55cb7fb91e69b3cdc36c3b6c6dce5e6638701780538485ef4cfd | 42,923 | [
36029,
200652
] |
42,924 | errors.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/errors.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/errors.lisp,v 1.22 2009/09/17 19:17:31 edi Exp $
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defvar *syntax-error-string* nil
"The string which caused the syntax error.")
(define-condition ppcre-error (simple-error)
()
(:documentation "All errors signaled by CL-PPCRE are of
this type."))
(define-condition ppcre-syntax-error (ppcre-error)
((string :initarg :string
:reader ppcre-syntax-error-string)
(pos :initarg :pos
:reader ppcre-syntax-error-pos))
(:default-initargs
:pos nil
:string *syntax-error-string*)
(:report (lambda (condition stream)
(format stream "~?~@[ at position ~A~]~@[ in string ~S~]"
(simple-condition-format-control condition)
(simple-condition-format-arguments condition)
(ppcre-syntax-error-pos condition)
(ppcre-syntax-error-string condition))))
(:documentation "Signaled if CL-PPCRE's parser encounters an error
when trying to parse a regex string or to convert a parse tree into
its internal representation."))
(setf (documentation 'ppcre-syntax-error-string 'function)
"Returns the string the parser was parsing when the error was
encountered \(or NIL if the error happened while trying to convert a
parse tree).")
(setf (documentation 'ppcre-syntax-error-pos 'function)
"Returns the position within the string where the error occurred
\(or NIL if the error happened while trying to convert a parse tree")
(define-condition ppcre-invocation-error (ppcre-error)
()
(:documentation "Signaled when CL-PPCRE functions are
invoked with wrong arguments."))
(defmacro signal-syntax-error* (pos format-control &rest format-arguments)
`(error 'ppcre-syntax-error
:pos ,pos
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
(defmacro signal-syntax-error (format-control &rest format-arguments)
`(signal-syntax-error* nil ,format-control ,@format-arguments))
(defmacro signal-invocation-error (format-control &rest format-arguments)
`(error 'ppcre-invocation-error
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
| 3,662 | Common Lisp | .lisp | 69 | 48.710145 | 88 | 0.727222 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 7fcde063c0edd26a8d25769e345633413a540a3b6f1f3c805241058323631770 | 42,924 | [
69871,
433907
] |
42,925 | charmap.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/charmap.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/charmap.lisp,v 1.19 2009/09/17 19:17:30 edi Exp $
;;; An optimized representation of sets of characters.
;;; Copyright (c) 2008-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defstruct (charmap (:constructor make-charmap%))
;; a bit vector mapping char codes to "booleans" (1 for set members,
;; 0 for others)
(vector #*0 :type simple-bit-vector)
;; the smallest character code of all characters in the set
(start 0 :type fixnum)
;; the upper (exclusive) bound of all character codes in the set
(end 0 :type fixnum)
;; the number of characters in the set, or NIL if this is unknown
(count nil :type (or fixnum null))
;; whether the charmap actually represents the complement of the set
(complementp nil :type boolean))
;; seems to be necessary for some Lisps like ClozureCL
(defmethod make-load-form ((map charmap) &optional environment)
(make-load-form-saving-slots map :environment environment))
(declaim (inline in-charmap-p))
(defun in-charmap-p (char charmap)
"Tests whether the character CHAR belongs to the set represented by CHARMAP."
(declare #.*standard-optimize-settings*)
(declare (character char) (charmap charmap))
(let* ((char-code (char-code char))
(char-in-vector-p
(let ((charmap-start (charmap-start charmap)))
(declare (fixnum charmap-start))
(and (<= charmap-start char-code)
(< char-code (the fixnum (charmap-end charmap)))
(= 1 (sbit (the simple-bit-vector (charmap-vector charmap))
(- char-code charmap-start)))))))
(cond ((charmap-complementp charmap) (not char-in-vector-p))
(t char-in-vector-p))))
(defun charmap-contents (charmap)
"Returns a list of all characters belonging to a character map.
Only works for non-complement charmaps."
(declare #.*standard-optimize-settings*)
(declare (charmap charmap))
(and (not (charmap-complementp charmap))
(loop for code of-type fixnum from (charmap-start charmap) to (charmap-end charmap)
for i across (the simple-bit-vector (charmap-vector charmap))
when (= i 1)
collect (code-char code))))
(defun make-charmap (start end test-function &optional complementp)
"Creates and returns a charmap representing all characters with
character codes in the interval [start end) that satisfy
TEST-FUNCTION. The COMPLEMENTP slot of the charmap is set to the
value of the optional argument, but this argument doesn't have an
effect on how TEST-FUNCTION is used."
(declare #.*standard-optimize-settings*)
(declare (fixnum start end))
(let ((vector (make-array (- end start) :element-type 'bit))
(count 0))
(declare (fixnum count))
(loop for code from start below end
for char = (code-char code)
for index from 0
when char do
(incf count)
(setf (sbit vector index) (if (funcall test-function char) 1 0)))
(make-charmap% :vector vector
:start start
:end end
;; we don't know for sure if COMPLEMENTP is true as
;; there isn't a necessary a character for each
;; integer below *REGEX-CHAR-CODE-LIMIT*
:count (and (not complementp) count)
;; make sure it's boolean
:complementp (not (not complementp)))))
(defun create-charmap-from-test-function (test-function start end)
"Creates and returns a charmap representing all characters with
character codes between START and END which satisfy TEST-FUNCTION.
Tries to find the smallest interval which is necessary to represent
the character set and uses the complement representation if that
helps."
(declare #.*standard-optimize-settings*)
(let (start-in end-in start-out end-out)
;; determine the smallest intervals containing the set and its
;; complement, [start-in, end-in) and [start-out, end-out) - first
;; the lower bound
(loop for code from start below end
for char = (code-char code)
until (and start-in start-out)
when (and char
(not start-in)
(funcall test-function char))
do (setq start-in code)
when (and char
(not start-out)
(not (funcall test-function char)))
do (setq start-out code))
(unless start-in
;; no character satisfied the test, so return a "pseudo" charmap
;; where IN-CHARMAP-P is always false
(return-from create-charmap-from-test-function
(make-charmap% :count 0)))
(unless start-out
;; no character failed the test, so return a "pseudo" charmap
;; where IN-CHARMAP-P is always true
(return-from create-charmap-from-test-function
(make-charmap% :complementp t)))
;; now determine upper bound
(loop for code from (1- end) downto start
for char = (code-char code)
until (and end-in end-out)
when (and char
(not end-in)
(funcall test-function char))
do (setq end-in (1+ code))
when (and char
(not end-out)
(not (funcall test-function char)))
do (setq end-out (1+ code)))
;; use the smaller interval
(cond ((<= (- end-in start-in) (- end-out start-out))
(make-charmap start-in end-in test-function))
(t (make-charmap start-out end-out (complement* test-function) t)))))
| 6,957 | Common Lisp | .lisp | 139 | 42.942446 | 90 | 0.666863 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 5a2ffac4d10194098dc781ffb7867c3db9774edee0e58fd306e7b5d7115913cc | 42,925 | [
2705,
286726
] |
42,926 | regex-class.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/regex-class.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/regex-class.lisp,v 1.44 2009/10/28 07:36:15 edi Exp $
;;; This file defines the REGEX class. REGEX objects are used to
;;; represent the (transformed) parse trees internally
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defclass regex ()
()
(:documentation "The REGEX base class. All other classes inherit
from this one."))
(defclass seq (regex)
((elements :initarg :elements
:accessor elements
:type cons
:documentation "A list of REGEX objects."))
(:documentation "SEQ objects represents sequences of regexes.
\(Like \"ab\" is the sequence of \"a\" and \"b\".)"))
(defclass alternation (regex)
((choices :initarg :choices
:accessor choices
:type cons
:documentation "A list of REGEX objects"))
(:documentation "ALTERNATION objects represent alternations of
regexes. \(Like \"a|b\" ist the alternation of \"a\" or \"b\".)"))
(defclass lookahead (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive."))
(:documentation "LOOKAHEAD objects represent look-ahead assertions."))
(defclass lookbehind (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive.")
(len :initarg :len
:accessor len
:type fixnum
:documentation "The \(fixed) length of the enclosed regex."))
(:documentation "LOOKBEHIND objects represent look-behind assertions."))
(defclass repetition (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX that's repeated.")
(greedyp :initarg :greedyp
:reader greedyp
:documentation "Whether the repetition is greedy.")
(minimum :initarg :minimum
:accessor minimum
:type fixnum
:documentation "The minimal number of repetitions.")
(maximum :initarg :maximum
:accessor maximum
:documentation "The maximal number of repetitions.
Can be NIL for unbounded.")
(min-len :initarg :min-len
:reader min-len
:documentation "The minimal length of the enclosed regex.")
(len :initarg :len
:reader len
:documentation "The length of the enclosed regex. NIL if
unknown.")
(min-rest :initform 0
:accessor min-rest
:type fixnum
:documentation "The minimal number of characters which
must appear after this repetition.")
(contains-register-p :initarg :contains-register-p
:reader contains-register-p
:documentation "Whether the regex contains a
register."))
(:documentation "REPETITION objects represent repetitions of regexes."))
(defmethod print-object ((repetition repetition) stream)
(print-unreadable-object (repetition stream :type t :identity t)
(princ (regex repetition) stream)))
(defclass register (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex.")
(num :initarg :num
:reader num
:type fixnum
:documentation "The number of this register, starting from 0.
This is the index into *REGS-START* and *REGS-END*.")
(name :initarg :name
:reader name
:documentation "Name of this register or NIL."))
(:documentation "REGISTER objects represent register groups."))
(defmethod print-object ((register register) stream)
(print-unreadable-object (register stream :type t :identity t)
(princ (regex register) stream)))
(defclass standalone (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex."))
(:documentation "A standalone regular expression."))
(defclass back-reference (regex)
((num :initarg :num
:accessor num
:type fixnum
:documentation "The number of the register this
reference refers to.")
(name :initarg :name
:accessor name
:documentation "The name of the register this
reference refers to or NIL.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "Whether we check
case-insensitively."))
(:documentation "BACK-REFERENCE objects represent backreferences."))
(defclass char-class (regex)
((test-function :initarg :test-function
:reader test-function
:type (or function symbol nil)
:documentation "A unary function \(accepting a
character) which stands in for the character class and does the work
of checking whether a character belongs to the class."))
(:documentation "CHAR-CLASS objects represent character classes."))
(defclass str (regex)
((str :initarg :str
:accessor str
:type string
:documentation "The actual string.")
(len :initform 0
:accessor len
:type fixnum
:documentation "The length of the string.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "If we match case-insensitively.")
(offset :initform nil
:accessor offset
:documentation "Offset from the left of the whole
parse tree. The first regex has offset 0. NIL if unknown, i.e. behind
a variable-length regex.")
(skip :initform nil
:initarg :skip
:accessor skip
:documentation "If we can avoid testing for this
string because the SCAN function has done this already.")
(start-of-end-string-p :initform nil
:accessor start-of-end-string-p
:documentation "If this is the unique
STR which starts END-STRING (a slot of MATCHER)."))
(:documentation "STR objects represent string."))
(defmethod print-object ((str str) stream)
(print-unreadable-object (str stream :type t :identity t)
(princ (str str) stream)))
(defclass anchor (regex)
((startp :initarg :startp
:reader startp
:documentation "Whether this is a \"start anchor\".")
(multi-line-p :initarg :multi-line-p
:initform nil
:reader multi-line-p
:documentation "Whether we're in multi-line mode,
i.e. whether each #\\Newline is surrounded by anchors.")
(no-newline-p :initarg :no-newline-p
:initform nil
:reader no-newline-p
:documentation "Whether we ignore #\\Newline at the end."))
(:documentation "ANCHOR objects represent anchors like \"^\" or \"$\"."))
(defclass everything (regex)
((single-line-p :initarg :single-line-p
:reader single-line-p
:documentation "Whether we're in single-line mode,
i.e. whether we also match #\\Newline."))
(:documentation "EVERYTHING objects represent regexes matching
\"everything\", i.e. dots."))
(defclass word-boundary (regex)
((negatedp :initarg :negatedp
:reader negatedp
:documentation "Whether we mean the opposite,
i.e. no word-boundary."))
(:documentation "WORD-BOUNDARY objects represent word-boundary assertions."))
(defclass branch (regex)
((test :initarg :test
:accessor test
:documentation "The test of this branch, one of
LOOKAHEAD, LOOKBEHIND, or a number.")
(then-regex :initarg :then-regex
:accessor then-regex
:documentation "The regex that's to be matched if the
test succeeds.")
(else-regex :initarg :else-regex
:initform (make-instance 'void)
:accessor else-regex
:documentation "The regex that's to be matched if the
test fails."))
(:documentation "BRANCH objects represent Perl's conditional regular
expressions."))
(defclass filter (regex)
((fn :initarg :fn
:accessor fn
:type (or function symbol)
:documentation "The user-defined function.")
(len :initarg :len
:reader len
:documentation "The fixed length of this filter or NIL."))
(:documentation "FILTER objects represent arbitrary functions
defined by the user."))
(defclass void (regex)
()
(:documentation "VOID objects represent empty regular expressions."))
(defmethod initialize-instance :after ((str str) &rest init-args)
(declare #.*standard-optimize-settings*)
(declare (ignore init-args))
"Automatically computes the length of a STR after initialization."
(let ((str-slot (slot-value str 'str)))
(unless (typep str-slot
#-:lispworks 'simple-string
#+:lispworks 'lw:simple-text-string)
(setf (slot-value str 'str)
(coerce str-slot
#-:lispworks 'simple-string
#+:lispworks 'lw:simple-text-string))))
(setf (len str) (length (str str))))
| 10,539 | Common Lisp | .lisp | 242 | 36.508264 | 93 | 0.66907 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 232e08414a900bc3169227fcb183961e1f5ba264550a86e055dcd216040d1d7e | 42,926 | [
165132,
481658
] |
42,927 | specials.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/specials.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/specials.lisp,v 1.43 2009/10/28 07:36:15 edi Exp $
;;; globally declared special variables
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
;;; special variables used to effect declarations
(defvar *standard-optimize-settings*
'(optimize
speed
(space 0)
(debug 1)
(compilation-speed 0))
"The standard optimize settings used by most declaration expressions.")
(defvar *special-optimize-settings*
'(optimize speed space)
"Special optimize settings used only by a few declaration expressions.")
;;; special variables used by the lexer/parser combo
(defvar *extended-mode-p* nil
"Whether the parser will start in extended mode.")
(declaim (boolean *extended-mode-p*))
;;; special variables used by the SCAN function and the matchers
(defvar *regex-char-code-limit* char-code-limit
"The upper exclusive bound on the char-codes of characters which can
occur in character classes. Change this value BEFORE creating
scanners if you don't need the \(full) Unicode support of
implementations like AllegroCL, CLISP, LispWorks, or SBCL.")
(declaim (fixnum *regex-char-code-limit*))
(defvar *string* (make-sequence #+:lispworks 'lw:simple-text-string
#-:lispworks 'simple-string
0)
"The string which is currently scanned by SCAN.
Will always be coerced to a SIMPLE-STRING.")
#+:lispworks
(declaim (lw:simple-text-string *string*))
#-:lispworks
(declaim (simple-string *string*))
(defvar *start-pos* 0
"Where to start scanning within *STRING*.")
(declaim (fixnum *start-pos*))
(defvar *real-start-pos* nil
"The real start of *STRING*. This is for repeated scans and is only used internally.")
(declaim (type (or null fixnum) *real-start-pos*))
(defvar *end-pos* 0
"Where to stop scanning within *STRING*.")
(declaim (fixnum *end-pos*))
(defvar *reg-starts* (make-array 0)
"An array which holds the start positions
of the current register candidates.")
(declaim (simple-vector *reg-starts*))
(defvar *regs-maybe-start* (make-array 0)
"An array which holds the next start positions
of the current register candidates.")
(declaim (simple-vector *regs-maybe-start*))
(defvar *reg-ends* (make-array 0)
"An array which holds the end positions
of the current register candidates.")
(declaim (simple-vector *reg-ends*))
(defvar *end-string-pos* nil
"Start of the next possible end-string candidate.")
(defvar *rep-num* 0
"Counts the number of \"complicated\" repetitions while the matchers
are built.")
(declaim (fixnum *rep-num*))
(defvar *zero-length-num* 0
"Counts the number of repetitions the inner regexes of which may
have zero-length while the matchers are built.")
(declaim (fixnum *zero-length-num*))
(defvar *repeat-counters* (make-array 0
:initial-element 0
:element-type 'fixnum)
"An array to keep track of how often
repetitive patterns have been tested already.")
(declaim (type (array fixnum (*)) *repeat-counters*))
(defvar *last-pos-stores* (make-array 0)
"An array to keep track of the last positions
where we saw repetitive patterns.
Only used for patterns which might have zero length.")
(declaim (simple-vector *last-pos-stores*))
(defvar *use-bmh-matchers* nil
"Whether the scanners created by CREATE-SCANNER should use the \(fast
but large) Boyer-Moore-Horspool matchers.")
(defvar *optimize-char-classes* nil
"Whether character classes should be compiled into look-ups into
O\(1) data structures. This is usually fast but will be costly in
terms of scanner creation time and might be costly in terms of size if
*REGEX-CHAR-CODE-LIMIT* is high. This value will be used as the :KIND
keyword argument to CREATE-OPTIMIZED-TEST-FUNCTION - see there for the
possible non-NIL values.")
(defvar *property-resolver* nil
"Should be NIL or a designator for a function which accepts strings
and returns unary character test functions or NIL. This 'resolver' is
intended to handle `character properties' like \\p{IsAlpha}. If
*PROPERTY-RESOLVER* is NIL, then the parser will simply treat \\p and
\\P as #\\p and #\\P as in older versions of CL-PPCRE.")
(defvar *allow-quoting* nil
"Whether the parser should support Perl's \\Q and \\E.")
(defvar *allow-named-registers* nil
"Whether the parser should support AllegroCL's named registers
\(?<name>\"<regex>\") and back-reference \\k<name> syntax.")
(pushnew :cl-ppcre *features*)
;; stuff for Nikodemus Siivola's HYPERDOC
;; see <http://common-lisp.net/project/hyperdoc/>
;; and <http://www.cliki.net/hyperdoc>
;; also used by LW-ADD-ONS
(defvar *hyperdoc-base-uri* "http://weitz.de/cl-ppcre/")
(let ((exported-symbols-alist
(loop for symbol being the external-symbols of :cl-ppcre
collect (cons symbol
(concatenate 'string
"#"
(string-downcase symbol))))))
(defun hyperdoc-lookup (symbol type)
(declare (ignore type))
(cdr (assoc symbol
exported-symbols-alist
:test #'eq))))
| 6,580 | Common Lisp | .lisp | 136 | 44.25 | 90 | 0.721553 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 982cbd1aaaf850c930822ae73a20f50ea13100b4688f800381e1f79388194bc8 | 42,927 | [
49508
] |
42,928 | scanner.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/scanner.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/scanner.lisp,v 1.36 2009/09/17 19:17:31 edi Exp $
;;; Here the scanner for the actual regex as well as utility scanners
;;; for the constant start and end strings are created.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defmacro bmh-matcher-aux (&key case-insensitive-p)
"Auxiliary macro used by CREATE-BMH-MATCHER."
(let ((char-compare (if case-insensitive-p 'char-equal 'char=)))
`(lambda (start-pos)
(declare (fixnum start-pos))
(if (or (minusp start-pos)
(> (the fixnum (+ start-pos m)) *end-pos*))
nil
(loop named bmh-matcher
for k of-type fixnum = (+ start-pos m -1)
then (+ k (max 1 (aref skip (char-code (schar *string* k)))))
while (< k *end-pos*)
do (loop for j of-type fixnum downfrom (1- m)
for i of-type fixnum downfrom k
while (and (>= j 0)
(,char-compare (schar *string* i)
(schar pattern j)))
finally (if (minusp j)
(return-from bmh-matcher (1+ i)))))))))
(defun create-bmh-matcher (pattern case-insensitive-p)
"Returns a Boyer-Moore-Horspool matcher which searches the (special)
simple-string *STRING* for the first occurence of the substring
PATTERN. The search starts at the position START-POS within *STRING*
and stops before *END-POS* is reached. Depending on the second
argument the search is case-insensitive or not. If the special
variable *USE-BMH-MATCHERS* is NIL, use the standard SEARCH function
instead. \(BMH matchers are faster but need much more space.)"
(declare #.*standard-optimize-settings*)
;; see <http://www-igm.univ-mlv.fr/~lecroq/string/node18.html> for
;; details
(unless *use-bmh-matchers*
(let ((test (if case-insensitive-p #'char-equal #'char=)))
(return-from create-bmh-matcher
(lambda (start-pos)
(declare (fixnum start-pos))
(and (not (minusp start-pos))
(search pattern
*string*
:start2 start-pos
:end2 *end-pos*
:test test))))))
(let* ((m (length pattern))
(skip (make-array *regex-char-code-limit*
:element-type 'fixnum
:initial-element m)))
(declare (fixnum m))
(loop for k of-type fixnum below m
if case-insensitive-p
do (setf (aref skip (char-code (char-upcase (schar pattern k)))) (- m k 1)
(aref skip (char-code (char-downcase (schar pattern k)))) (- m k 1))
else
do (setf (aref skip (char-code (schar pattern k))) (- m k 1)))
(if case-insensitive-p
(bmh-matcher-aux :case-insensitive-p t)
(bmh-matcher-aux))))
(defmacro char-searcher-aux (&key case-insensitive-p)
"Auxiliary macro used by CREATE-CHAR-SEARCHER."
(let ((char-compare (if case-insensitive-p 'char-equal 'char=)))
`(lambda (start-pos)
(declare (fixnum start-pos))
(and (not (minusp start-pos))
(loop for i of-type fixnum from start-pos below *end-pos*
thereis (and (,char-compare (schar *string* i) chr) i))))))
(defun create-char-searcher (chr case-insensitive-p)
"Returns a function which searches the (special) simple-string
*STRING* for the first occurence of the character CHR. The search
starts at the position START-POS within *STRING* and stops before
*END-POS* is reached. Depending on the second argument the search is
case-insensitive or not."
(declare #.*standard-optimize-settings*)
(if case-insensitive-p
(char-searcher-aux :case-insensitive-p t)
(char-searcher-aux)))
(declaim (inline newline-skipper))
(defun newline-skipper (start-pos)
"Finds the next occurence of a character in *STRING* which is behind
a #\Newline."
(declare #.*standard-optimize-settings*)
(declare (fixnum start-pos))
;; we can start with (1- START-POS) without testing for (PLUSP
;; START-POS) because we know we'll never call NEWLINE-SKIPPER on
;; the first iteration
(loop for i of-type fixnum from (1- start-pos) below *end-pos*
thereis (and (char= (schar *string* i)
#\Newline)
(1+ i))))
(defmacro insert-advance-fn (advance-fn)
"Creates the actual closure returned by CREATE-SCANNER-AUX by
replacing '(ADVANCE-FN-DEFINITION) with a suitable definition for
ADVANCE-FN. This is a utility macro used by CREATE-SCANNER-AUX."
(subst
advance-fn '(advance-fn-definition)
'(lambda (string start end)
(block scan
;; initialize a couple of special variables used by the
;; matchers (see file specials.lisp)
(let* ((*string* string)
(*start-pos* start)
(*end-pos* end)
;; we will search forward for END-STRING if this value
;; isn't at least as big as POS (see ADVANCE-FN), so it
;; is safe to start to the left of *START-POS*; note
;; that this value will _never_ be decremented - this
;; is crucial to the scanning process
(*end-string-pos* (1- *start-pos*))
;; the next five will shadow the variables defined by
;; DEFPARAMETER; at this point, we don't know if we'll
;; actually use them, though
(*repeat-counters* *repeat-counters*)
(*last-pos-stores* *last-pos-stores*)
(*reg-starts* *reg-starts*)
(*regs-maybe-start* *regs-maybe-start*)
(*reg-ends* *reg-ends*)
;; we might be able to optimize the scanning process by
;; (virtually) shifting *START-POS* to the right
(scan-start-pos *start-pos*)
(starts-with-str (if start-string-test
(str starts-with)
nil))
;; we don't need to try further than MAX-END-POS
(max-end-pos (- *end-pos* min-len)))
(declare (fixnum scan-start-pos)
(function match-fn))
;; definition of ADVANCE-FN will be inserted here by macrology
(labels ((advance-fn-definition))
(declare (inline advance-fn))
(when (plusp rep-num)
;; we have at least one REPETITION which needs to count
;; the number of repetitions
(setq *repeat-counters* (make-array rep-num
:initial-element 0
:element-type 'fixnum)))
(when (plusp zero-length-num)
;; we have at least one REPETITION which needs to watch
;; out for zero-length repetitions
(setq *last-pos-stores* (make-array zero-length-num
:initial-element nil)))
(when (plusp reg-num)
;; we have registers in our regular expression
(setq *reg-starts* (make-array reg-num :initial-element nil)
*regs-maybe-start* (make-array reg-num :initial-element nil)
*reg-ends* (make-array reg-num :initial-element nil)))
(when end-anchored-p
;; the regular expression has a constant end string which
;; is anchored at the very end of the target string
;; (perhaps modulo a #\Newline)
(let ((end-test-pos (- *end-pos* (the fixnum end-string-len))))
(declare (fixnum end-test-pos)
(function end-string-test))
(unless (setq *end-string-pos* (funcall end-string-test
end-test-pos))
(when (and (= 1 (the fixnum end-anchored-p))
(> *end-pos* scan-start-pos)
(char= #\Newline (schar *string* (1- *end-pos*))))
;; if we didn't find an end string candidate from
;; END-TEST-POS and if a #\Newline at the end is
;; allowed we try it again from one position to the
;; left
(setq *end-string-pos* (funcall end-string-test
(1- end-test-pos))))))
(unless (and *end-string-pos*
(<= *start-pos* *end-string-pos*))
;; no end string candidate found, so give up
(return-from scan nil))
(when end-string-offset
;; if the offset of the constant end string from the
;; left of the regular expression is known we can start
;; scanning further to the right; this is similar to
;; what we might do in ADVANCE-FN
(setq scan-start-pos (max scan-start-pos
(- (the fixnum *end-string-pos*)
(the fixnum end-string-offset))))))
(cond
(start-anchored-p
;; we're anchored at the start of the target string,
;; so no need to try again after first failure
(when (or (/= *start-pos* scan-start-pos)
(< max-end-pos *start-pos*))
;; if END-STRING-OFFSET has proven that we don't
;; need to bother to scan from *START-POS* or if the
;; minimal length of the regular expression is
;; longer than the target string we give up
(return-from scan nil))
(when starts-with-str
(locally
(declare (fixnum starts-with-len))
(cond ((and (case-insensitive-p starts-with)
(not (*string*-equal starts-with-str
*start-pos*
(+ *start-pos*
starts-with-len)
0 starts-with-len)))
;; the regular expression has a
;; case-insensitive constant start string
;; and we didn't find it
(return-from scan nil))
((and (not (case-insensitive-p starts-with))
(not (*string*= starts-with-str
*start-pos*
(+ *start-pos* starts-with-len)
0 starts-with-len)))
;; the regular expression has a
;; case-sensitive constant start string
;; and we didn't find it
(return-from scan nil))
(t nil))))
(when (and end-string-test
(not end-anchored-p))
;; the regular expression has a constant end string
;; which isn't anchored so we didn't check for it
;; already
(block end-string-loop
;; we temporarily use *END-STRING-POS* as our
;; starting position to look for end string
;; candidates
(setq *end-string-pos* *start-pos*)
(loop
(unless (setq *end-string-pos*
(funcall (the function end-string-test)
*end-string-pos*))
;; no end string candidate found, so give up
(return-from scan nil))
(unless end-string-offset
;; end string doesn't have an offset so we
;; can start scanning now
(return-from end-string-loop))
(let ((maybe-start-pos (- (the fixnum *end-string-pos*)
(the fixnum end-string-offset))))
(cond ((= maybe-start-pos *start-pos*)
;; offset of end string into regular
;; expression matches start anchor -
;; fine...
(return-from end-string-loop))
((and (< maybe-start-pos *start-pos*)
(< (+ *end-string-pos* end-string-len) *end-pos*))
;; no match but maybe we find another
;; one to the right - try again
(incf *end-string-pos*))
(t
;; otherwise give up
(return-from scan nil)))))))
;; if we got here we scan exactly once
(let ((next-pos (funcall match-fn *start-pos*)))
(when next-pos
(values (if next-pos *start-pos* nil)
next-pos
*reg-starts*
*reg-ends*))))
(t
(loop for pos = (if starts-with-everything
;; don't jump to the next
;; #\Newline on the first
;; iteration
scan-start-pos
(advance-fn scan-start-pos))
then (advance-fn pos)
;; give up if the regular expression can't fit
;; into the rest of the target string
while (and pos
(<= (the fixnum pos) max-end-pos))
do (let ((next-pos (funcall match-fn pos)))
(when next-pos
(return-from scan (values pos
next-pos
*reg-starts*
*reg-ends*)))
;; not yet found, increment POS
#-cormanlisp (incf (the fixnum pos))
#+cormanlisp (incf pos)))))))))
:test #'equalp))
(defun create-scanner-aux (match-fn
min-len
start-anchored-p
starts-with
start-string-test
end-anchored-p
end-string-test
end-string-len
end-string-offset
rep-num
zero-length-num
reg-num)
"Auxiliary function to create and return a scanner \(which is
actually a closure). Used by CREATE-SCANNER."
(declare #.*standard-optimize-settings*)
(declare (fixnum min-len zero-length-num rep-num reg-num))
(let ((starts-with-len (if (typep starts-with 'str)
(len starts-with)))
(starts-with-everything (typep starts-with 'everything)))
(cond
;; this COND statement dispatches on the different versions we
;; have for ADVANCE-FN and creates different closures for each;
;; note that you see only the bodies of ADVANCE-FN below - the
;; actual scanner is defined in INSERT-ADVANCE-FN above; (we
;; could have done this with closures instead of macrology but
;; would have consed a lot more)
((and start-string-test end-string-test end-string-offset)
;; we know that the regular expression has constant start and
;; end strings and we know the end string's offset (from the
;; left)
(insert-advance-fn
(advance-fn (pos)
(declare (fixnum end-string-offset starts-with-len)
(function start-string-test end-string-test))
(loop
(unless (setq pos (funcall start-string-test pos))
;; give up completely if we can't find a start string
;; candidate
(return-from scan nil))
(locally
;; from here we know that POS is a FIXNUM
(declare (fixnum pos))
(when (= pos (- (the fixnum *end-string-pos*) end-string-offset))
;; if we already found an end string candidate the
;; position of which matches the start string
;; candidate we're done
(return-from advance-fn pos))
(let ((try-pos (+ pos starts-with-len)))
;; otherwise try (again) to find an end string
;; candidate which starts behind the start string
;; candidate
(loop
(unless (setq *end-string-pos*
(funcall end-string-test try-pos))
;; no end string candidate found, so give up
(return-from scan nil))
;; NEW-POS is where we should start scanning
;; according to the end string candidate
(let ((new-pos (- (the fixnum *end-string-pos*)
end-string-offset)))
(declare (fixnum new-pos *end-string-pos*))
(cond ((= new-pos pos)
;; if POS and NEW-POS are equal then the
;; two candidates agree so we're fine
(return-from advance-fn pos))
((> new-pos pos)
;; if NEW-POS is further to the right we
;; advance POS and try again, i.e. we go
;; back to the start of the outer LOOP
(setq pos new-pos)
;; this means "return from inner LOOP"
(return))
(t
;; otherwise NEW-POS is smaller than POS,
;; so we have to redo the inner LOOP to
;; find another end string candidate
;; further to the right
(setq try-pos (1+ *end-string-pos*))))))))))))
((and starts-with-everything end-string-test end-string-offset)
;; we know that the regular expression starts with ".*" (which
;; is not in single-line-mode, see CREATE-SCANNER-AUX) and ends
;; with a constant end string and we know the end string's
;; offset (from the left)
(insert-advance-fn
(advance-fn (pos)
(declare (fixnum end-string-offset)
(function end-string-test))
(loop
(unless (setq pos (newline-skipper pos))
;; if we can't find a #\Newline we give up immediately
(return-from scan nil))
(locally
;; from here we know that POS is a FIXNUM
(declare (fixnum pos))
(when (= pos (- (the fixnum *end-string-pos*) end-string-offset))
;; if we already found an end string candidate the
;; position of which matches the place behind the
;; #\Newline we're done
(return-from advance-fn pos))
(let ((try-pos pos))
;; otherwise try (again) to find an end string
;; candidate which starts behind the #\Newline
(loop
(unless (setq *end-string-pos*
(funcall end-string-test try-pos))
;; no end string candidate found, so we give up
(return-from scan nil))
;; NEW-POS is where we should start scanning
;; according to the end string candidate
(let ((new-pos (- (the fixnum *end-string-pos*)
end-string-offset)))
(declare (fixnum new-pos *end-string-pos*))
(cond ((= new-pos pos)
;; if POS and NEW-POS are equal then the
;; the end string candidate agrees with
;; the #\Newline so we're fine
(return-from advance-fn pos))
((> new-pos pos)
;; if NEW-POS is further to the right we
;; advance POS and try again, i.e. we go
;; back to the start of the outer LOOP
(setq pos new-pos)
;; this means "return from inner LOOP"
(return))
(t
;; otherwise NEW-POS is smaller than POS,
;; so we have to redo the inner LOOP to
;; find another end string candidate
;; further to the right
(setq try-pos (1+ *end-string-pos*))))))))))))
((and start-string-test end-string-test)
;; we know that the regular expression has constant start and
;; end strings; similar to the first case but we only need to
;; check for the end string, it doesn't provide enough
;; information to advance POS
(insert-advance-fn
(advance-fn (pos)
(declare (function start-string-test end-string-test))
(unless (setq pos (funcall start-string-test pos))
(return-from scan nil))
(if (<= (the fixnum pos)
(the fixnum *end-string-pos*))
(return-from advance-fn pos))
(unless (setq *end-string-pos* (funcall end-string-test pos))
(return-from scan nil))
pos)))
((and starts-with-everything end-string-test)
;; we know that the regular expression starts with ".*" (which
;; is not in single-line-mode, see CREATE-SCANNER-AUX) and ends
;; with a constant end string; similar to the second case but we
;; only need to check for the end string, it doesn't provide
;; enough information to advance POS
(insert-advance-fn
(advance-fn (pos)
(declare (function end-string-test))
(unless (setq pos (newline-skipper pos))
(return-from scan nil))
(if (<= (the fixnum pos)
(the fixnum *end-string-pos*))
(return-from advance-fn pos))
(unless (setq *end-string-pos* (funcall end-string-test pos))
(return-from scan nil))
pos)))
(start-string-test
;; just check for constant start string candidate
(insert-advance-fn
(advance-fn (pos)
(declare (function start-string-test))
(unless (setq pos (funcall start-string-test pos))
(return-from scan nil))
pos)))
(starts-with-everything
;; just advance POS with NEWLINE-SKIPPER
(insert-advance-fn
(advance-fn (pos)
(unless (setq pos (newline-skipper pos))
(return-from scan nil))
pos)))
(end-string-test
;; just check for the next end string candidate if POS has
;; advanced beyond the last one
(insert-advance-fn
(advance-fn (pos)
(declare (function end-string-test))
(if (<= (the fixnum pos)
(the fixnum *end-string-pos*))
(return-from advance-fn pos))
(unless (setq *end-string-pos* (funcall end-string-test pos))
(return-from scan nil))
pos)))
(t
;; not enough optimization information about the regular
;; expression to optimize so we just return POS
(insert-advance-fn
(advance-fn (pos)
pos))))))
| 26,137 | Common Lisp | .lisp | 492 | 35.386179 | 89 | 0.504038 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 3877041101f9158cbf5064403b54b18756adbdce9b168fb9616afdf906c78687 | 42,928 | [
297940,
298375
] |
42,929 | repetition-closures.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/repetition-closures.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/repetition-closures.lisp,v 1.34 2009/09/17 19:17:31 edi Exp $
;;; This is actually a part of closures.lisp which we put into a
;;; separate file because it is rather complex. We only deal with
;;; REPETITIONs here. Note that this part of the code contains some
;;; rather crazy micro-optimizations which were introduced to be as
;;; competitive with Perl as possible in tight loops.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defmacro incf-after (place &optional (delta 1) &environment env)
"Utility macro inspired by C's \"place++\", i.e. first return the
value of PLACE and afterwards increment it by DELTA."
(with-unique-names (%temp)
(multiple-value-bind (vars vals store-vars writer-form reader-form)
(get-setf-expansion place env)
`(let* (,@(mapcar #'list vars vals)
(,%temp ,reader-form)
(,(car store-vars) (+ ,%temp ,delta)))
,writer-form
,%temp))))
;; code for greedy repetitions with minimum zero
(defmacro greedy-constant-length-closure (check-curr-pos)
"This is the template for simple greedy repetitions (where simple
means that the minimum number of repetitions is zero, that the inner
regex to be checked is of fixed length LEN, and that it doesn't
contain registers, i.e. there's no need for backtracking).
CHECK-CURR-POS is a form which checks whether the inner regex of the
repetition matches at CURR-POS."
`(if maximum
(lambda (start-pos)
(declare (fixnum start-pos maximum))
;; because we know LEN we know in advance where to stop at the
;; latest; we also take into consideration MIN-REST, i.e. the
;; minimal length of the part behind the repetition
(let ((target-end-pos (min (1+ (- *end-pos* len min-rest))
;; don't go further than MAXIMUM
;; repetitions, of course
(+ start-pos
(the fixnum (* len maximum)))))
(curr-pos start-pos))
(declare (fixnum target-end-pos curr-pos))
(block greedy-constant-length-matcher
;; we use an ugly TAGBODY construct because this might be a
;; tight loop and this version is a bit faster than our LOOP
;; version (at least in CMUCL)
(tagbody
forward-loop
;; first go forward as far as possible, i.e. while
;; the inner regex matches
(when (>= curr-pos target-end-pos)
(go backward-loop))
(when ,check-curr-pos
(incf curr-pos len)
(go forward-loop))
backward-loop
;; now go back LEN steps each until we're able to match
;; the rest of the regex
(when (< curr-pos start-pos)
(return-from greedy-constant-length-matcher nil))
(let ((result (funcall next-fn curr-pos)))
(when result
(return-from greedy-constant-length-matcher result)))
(decf curr-pos len)
(go backward-loop)))))
;; basically the same code; it's just a bit easier because we're
;; not bounded by MAXIMUM
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((target-end-pos (1+ (- *end-pos* len min-rest)))
(curr-pos start-pos))
(declare (fixnum target-end-pos curr-pos))
(block greedy-constant-length-matcher
(tagbody
forward-loop
(when (>= curr-pos target-end-pos)
(go backward-loop))
(when ,check-curr-pos
(incf curr-pos len)
(go forward-loop))
backward-loop
(when (< curr-pos start-pos)
(return-from greedy-constant-length-matcher nil))
(let ((result (funcall next-fn curr-pos)))
(when result
(return-from greedy-constant-length-matcher result)))
(decf curr-pos len)
(go backward-loop)))))))
(defun create-greedy-everything-matcher (maximum min-rest next-fn)
"Creates a closure which just matches as far ahead as possible,
i.e. a closure for a dot in single-line mode."
(declare #.*standard-optimize-settings*)
(declare (fixnum min-rest) (function next-fn))
(if maximum
(lambda (start-pos)
(declare (fixnum start-pos maximum))
;; because we know LEN we know in advance where to stop at the
;; latest; we also take into consideration MIN-REST, i.e. the
;; minimal length of the part behind the repetition
(let ((target-end-pos (min (+ start-pos maximum)
(- *end-pos* min-rest))))
(declare (fixnum target-end-pos))
;; start from the highest possible position and go backward
;; until we're able to match the rest of the regex
(loop for curr-pos of-type fixnum from target-end-pos downto start-pos
thereis (funcall next-fn curr-pos))))
;; basically the same code; it's just a bit easier because we're
;; not bounded by MAXIMUM
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((target-end-pos (- *end-pos* min-rest)))
(declare (fixnum target-end-pos))
(loop for curr-pos of-type fixnum from target-end-pos downto start-pos
thereis (funcall next-fn curr-pos))))))
(defgeneric create-greedy-constant-length-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is greedy and the minimal number of
repetitions is zero. It is furthermore assumed that the inner regex
of REPETITION is of fixed length and doesn't contain registers."))
(defmethod create-greedy-constant-length-matcher ((repetition repetition)
next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len repetition))
(maximum (maximum repetition))
(regex (regex repetition))
(min-rest (min-rest repetition)))
(declare (fixnum len min-rest)
(function next-fn))
(cond ((zerop len)
;; inner regex has zero-length, so we can discard it
;; completely
next-fn)
(t
;; now first try to optimize for a couple of common cases
(typecase regex
(str
(let ((str (str regex)))
(if (= 1 len)
;; a single character
(let ((chr (schar str 0)))
(if (case-insensitive-p regex)
(greedy-constant-length-closure
(char-equal chr (schar *string* curr-pos)))
(greedy-constant-length-closure
(char= chr (schar *string* curr-pos)))))
;; a string
(if (case-insensitive-p regex)
(greedy-constant-length-closure
(*string*-equal str curr-pos (+ curr-pos len) 0 len))
(greedy-constant-length-closure
(*string*= str curr-pos (+ curr-pos len) 0 len))))))
(char-class
;; a character class
(insert-char-class-tester (regex (schar *string* curr-pos))
(greedy-constant-length-closure
(char-class-test))))
(everything
;; an EVERYTHING object, i.e. a dot
(if (single-line-p regex)
(create-greedy-everything-matcher maximum min-rest next-fn)
(greedy-constant-length-closure
(char/= #\Newline (schar *string* curr-pos)))))
(t
;; the general case - we build an inner matcher which
;; just checks for immediate success, i.e. NEXT-FN is
;; #'IDENTITY
(let ((inner-matcher (create-matcher-aux regex #'identity)))
(declare (function inner-matcher))
(greedy-constant-length-closure
(funcall inner-matcher curr-pos)))))))))
(defgeneric create-greedy-no-zero-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is greedy and the minimal number of
repetitions is zero. It is furthermore assumed that the inner regex
of REPETITION can never match a zero-length string \(or instead the
maximal number of repetitions is 1)."))
(defmethod create-greedy-no-zero-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((maximum (maximum repetition))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after GREEDY-AUX is defined
repeat-matcher)
(declare (function next-fn))
(cond
((eql maximum 1)
;; this is essentially like the next case but with a known
;; MAXIMUM of 1 we can get away without a counter; note that
;; we always arrive here if CONVERT optimizes <regex>* to
;; (?:<regex'>*<regex>)?
(setq repeat-matcher
(create-matcher-aux (regex repetition) next-fn))
(lambda (start-pos)
(declare (function repeat-matcher))
(or (funcall repeat-matcher start-pos)
(funcall next-fn start-pos))))
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((greedy-aux (start-pos)
(declare (fixnum start-pos maximum rep-num)
(function repeat-matcher))
;; the actual matcher which first tries to match the
;; inner regex of REPETITION (if we haven't done so
;; too often) and on failure calls NEXT-FN
(or (and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))))
(funcall next-fn start-pos))))
;; create a closure to match the inner regex and to
;; implement backtracking via GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
;; the closure we return is just a thin wrapper around
;; GREEDY-AUX to initialize the repetition counter
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0)
(greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((greedy-aux (start-pos)
(declare (fixnum start-pos)
(function repeat-matcher))
(or (funcall repeat-matcher start-pos)
(funcall next-fn start-pos))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
#'greedy-aux)))))
(defgeneric create-greedy-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is greedy and the minimal number of
repetitions is zero."))
(defmethod create-greedy-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((maximum (maximum repetition))
;; we make a reservation for our slot in *LAST-POS-STORES* because
;; we have to watch out for endless loops as the inner regex might
;; match zero-length strings
(zero-length-num (incf-after *zero-length-num*))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after GREEDY-AUX is defined
repeat-matcher)
(declare (fixnum zero-length-num)
(function next-fn))
(cond
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((greedy-aux (start-pos)
;; the actual matcher which first tries to match the
;; inner regex of REPETITION (if we haven't done so
;; too often) and on failure calls NEXT-FN
(declare (fixnum start-pos maximum rep-num)
(function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
;; stop immediately if we've been here before,
;; i.e. if the last attempt matched a zero-length
;; string
(return-from greedy-aux (funcall next-fn start-pos)))
;; otherwise remember this position for the next
;; repetition
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos)))
(funcall next-fn start-pos)))))
;; create a closure to match the inner regex and to
;; implement backtracking via GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
;; the closure we return is just a thin wrapper around
;; GREEDY-AUX to initialize the repetition counter and our
;; slot in *LAST-POS-STORES*
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0
(svref *last-pos-stores* zero-length-num) nil)
(greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((greedy-aux (start-pos)
(declare (fixnum start-pos)
(function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
(return-from greedy-aux (funcall next-fn start-pos)))
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (prog1
(funcall repeat-matcher start-pos)
(setf (svref *last-pos-stores* zero-length-num) old-last-pos))
(funcall next-fn start-pos)))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (svref *last-pos-stores* zero-length-num) nil)
(greedy-aux start-pos)))))))
;; code for non-greedy repetitions with minimum zero
(defmacro non-greedy-constant-length-closure (check-curr-pos)
"This is the template for simple non-greedy repetitions \(where
simple means that the minimum number of repetitions is zero, that the
inner regex to be checked is of fixed length LEN, and that it doesn't
contain registers, i.e. there's no need for backtracking).
CHECK-CURR-POS is a form which checks whether the inner regex of the
repetition matches at CURR-POS."
`(if maximum
(lambda (start-pos)
(declare (fixnum start-pos maximum))
;; because we know LEN we know in advance where to stop at the
;; latest; we also take into consideration MIN-REST, i.e. the
;; minimal length of the part behind the repetition
(let ((target-end-pos (min (1+ (- *end-pos* len min-rest))
(+ start-pos
(the fixnum (* len maximum))))))
;; move forward by LEN and always try NEXT-FN first, then
;; CHECK-CUR-POS
(loop for curr-pos of-type fixnum from start-pos
below target-end-pos
by len
thereis (funcall next-fn curr-pos)
while ,check-curr-pos
finally (return (funcall next-fn curr-pos)))))
;; basically the same code; it's just a bit easier because we're
;; not bounded by MAXIMUM
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((target-end-pos (1+ (- *end-pos* len min-rest))))
(loop for curr-pos of-type fixnum from start-pos
below target-end-pos
by len
thereis (funcall next-fn curr-pos)
while ,check-curr-pos
finally (return (funcall next-fn curr-pos)))))))
(defgeneric create-non-greedy-constant-length-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is non-greedy and the minimal number of
repetitions is zero. It is furthermore assumed that the inner regex
of REPETITION is of fixed length and doesn't contain registers."))
(defmethod create-non-greedy-constant-length-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len repetition))
(maximum (maximum repetition))
(regex (regex repetition))
(min-rest (min-rest repetition)))
(declare (fixnum len min-rest)
(function next-fn))
(cond ((zerop len)
;; inner regex has zero-length, so we can discard it
;; completely
next-fn)
(t
;; now first try to optimize for a couple of common cases
(typecase regex
(str
(let ((str (str regex)))
(if (= 1 len)
;; a single character
(let ((chr (schar str 0)))
(if (case-insensitive-p regex)
(non-greedy-constant-length-closure
(char-equal chr (schar *string* curr-pos)))
(non-greedy-constant-length-closure
(char= chr (schar *string* curr-pos)))))
;; a string
(if (case-insensitive-p regex)
(non-greedy-constant-length-closure
(*string*-equal str curr-pos (+ curr-pos len) 0 len))
(non-greedy-constant-length-closure
(*string*= str curr-pos (+ curr-pos len) 0 len))))))
(char-class
;; a character class
(insert-char-class-tester (regex (schar *string* curr-pos))
(non-greedy-constant-length-closure
(char-class-test))))
(everything
(if (single-line-p regex)
;; a dot which really can match everything; we rely
;; on the compiler to optimize this away
(non-greedy-constant-length-closure
t)
;; a dot which has to watch out for #\Newline
(non-greedy-constant-length-closure
(char/= #\Newline (schar *string* curr-pos)))))
(t
;; the general case - we build an inner matcher which
;; just checks for immediate success, i.e. NEXT-FN is
;; #'IDENTITY
(let ((inner-matcher (create-matcher-aux regex #'identity)))
(declare (function inner-matcher))
(non-greedy-constant-length-closure
(funcall inner-matcher curr-pos)))))))))
(defgeneric create-non-greedy-no-zero-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is non-greedy and the minimal number of
repetitions is zero. It is furthermore assumed that the inner regex
of REPETITION can never match a zero-length string \(or instead the
maximal number of repetitions is 1)."))
(defmethod create-non-greedy-no-zero-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((maximum (maximum repetition))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after NON-GREEDY-AUX is defined
repeat-matcher)
(declare (function next-fn))
(cond
((eql maximum 1)
;; this is essentially like the next case but with a known
;; MAXIMUM of 1 we can get away without a counter
(setq repeat-matcher
(create-matcher-aux (regex repetition) next-fn))
(lambda (start-pos)
(declare (function repeat-matcher))
(or (funcall next-fn start-pos)
(funcall repeat-matcher start-pos))))
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((non-greedy-aux (start-pos)
;; the actual matcher which first calls NEXT-FN and
;; on failure tries to match the inner regex of
;; REPETITION (if we haven't done so too often)
(declare (fixnum start-pos maximum rep-num)
(function repeat-matcher))
(or (funcall next-fn start-pos)
(and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; NON-GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num)))))))
;; create a closure to match the inner regex and to
;; implement backtracking via NON-GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
;; the closure we return is just a thin wrapper around
;; NON-GREEDY-AUX to initialize the repetition counter
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0)
(non-greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((non-greedy-aux (start-pos)
(declare (fixnum start-pos)
(function repeat-matcher))
(or (funcall next-fn start-pos)
(funcall repeat-matcher start-pos))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
#'non-greedy-aux)))))
(defgeneric create-non-greedy-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is non-greedy and the minimal number of
repetitions is zero."))
(defmethod create-non-greedy-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
;; we make a reservation for our slot in *LAST-POS-STORES* because
;; we have to watch out for endless loops as the inner regex might
;; match zero-length strings
(let ((zero-length-num (incf-after *zero-length-num*))
(maximum (maximum repetition))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after NON-GREEDY-AUX is defined
repeat-matcher)
(declare (fixnum zero-length-num)
(function next-fn))
(cond
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((non-greedy-aux (start-pos)
;; the actual matcher which first calls NEXT-FN and
;; on failure tries to match the inner regex of
;; REPETITION (if we haven't done so too often)
(declare (fixnum start-pos maximum rep-num)
(function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
;; stop immediately if we've been here before,
;; i.e. if the last attempt matched a zero-length
;; string
(return-from non-greedy-aux (funcall next-fn start-pos)))
;; otherwise remember this position for the next
;; repetition
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (funcall next-fn start-pos)
(and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; NON-GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos)))))))
;; create a closure to match the inner regex and to
;; implement backtracking via NON-GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
;; the closure we return is just a thin wrapper around
;; NON-GREEDY-AUX to initialize the repetition counter and our
;; slot in *LAST-POS-STORES*
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0
(svref *last-pos-stores* zero-length-num) nil)
(non-greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((non-greedy-aux (start-pos)
(declare (fixnum start-pos)
(function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
(return-from non-greedy-aux (funcall next-fn start-pos)))
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (funcall next-fn start-pos)
(prog1
(funcall repeat-matcher start-pos)
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos))))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (svref *last-pos-stores* zero-length-num) nil)
(non-greedy-aux start-pos)))))))
;; code for constant repetitions, i.e. those with a fixed number of repetitions
(defmacro constant-repetition-constant-length-closure (check-curr-pos)
"This is the template for simple constant repetitions (where simple
means that the inner regex to be checked is of fixed length LEN, and
that it doesn't contain registers, i.e. there's no need for
backtracking) and where constant means that MINIMUM is equal to
MAXIMUM. CHECK-CURR-POS is a form which checks whether the inner
regex of the repetition matches at CURR-POS."
`(lambda (start-pos)
(declare (fixnum start-pos))
(let ((target-end-pos (+ start-pos
(the fixnum (* len repetitions)))))
(declare (fixnum target-end-pos))
;; first check if we won't go beyond the end of the string
(and (>= *end-pos* target-end-pos)
;; then loop through all repetitions step by step
(loop for curr-pos of-type fixnum from start-pos
below target-end-pos
by len
always ,check-curr-pos)
;; finally call NEXT-FN if we made it that far
(funcall next-fn target-end-pos)))))
(defgeneric create-constant-repetition-constant-length-matcher
(repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION has a constant number of repetitions.
It is furthermore assumed that the inner regex of REPETITION is of
fixed length and doesn't contain registers."))
(defmethod create-constant-repetition-constant-length-matcher
((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len repetition))
(repetitions (minimum repetition))
(regex (regex repetition)))
(declare (fixnum len repetitions)
(function next-fn))
(if (zerop len)
;; if the length is zero it suffices to try once
(create-matcher-aux regex next-fn)
;; otherwise try to optimize for a couple of common cases
(typecase regex
(str
(let ((str (str regex)))
(if (= 1 len)
;; a single character
(let ((chr (schar str 0)))
(if (case-insensitive-p regex)
(constant-repetition-constant-length-closure
(and (char-equal chr (schar *string* curr-pos))
(1+ curr-pos)))
(constant-repetition-constant-length-closure
(and (char= chr (schar *string* curr-pos))
(1+ curr-pos)))))
;; a string
(if (case-insensitive-p regex)
(constant-repetition-constant-length-closure
(let ((next-pos (+ curr-pos len)))
(declare (fixnum next-pos))
(and (*string*-equal str curr-pos next-pos 0 len)
next-pos)))
(constant-repetition-constant-length-closure
(let ((next-pos (+ curr-pos len)))
(declare (fixnum next-pos))
(and (*string*= str curr-pos next-pos 0 len)
next-pos)))))))
(char-class
;; a character class
(insert-char-class-tester (regex (schar *string* curr-pos))
(constant-repetition-constant-length-closure
(and (char-class-test)
(1+ curr-pos)))))
(everything
(if (single-line-p regex)
;; a dot which really matches everything - we just have to
;; advance the index into *STRING* accordingly and check
;; if we didn't go past the end
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((next-pos (+ start-pos repetitions)))
(declare (fixnum next-pos))
(and (<= next-pos *end-pos*)
(funcall next-fn next-pos))))
;; a dot which is not in single-line-mode - make sure we
;; don't match #\Newline
(constant-repetition-constant-length-closure
(and (char/= #\Newline (schar *string* curr-pos))
(1+ curr-pos)))))
(t
;; the general case - we build an inner matcher which just
;; checks for immediate success, i.e. NEXT-FN is #'IDENTITY
(let ((inner-matcher (create-matcher-aux regex #'identity)))
(declare (function inner-matcher))
(constant-repetition-constant-length-closure
(funcall inner-matcher curr-pos))))))))
(defgeneric create-constant-repetition-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION has a constant number of repetitions."))
(defmethod create-constant-repetition-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((repetitions (minimum repetition))
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track of the number of repetitions
(rep-num (incf-after *rep-num*))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after NON-GREEDY-AUX is defined
repeat-matcher)
(declare (fixnum repetitions rep-num)
(function next-fn))
(if (zerop (min-len repetition))
;; we make a reservation for our slot in *LAST-POS-STORES*
;; because we have to watch out for needless loops as the inner
;; regex might match zero-length strings
(let ((zero-length-num (incf-after *zero-length-num*)))
(declare (fixnum zero-length-num))
(flet ((constant-aux (start-pos)
;; the actual matcher which first calls NEXT-FN and
;; on failure tries to match the inner regex of
;; REPETITION (if we haven't done so too often)
(declare (fixnum start-pos)
(function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
;; if we've been here before we matched a
;; zero-length string the last time, so we can
;; just carry on because we will definitely be
;; able to do this again often enough
(return-from constant-aux (funcall next-fn start-pos)))
;; otherwise remember this position for the next
;; repetition
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(cond ((< (aref *repeat-counters* rep-num) repetitions)
;; not enough repetitions yet, try it again
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; CONSTANT-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos)))
(t
;; we're done - call NEXT-FN
(funcall next-fn start-pos))))))
;; create a closure to match the inner regex and to
;; implement backtracking via CONSTANT-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'constant-aux))
;; the closure we return is just a thin wrapper around
;; CONSTANT-AUX to initialize the repetition counter
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0
(aref *last-pos-stores* zero-length-num) nil)
(constant-aux start-pos))))
;; easier code because we don't have to care about zero-length
;; matches but basically the same
(flet ((constant-aux (start-pos)
(declare (fixnum start-pos)
(function repeat-matcher))
(cond ((< (aref *repeat-counters* rep-num) repetitions)
(incf (aref *repeat-counters* rep-num))
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))))
(t (funcall next-fn start-pos)))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'constant-aux))
(lambda (start-pos)
(declare (fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0)
(constant-aux start-pos))))))
;; the actual CREATE-MATCHER-AUX method for REPETITION objects which
;; utilizes all the functions and macros defined above
(defmethod create-matcher-aux ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(with-slots (minimum maximum len min-len greedyp contains-register-p)
repetition
(cond ((and maximum
(zerop maximum))
;; this should have been optimized away by CONVERT but just
;; in case...
(error "Got REPETITION with MAXIMUM 0 \(should not happen)"))
((and maximum
(= minimum maximum 1))
;; this should have been optimized away by CONVERT but just
;; in case...
(error "Got REPETITION with MAXIMUM 1 and MINIMUM 1 \(should not happen)"))
((and (eql minimum maximum)
len
(not contains-register-p))
(create-constant-repetition-constant-length-matcher repetition next-fn))
((eql minimum maximum)
(create-constant-repetition-matcher repetition next-fn))
((and greedyp
len
(not contains-register-p))
(create-greedy-constant-length-matcher repetition next-fn))
((and greedyp
(or (plusp min-len)
(eql maximum 1)))
(create-greedy-no-zero-matcher repetition next-fn))
(greedyp
(create-greedy-matcher repetition next-fn))
((and len
(plusp len)
(not contains-register-p))
(create-non-greedy-constant-length-matcher repetition next-fn))
((or (plusp min-len)
(eql maximum 1))
(create-non-greedy-no-zero-matcher repetition next-fn))
(t
(create-non-greedy-matcher repetition next-fn)))))
| 41,320 | Common Lisp | .lisp | 800 | 38.08875 | 101 | 0.57229 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | ed28896287e99b70cef294a53353af1edfc0e8d8a5afd95d7dcf4d128a37ae1e | 42,929 | [
18225,
479998
] |
42,930 | convert.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/convert.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/convert.lisp,v 1.57 2009/09/17 19:17:31 edi Exp $
;;; Here the parse tree is converted into its internal representation
;;; using REGEX objects. At the same time some optimizations are
;;; already applied.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
;;; The flags that represent the "ism" modifiers are always kept
;;; together in a three-element list. We use the following macros to
;;; access individual elements.
(defmacro case-insensitive-mode-p (flags)
"Accessor macro to extract the first flag out of a three-element flag list."
`(first ,flags))
(defmacro multi-line-mode-p (flags)
"Accessor macro to extract the second flag out of a three-element flag list."
`(second ,flags))
(defmacro single-line-mode-p (flags)
"Accessor macro to extract the third flag out of a three-element flag list."
`(third ,flags))
(defun set-flag (token)
"Reads a flag token and sets or unsets the corresponding entry in
the special FLAGS list."
(declare #.*standard-optimize-settings*)
(declare (special flags))
(case token
((:case-insensitive-p)
(setf (case-insensitive-mode-p flags) t))
((:case-sensitive-p)
(setf (case-insensitive-mode-p flags) nil))
((:multi-line-mode-p)
(setf (multi-line-mode-p flags) t))
((:not-multi-line-mode-p)
(setf (multi-line-mode-p flags) nil))
((:single-line-mode-p)
(setf (single-line-mode-p flags) t))
((:not-single-line-mode-p)
(setf (single-line-mode-p flags) nil))
(otherwise
(signal-syntax-error "Unknown flag token ~A." token))))
(defgeneric resolve-property (property)
(:documentation "Resolves PROPERTY to a unary character test
function. PROPERTY can either be a function designator or it can be a
string which is resolved using *PROPERTY-RESOLVER*.")
(:method ((property-name string))
(funcall *property-resolver* property-name))
(:method ((function-name symbol))
function-name)
(:method ((test-function function))
test-function))
(defun convert-char-class-to-test-function (list invertedp case-insensitive-p)
"Combines all items in LIST into test function and returns a
logical-OR combination of these functions. Items can be single
characters, character ranges like \(:RANGE #\\A #\\E), or special
character classes like :DIGIT-CLASS. Does the right thing with
respect to case-\(in)sensitivity as specified by the special variable
FLAGS."
(declare #.*standard-optimize-settings*)
(declare (special flags))
(let ((test-functions
(loop for item in list
collect (cond ((characterp item)
;; rebind so closure captures the right one
(let ((this-char item))
(lambda (char)
(declare (character char this-char))
(char= char this-char))))
((symbolp item)
(case item
((:digit-class) #'digit-char-p)
((:non-digit-class) (complement* #'digit-char-p))
((:whitespace-char-class) #'whitespacep)
((:non-whitespace-char-class) (complement* #'whitespacep))
((:word-char-class) #'word-char-p)
((:non-word-char-class) (complement* #'word-char-p))
(otherwise
(signal-syntax-error "Unknown symbol ~A in character class." item))))
((and (consp item)
(eq (first item) :property))
(resolve-property (second item)))
((and (consp item)
(eq (first item) :inverted-property))
(complement* (resolve-property (second item))))
((and (consp item)
(eq (first item) :range))
(let ((from (second item))
(to (third item)))
(when (char> from to)
(signal-syntax-error "Invalid range from ~S to ~S in char-class." from to))
(lambda (char)
(declare (character char from to))
(char<= from char to))))
(t (signal-syntax-error "Unknown item ~A in char-class list." item))))))
(unless test-functions
(signal-syntax-error "Empty character class."))
(cond ((cdr test-functions)
(cond ((and invertedp case-insensitive-p)
(lambda (char)
(declare (character char))
(loop with both-case-p = (both-case-p char)
with char-down = (if both-case-p (char-downcase char) char)
with char-up = (if both-case-p (char-upcase char) nil)
for test-function in test-functions
never (or (funcall test-function char-down)
(and char-up (funcall test-function char-up))))))
(case-insensitive-p
(lambda (char)
(declare (character char))
(loop with both-case-p = (both-case-p char)
with char-down = (if both-case-p (char-downcase char) char)
with char-up = (if both-case-p (char-upcase char) nil)
for test-function in test-functions
thereis (or (funcall test-function char-down)
(and char-up (funcall test-function char-up))))))
(invertedp
(lambda (char)
(loop for test-function in test-functions
never (funcall test-function char))))
(t
(lambda (char)
(loop for test-function in test-functions
thereis (funcall test-function char))))))
;; there's only one test-function
(t (let ((test-function (first test-functions)))
(cond ((and invertedp case-insensitive-p)
(lambda (char)
(declare (character char))
(not (or (funcall test-function (char-downcase char))
(and (both-case-p char)
(funcall test-function (char-upcase char)))))))
(case-insensitive-p
(lambda (char)
(declare (character char))
(or (funcall test-function (char-downcase char))
(and (both-case-p char)
(funcall test-function (char-upcase char))))))
(invertedp (complement* test-function))
(t test-function)))))))
(defun maybe-split-repetition (regex
greedyp
minimum
maximum
min-len
length
reg-seen)
"Splits a REPETITION object into a constant and a varying part if
applicable, i.e. something like
a{3,} -> a{3}a*
The arguments to this function correspond to the REPETITION slots of
the same name."
(declare #.*standard-optimize-settings*)
(declare (fixnum minimum)
(type (or fixnum null) maximum))
;; note the usage of COPY-REGEX here; we can't use the same REGEX
;; object in both REPETITIONS because they will have different
;; offsets
(when maximum
(when (zerop maximum)
;; trivial case: don't repeat at all
(return-from maybe-split-repetition
(make-instance 'void)))
(when (= 1 minimum maximum)
;; another trivial case: "repeat" exactly once
(return-from maybe-split-repetition
regex)))
;; first set up the constant part of the repetition
;; maybe that's all we need
(let ((constant-repetition (if (plusp minimum)
(make-instance 'repetition
:regex (copy-regex regex)
:greedyp greedyp
:minimum minimum
:maximum minimum
:min-len min-len
:len length
:contains-register-p reg-seen)
;; don't create garbage if minimum is 0
nil)))
(when (and maximum
(= maximum minimum))
(return-from maybe-split-repetition
;; no varying part needed because min = max
constant-repetition))
;; now construct the varying part
(let ((varying-repetition
(make-instance 'repetition
:regex regex
:greedyp greedyp
:minimum 0
:maximum (if maximum (- maximum minimum) nil)
:min-len min-len
:len length
:contains-register-p reg-seen)))
(cond ((zerop minimum)
;; min = 0, no constant part needed
varying-repetition)
((= 1 minimum)
;; min = 1, constant part needs no REPETITION wrapped around
(make-instance 'seq
:elements (list (copy-regex regex)
varying-repetition)))
(t
;; general case
(make-instance 'seq
:elements (list constant-repetition
varying-repetition)))))))
;; During the conversion of the parse tree we keep track of the start
;; of the parse tree in the special variable STARTS-WITH which'll
;; either hold a STR object or an EVERYTHING object. The latter is the
;; case if the regex starts with ".*" which implicitly anchors the
;; regex at the start (perhaps modulo #\Newline).
(defun maybe-accumulate (str)
"Accumulate STR into the special variable STARTS-WITH if
ACCUMULATE-START-P (also special) is true and STARTS-WITH is either
NIL or a STR object of the same case mode. Always returns NIL."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
(declare (ftype (function (t) fixnum) len))
(when accumulate-start-p
(etypecase starts-with
(str
;; STARTS-WITH already holds a STR, so we check if we can
;; concatenate
(cond ((eq (case-insensitive-p starts-with)
(case-insensitive-p str))
;; we modify STARTS-WITH in place
(setf (len starts-with)
(+ (len starts-with) (len str)))
;; note that we use SLOT-VALUE because the accessor
;; STR has a declared FTYPE which doesn't fit here
(adjust-array (slot-value starts-with 'str)
(len starts-with)
:fill-pointer t)
(setf (subseq (slot-value starts-with 'str)
(- (len starts-with) (len str)))
(str str)
;; STR objects that are parts of STARTS-WITH
;; always have their SKIP slot set to true
;; because the SCAN function will take care of
;; them, i.e. the matcher can ignore them
(skip str) t))
(t (setq accumulate-start-p nil))))
(null
;; STARTS-WITH is still empty, so we create a new STR object
(setf starts-with
(make-instance 'str
:str ""
:case-insensitive-p (case-insensitive-p str))
;; INITIALIZE-INSTANCE will coerce the STR to a simple
;; string, so we have to fill it afterwards
(slot-value starts-with 'str)
(make-array (len str)
:initial-contents (str str)
:element-type 'character
:fill-pointer t
:adjustable t)
(len starts-with)
(len str)
;; see remark about SKIP above
(skip str) t))
(everything
;; STARTS-WITH already holds an EVERYTHING object - we can't
;; concatenate
(setq accumulate-start-p nil))))
nil)
(declaim (inline convert-aux))
(defun convert-aux (parse-tree)
"Converts the parse tree PARSE-TREE into a REGEX object and returns
it. Will also
- split and optimize repetitions,
- accumulate strings or EVERYTHING objects into the special variable
STARTS-WITH,
- keep track of all registers seen in the special variable REG-NUM,
- keep track of all named registers seen in the special variable REG-NAMES
- keep track of the highest backreference seen in the special
variable MAX-BACK-REF,
- maintain and adher to the currently applicable modifiers in the special
variable FLAGS, and
- maybe even wash your car..."
(declare #.*standard-optimize-settings*)
(if (consp parse-tree)
(convert-compound-parse-tree (first parse-tree) parse-tree)
(convert-simple-parse-tree parse-tree)))
(defgeneric convert-compound-parse-tree (token parse-tree &key)
(declare #.*standard-optimize-settings*)
(:documentation "Helper function for CONVERT-AUX which converts
parse trees which are conses and dispatches on TOKEN which is the
first element of the parse tree.")
(:method ((token t) (parse-tree t) &key)
(signal-syntax-error "Unknown token ~A in parse-tree." token)))
(defmethod convert-compound-parse-tree ((token (eql :sequence)) parse-tree &key)
"The case for parse trees like \(:SEQUENCE {<regex>}*)."
(declare #.*standard-optimize-settings*)
(cond ((cddr parse-tree)
;; this is essentially like
;; (MAPCAR 'CONVERT-AUX (REST PARSE-TREE))
;; but we don't cons a new list
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq :elements (rest parse-tree)))
(t (convert-aux (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :group)) parse-tree &key)
"The case for parse trees like \(:GROUP {<regex>}*).
This is a syntactical construct equivalent to :SEQUENCE intended to
keep the effect of modifiers local."
(declare #.*standard-optimize-settings*)
(declare (special flags))
;; make a local copy of FLAGS and shadow the global value while we
;; descend into the enclosed regexes
(let ((flags (copy-list flags)))
(declare (special flags))
(cond ((cddr parse-tree)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq :elements (rest parse-tree)))
(t (convert-aux (second parse-tree))))))
(defmethod convert-compound-parse-tree ((token (eql :alternation)) parse-tree &key)
"The case for \(:ALTERNATION {<regex>}*)."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
;; we must stop accumulating objects into STARTS-WITH once we reach
;; an alternation
(setq accumulate-start-p nil)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'alternation :choices (rest parse-tree)))
(defmethod convert-compound-parse-tree ((token (eql :branch)) parse-tree &key)
"The case for \(:BRANCH <test> <regex>).
Here, <test> must be look-ahead, look-behind or number; if <regex> is
an alternation it must have one or two choices."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(let* ((test-candidate (second parse-tree))
(test (cond ((numberp test-candidate)
(when (zerop (the fixnum test-candidate))
(signal-syntax-error "Register 0 doesn't exist: ~S." parse-tree))
(1- (the fixnum test-candidate)))
(t (convert-aux test-candidate))))
(alternations (convert-aux (third parse-tree))))
(when (and (not (numberp test))
(not (typep test 'lookahead))
(not (typep test 'lookbehind)))
(signal-syntax-error "Branch test must be look-ahead, look-behind or number: ~S." parse-tree))
(typecase alternations
(alternation
(case (length (choices alternations))
((0)
(signal-syntax-error "No choices in branch: ~S." parse-tree))
((1)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))))
((2)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))
:else-regex (second
(choices alternations))))
(otherwise
(signal-syntax-error "Too much choices in branch: ~S." parse-tree))))
(t
(make-instance 'branch
:test test
:then-regex alternations)))))
(defmethod convert-compound-parse-tree ((token (eql :positive-lookahead)) parse-tree &key)
"The case for \(:POSITIVE-LOOKAHEAD <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
;; keep the effect of modifiers local to the enclosed regex and stop
;; accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'lookahead
:regex (convert-aux (second parse-tree))
:positivep t)))
(defmethod convert-compound-parse-tree ((token (eql :negative-lookahead)) parse-tree &key)
"The case for \(:NEGATIVE-LOOKAHEAD <regex>)."
(declare #.*standard-optimize-settings*)
;; do the same as for positive look-aheads and just switch afterwards
(let ((regex (convert-compound-parse-tree :positive-lookahead parse-tree)))
(setf (slot-value regex 'positivep) nil)
regex))
(defmethod convert-compound-parse-tree ((token (eql :positive-lookbehind)) parse-tree &key)
"The case for \(:POSITIVE-LOOKBEHIND <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
;; keep the effect of modifiers local to the enclosed regex and stop
;; accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let* ((flags (copy-list flags))
(regex (convert-aux (second parse-tree)))
(len (regex-length regex)))
(declare (special flags))
;; lookbehind assertions must be of fixed length
(unless len
(signal-syntax-error "Variable length look-behind not implemented \(yet): ~S." parse-tree))
(make-instance 'lookbehind
:regex regex
:positivep t
:len len)))
(defmethod convert-compound-parse-tree ((token (eql :negative-lookbehind)) parse-tree &key)
"The case for \(:NEGATIVE-LOOKBEHIND <regex>)."
(declare #.*standard-optimize-settings*)
;; do the same as for positive look-behinds and just switch afterwards
(let ((regex (convert-compound-parse-tree :positive-lookbehind parse-tree)))
(setf (slot-value regex 'positivep) nil)
regex))
(defmethod convert-compound-parse-tree ((token (eql :greedy-repetition)) parse-tree &key (greedyp t))
"The case for \(:GREEDY-REPETITION|:NON-GREEDY-REPETITION <min> <max> <regex>).
This function is also used for the non-greedy case in which case it is
called with GREEDYP set to NIL as you would expect."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
;; remember the value of ACCUMULATE-START-P upon entering
(let ((local-accumulate-start-p accumulate-start-p))
(let ((minimum (second parse-tree))
(maximum (third parse-tree)))
(declare (fixnum minimum))
(declare (type (or null fixnum) maximum))
(unless (and maximum
(= 1 minimum maximum))
;; set ACCUMULATE-START-P to NIL for the rest of
;; the conversion because we can't continue to
;; accumulate inside as well as after a proper
;; repetition
(setq accumulate-start-p nil))
(let* (reg-seen
(regex (convert-aux (fourth parse-tree)))
(min-len (regex-min-length regex))
(length (regex-length regex)))
;; note that this declaration already applies to
;; the call to CONVERT-AUX above
(declare (special reg-seen))
(when (and local-accumulate-start-p
(not starts-with)
(zerop minimum)
(not maximum))
;; if this repetition is (equivalent to) ".*"
;; and if we're at the start of the regex we
;; remember it for ADVANCE-FN (see the SCAN
;; function)
(setq starts-with (everythingp regex)))
(if (or (not reg-seen)
(not greedyp)
(not length)
(zerop length)
(and maximum (= minimum maximum)))
;; the repetition doesn't enclose a register, or
;; it's not greedy, or we can't determine it's
;; (inner) length, or the length is zero, or the
;; number of repetitions is fixed; in all of
;; these cases we don't bother to optimize
(maybe-split-repetition regex
greedyp
minimum
maximum
min-len
length
reg-seen)
;; otherwise we make a transformation that looks
;; roughly like one of
;; <regex>* -> (?:<regex'>*<regex>)?
;; <regex>+ -> <regex'>*<regex>
;; where the trick is that as much as possible
;; registers from <regex> are removed in
;; <regex'>
(let* (reg-seen ; new instance for REMOVE-REGISTERS
(remove-registers-p t)
(inner-regex (remove-registers regex))
(inner-repetition
;; this is the "<regex'>" part
(maybe-split-repetition inner-regex
;; always greedy
t
;; reduce minimum by 1
;; unless it's already 0
(if (zerop minimum)
0
(1- minimum))
;; reduce maximum by 1
;; unless it's NIL
(and maximum
(1- maximum))
min-len
length
reg-seen))
(inner-seq
;; this is the "<regex'>*<regex>" part
(make-instance 'seq
:elements (list inner-repetition
regex))))
;; note that this declaration already applies
;; to the call to REMOVE-REGISTERS above
(declare (special remove-registers-p reg-seen))
;; wrap INNER-SEQ with a greedy
;; {0,1}-repetition (i.e. "?") if necessary
(if (plusp minimum)
inner-seq
(maybe-split-repetition inner-seq
t
0
1
min-len
nil
t))))))))
(defmethod convert-compound-parse-tree ((token (eql :non-greedy-repetition)) parse-tree &key)
"The case for \(:NON-GREEDY-REPETITION <min> <max> <regex>)."
(declare #.*standard-optimize-settings*)
;; just dispatch to the method above with GREEDYP explicitly set to NIL
(convert-compound-parse-tree :greedy-repetition parse-tree :greedyp nil))
(defmethod convert-compound-parse-tree ((token (eql :register)) parse-tree &key name)
"The case for \(:REGISTER <regex>). Also used for named registers
when NAME is not NIL."
(declare #.*standard-optimize-settings*)
(declare (special flags reg-num reg-names))
;; keep the effect of modifiers local to the enclosed regex; also,
;; assign the current value of REG-NUM to the corresponding slot of
;; the REGISTER object and increase this counter afterwards; for
;; named register update REG-NAMES and set the corresponding name
;; slot of the REGISTER object too
(let ((flags (copy-list flags))
(stored-reg-num reg-num))
(declare (special flags reg-seen named-reg-seen))
(setq reg-seen t)
(when name (setq named-reg-seen t))
(incf (the fixnum reg-num))
(push name reg-names)
(make-instance 'register
:regex (convert-aux (if name (third parse-tree) (second parse-tree)))
:num stored-reg-num
:name name)))
(defmethod convert-compound-parse-tree ((token (eql :named-register)) parse-tree &key)
"The case for \(:NAMED-REGISTER <regex>)."
(declare #.*standard-optimize-settings*)
;; call the method above and use the :NAME keyword argument
(convert-compound-parse-tree :register parse-tree :name (copy-seq (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :filter)) parse-tree &key)
"The case for \(:FILTER <function> &optional <length>)."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'filter
:fn (second parse-tree)
:len (third parse-tree)))
(defmethod convert-compound-parse-tree ((token (eql :standalone)) parse-tree &key)
"The case for \(:STANDALONE <regex>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
;; keep the effect of modifiers local to the enclosed regex
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'standalone :regex (convert-aux (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :back-reference)) parse-tree &key)
"The case for \(:BACK-REFERENCE <number>|<name>)."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p reg-num reg-names max-back-ref))
(let* ((backref-name (and (stringp (second parse-tree))
(second parse-tree)))
(referred-regs
(when backref-name
;; find which register corresponds to the given name
;; we have to deal with case where several registers share
;; the same name and collect their respective numbers
(loop for name in reg-names
for reg-index from 0
when (string= name backref-name)
;; NOTE: REG-NAMES stores register names in reversed
;; order REG-NUM contains number of (any) registers
;; seen so far; 1- will be done later
collect (- reg-num reg-index))))
;; store the register number for the simple case
(backref-number (or (first referred-regs) (second parse-tree))))
(declare (type (or fixnum null) backref-number))
(when (or (not (typep backref-number 'fixnum))
(<= backref-number 0))
(signal-syntax-error "Illegal back-reference: ~S." parse-tree))
;; stop accumulating into STARTS-WITH and increase MAX-BACK-REF if
;; necessary
(setq accumulate-start-p nil
max-back-ref (max (the fixnum max-back-ref)
backref-number))
(flet ((make-back-ref (backref-number)
(make-instance 'back-reference
;; we start counting from 0 internally
:num (1- backref-number)
:case-insensitive-p (case-insensitive-mode-p flags)
;; backref-name is NIL or string, safe to copy
:name (copy-seq backref-name))))
(cond
((cdr referred-regs)
;; several registers share the same name we will try to match
;; any of them, starting with the most recent first
;; alternation is used to accomplish matching
(make-instance 'alternation
:choices (loop
for reg-index in referred-regs
collect (make-back-ref reg-index))))
;; simple case - backref corresponds to only one register
(t
(make-back-ref backref-number))))))
(defmethod convert-compound-parse-tree ((token (eql :regex)) parse-tree &key)
"The case for \(:REGEX <string>)."
(declare #.*standard-optimize-settings*)
(convert-aux (parse-string (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :char-class)) parse-tree &key invertedp)
"The case for \(:CHAR-CLASS {<item>}*) where item is one of
- a character,
- a character range: \(:RANGE <char1> <char2>), or
- a special char class symbol like :DIGIT-CHAR-CLASS.
Also used for inverted char classes when INVERTEDP is true."
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(let ((test-function
(create-optimized-test-function
(convert-char-class-to-test-function (rest parse-tree)
invertedp
(case-insensitive-mode-p flags)))))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function test-function)))
(defmethod convert-compound-parse-tree ((token (eql :inverted-char-class)) parse-tree &key)
"The case for \(:INVERTED-CHAR-CLASS {<item>}*)."
(declare #.*standard-optimize-settings*)
;; just dispatch to the "real" method
(convert-compound-parse-tree :char-class parse-tree :invertedp t))
(defmethod convert-compound-parse-tree ((token (eql :property)) parse-tree &key)
"The case for \(:PROPERTY <name>) where <name> is a string."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (resolve-property (second parse-tree))))
(defmethod convert-compound-parse-tree ((token (eql :inverted-property)) parse-tree &key)
"The case for \(:INVERTED-PROPERTY <name>) where <name> is a string."
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* (resolve-property (second parse-tree)))))
(defmethod convert-compound-parse-tree ((token (eql :flags)) parse-tree &key)
"The case for \(:FLAGS {<flag>}*) where flag is a modifier symbol
like :CASE-INSENSITIVE-P."
(declare #.*standard-optimize-settings*)
;; set/unset the flags corresponding to the symbols
;; following :FLAGS
(mapc #'set-flag (rest parse-tree))
;; we're only interested in the side effect of
;; setting/unsetting the flags and turn this syntactical
;; construct into a VOID object which'll be optimized
;; away when creating the matcher
(make-instance 'void))
(defgeneric convert-simple-parse-tree (parse-tree)
(declare #.*standard-optimize-settings*)
(:documentation "Helper function for CONVERT-AUX which converts
parse trees which are atoms.")
(:method ((parse-tree (eql :void)))
(declare #.*standard-optimize-settings*)
(make-instance 'void))
(:method ((parse-tree (eql :word-boundary)))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary :negatedp nil))
(:method ((parse-tree (eql :non-word-boundary)))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary :negatedp t))
(:method ((parse-tree (eql :everything)))
(declare #.*standard-optimize-settings*)
(declare (special flags accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'everything :single-line-p (single-line-mode-p flags)))
(:method ((parse-tree (eql :digit-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'digit-char-p))
(:method ((parse-tree (eql :word-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'word-char-p))
(:method ((parse-tree (eql :whitespace-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function #'whitespacep))
(:method ((parse-tree (eql :non-digit-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'digit-char-p)))
(:method ((parse-tree (eql :non-word-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'word-char-p)))
(:method ((parse-tree (eql :non-whitespace-char-class)))
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p))
(setq accumulate-start-p nil)
(make-instance 'char-class :test-function (complement* #'whitespacep)))
(:method ((parse-tree (eql :start-anchor)))
;; Perl's "^"
(declare #.*standard-optimize-settings*)
(declare (special flags))
(make-instance 'anchor :startp t :multi-line-p (multi-line-mode-p flags)))
(:method ((parse-tree (eql :end-anchor)))
;; Perl's "$"
(declare #.*standard-optimize-settings*)
(declare (special flags))
(make-instance 'anchor :startp nil :multi-line-p (multi-line-mode-p flags)))
(:method ((parse-tree (eql :modeless-start-anchor)))
;; Perl's "\A"
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp t))
(:method ((parse-tree (eql :modeless-end-anchor)))
;; Perl's "$\Z"
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp nil))
(:method ((parse-tree (eql :modeless-end-anchor-no-newline)))
;; Perl's "$\z"
(declare #.*standard-optimize-settings*)
(make-instance 'anchor :startp nil :no-newline-p t))
(:method ((parse-tree (eql :case-insensitive-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :case-sensitive-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :multi-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :not-multi-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :single-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void))
(:method ((parse-tree (eql :not-single-line-mode-p)))
(declare #.*standard-optimize-settings*)
(set-flag parse-tree)
(make-instance 'void)))
(defmethod convert-simple-parse-tree ((parse-tree string))
(declare #.*standard-optimize-settings*)
(declare (special flags))
;; turn strings into STR objects and try to accumulate into
;; STARTS-WITH
(let ((str (make-instance 'str
:str parse-tree
:case-insensitive-p (case-insensitive-mode-p flags))))
(maybe-accumulate str)
str))
(defmethod convert-simple-parse-tree ((parse-tree character))
(declare #.*standard-optimize-settings*)
;; dispatch to the method for strings
(convert-simple-parse-tree (string parse-tree)))
(defmethod convert-simple-parse-tree (parse-tree)
"The default method - check if there's a translation."
(declare #.*standard-optimize-settings*)
(let ((translation (and (symbolp parse-tree) (parse-tree-synonym parse-tree))))
(if translation
(convert-aux (copy-tree translation))
(signal-syntax-error "Unknown token ~A in parse tree." parse-tree))))
(defun convert (parse-tree)
"Converts the parse tree PARSE-TREE into an equivalent REGEX object
and returns three values: the REGEX object, the number of registers
seen and an object the regex starts with which is either a STR object
or an EVERYTHING object \(if the regex starts with something like
\".*\") or NIL."
(declare #.*standard-optimize-settings*)
;; this function basically just initializes the special variables
;; and then calls CONVERT-AUX to do all the work
(let* ((flags (list nil nil nil))
(reg-num 0)
reg-names
named-reg-seen
(accumulate-start-p t)
starts-with
(max-back-ref 0)
(converted-parse-tree (convert-aux parse-tree)))
(declare (special flags reg-num reg-names named-reg-seen
accumulate-start-p starts-with max-back-ref))
;; make sure we don't reference registers which aren't there
(when (> (the fixnum max-back-ref)
(the fixnum reg-num))
(signal-syntax-error "Backreference to register ~A which has not been defined." max-back-ref))
(when (typep starts-with 'str)
(setf (slot-value starts-with 'str)
(coerce (slot-value starts-with 'str)
#+:lispworks 'lw:simple-text-string
#-:lispworks 'simple-string)))
(values converted-parse-tree reg-num starts-with
;; we can't simply use *ALLOW-NAMED-REGISTERS*
;; since parse-tree syntax ignores it
(when named-reg-seen
(nreverse reg-names)))))
| 40,807 | Common Lisp | .lisp | 828 | 37.822464 | 109 | 0.593086 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 4851f4b0ac91896e775d289d3648740d8cedec5c3266eaaca7330460e4f4baa9 | 42,930 | [
278192,
357365
] |
42,931 | parser.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/parser.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/parser.lisp,v 1.31 2009/09/17 19:17:31 edi Exp $
;;; The parser will - with the help of the lexer - parse a regex
;;; string and convert it into a "parse tree" (see docs for details
;;; about the syntax of these trees). Note that the lexer might
;;; return illegal parse trees. It is assumed that the conversion
;;; process later on will track them down.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defun group (lexer)
"Parses and consumes a <group>.
The productions are: <group> -> \"\(\"<regex>\")\"
\"\(?:\"<regex>\")\"
\"\(?>\"<regex>\")\"
\"\(?<flags>:\"<regex>\")\"
\"\(?=\"<regex>\")\"
\"\(?!\"<regex>\")\"
\"\(?<=\"<regex>\")\"
\"\(?<!\"<regex>\")\"
\"\(?\(\"<num>\")\"<regex>\")\"
\"\(?\(\"<regex>\")\"<regex>\")\"
\"\(?<name>\"<regex>\")\" \(when *ALLOW-NAMED-REGISTERS* is T)
<legal-token>
where <flags> is parsed by the lexer function MAYBE-PARSE-FLAGS.
Will return <parse-tree> or \(<grouping-type> <parse-tree>) where
<grouping-type> is one of six keywords - see source for details."
(declare #.*standard-optimize-settings*)
(multiple-value-bind (open-token flags)
(get-token lexer)
(cond ((eq open-token :open-paren-paren)
;; special case for conditional regular expressions; note
;; that at this point we accept a couple of illegal
;; combinations which'll be sorted out later by the
;; converter
(let* ((open-paren-pos (car (lexer-last-pos lexer)))
;; check if what follows "(?(" is a number
(number (try-number lexer :no-whitespace-p t))
;; make changes to extended-mode-p local
(*extended-mode-p* *extended-mode-p*))
(declare (fixnum open-paren-pos))
(cond (number
;; condition is a number (i.e. refers to a
;; back-reference)
(let* ((inner-close-token (get-token lexer))
(reg-expr (reg-expr lexer))
(close-token (get-token lexer)))
(unless (eq inner-close-token :close-paren)
(signal-syntax-error* (+ open-paren-pos 2)
"Opening paren has no matching closing paren."))
(unless (eq close-token :close-paren)
(signal-syntax-error* open-paren-pos
"Opening paren has no matching closing paren."))
(list :branch number reg-expr)))
(t
;; condition must be a full regex (actually a
;; look-behind or look-ahead); and here comes a
;; terrible kludge: instead of being cleanly
;; separated from the lexer, the parser pushes
;; back the lexer by one position, thereby
;; landing in the middle of the 'token' "(?(" -
;; yuck!!
(decf (lexer-pos lexer))
(let* ((inner-reg-expr (group lexer))
(reg-expr (reg-expr lexer))
(close-token (get-token lexer)))
(unless (eq close-token :close-paren)
(signal-syntax-error* open-paren-pos
"Opening paren has no matching closing paren."))
(list :branch inner-reg-expr reg-expr))))))
((member open-token '(:open-paren
:open-paren-colon
:open-paren-greater
:open-paren-equal
:open-paren-exclamation
:open-paren-less-equal
:open-paren-less-exclamation
:open-paren-less-letter)
:test #'eq)
;; make changes to extended-mode-p local
(let ((*extended-mode-p* *extended-mode-p*))
;; we saw one of the six token representing opening
;; parentheses
(let* ((open-paren-pos (car (lexer-last-pos lexer)))
(register-name (when (eq open-token :open-paren-less-letter)
(parse-register-name-aux lexer)))
(reg-expr (reg-expr lexer))
(close-token (get-token lexer)))
(when (or (eq open-token :open-paren)
(eq open-token :open-paren-less-letter))
;; if this is the "("<regex>")" or "(?"<name>""<regex>")" production we have to
;; increment the register counter of the lexer
(incf (lexer-reg lexer)))
(unless (eq close-token :close-paren)
;; the token following <regex> must be the closing
;; parenthesis or this is a syntax error
(signal-syntax-error* open-paren-pos
"Opening paren has no matching closing paren."))
(if flags
;; if the lexer has returned a list of flags this must
;; have been the "(?:"<regex>")" production
(cons :group (nconc flags (list reg-expr)))
(if (eq open-token :open-paren-less-letter)
(list :named-register register-name
reg-expr)
(list (case open-token
((:open-paren)
:register)
((:open-paren-colon)
:group)
((:open-paren-greater)
:standalone)
((:open-paren-equal)
:positive-lookahead)
((:open-paren-exclamation)
:negative-lookahead)
((:open-paren-less-equal)
:positive-lookbehind)
((:open-paren-less-exclamation)
:negative-lookbehind))
reg-expr))))))
(t
;; this is the <legal-token> production; <legal-token> is
;; any token which passes START-OF-SUBEXPR-P (otherwise
;; parsing had already stopped in the SEQ method)
open-token))))
(defun greedy-quant (lexer)
"Parses and consumes a <greedy-quant>.
The productions are: <greedy-quant> -> <group> | <group><quantifier>
where <quantifier> is parsed by the lexer function GET-QUANTIFIER.
Will return <parse-tree> or (:GREEDY-REPETITION <min> <max> <parse-tree>)."
(declare #.*standard-optimize-settings*)
(let* ((group (group lexer))
(token (get-quantifier lexer)))
(if token
;; if GET-QUANTIFIER returned a non-NIL value it's the
;; two-element list (<min> <max>)
(list :greedy-repetition (first token) (second token) group)
group)))
(defun quant (lexer)
"Parses and consumes a <quant>.
The productions are: <quant> -> <greedy-quant> | <greedy-quant>\"?\".
Will return the <parse-tree> returned by GREEDY-QUANT and optionally
change :GREEDY-REPETITION to :NON-GREEDY-REPETITION."
(declare #.*standard-optimize-settings*)
(let* ((greedy-quant (greedy-quant lexer))
(pos (lexer-pos lexer))
(next-char (next-char lexer)))
(when next-char
(if (char= next-char #\?)
(setf (car greedy-quant) :non-greedy-repetition)
(setf (lexer-pos lexer) pos)))
greedy-quant))
(defun seq (lexer)
"Parses and consumes a <seq>.
The productions are: <seq> -> <quant> | <quant><seq>.
Will return <parse-tree> or (:SEQUENCE <parse-tree> <parse-tree>)."
(declare #.*standard-optimize-settings*)
(flet ((make-array-from-two-chars (char1 char2)
(let ((string (make-array 2
:element-type 'character
:fill-pointer t
:adjustable t)))
(setf (aref string 0) char1)
(setf (aref string 1) char2)
string)))
;; Note that we're calling START-OF-SUBEXPR-P before we actually try
;; to parse a <seq> or <quant> in order to catch empty regular
;; expressions
(if (start-of-subexpr-p lexer)
(loop with seq-is-sequence-p = nil
with last-cdr
for quant = (quant lexer)
for quant-is-char-p = (characterp quant)
for seq = quant
then
(cond ((and quant-is-char-p (characterp seq))
(make-array-from-two-chars seq quant))
((and quant-is-char-p (stringp seq))
(vector-push-extend quant seq)
seq)
((not seq-is-sequence-p)
(setf last-cdr (list quant)
seq-is-sequence-p t)
(list* :sequence seq last-cdr))
((and quant-is-char-p
(characterp (car last-cdr)))
(setf (car last-cdr)
(make-array-from-two-chars (car last-cdr)
quant))
seq)
((and quant-is-char-p
(stringp (car last-cdr)))
(vector-push-extend quant (car last-cdr))
seq)
(t
;; if <seq> is also a :SEQUENCE parse tree we merge
;; both lists into one
(let ((cons (list quant)))
(psetf last-cdr cons
(cdr last-cdr) cons))
seq))
while (start-of-subexpr-p lexer)
finally (return seq))
:void)))
(defun reg-expr (lexer)
"Parses and consumes a <regex>, a complete regular expression.
The productions are: <regex> -> <seq> | <seq>\"|\"<regex>.
Will return <parse-tree> or (:ALTERNATION <parse-tree> <parse-tree>)."
(declare #.*standard-optimize-settings*)
(let ((pos (lexer-pos lexer)))
(case (next-char lexer)
((nil)
;; if we didn't get any token we return :VOID which stands for
;; "empty regular expression"
:void)
((#\|)
;; now check whether the expression started with a vertical
;; bar, i.e. <seq> - the left alternation - is empty
(list :alternation :void (reg-expr lexer)))
(otherwise
;; otherwise un-read the character we just saw and parse a
;; <seq> plus the character following it
(setf (lexer-pos lexer) pos)
(let* ((seq (seq lexer))
(pos (lexer-pos lexer)))
(case (next-char lexer)
((nil)
;; no further character, just a <seq>
seq)
((#\|)
;; if the character was a vertical bar, this is an
;; alternation and we have the second production
(let ((reg-expr (reg-expr lexer)))
(cond ((and (consp reg-expr)
(eq (first reg-expr) :alternation))
;; again we try to merge as above in SEQ
(setf (cdr reg-expr)
(cons seq (cdr reg-expr)))
reg-expr)
(t (list :alternation seq reg-expr)))))
(otherwise
;; a character which is not a vertical bar - this is
;; either a syntax error or we're inside of a group and
;; the next character is a closing parenthesis; so we
;; just un-read the character and let another function
;; take care of it
(setf (lexer-pos lexer) pos)
seq)))))))
(defun parse-string (string)
"Translate the regex string STRING into a parse tree."
(declare #.*standard-optimize-settings*)
(let* ((lexer (make-lexer string))
(parse-tree (reg-expr lexer)))
;; check whether we've consumed the whole regex string
(if (end-of-string-p lexer)
parse-tree
(signal-syntax-error* (lexer-pos lexer) "Expected end of string."))))
| 14,290 | Common Lisp | .lisp | 277 | 35.722022 | 97 | 0.512143 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | f640f7a05a0f317cc649a727a6b98a9c9104925c441448545d0d3f7f9202969c | 42,931 | [
318104,
476500
] |
42,932 | charset.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/charset.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/charset.lisp,v 1.10 2009/09/17 19:17:30 edi Exp $
;;; A specialized set implementation for characters by Nikodemus Siivola.
;;; Copyright (c) 2008, Nikodemus Siivola. All rights reserved.
;;; Copyright (c) 2008-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defconstant +probe-depth+ 3
"Maximum number of collisions \(for any element) we accept before we
allocate more storage. This is now fixed, but could be made to vary
depending on the size of the storage vector \(e.g. in the range of
1-4). Larger probe-depths mean more collisions are tolerated before
the table grows, but increase the constant factor.")
(defun make-char-vector (size)
"Returns a vector of size SIZE to hold characters. All elements are
initialized to #\Null except for the first one which is initialized to
#\?."
(declare #.*standard-optimize-settings*)
(declare (type (integer 2 #.(1- array-total-size-limit)) size))
;; since #\Null always hashes to 0, store something else there
;; initially, and #\Null everywhere else
(let ((result (make-array size
:element-type #-:lispworks 'character #+:lispworks 'lw:simple-char
:initial-element (code-char 0))))
(setf (char result 0) #\?)
result))
(defstruct (charset (:constructor make-charset ()))
;; this is set to 0 when we stop hashing and just use a CHAR-CODE
;; indexed vector
(depth +probe-depth+ :type fixnum)
;; the number of characters in this set
(count 0 :type fixnum)
;; the storage vector
(vector (make-char-vector 12) :type (simple-array character (*))))
;; seems to be necessary for some Lisps like ClozureCL
(defmethod make-load-form ((set charset) &optional environment)
(make-load-form-saving-slots set :environment environment))
(declaim (inline mix))
(defun mix (code hash)
"Given a character code CODE and a hash code HASH, computes and
returns the \"next\" hash code. See comments below."
(declare #.*standard-optimize-settings*)
;; mixing the CHAR-CODE back in at each step makes sure that if two
;; characters collide (their hashes end up pointing in the same
;; storage vector index) on one round, they should (hopefully!) not
;; collide on the next
(sxhash (logand most-positive-fixnum (+ code hash))))
(declaim (inline compute-index))
(defun compute-index (hash vector)
"Computes and returns the index into the vector VECTOR corresponding
to the hash code HASH."
(declare #.*standard-optimize-settings*)
(1+ (mod hash (1- (length vector)))))
(defun in-charset-p (char set)
"Checks whether the character CHAR is in the charset SET."
(declare #.*standard-optimize-settings*)
(declare (character char) (charset set))
(let ((vector (charset-vector set))
(depth (charset-depth set))
(code (char-code char)))
(declare (fixnum depth))
;; as long as the set remains reasonably small, we use non-linear
;; hashing - the first hash of any character is its CHAR-CODE, and
;; subsequent hashes are computed by MIX above
(cond ((or
;; depth 0 is special - each char maps only to its code,
;; nothing else
(zerop depth)
;; index 0 is special - only #\Null maps to it, no matter
;; what the depth is
(zerop code))
(eq char (char vector code)))
(t
;; otherwise hash starts out as the character code, but
;; maps to indexes 1-N
(let ((hash code))
(tagbody
:retry
(let* ((index (compute-index hash vector))
(x (char vector index)))
(cond ((eq x (code-char 0))
;; empty, no need to probe further
(return-from in-charset-p nil))
((eq x char)
;; got it
(return-from in-charset-p t))
((zerop (decf depth))
;; max probe depth reached, nothing found
(return-from in-charset-p nil))
(t
;; nothing yet, try next place
(setf hash (mix code hash))
(go :retry))))))))))
(defun add-to-charset (char set)
"Adds the character CHAR to the charset SET, extending SET if
necessary. Returns CHAR."
(declare #.*standard-optimize-settings*)
(or (%add-to-charset char set t)
(%add-to-charset/expand char set)
(error "Oops, this should not happen..."))
char)
(defun %add-to-charset (char set count)
"Tries to add the character CHAR to the charset SET without
extending it. Returns NIL if this fails. Counts CHAR as new
if COUNT is true and it is added to SET."
(declare #.*standard-optimize-settings*)
(declare (character char) (charset set))
(let ((vector (charset-vector set))
(depth (charset-depth set))
(code (char-code char)))
(declare (fixnum depth))
;; see comments in IN-CHARSET-P for algorithm
(cond ((or (zerop depth) (zerop code))
(unless (eq char (char vector code))
(setf (char vector code) char)
(when count
(incf (charset-count set))))
char)
(t
(let ((hash code))
(tagbody
:retry
(let* ((index (compute-index hash vector))
(x (char vector index)))
(cond ((eq x (code-char 0))
(setf (char vector index) char)
(when count
(incf (charset-count set)))
(return-from %add-to-charset char))
((eq x char)
(return-from %add-to-charset char))
((zerop (decf depth))
;; need to expand the table
(return-from %add-to-charset nil))
(t
(setf hash (mix code hash))
(go :retry))))))))))
(defun %add-to-charset/expand (char set)
"Extends the charset SET and then adds the character CHAR to it."
(declare #.*standard-optimize-settings*)
(declare (character char) (charset set))
(let* ((old-vector (charset-vector set))
(new-size (* 2 (length old-vector))))
(tagbody
:retry
;; when the table grows large (currently over 1/3 of
;; CHAR-CODE-LIMIT), we dispense with hashing and just allocate a
;; storage vector with space for all characters, so that each
;; character always uses only the CHAR-CODE
(multiple-value-bind (new-depth new-vector)
(if (>= new-size #.(truncate char-code-limit 3))
(values 0 (make-char-vector char-code-limit))
(values +probe-depth+ (make-char-vector new-size)))
(setf (charset-depth set) new-depth
(charset-vector set) new-vector)
(flet ((try-add (x)
;; don't count - old characters are already accounted
;; for, and might count the new one multiple times as
;; well
(unless (%add-to-charset x set nil)
(assert (not (zerop new-depth)))
(setf new-size (* 2 new-size))
(go :retry))))
(try-add char)
(dotimes (i (length old-vector))
(let ((x (char old-vector i)))
(if (eq x (code-char 0))
(when (zerop i)
(try-add x))
(unless (zerop i)
(try-add x))))))))
;; added and expanded, /now/ count the new character.
(incf (charset-count set))
t))
(defun map-charset (function charset)
"Calls FUNCTION with all characters in SET. Returns NIL."
(declare #.*standard-optimize-settings*)
(declare (function function))
(let* ((n (charset-count charset))
(vector (charset-vector charset))
(size (length vector)))
;; see comments in IN-CHARSET-P for algorithm
(when (eq (code-char 0) (char vector 0))
(funcall function (code-char 0))
(decf n))
(loop for i from 1 below size
for char = (char vector i)
unless (eq (code-char 0) char) do
(funcall function char)
;; this early termination test should be worth it when
;; mapping across depth 0 charsets.
(when (zerop (decf n))
(return-from map-charset nil))))
nil)
(defun create-charset-from-test-function (test-function start end)
"Creates and returns a charset representing all characters with
character codes between START and END which satisfy TEST-FUNCTION."
(declare #.*standard-optimize-settings*)
(loop with charset = (make-charset)
for code from start below end
for char = (code-char code)
when (and char (funcall test-function char))
do (add-to-charset char charset)
finally (return charset)))
| 10,346 | Common Lisp | .lisp | 223 | 37.941704 | 94 | 0.622724 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 70cfb8fefa29c82dfaedebd00b3b5b00988d711eb830fb1099dee13c17a9643a | 42,932 | [
177817,
408738
] |
42,933 | closures.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/closures.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/closures.lisp,v 1.45 2009/09/17 19:17:30 edi Exp $
;;; Here we create the closures which together build the final
;;; scanner.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(declaim (inline *string*= *string*-equal))
(defun *string*= (string2 start1 end1 start2 end2)
"Like STRING=, i.e. compares the special string *STRING* from START1
to END1 with STRING2 from START2 to END2. Note that there's no
boundary check - this has to be implemented by the caller."
(declare #.*standard-optimize-settings*)
(declare (fixnum start1 end1 start2 end2))
(loop for string1-idx of-type fixnum from start1 below end1
for string2-idx of-type fixnum from start2 below end2
always (char= (schar *string* string1-idx)
(schar string2 string2-idx))))
(defun *string*-equal (string2 start1 end1 start2 end2)
"Like STRING-EQUAL, i.e. compares the special string *STRING* from
START1 to END1 with STRING2 from START2 to END2. Note that there's no
boundary check - this has to be implemented by the caller."
(declare #.*standard-optimize-settings*)
(declare (fixnum start1 end1 start2 end2))
(loop for string1-idx of-type fixnum from start1 below end1
for string2-idx of-type fixnum from start2 below end2
always (char-equal (schar *string* string1-idx)
(schar string2 string2-idx))))
(defgeneric create-matcher-aux (regex next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which takes one parameter,
START-POS, and tests whether REGEX can match *STRING* at START-POS
such that the call to NEXT-FN after the match would succeed."))
(defmethod create-matcher-aux ((seq seq) next-fn)
(declare #.*standard-optimize-settings*)
;; the closure for a SEQ is a chain of closures for the elements of
;; this sequence which call each other in turn; the last closure
;; calls NEXT-FN
(loop for element in (reverse (elements seq))
for curr-matcher = next-fn then next-matcher
for next-matcher = (create-matcher-aux element curr-matcher)
finally (return next-matcher)))
(defmethod create-matcher-aux ((alternation alternation) next-fn)
(declare #.*standard-optimize-settings*)
;; first create closures for all alternations of ALTERNATION
(let ((all-matchers (mapcar #'(lambda (choice)
(create-matcher-aux choice next-fn))
(choices alternation))))
;; now create a closure which checks if one of the closures
;; created above can succeed
(lambda (start-pos)
(declare (fixnum start-pos))
(loop for matcher in all-matchers
thereis (funcall (the function matcher) start-pos)))))
(defmethod create-matcher-aux ((register register) next-fn)
(declare #.*standard-optimize-settings*)
;; the position of this REGISTER within the whole regex; we start to
;; count at 0
(let ((num (num register)))
(declare (fixnum num))
;; STORE-END-OF-REG is a thin wrapper around NEXT-FN which will
;; update the corresponding values of *REGS-START* and *REGS-END*
;; after the inner matcher has succeeded
(flet ((store-end-of-reg (start-pos)
(declare (fixnum start-pos)
(function next-fn))
(setf (svref *reg-starts* num) (svref *regs-maybe-start* num)
(svref *reg-ends* num) start-pos)
(funcall next-fn start-pos)))
;; the inner matcher is a closure corresponding to the regex
;; wrapped by this REGISTER
(let ((inner-matcher (create-matcher-aux (regex register)
#'store-end-of-reg)))
(declare (function inner-matcher))
;; here comes the actual closure for REGISTER
(lambda (start-pos)
(declare (fixnum start-pos))
;; remember the old values of *REGS-START* and friends in
;; case we cannot match
(let ((old-*reg-starts* (svref *reg-starts* num))
(old-*regs-maybe-start* (svref *regs-maybe-start* num))
(old-*reg-ends* (svref *reg-ends* num)))
;; we cannot use *REGS-START* here because Perl allows
;; regular expressions like /(a|\1x)*/
(setf (svref *regs-maybe-start* num) start-pos)
(let ((next-pos (funcall inner-matcher start-pos)))
(unless next-pos
;; restore old values on failure
(setf (svref *reg-starts* num) old-*reg-starts*
(svref *regs-maybe-start* num) old-*regs-maybe-start*
(svref *reg-ends* num) old-*reg-ends*))
next-pos)))))))
(defmethod create-matcher-aux ((lookahead lookahead) next-fn)
(declare #.*standard-optimize-settings*)
;; create a closure which just checks for the inner regex and
;; doesn't care about NEXT-FN
(let ((test-matcher (create-matcher-aux (regex lookahead) #'identity)))
(declare (function next-fn test-matcher))
(if (positivep lookahead)
;; positive look-ahead: check success of inner regex, then call
;; NEXT-FN
(lambda (start-pos)
(and (funcall test-matcher start-pos)
(funcall next-fn start-pos)))
;; negative look-ahead: check failure of inner regex, then call
;; NEXT-FN
(lambda (start-pos)
(and (not (funcall test-matcher start-pos))
(funcall next-fn start-pos))))))
(defmethod create-matcher-aux ((lookbehind lookbehind) next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len lookbehind))
;; create a closure which just checks for the inner regex and
;; doesn't care about NEXT-FN
(test-matcher (create-matcher-aux (regex lookbehind) #'identity)))
(declare (function next-fn test-matcher)
(fixnum len))
(if (positivep lookbehind)
;; positive look-behind: check success of inner regex (if we're
;; far enough from the start of *STRING*), then call NEXT-FN
(lambda (start-pos)
(declare (fixnum start-pos))
(and (>= (- start-pos (or *real-start-pos* *start-pos*)) len)
(funcall test-matcher (- start-pos len))
(funcall next-fn start-pos)))
;; negative look-behind: check failure of inner regex (if we're
;; far enough from the start of *STRING*), then call NEXT-FN
(lambda (start-pos)
(declare (fixnum start-pos))
(and (or (< (- start-pos (or *real-start-pos* *start-pos*)) len)
(not (funcall test-matcher (- start-pos len))))
(funcall next-fn start-pos))))))
(defmacro insert-char-class-tester ((char-class chr-expr) &body body)
"Utility macro to replace each occurence of '\(CHAR-CLASS-TEST)
within BODY with the correct test (corresponding to CHAR-CLASS)
against CHR-EXPR."
(with-rebinding (char-class)
(with-unique-names (test-function)
(flet ((substitute-char-class-tester (new)
(subst new '(char-class-test) body
:test #'equalp)))
`(let ((,test-function (test-function ,char-class)))
,@(substitute-char-class-tester
`(funcall ,test-function ,chr-expr)))))))
(defmethod create-matcher-aux ((char-class char-class) next-fn)
(declare #.*standard-optimize-settings*)
(declare (function next-fn))
;; insert a test against the current character within *STRING*
(insert-char-class-tester (char-class (schar *string* start-pos))
(lambda (start-pos)
(declare (fixnum start-pos))
(and (< start-pos *end-pos*)
(char-class-test)
(funcall next-fn (1+ start-pos))))))
(defmethod create-matcher-aux ((str str) next-fn)
(declare #.*standard-optimize-settings*)
(declare (fixnum *end-string-pos*)
(function next-fn)
;; this special value is set by CREATE-SCANNER when the
;; closures are built
(special end-string))
(let* ((len (len str))
(case-insensitive-p (case-insensitive-p str))
(start-of-end-string-p (start-of-end-string-p str))
(skip (skip str))
(str (str str))
(chr (schar str 0))
(end-string (and end-string (str end-string)))
(end-string-len (if end-string
(length end-string)
nil)))
(declare (fixnum len))
(cond ((and start-of-end-string-p case-insensitive-p)
;; closure for the first STR which belongs to the constant
;; string at the end of the regular expression;
;; case-insensitive version
(lambda (start-pos)
(declare (fixnum start-pos end-string-len))
(let ((test-end-pos (+ start-pos end-string-len)))
(declare (fixnum test-end-pos))
;; either we're at *END-STRING-POS* (which means that
;; it has already been confirmed that end-string
;; starts here) or we really have to test
(and (or (= start-pos *end-string-pos*)
(and (<= test-end-pos *end-pos*)
(*string*-equal end-string start-pos test-end-pos
0 end-string-len)))
(funcall next-fn (+ start-pos len))))))
(start-of-end-string-p
;; closure for the first STR which belongs to the constant
;; string at the end of the regular expression;
;; case-sensitive version
(lambda (start-pos)
(declare (fixnum start-pos end-string-len))
(let ((test-end-pos (+ start-pos end-string-len)))
(declare (fixnum test-end-pos))
;; either we're at *END-STRING-POS* (which means that
;; it has already been confirmed that end-string
;; starts here) or we really have to test
(and (or (= start-pos *end-string-pos*)
(and (<= test-end-pos *end-pos*)
(*string*= end-string start-pos test-end-pos
0 end-string-len)))
(funcall next-fn (+ start-pos len))))))
(skip
;; a STR which can be skipped because some other function
;; has already confirmed that it matches
(lambda (start-pos)
(declare (fixnum start-pos))
(funcall next-fn (+ start-pos len))))
((and (= len 1) case-insensitive-p)
;; STR represent exactly one character; case-insensitive
;; version
(lambda (start-pos)
(declare (fixnum start-pos))
(and (< start-pos *end-pos*)
(char-equal (schar *string* start-pos) chr)
(funcall next-fn (1+ start-pos)))))
((= len 1)
;; STR represent exactly one character; case-sensitive
;; version
(lambda (start-pos)
(declare (fixnum start-pos))
(and (< start-pos *end-pos*)
(char= (schar *string* start-pos) chr)
(funcall next-fn (1+ start-pos)))))
(case-insensitive-p
;; general case, case-insensitive version
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((next-pos (+ start-pos len)))
(declare (fixnum next-pos))
(and (<= next-pos *end-pos*)
(*string*-equal str start-pos next-pos 0 len)
(funcall next-fn next-pos)))))
(t
;; general case, case-sensitive version
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((next-pos (+ start-pos len)))
(declare (fixnum next-pos))
(and (<= next-pos *end-pos*)
(*string*= str start-pos next-pos 0 len)
(funcall next-fn next-pos))))))))
(declaim (inline word-boundary-p))
(defun word-boundary-p (start-pos)
"Check whether START-POS is a word-boundary within *STRING*."
(declare #.*standard-optimize-settings*)
(declare (fixnum start-pos))
(let ((1-start-pos (1- start-pos))
(*start-pos* (or *real-start-pos* *start-pos*)))
;; either the character before START-POS is a word-constituent and
;; the character at START-POS isn't...
(or (and (or (= start-pos *end-pos*)
(and (< start-pos *end-pos*)
(not (word-char-p (schar *string* start-pos)))))
(and (< 1-start-pos *end-pos*)
(<= *start-pos* 1-start-pos)
(word-char-p (schar *string* 1-start-pos))))
;; ...or vice versa
(and (or (= start-pos *start-pos*)
(and (< 1-start-pos *end-pos*)
(<= *start-pos* 1-start-pos)
(not (word-char-p (schar *string* 1-start-pos)))))
(and (< start-pos *end-pos*)
(word-char-p (schar *string* start-pos)))))))
(defmethod create-matcher-aux ((word-boundary word-boundary) next-fn)
(declare #.*standard-optimize-settings*)
(declare (function next-fn))
(if (negatedp word-boundary)
(lambda (start-pos)
(and (not (word-boundary-p start-pos))
(funcall next-fn start-pos)))
(lambda (start-pos)
(and (word-boundary-p start-pos)
(funcall next-fn start-pos)))))
(defmethod create-matcher-aux ((everything everything) next-fn)
(declare #.*standard-optimize-settings*)
(declare (function next-fn))
(if (single-line-p everything)
;; closure for single-line-mode: we really match everything, so we
;; just advance the index into *STRING* by one and carry on
(lambda (start-pos)
(declare (fixnum start-pos))
(and (< start-pos *end-pos*)
(funcall next-fn (1+ start-pos))))
;; not single-line-mode, so we have to make sure we don't match
;; #\Newline
(lambda (start-pos)
(declare (fixnum start-pos))
(and (< start-pos *end-pos*)
(char/= (schar *string* start-pos) #\Newline)
(funcall next-fn (1+ start-pos))))))
(defmethod create-matcher-aux ((anchor anchor) next-fn)
(declare #.*standard-optimize-settings*)
(declare (function next-fn))
(let ((startp (startp anchor))
(multi-line-p (multi-line-p anchor)))
(cond ((no-newline-p anchor)
;; this must be an end-anchor and it must be modeless, so
;; we just have to check whether START-POS equals
;; *END-POS*
(lambda (start-pos)
(declare (fixnum start-pos))
(and (= start-pos *end-pos*)
(funcall next-fn start-pos))))
((and startp multi-line-p)
;; a start-anchor in multi-line-mode: check if we're at
;; *START-POS* or if the last character was #\Newline
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((*start-pos* (or *real-start-pos* *start-pos*)))
(and (or (= start-pos *start-pos*)
(and (<= start-pos *end-pos*)
(> start-pos *start-pos*)
(char= #\Newline
(schar *string* (1- start-pos)))))
(funcall next-fn start-pos)))))
(startp
;; a start-anchor which is not in multi-line-mode, so just
;; check whether we're at *START-POS*
(lambda (start-pos)
(declare (fixnum start-pos))
(and (= start-pos (or *real-start-pos* *start-pos*))
(funcall next-fn start-pos))))
(multi-line-p
;; an end-anchor in multi-line-mode: check if we're at
;; *END-POS* or if the character we're looking at is
;; #\Newline
(lambda (start-pos)
(declare (fixnum start-pos))
(and (or (= start-pos *end-pos*)
(and (< start-pos *end-pos*)
(char= #\Newline
(schar *string* start-pos))))
(funcall next-fn start-pos))))
(t
;; an end-anchor which is not in multi-line-mode, so just
;; check if we're at *END-POS* or if we're looking at
;; #\Newline and there's nothing behind it
(lambda (start-pos)
(declare (fixnum start-pos))
(and (or (= start-pos *end-pos*)
(and (= start-pos (1- *end-pos*))
(char= #\Newline
(schar *string* start-pos))))
(funcall next-fn start-pos)))))))
(defmethod create-matcher-aux ((back-reference back-reference) next-fn)
(declare #.*standard-optimize-settings*)
(declare (function next-fn))
;; the position of the corresponding REGISTER within the whole
;; regex; we start to count at 0
(let ((num (num back-reference)))
(if (case-insensitive-p back-reference)
;; the case-insensitive version
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((reg-start (svref *reg-starts* num))
(reg-end (svref *reg-ends* num)))
;; only bother to check if the corresponding REGISTER as
;; matched successfully already
(and reg-start
(let ((next-pos (+ start-pos (- (the fixnum reg-end)
(the fixnum reg-start)))))
(declare (fixnum next-pos))
(and
(<= next-pos *end-pos*)
(*string*-equal *string* start-pos next-pos
reg-start reg-end)
(funcall next-fn next-pos))))))
;; the case-sensitive version
(lambda (start-pos)
(declare (fixnum start-pos))
(let ((reg-start (svref *reg-starts* num))
(reg-end (svref *reg-ends* num)))
;; only bother to check if the corresponding REGISTER as
;; matched successfully already
(and reg-start
(let ((next-pos (+ start-pos (- (the fixnum reg-end)
(the fixnum reg-start)))))
(declare (fixnum next-pos))
(and
(<= next-pos *end-pos*)
(*string*= *string* start-pos next-pos
reg-start reg-end)
(funcall next-fn next-pos)))))))))
(defmethod create-matcher-aux ((branch branch) next-fn)
(declare #.*standard-optimize-settings*)
(let* ((test (test branch))
(then-matcher (create-matcher-aux (then-regex branch) next-fn))
(else-matcher (create-matcher-aux (else-regex branch) next-fn)))
(declare (function then-matcher else-matcher))
(cond ((numberp test)
(lambda (start-pos)
(declare (fixnum test))
(if (and (< test (length *reg-starts*))
(svref *reg-starts* test))
(funcall then-matcher start-pos)
(funcall else-matcher start-pos))))
(t
(let ((test-matcher (create-matcher-aux test #'identity)))
(declare (function test-matcher))
(lambda (start-pos)
(if (funcall test-matcher start-pos)
(funcall then-matcher start-pos)
(funcall else-matcher start-pos))))))))
(defmethod create-matcher-aux ((standalone standalone) next-fn)
(declare #.*standard-optimize-settings*)
(let ((inner-matcher (create-matcher-aux (regex standalone) #'identity)))
(declare (function next-fn inner-matcher))
(lambda (start-pos)
(let ((next-pos (funcall inner-matcher start-pos)))
(and next-pos
(funcall next-fn next-pos))))))
(defmethod create-matcher-aux ((filter filter) next-fn)
(declare #.*standard-optimize-settings*)
(let ((fn (fn filter)))
(lambda (start-pos)
(let ((next-pos (funcall fn start-pos)))
(and next-pos
(funcall next-fn next-pos))))))
(defmethod create-matcher-aux ((void void) next-fn)
(declare #.*standard-optimize-settings*)
;; optimize away VOIDs: don't create a closure, just return NEXT-FN
next-fn)
| 21,911 | Common Lisp | .lisp | 444 | 38.371622 | 90 | 0.583364 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | fd5e9353a5f39affdc896265de5699361cdc4c3c04b2e5966a953214e9ca774f | 42,933 | [
220646,
230061
] |
42,934 | chartest.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/chartest.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/chartest.lisp,v 1.5 2009/09/17 19:17:30 edi Exp $
;;; Copyright (c) 2008-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defun create-hash-table-from-test-function (test-function start end)
"Creates and returns a hash table representing all characters with
character codes between START and END which satisfy TEST-FUNCTION."
(declare #.*standard-optimize-settings*)
(loop with hash-table = (make-hash-table)
for code from start below end
for char = (code-char code)
when (and char (funcall test-function char))
do (setf (gethash char hash-table) t)
finally (return hash-table)))
(defun create-optimized-test-function (test-function &key
(start 0)
(end *regex-char-code-limit*)
(kind *optimize-char-classes*))
"Given a unary test function which is applicable to characters
returns a function which yields the same boolean results for all
characters with character codes from START to \(excluding) END. If
KIND is NIL, TEST-FUNCTION will simply be returned. Otherwise, KIND
should be one of:
* :HASH-TABLE - builds a hash table representing all characters which
satisfy the test and returns a closure which checks if
a character is in that hash table
* :CHARSET - instead of a hash table uses a \"charset\" which is a
data structure using non-linear hashing and optimized to
represent \(sparse) sets of characters in a fast and
space-efficient way \(contributed by Nikodemus Siivola)
* :CHARMAP - instead of a hash table uses a bit vector to represent
the set of characters
You can also use :HASH-TABLE* or :CHARSET* which are like :HASH-TABLE
and :CHARSET but use the complement of the set if the set contains
more than half of all characters between START and END. This saves
space but needs an additional pass across all characters to create the
data structure. There is no corresponding :CHARMAP* kind as the bit
vectors are already created to cover the smallest possible interval
which contains either the set or its complement."
(declare #.*standard-optimize-settings*)
(ecase kind
((nil) test-function)
(:charmap
(let ((charmap (create-charmap-from-test-function test-function start end)))
(lambda (char)
(in-charmap-p char charmap))))
((:charset :charset*)
(let ((charset (create-charset-from-test-function test-function start end)))
(cond ((or (eq kind :charset)
(<= (charset-count charset) (ceiling (- end start) 2)))
(lambda (char)
(in-charset-p char charset)))
(t (setq charset (create-charset-from-test-function (complement* test-function)
start end))
(lambda (char)
(not (in-charset-p char charset)))))))
((:hash-table :hash-table*)
(let ((hash-table (create-hash-table-from-test-function test-function start end)))
(cond ((or (eq kind :hash-table)
(<= (hash-table-count hash-table) (ceiling (- end start) 2)))
(lambda (char)
(gethash char hash-table)))
(t (setq hash-table (create-hash-table-from-test-function (complement* test-function)
start end))
(lambda (char)
(not (gethash char hash-table)))))))))
| 5,030 | Common Lisp | .lisp | 86 | 49.418605 | 98 | 0.65957 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b281f15ed553685be207d4a4d706b14fce5481caa612dbddc4f720617a4d7876 | 42,934 | [
258018,
468568
] |
42,935 | optimize.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/optimize.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/optimize.lisp,v 1.36 2009/09/17 19:17:31 edi Exp $
;;; This file contains optimizations which can be applied to converted
;;; parse trees.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defgeneric flatten (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Merges adjacent sequences and alternations, i.e. it
transforms #<SEQ #<STR \"a\"> #<SEQ #<STR \"b\"> #<STR \"c\">>> to
#<SEQ #<STR \"a\"> #<STR \"b\"> #<STR \"c\">>. This is a destructive
operation on REGEX."))
(defmethod flatten ((seq seq))
(declare #.*standard-optimize-settings*)
;; this looks more complicated than it is because we modify SEQ in
;; place to avoid unnecessary consing
(let ((elements-rest (elements seq)))
(loop
(unless elements-rest
(return))
(let ((flattened-element (flatten (car elements-rest)))
(next-elements-rest (cdr elements-rest)))
(cond ((typep flattened-element 'seq)
;; FLATTENED-ELEMENT is a SEQ object, so we "splice"
;; it into out list of elements
(let ((flattened-element-elements
(elements flattened-element)))
(setf (car elements-rest)
(car flattened-element-elements)
(cdr elements-rest)
(nconc (cdr flattened-element-elements)
(cdr elements-rest)))))
(t
;; otherwise we just replace the current element with
;; its flattened counterpart
(setf (car elements-rest) flattened-element)))
(setq elements-rest next-elements-rest))))
(let ((elements (elements seq)))
(cond ((cadr elements)
seq)
((cdr elements)
(first elements))
(t (make-instance 'void)))))
(defmethod flatten ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; same algorithm as above
(let ((choices-rest (choices alternation)))
(loop
(unless choices-rest
(return))
(let ((flattened-choice (flatten (car choices-rest)))
(next-choices-rest (cdr choices-rest)))
(cond ((typep flattened-choice 'alternation)
(let ((flattened-choice-choices
(choices flattened-choice)))
(setf (car choices-rest)
(car flattened-choice-choices)
(cdr choices-rest)
(nconc (cdr flattened-choice-choices)
(cdr choices-rest)))))
(t
(setf (car choices-rest) flattened-choice)))
(setq choices-rest next-choices-rest))))
(let ((choices (choices alternation)))
(cond ((cadr choices)
alternation)
((cdr choices)
(first choices))
(t (signal-syntax-error "Encountered alternation without choices.")))))
(defmethod flatten ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test then-regex else-regex)
branch
(setq test
(if (numberp test)
test
(flatten test))
then-regex (flatten then-regex)
else-regex (flatten else-regex))
branch))
(defmethod flatten ((regex regex))
(declare #.*standard-optimize-settings*)
(typecase regex
((or repetition register lookahead lookbehind standalone)
;; if REGEX contains exactly one inner REGEX object flatten it
(setf (regex regex)
(flatten (regex regex)))
regex)
(t
;; otherwise (ANCHOR, BACK-REFERENCE, CHAR-CLASS, EVERYTHING,
;; LOOKAHEAD, LOOKBEHIND, STR, VOID, FILTER, and WORD-BOUNDARY)
;; do nothing
regex)))
(defgeneric gather-strings (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Collects adjacent strings or characters into one
string provided they have the same case mode. This is a destructive
operation on REGEX."))
(defmethod gather-strings ((seq seq))
(declare #.*standard-optimize-settings*)
;; note that GATHER-STRINGS is to be applied after FLATTEN, i.e. it
;; expects SEQ to be flattened already; in particular, SEQ cannot be
;; empty and cannot contain embedded SEQ objects
(let* ((start-point (cons nil (elements seq)))
(curr-point start-point)
old-case-mode
collector
collector-start
(collector-length 0)
skip)
(declare (fixnum collector-length))
(loop
(let ((elements-rest (cdr curr-point)))
(unless elements-rest
(return))
(let* ((element (car elements-rest))
(case-mode (case-mode element old-case-mode)))
(cond ((and case-mode
(eq case-mode old-case-mode))
;; if ELEMENT is a STR and we have collected a STR of
;; the same case mode in the last iteration we
;; concatenate ELEMENT onto COLLECTOR and remember the
;; value of its SKIP slot
(let ((old-collector-length collector-length))
(unless (and (adjustable-array-p collector)
(array-has-fill-pointer-p collector))
(setq collector
(make-array collector-length
:initial-contents collector
:element-type 'character
:fill-pointer t
:adjustable t)
collector-start nil))
(adjust-array collector
(incf collector-length (len element))
:fill-pointer t)
(setf (subseq collector
old-collector-length)
(str element)
;; it suffices to remember the last SKIP slot
;; because due to the way MAYBE-ACCUMULATE
;; works adjacent STR objects have the same
;; SKIP value
skip (skip element)))
(setf (cdr curr-point) (cdr elements-rest)))
(t
(let ((collected-string
(cond (collector-start
collector-start)
(collector
;; if we have collected something already
;; we convert it into a STR
(make-instance 'str
:skip skip
:str collector
:case-insensitive-p
(eq old-case-mode
:case-insensitive)))
(t nil))))
(cond (case-mode
;; if ELEMENT is a string with a different case
;; mode than the last one we have either just
;; converted COLLECTOR into a STR or COLLECTOR
;; is still empty; in both cases we can now
;; begin to fill it anew
(setq collector (str element)
collector-start element
;; and we remember the SKIP value as above
skip (skip element)
collector-length (len element))
(cond (collected-string
(setf (car elements-rest)
collected-string
curr-point
(cdr curr-point)))
(t
(setf (cdr curr-point)
(cdr elements-rest)))))
(t
;; otherwise this is not a STR so we apply
;; GATHER-STRINGS to it and collect it directly
;; into RESULT
(cond (collected-string
(setf (car elements-rest)
collected-string
curr-point
(cdr curr-point)
(cdr curr-point)
(cons (gather-strings element)
(cdr curr-point))
curr-point
(cdr curr-point)))
(t
(setf (car elements-rest)
(gather-strings element)
curr-point
(cdr curr-point))))
;; we also have to empty COLLECTOR here in case
;; it was still filled from the last iteration
(setq collector nil
collector-start nil))))))
(setq old-case-mode case-mode))))
(when collector
(setf (cdr curr-point)
(cons
(make-instance 'str
:skip skip
:str collector
:case-insensitive-p
(eq old-case-mode
:case-insensitive))
nil)))
(setf (elements seq) (cdr start-point))
seq))
(defmethod gather-strings ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; loop ON the choices of ALTERNATION so we can modify them directly
(loop for choices-rest on (choices alternation)
while choices-rest
do (setf (car choices-rest)
(gather-strings (car choices-rest))))
alternation)
(defmethod gather-strings ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test then-regex else-regex)
branch
(setq test
(if (numberp test)
test
(gather-strings test))
then-regex (gather-strings then-regex)
else-regex (gather-strings else-regex))
branch))
(defmethod gather-strings ((regex regex))
(declare #.*standard-optimize-settings*)
(typecase regex
((or repetition register lookahead lookbehind standalone)
;; if REGEX contains exactly one inner REGEX object apply
;; GATHER-STRINGS to it
(setf (regex regex)
(gather-strings (regex regex)))
regex)
(t
;; otherwise (ANCHOR, BACK-REFERENCE, CHAR-CLASS, EVERYTHING,
;; LOOKAHEAD, LOOKBEHIND, STR, VOID, FILTER, and WORD-BOUNDARY)
;; do nothing
regex)))
;; Note that START-ANCHORED-P will be called after FLATTEN and GATHER-STRINGS.
(defgeneric start-anchored-p (regex &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(:documentation "Returns T if REGEX starts with a \"real\" start
anchor, i.e. one that's not in multi-line mode, NIL otherwise. If
IN-SEQ-P is true the function will return :ZERO-LENGTH if REGEX is a
zero-length assertion."))
(defmethod start-anchored-p ((seq seq) &optional in-seq-p)
(declare (ignore in-seq-p))
;; note that START-ANCHORED-P is to be applied after FLATTEN and
;; GATHER-STRINGS, i.e. SEQ cannot be empty and cannot contain
;; embedded SEQ objects
(loop for element in (elements seq)
for anchored-p = (start-anchored-p element t)
;; skip zero-length elements because they won't affect the
;; "anchoredness" of the sequence
while (eq anchored-p :zero-length)
finally (return (and anchored-p (not (eq anchored-p :zero-length))))))
(defmethod start-anchored-p ((alternation alternation) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
;; clearly an alternation can only be start-anchored if all of its
;; choices are start-anchored
(loop for choice in (choices alternation)
always (start-anchored-p choice)))
(defmethod start-anchored-p ((branch branch) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(and (start-anchored-p (then-regex branch))
(start-anchored-p (else-regex branch))))
(defmethod start-anchored-p ((repetition repetition) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
;; well, this wouldn't make much sense, but anyway...
(and (plusp (minimum repetition))
(start-anchored-p (regex repetition))))
(defmethod start-anchored-p ((register register) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(start-anchored-p (regex register)))
(defmethod start-anchored-p ((standalone standalone) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(start-anchored-p (regex standalone)))
(defmethod start-anchored-p ((anchor anchor) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(and (startp anchor)
(not (multi-line-p anchor))))
(defmethod start-anchored-p ((regex regex) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(typecase regex
((or lookahead lookbehind word-boundary void)
;; zero-length assertions
(if in-seq-p
:zero-length
nil))
(filter
(if (and in-seq-p
(len regex)
(zerop (len regex)))
:zero-length
nil))
(t
;; BACK-REFERENCE, CHAR-CLASS, EVERYTHING, and STR
nil)))
;; Note that END-STRING-AUX will be called after FLATTEN and GATHER-STRINGS.
(defgeneric end-string-aux (regex &optional old-case-insensitive-p)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the constant string (if it exists) REGEX
ends with wrapped into a STR object, otherwise NIL.
OLD-CASE-INSENSITIVE-P is the CASE-INSENSITIVE-P slot of the last STR
collected or :VOID if no STR has been collected yet. (This is a helper
function called by END-STRING.)"))
(defmethod end-string-aux ((str str)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(declare (special last-str))
(cond ((and (not (skip str)) ; avoid constituents of STARTS-WITH
;; only use STR if nothing has been collected yet or if
;; the collected string has the same value for
;; CASE-INSENSITIVE-P
(or (eq old-case-insensitive-p :void)
(eq (case-insensitive-p str) old-case-insensitive-p)))
(setf last-str str
;; set the SKIP property of this STR
(skip str) t)
str)
(t nil)))
(defmethod end-string-aux ((seq seq)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(declare (special continuep))
(let (case-insensitive-p
concatenated-string
concatenated-start
(concatenated-length 0))
(declare (fixnum concatenated-length))
(loop for element in (reverse (elements seq))
;; remember the case-(in)sensitivity of the last relevant
;; STR object
for loop-old-case-insensitive-p = old-case-insensitive-p
then (if skip
loop-old-case-insensitive-p
(case-insensitive-p element-end))
;; the end-string of the current element
for element-end = (end-string-aux element
loop-old-case-insensitive-p)
;; whether we encountered a zero-length element
for skip = (if element-end
(zerop (len element-end))
nil)
;; set CONTINUEP to NIL if we have to stop collecting to
;; alert END-STRING-AUX methods on enclosing SEQ objects
unless element-end
do (setq continuep nil)
;; end loop if we neither got a STR nor a zero-length
;; element
while element-end
;; only collect if not zero-length
unless skip
do (cond (concatenated-string
(when concatenated-start
(setf concatenated-string
(make-array concatenated-length
:initial-contents (reverse (str concatenated-start))
:element-type 'character
:fill-pointer t
:adjustable t)
concatenated-start nil))
(let ((len (len element-end))
(str (str element-end)))
(declare (fixnum len))
(incf concatenated-length len)
(loop for i of-type fixnum downfrom (1- len) to 0
do (vector-push-extend (char str i)
concatenated-string))))
(t
(setf concatenated-string
t
concatenated-start
element-end
concatenated-length
(len element-end)
case-insensitive-p
(case-insensitive-p element-end))))
;; stop collecting if END-STRING-AUX on inner SEQ has said so
while continuep)
(cond ((zerop concatenated-length)
;; don't bother to return zero-length strings
nil)
(concatenated-start
concatenated-start)
(t
(make-instance 'str
:str (nreverse concatenated-string)
:case-insensitive-p case-insensitive-p)))))
(defmethod end-string-aux ((register register)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(end-string-aux (regex register) old-case-insensitive-p))
(defmethod end-string-aux ((standalone standalone)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(end-string-aux (regex standalone) old-case-insensitive-p))
(defmethod end-string-aux ((regex regex)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(declare (special last-str end-anchored-p continuep))
(typecase regex
((or anchor lookahead lookbehind word-boundary void)
;; a zero-length REGEX object - for the sake of END-STRING-AUX
;; this is a zero-length string
(when (and (typep regex 'anchor)
(not (startp regex))
(or (no-newline-p regex)
(not (multi-line-p regex)))
(eq old-case-insensitive-p :void))
;; if this is a "real" end-anchor and we haven't collected
;; anything so far we can set END-ANCHORED-P (where 1 or 0
;; indicate whether we accept a #\Newline at the end or not)
(setq end-anchored-p (if (no-newline-p regex) 0 1)))
(make-instance 'str
:str ""
:case-insensitive-p :void))
(t
;; (ALTERNATION, BACK-REFERENCE, BRANCH, CHAR-CLASS, EVERYTHING,
;; REPETITION, FILTER)
nil)))
(defun end-string (regex)
(declare (special end-string-offset))
(declare #.*standard-optimize-settings*)
"Returns the constant string (if it exists) REGEX ends with wrapped
into a STR object, otherwise NIL."
;; LAST-STR points to the last STR object (seen from the end) that's
;; part of END-STRING; CONTINUEP is set to T if we stop collecting
;; in the middle of a SEQ
(let ((continuep t)
last-str)
(declare (special continuep last-str))
(prog1
(end-string-aux regex)
(when last-str
;; if we've found something set the START-OF-END-STRING-P of
;; the leftmost STR collected accordingly and remember the
;; OFFSET of this STR (in a special variable provided by the
;; caller of this function)
(setf (start-of-end-string-p last-str) t
end-string-offset (offset last-str))))))
(defgeneric compute-min-rest (regex current-min-rest)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the minimal length of REGEX plus
CURRENT-MIN-REST. This is similar to REGEX-MIN-LENGTH except that it
recurses down into REGEX and sets the MIN-REST slots of REPETITION
objects."))
(defmethod compute-min-rest ((seq seq) current-min-rest)
(declare #.*standard-optimize-settings*)
(loop for element in (reverse (elements seq))
for last-min-rest = current-min-rest then this-min-rest
for this-min-rest = (compute-min-rest element last-min-rest)
finally (return this-min-rest)))
(defmethod compute-min-rest ((alternation alternation) current-min-rest)
(declare #.*standard-optimize-settings*)
(loop for choice in (choices alternation)
minimize (compute-min-rest choice current-min-rest)))
(defmethod compute-min-rest ((branch branch) current-min-rest)
(declare #.*standard-optimize-settings*)
(min (compute-min-rest (then-regex branch) current-min-rest)
(compute-min-rest (else-regex branch) current-min-rest)))
(defmethod compute-min-rest ((str str) current-min-rest)
(declare #.*standard-optimize-settings*)
(+ current-min-rest (len str)))
(defmethod compute-min-rest ((filter filter) current-min-rest)
(declare #.*standard-optimize-settings*)
(+ current-min-rest (or (len filter) 0)))
(defmethod compute-min-rest ((repetition repetition) current-min-rest)
(declare #.*standard-optimize-settings*)
(setf (min-rest repetition) current-min-rest)
(compute-min-rest (regex repetition) current-min-rest)
(+ current-min-rest (* (minimum repetition) (min-len repetition))))
(defmethod compute-min-rest ((register register) current-min-rest)
(declare #.*standard-optimize-settings*)
(compute-min-rest (regex register) current-min-rest))
(defmethod compute-min-rest ((standalone standalone) current-min-rest)
(declare #.*standard-optimize-settings*)
(declare (ignore current-min-rest))
(compute-min-rest (regex standalone) 0))
(defmethod compute-min-rest ((lookahead lookahead) current-min-rest)
(declare #.*standard-optimize-settings*)
(compute-min-rest (regex lookahead) 0)
current-min-rest)
(defmethod compute-min-rest ((lookbehind lookbehind) current-min-rest)
(declare #.*standard-optimize-settings*)
(compute-min-rest (regex lookbehind) (+ current-min-rest (len lookbehind)))
current-min-rest)
(defmethod compute-min-rest ((regex regex) current-min-rest)
(declare #.*standard-optimize-settings*)
(typecase regex
((or char-class everything)
(1+ current-min-rest))
(t
;; zero min-len and no embedded regexes (ANCHOR,
;; BACK-REFERENCE, VOID, and WORD-BOUNDARY)
current-min-rest)))
| 25,265 | Common Lisp | .lisp | 531 | 34.559322 | 97 | 0.572025 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 737314dbf078462f532d3684b1e6d11b323aa074867894d4eab12dca0b5ca7eb | 42,935 | [
260276,
338517
] |
42,936 | packages.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/packages.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/packages.lisp,v 1.39 2009/09/17 19:17:31 edi Exp $
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :cl-ppcre
(:nicknames :ppcre)
#+:genera
(:shadowing-import-from :common-lisp :lambda :simple-string :string)
(:use #-:genera :cl #+:genera :future-common-lisp)
(:shadow :digit-char-p :defconstant)
(:export :parse-string
:create-scanner
:create-optimized-test-function
:parse-tree-synonym
:define-parse-tree-synonym
:scan
:scan-to-strings
:do-scans
:do-matches
:do-matches-as-strings
:count-matches
:all-matches
:all-matches-as-strings
:split
:regex-replace
:regex-replace-all
:regex-apropos
:regex-apropos-list
:quote-meta-chars
:*regex-char-code-limit*
:*use-bmh-matchers*
:*allow-quoting*
:*allow-named-registers*
:*optimize-char-classes*
:*property-resolver*
:*look-ahead-for-suffix*
:ppcre-error
:ppcre-invocation-error
:ppcre-syntax-error
:ppcre-syntax-error-string
:ppcre-syntax-error-pos
:register-groups-bind
:do-register-groups))
| 2,755 | Common Lisp | .lisp | 63 | 36.84127 | 90 | 0.663315 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | a6ee2412eafe418b439cf4732adcad312b37fb9a5549c46999bdd2603c665bc4 | 42,936 | [
209487
] |
42,937 | regex-class-util.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/regex-class-util.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/regex-class-util.lisp,v 1.9 2009/09/17 19:17:31 edi Exp $
;;; This file contains some utility methods for REGEX objects.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
;;; The following four methods allow a VOID object to behave like a
;;; zero-length STR object (only readers needed)
(defmethod len ((void void))
(declare #.*standard-optimize-settings*)
0)
(defmethod str ((void void))
(declare #.*standard-optimize-settings*)
"")
(defmethod skip ((void void))
(declare #.*standard-optimize-settings*)
nil)
(defmethod start-of-end-string-p ((void void))
(declare #.*standard-optimize-settings*)
nil)
(defgeneric case-mode (regex old-case-mode)
(declare #.*standard-optimize-settings*)
(:documentation "Utility function used by the optimizer (see GATHER-STRINGS).
Returns a keyword denoting the case-(in)sensitivity of a STR or its
second argument if the STR has length 0. Returns NIL for REGEX objects
which are not of type STR."))
(defmethod case-mode ((str str) old-case-mode)
(declare #.*standard-optimize-settings*)
(cond ((zerop (len str))
old-case-mode)
((case-insensitive-p str)
:case-insensitive)
(t
:case-sensitive)))
(defmethod case-mode ((regex regex) old-case-mode)
(declare #.*standard-optimize-settings*)
(declare (ignore old-case-mode))
nil)
(defgeneric copy-regex (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Implements a deep copy of a REGEX object."))
(defmethod copy-regex ((anchor anchor))
(declare #.*standard-optimize-settings*)
(make-instance 'anchor
:startp (startp anchor)
:multi-line-p (multi-line-p anchor)
:no-newline-p (no-newline-p anchor)))
(defmethod copy-regex ((everything everything))
(declare #.*standard-optimize-settings*)
(make-instance 'everything
:single-line-p (single-line-p everything)))
(defmethod copy-regex ((word-boundary word-boundary))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary
:negatedp (negatedp word-boundary)))
(defmethod copy-regex ((void void))
(declare #.*standard-optimize-settings*)
(make-instance 'void))
(defmethod copy-regex ((lookahead lookahead))
(declare #.*standard-optimize-settings*)
(make-instance 'lookahead
:regex (copy-regex (regex lookahead))
:positivep (positivep lookahead)))
(defmethod copy-regex ((seq seq))
(declare #.*standard-optimize-settings*)
(make-instance 'seq
:elements (mapcar #'copy-regex (elements seq))))
(defmethod copy-regex ((alternation alternation))
(declare #.*standard-optimize-settings*)
(make-instance 'alternation
:choices (mapcar #'copy-regex (choices alternation))))
(defmethod copy-regex ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test)
branch
(make-instance 'branch
:test (if (typep test 'regex)
(copy-regex test)
test)
:then-regex (copy-regex (then-regex branch))
:else-regex (copy-regex (else-regex branch)))))
(defmethod copy-regex ((lookbehind lookbehind))
(declare #.*standard-optimize-settings*)
(make-instance 'lookbehind
:regex (copy-regex (regex lookbehind))
:positivep (positivep lookbehind)
:len (len lookbehind)))
(defmethod copy-regex ((repetition repetition))
(declare #.*standard-optimize-settings*)
(make-instance 'repetition
:regex (copy-regex (regex repetition))
:greedyp (greedyp repetition)
:minimum (minimum repetition)
:maximum (maximum repetition)
:min-len (min-len repetition)
:len (len repetition)
:contains-register-p (contains-register-p repetition)))
(defmethod copy-regex ((register register))
(declare #.*standard-optimize-settings*)
(make-instance 'register
:regex (copy-regex (regex register))
:num (num register)
:name (name register)))
(defmethod copy-regex ((standalone standalone))
(declare #.*standard-optimize-settings*)
(make-instance 'standalone
:regex (copy-regex (regex standalone))))
(defmethod copy-regex ((back-reference back-reference))
(declare #.*standard-optimize-settings*)
(make-instance 'back-reference
:num (num back-reference)
:case-insensitive-p (case-insensitive-p back-reference)))
(defmethod copy-regex ((char-class char-class))
(declare #.*standard-optimize-settings*)
(make-instance 'char-class
:test-function (test-function char-class)))
(defmethod copy-regex ((str str))
(declare #.*standard-optimize-settings*)
(make-instance 'str
:str (str str)
:case-insensitive-p (case-insensitive-p str)))
(defmethod copy-regex ((filter filter))
(declare #.*standard-optimize-settings*)
(make-instance 'filter
:fn (fn filter)
:len (len filter)))
;;; Note that COPY-REGEX and REMOVE-REGISTERS could have easily been
;;; wrapped into one function. Maybe in the next release...
;;; Further note that this function is used by CONVERT to factor out
;;; complicated repetitions, i.e. cases like
;;; (a)* -> (?:a*(a))?
;;; This won't work for, say,
;;; ((a)|(b))* -> (?:(?:a|b)*((a)|(b)))?
;;; and therefore we stop REGISTER removal once we see an ALTERNATION.
(defgeneric remove-registers (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Returns a deep copy of a REGEX (see COPY-REGEX) and
optionally removes embedded REGISTER objects if possible and if the
special variable REMOVE-REGISTERS-P is true."))
(defmethod remove-registers ((register register))
(declare #.*standard-optimize-settings*)
(declare (special remove-registers-p reg-seen))
(cond (remove-registers-p
(remove-registers (regex register)))
(t
;; mark REG-SEEN as true so enclosing REPETITION objects
;; (see method below) know if they contain a register or not
(setq reg-seen t)
(copy-regex register))))
(defmethod remove-registers ((repetition repetition))
(declare #.*standard-optimize-settings*)
(let* (reg-seen
(inner-regex (remove-registers (regex repetition))))
;; REMOVE-REGISTERS will set REG-SEEN (see method above) if
;; (REGEX REPETITION) contains a REGISTER
(declare (special reg-seen))
(make-instance 'repetition
:regex inner-regex
:greedyp (greedyp repetition)
:minimum (minimum repetition)
:maximum (maximum repetition)
:min-len (min-len repetition)
:len (len repetition)
:contains-register-p reg-seen)))
(defmethod remove-registers ((standalone standalone))
(declare #.*standard-optimize-settings*)
(make-instance 'standalone
:regex (remove-registers (regex standalone))))
(defmethod remove-registers ((lookahead lookahead))
(declare #.*standard-optimize-settings*)
(make-instance 'lookahead
:regex (remove-registers (regex lookahead))
:positivep (positivep lookahead)))
(defmethod remove-registers ((lookbehind lookbehind))
(declare #.*standard-optimize-settings*)
(make-instance 'lookbehind
:regex (remove-registers (regex lookbehind))
:positivep (positivep lookbehind)
:len (len lookbehind)))
(defmethod remove-registers ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test)
branch
(make-instance 'branch
:test (if (typep test 'regex)
(remove-registers test)
test)
:then-regex (remove-registers (then-regex branch))
:else-regex (remove-registers (else-regex branch)))))
(defmethod remove-registers ((alternation alternation))
(declare #.*standard-optimize-settings*)
(declare (special remove-registers-p))
;; an ALTERNATION, so we can't remove REGISTER objects further down
(setq remove-registers-p nil)
(copy-regex alternation))
(defmethod remove-registers ((regex regex))
(declare #.*standard-optimize-settings*)
(copy-regex regex))
(defmethod remove-registers ((seq seq))
(declare #.*standard-optimize-settings*)
(make-instance 'seq
:elements (mapcar #'remove-registers (elements seq))))
(defgeneric everythingp (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Returns an EVERYTHING object if REGEX is equivalent
to this object, otherwise NIL. So, \"(.){1}\" would return true
\(i.e. the object corresponding to \".\", for example."))
(defmethod everythingp ((seq seq))
(declare #.*standard-optimize-settings*)
;; we might have degenerate cases like (:SEQUENCE :VOID ...)
;; due to the parsing process
(let ((cleaned-elements (remove-if #'(lambda (element)
(typep element 'void))
(elements seq))))
(and (= 1 (length cleaned-elements))
(everythingp (first cleaned-elements)))))
(defmethod everythingp ((alternation alternation))
(declare #.*standard-optimize-settings*)
(with-slots (choices)
alternation
(and (= 1 (length choices))
;; this is unlikely to happen for human-generated regexes,
;; but machine-generated ones might look like this
(everythingp (first choices)))))
(defmethod everythingp ((repetition repetition))
(declare #.*standard-optimize-settings*)
(with-slots (maximum minimum regex)
repetition
(and maximum
(= 1 minimum maximum)
;; treat "<regex>{1,1}" like "<regex>"
(everythingp regex))))
(defmethod everythingp ((register register))
(declare #.*standard-optimize-settings*)
(everythingp (regex register)))
(defmethod everythingp ((standalone standalone))
(declare #.*standard-optimize-settings*)
(everythingp (regex standalone)))
(defmethod everythingp ((everything everything))
(declare #.*standard-optimize-settings*)
everything)
(defmethod everythingp ((regex regex))
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, BACK-REFERENCE, BRANCH, CHAR-CLASS,
;; LOOKAHEAD, LOOKBEHIND, STR, VOID, FILTER, and WORD-BOUNDARY
nil)
(defgeneric regex-length (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Return the length of REGEX if it is fixed, NIL otherwise."))
(defmethod regex-length ((seq seq))
(declare #.*standard-optimize-settings*)
;; simply add all inner lengths unless one of them is NIL
(loop for sub-regex in (elements seq)
for len = (regex-length sub-regex)
if (not len) do (return nil)
sum len))
(defmethod regex-length ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; only return a true value if all inner lengths are non-NIL and
;; mutually equal
(loop for sub-regex in (choices alternation)
for old-len = nil then len
for len = (regex-length sub-regex)
if (or (not len)
(and old-len (/= len old-len))) do (return nil)
finally (return len)))
(defmethod regex-length ((branch branch))
(declare #.*standard-optimize-settings*)
;; only return a true value if both alternations have a length and
;; if they're equal
(let ((then-length (regex-length (then-regex branch))))
(and then-length
(eql then-length (regex-length (else-regex branch)))
then-length)))
(defmethod regex-length ((repetition repetition))
(declare #.*standard-optimize-settings*)
;; we can only compute the length of a REPETITION object if the
;; number of repetitions is fixed; note that we don't call
;; REGEX-LENGTH for the inner regex, we assume that the LEN slot is
;; always set correctly
(with-slots (len minimum maximum)
repetition
(if (and len
(eql minimum maximum))
(* minimum len)
nil)))
(defmethod regex-length ((register register))
(declare #.*standard-optimize-settings*)
(regex-length (regex register)))
(defmethod regex-length ((standalone standalone))
(declare #.*standard-optimize-settings*)
(regex-length (regex standalone)))
(defmethod regex-length ((back-reference back-reference))
(declare #.*standard-optimize-settings*)
;; with enough effort we could possibly do better here, but
;; currently we just give up and return NIL
nil)
(defmethod regex-length ((char-class char-class))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-length ((everything everything))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-length ((str str))
(declare #.*standard-optimize-settings*)
(len str))
(defmethod regex-length ((filter filter))
(declare #.*standard-optimize-settings*)
(len filter))
(defmethod regex-length ((regex regex))
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and
;; WORD-BOUNDARY (which all have zero-length)
0)
(defgeneric regex-min-length (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the minimal length of REGEX."))
(defmethod regex-min-length ((seq seq))
(declare #.*standard-optimize-settings*)
;; simply add all inner minimal lengths
(loop for sub-regex in (elements seq)
for len = (regex-min-length sub-regex)
sum len))
(defmethod regex-min-length ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; minimal length of an alternation is the minimal length of the
;; "shortest" element
(loop for sub-regex in (choices alternation)
for len = (regex-min-length sub-regex)
minimize len))
(defmethod regex-min-length ((branch branch))
(declare #.*standard-optimize-settings*)
;; minimal length of both alternations
(min (regex-min-length (then-regex branch))
(regex-min-length (else-regex branch))))
(defmethod regex-min-length ((repetition repetition))
(declare #.*standard-optimize-settings*)
;; obviously the product of the inner minimal length and the minimal
;; number of repetitions
(* (minimum repetition) (min-len repetition)))
(defmethod regex-min-length ((register register))
(declare #.*standard-optimize-settings*)
(regex-min-length (regex register)))
(defmethod regex-min-length ((standalone standalone))
(declare #.*standard-optimize-settings*)
(regex-min-length (regex standalone)))
(defmethod regex-min-length ((char-class char-class))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-min-length ((everything everything))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-min-length ((str str))
(declare #.*standard-optimize-settings*)
(len str))
(defmethod regex-min-length ((filter filter))
(declare #.*standard-optimize-settings*)
(or (len filter)
0))
(defmethod regex-min-length ((regex regex))
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, BACK-REFERENCE, LOOKAHEAD,
;; LOOKBEHIND, VOID, and WORD-BOUNDARY
0)
(defgeneric compute-offsets (regex start-pos)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the offset the following regex would have
relative to START-POS or NIL if we can't compute it. Sets the OFFSET
slot of REGEX to START-POS if REGEX is a STR. May also affect OFFSET
slots of STR objects further down the tree."))
;; note that we're actually only interested in the offset of
;; "top-level" STR objects (see ADVANCE-FN in the SCAN function) so we
;; can stop at variable-length alternations and don't need to descend
;; into repetitions
(defmethod compute-offsets ((seq seq) start-pos)
(declare #.*standard-optimize-settings*)
(loop for element in (elements seq)
;; advance offset argument for next call while looping through
;; the elements
for pos = start-pos then curr-offset
for curr-offset = (compute-offsets element pos)
while curr-offset
finally (return curr-offset)))
(defmethod compute-offsets ((alternation alternation) start-pos)
(declare #.*standard-optimize-settings*)
(loop for choice in (choices alternation)
for old-offset = nil then curr-offset
for curr-offset = (compute-offsets choice start-pos)
;; we stop immediately if two alternations don't result in the
;; same offset
if (or (not curr-offset)
(and old-offset (/= curr-offset old-offset)))
do (return nil)
finally (return curr-offset)))
(defmethod compute-offsets ((branch branch) start-pos)
(declare #.*standard-optimize-settings*)
;; only return offset if both alternations have equal value
(let ((then-offset (compute-offsets (then-regex branch) start-pos)))
(and then-offset
(eql then-offset (compute-offsets (else-regex branch) start-pos))
then-offset)))
(defmethod compute-offsets ((repetition repetition) start-pos)
(declare #.*standard-optimize-settings*)
;; no need to descend into the inner regex
(with-slots (len minimum maximum)
repetition
(if (and len
(eq minimum maximum))
;; fixed number of repetitions, so we know how to proceed
(+ start-pos (* minimum len))
;; otherwise return NIL
nil)))
(defmethod compute-offsets ((register register) start-pos)
(declare #.*standard-optimize-settings*)
(compute-offsets (regex register) start-pos))
(defmethod compute-offsets ((standalone standalone) start-pos)
(declare #.*standard-optimize-settings*)
(compute-offsets (regex standalone) start-pos))
(defmethod compute-offsets ((char-class char-class) start-pos)
(declare #.*standard-optimize-settings*)
(1+ start-pos))
(defmethod compute-offsets ((everything everything) start-pos)
(declare #.*standard-optimize-settings*)
(1+ start-pos))
(defmethod compute-offsets ((str str) start-pos)
(declare #.*standard-optimize-settings*)
(setf (offset str) start-pos)
(+ start-pos (len str)))
(defmethod compute-offsets ((back-reference back-reference) start-pos)
(declare #.*standard-optimize-settings*)
;; with enough effort we could possibly do better here, but
;; currently we just give up and return NIL
(declare (ignore start-pos))
nil)
(defmethod compute-offsets ((filter filter) start-pos)
(declare #.*standard-optimize-settings*)
(let ((len (len filter)))
(if len
(+ start-pos len)
nil)))
(defmethod compute-offsets ((regex regex) start-pos)
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and
;; WORD-BOUNDARY (which all have zero-length)
start-pos)
| 20,424 | Common Lisp | .lisp | 464 | 38.275862 | 97 | 0.688247 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 82b401df3fd7c00bff6646bcdda5e5b5da0fdd85daa736a89d0e91ede03b74fa | 42,937 | [
282048,
406388
] |
42,938 | unicode-tests.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/test/unicode-tests.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE-TEST; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/test/unicode-tests.lisp,v 1.8 2008/07/23 00:17:53 edi Exp $
;;; Copyright (c) 2008, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre-test)
(defun unicode-test (&key (file-name
(make-pathname :name "unicodetestdata"
:type nil :version nil
:defaults *this-file*)
file-name-provided-p)
verbose)
"Loops through all test cases in FILE-NAME and prints a report if
VERBOSE is true. Returns a true value if all tests succeeded.
For the syntax of the tests in FILE-NAME refer to CL-UNICODE."
(with-open-file (stream file-name)
(let ((*regex-char-code-limit* (if file-name-provided-p *regex-char-code-limit* char-code-limit))
(*optimize-char-classes* (if file-name-provided-p *optimize-char-classes* nil))
;; we only check for correctness and don't care about speed
;; that match (but rather about space constraints of the
;; trial versions)
(*use-bmh-matchers* (if file-name-provided-p *use-bmh-matchers* nil)))
(do-tests ((format nil "Running Unicode tests in file ~S" (file-namestring file-name))
(not verbose))
(let ((input-line (or (read stream nil) (done)))
errors)
(destructuring-bind (char-code property-name expected-result)
input-line
(let ((char (and (< char-code char-code-limit) (code-char char-code))))
(when char
(when verbose
(format t "~&~A: #x~X" property-name char-code))
(let* ((string (string char))
(result-1 (scan (format nil "\\p{~A}" property-name) string))
(result-2 (scan (format nil "[\\p{~A}]" property-name) string))
(inverted-result-1 (scan (format nil "\\P{~A}" property-name) string))
(inverted-result-2 (scan (format nil "[\\P{~A}]" property-name) string)))
(unless (eq expected-result (not (not result-1)))
(push (format nil "\(code-char #x~X) should ~:[not ~;~]have matched \"\\p{~A}\""
char-code expected-result property-name)
errors))
(unless (eq expected-result (not (not result-2)))
(push (format nil "\(code-char #x~X) should ~:[not ~;~]have matched \"[\\p{~A}]\""
char-code expected-result property-name)
errors))
(unless (eq expected-result (not inverted-result-1))
(push (format nil "\(code-char #x~X) should ~:[~;not ~]have matched \"\\P{~A}\""
char-code expected-result property-name)
errors))
(unless (eq expected-result (not inverted-result-2))
(push (format nil "\(code-char #x~X) should ~:[~;not ~]have matched \"[\\P{~A}]\""
char-code expected-result property-name)
errors)))
errors))))))))
| 4,619 | Common Lisp | .lisp | 72 | 50.986111 | 102 | 0.589998 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | ad1643ea9ef5230e75141279190bfab5ea0231952823c5b92c08d7370bd86367 | 42,938 | [
1258,
72981
] |
42,939 | perl-tests.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/test/perl-tests.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE-TEST; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/test/perl-tests.lisp,v 1.8 2009/09/17 19:17:36 edi Exp $
;;; The tests in this file test CL-PPCRE against testdata generated by
;;; the Perl program `perltest.pl' from the input file `testinput' in
;;; order to check compatibility with Perl and correctness of the
;;; regex engine.
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre-test)
(defvar *tests-to-skip* '(636 638 662 790 1439)
"Some tests we skip because the testdata is generated by a Perl
program and CL-PPCRE differs from Perl for these tests - on purpose.")
(defun create-string-from-input (input)
"Converts INPUT to a string which can be used in TEST below. The
input file `testdata' encodes strings containing non-printable
characters as lists where those characters are represented by their
character code."
(etypecase input
((or null string) input)
(list (string-list-to-simple-string
(loop for element in input
if (stringp element)
collect element
else
collect (string (code-char element)))))))
(defun perl-test (&key (file-name
(make-pathname :name "perltestdata"
:type nil :version nil
:defaults *this-file*)
file-name-provided-p)
(external-format '(:latin-1 :eol-style :lf))
verbose)
"Loops through all test cases in FILE-NAME and prints a report if
VERBOSE is true. EXTERNAL-FORMAT is the FLEXI-STREAMS external format
which is used to read the file. Returns a true value if all tests
succeeded.
For the syntax of the tests in FILE-NAME refer to the source code of
this function and to the Perl script perltest.pl which generates such
test files."
(declare #.*standard-optimize-settings*)
(with-open-file (binary-stream file-name :element-type 'flex:octet)
(let ((stream (flex:make-flexi-stream binary-stream :external-format external-format))
;; the standard Perl tests don't need full Unicode support
(*regex-char-code-limit* (if file-name-provided-p *regex-char-code-limit* 256))
;; we need this for the standard test suite or otherwise we
;; might get stack overflows
(*optimize-char-classes* (if file-name-provided-p *optimize-char-classes* :charmap))
;; we only check for correctness and don't care about speed
;; that match (but rather about space constraints of the
;; trial versions)
(*use-bmh-matchers* (if file-name-provided-p *use-bmh-matchers* nil))
;; some tests in the Perl suite explicitly check for this
(*allow-quoting* (if file-name-provided-p *allow-quoting* t)))
(do-tests ((format nil "Running tests in file ~S" (file-namestring file-name))
(not verbose))
(let ((input-line (or (read stream nil) (done)))
errors)
(destructuring-bind (counter
info-string%
regex%
case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
target%
perl-error
expected-result%
expected-registers)
input-line
(destructuring-bind (info-string regex target expected-result)
(mapcar 'create-string-from-input
(list info-string% regex% target% expected-result%))
(setq expected-registers (mapcar 'create-string-from-input expected-registers))
(unless (find counter *tests-to-skip* :test #'=)
(when verbose
(format t "~&~4D: ~S" counter info-string))
(block inner-test-block
(let ((scanner
(handler-bind ((error (lambda (condition)
(declare (ignore condition))
(when perl-error
;; we expected an
;; error, so we can
;; signal success
(return-from inner-test-block)))))
(create-scanner regex
:case-insensitive-mode case-insensitive-mode
:multi-line-mode multi-line-mode
:single-line-mode single-line-mode
:extended-mode extended-mode))))
(multiple-value-bind (start end reg-starts reg-ends)
(scan scanner target)
(cond (perl-error
(push (format nil "expected an error but got a result.")
errors))
(t
(when (not (eq start expected-result))
(if start
(let ((result (subseq target start end)))
(unless (string= result expected-result)
(push (format nil "expected ~S but got ~S."
expected-result result)
errors))
(setq reg-starts (coerce reg-starts 'list)
reg-ends (coerce reg-ends 'list))
(loop for i from 0
for expected-register in expected-registers
for reg-start = (nth i reg-starts)
for reg-end = (nth i reg-ends)
for register = (if (and reg-start reg-end)
(subseq target reg-start reg-end)
nil)
unless (string= expected-register register)
do (push (format nil "\\~A: expected ~S but got ~S."
(1+ i) expected-register register)
errors)))
(push (format nil "expected ~S but got ~S."
expected-result start)
errors))))))
errors))))))))))
| 8,399 | Common Lisp | .lisp | 139 | 40.395683 | 96 | 0.521154 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 6fdbaac222a29bde9abb1f13650980ec4f942f0f5de9a4e8a4dff7002c2163ba | 42,939 | [
358813,
483139
] |
42,940 | packages.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/test/packages.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/test/packages.lisp,v 1.4 2009/09/17 19:17:36 edi Exp $
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :cl-ppcre-test
#+genera (:shadowing-import-from :common-lisp :lambda)
(:use #-:genera :cl #+:genera :future-common-lisp :cl-ppcre)
(:import-from :cl-ppcre :*standard-optimize-settings*
:string-list-to-simple-string)
(:export :run-all-tests :unicode-test))
| 1,846 | Common Lisp | .lisp | 30 | 59.166667 | 94 | 0.735766 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 4404e016560ac4f057553966ace0620adcb569091d4b064542cf4828c66e5405 | 42,940 | [
101870,
360452
] |
42,941 | resolver.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/cl-ppcre-unicode/resolver.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/cl-ppcre-unicode/resolver.lisp,v 1.5 2008/07/23 02:14:08 edi Exp $
;;; Copyright (c) 2008, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre-unicode)
(defun unicode-property-resolver (property-name)
"A property resolver which understands Unicode properties using
CL-UNICODE's PROPERTY-TEST function. This resolver is automatically
installed in *PROPERTY-RESOLVER* when the CL-PPCRE-UNICODE system is
loaded."
(or (property-test property-name :errorp nil)
(signal-syntax-error "There is no property named ~S." property-name)))
(setq *property-resolver* 'unicode-property-resolver)
(pushnew :cl-ppcre-unicode *features*)
;; stuff for Nikodemus Siivola's HYPERDOC
;; see <http://common-lisp.net/project/hyperdoc/>
;; and <http://www.cliki.net/hyperdoc>
;; also used by LW-ADD-ONS
(defvar *hyperdoc-base-uri* "http://weitz.de/cl-ppcre/")
(let ((exported-symbols-alist
(loop for symbol being the external-symbols of :cl-ppcre-unicode
collect (cons symbol
(concatenate 'string
"#"
(string-downcase symbol))))))
(defun hyperdoc-lookup (symbol type)
(declare (ignore type))
(cdr (assoc symbol
exported-symbols-alist
:test #'eq))))
| 2,719 | Common Lisp | .lisp | 49 | 50.591837 | 106 | 0.711061 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 3736dda40be7ffdd404a1577d9473c1f790957be47ad5376ab33854840ae26b7 | 42,941 | [
1297,
430315
] |
42,942 | packages.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-ppcre-20220220-git/cl-ppcre-unicode/packages.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/cl-ppcre-unicode/packages.lisp,v 1.3 2009/09/17 19:17:34 edi Exp $
;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :cl-ppcre-unicode
#+:genera
(:shadowing-import-from :common-lisp :lambda :string)
(:use #-:genera :cl #+:genera :future-common-lisp
:cl-ppcre :cl-unicode)
(:import-from :cl-ppcre :signal-syntax-error)
(:export :unicode-property-resolver))
| 1,825 | Common Lisp | .lisp | 31 | 57.064516 | 106 | 0.743705 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | bff0807c47e08832ae929f494520515266e5a61ffd820978a660fc351f69328e | 42,942 | [
184345,
231928
] |
42,943 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/winhttp-20200610-git/package.lisp | ;;;; Copyright (c) Frank James 2017 <[email protected]>
;;;; This code is licensed under the MIT license.
(defpackage #:winhttp
(:use #:cl #:cffi)
(:export #:http-request
#:with-http
#:with-connect
#:with-request
#:crack-url
#:http-open
#:close-handle
#:add-request-headers
#:http-connect
#:http-open-request
#:query-headers
#:query-status-code
#:read-data
#:receive-response
#:send-request
#:query-data-available
#:set-credentials
#:define-status-callback
#:set-status-callback
;; websocket
#:websocket-close
#:websocket-complete-upgrade
#:websocket-receive
#:websocket-send
#:websocket-shutdown
#:upgrade-to-websocket
#:with-websocket
#:websocket-query-close-status
))
| 798 | Common Lisp | .lisp | 33 | 19.515152 | 61 | 0.658344 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | ccb42e126f6681362021992c25ce7b12a54b918d4a9107094d9b0420cd19f9ee | 42,943 | [
296766
] |
42,944 | util.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/winhttp-20200610-git/util.lisp | ;;;; Copyright (c) Frank James 2017 <[email protected]>
;;;; This code is licensed under the MIT license.
(in-package #:winhttp)
(defmacro with-http ((var &optional user-agent) &body body)
"Evaluate body with VAR bound to a session handle."
`(let ((,var (http-open ,user-agent)))
(unwind-protect (progn ,@body)
(close-handle ,var))))
(defmacro with-connect ((var http hostname port) &body body)
"Evaluate body with VAR bound to a connection handle."
`(let ((,var (http-connect ,http ,hostname ,port)))
(unwind-protect (progn ,@body)
(close-handle ,var))))
(defmacro with-request ((var hconn &key verb url https-p) &body body)
"Evaludate body with VAR bound to a request handle."
`(let ((,var (http-open-request ,hconn
:verb ,verb
:url ,url
:https-p ,https-p)))
(unwind-protect (progn ,@body)
(close-handle ,var))))
(defun query-content-length (headers)
"Returns content length as specified in header."
(dolist (h headers)
(destructuring-bind (hname hval) h
(when (string-equal hname "Content-Length")
(return-from query-content-length (parse-integer hval)))))
nil)
(defparameter *status-cb-types*
'((:RESOLVING-NAME #x00000001)
(:NAME-RESOLVED #x00000002)
(:CONNECTING-TO-SERVER #x00000004)
(:CONNECTED-TO-SERVER #x00000008)
(:SENDING-REQUEST #x00000010)
(:REQUEST-SENT #x00000020)
(:RECEIVING-RESPONSE #x00000040)
(:RESPONSE-RECEIVED #x00000080)
(:CLOSING-CONNECTION #x00000100)
(:CONNECTION-CLOSED #x00000200)
(:HANDLE-CREATED #x00000400)
(:HANDLE-CLOSING #x00000800)
(:DETECTING-PROXY #x00001000)
(:REDIRECT #x00004000)
(:INTERMEDIATE-RESPONSE #x00008000)
(:SECURE-FAILURE #x00010000)
(:HEADERS-AVAILABLE #x00020000)
(:DATA-AVAILABLE #x00040000)
(:READ-COMPLETE #x00080000)
(:WRITE-COMPLETE #x00100000)
(:REQUEST-ERROR #x00200000)
(:SENDREQUEST-COMPLETE #x00400000)
(:GETPROXYFORURL-COMPLETE #x01000000)
(:CLOSE-COMPLETE #x02000000)
(:SHUTDOWN-COMPLETE #x04000000)))
(defmacro define-status-callback (name (hinternet context status infop infolen) &body body)
"Define a foreign callback function which can be used to receive http request status updates.
See MSDN for information on WinHttpSetStatusCallback function. Use SET-STATUS-CALLBACK to register
this with a request handle.
HINTERNET ::= handle
CONTEXT ::= pointer to DWORD context
STATUS ::= symbol naming status update type
INFOP ::= pointer to info buffer
INFOLEN ::= length of info buffer
"
(let ((gstatus (gensym)))
`(defcallback ,name :void
((,hinternet :pointer)
(,context :pointer)
(,gstatus :uint32)
(,infop :pointer)
(,infolen :uint32))
(let ((,status (first (find ,gstatus *status-cb-types* :key #'second))))
,@body))))
;; I got this list by doing a (maphash (lambda (k v) (list k (string k))) babel::*string-vector-mappings*)
;; We can support multiple string mappings to the same keyword identifier
;; by adding more strings to the end of the list.
;; e.g. both "UCS-2" and "UCS2" both map to :UCS-2
(defparameter *charsets*
'((:US-ASCII "US-ASCII")
(:ASCII "ASCII")
(:IBM-037 "IBM-037")
(:EBCDIC-US "EBCDIC-US")
(:EBCDIC-INTERNATIONAL "EBCDIC-INTERNATIONAL")
(:LATIN1 "LATIN1")
(:LATIN-1 "LATIN-1")
(:ISO-8859-1 "ISO-8859-1")
(:LATIN2 "LATIN2")
(:LATIN-2 "LATIN-2")
(:ISO-8859-2 "ISO-8859-2")
(:LATIN3 "LATIN3")
(:LATIN-3 "LATIN-3")
(:ISO-8859-3 "ISO-8859-3")
(:LATIN4 "LATIN4")
(:LATIN-4 "LATIN-4")
(:ISO-8859-4 "ISO-8859-4")
(:CYRILLIC "CYRILLIC")
(:ISO-8859-5 "ISO-8859-5")
(:ARABIC "ARABIC")
(:ISO-8859-6 "ISO-8859-6")
(:GREEK "GREEK")
(:ISO-8859-7 "ISO-8859-7")
(:HEBREW "HEBREW")
(:ISO-8859-8 "ISO-8859-8")
(:LATIN5 "LATIN5")
(:LATIN-5 "LATIN-5")
(:ISO-8859-9 "ISO-8859-9")
(:LATIN6 "LATIN6")
(:LATIN-6 "LATIN-6")
(:ISO-8859-10 "ISO-8859-10")
(:ISO-8859-11 "ISO-8859-11")
(:ISO-8859-13 "ISO-8859-13")
(:LATIN8 "LATIN8")
(:LATIN-8 "LATIN-8")
(:ISO-8859-14 "ISO-8859-14")
(:LATIN9 "LATIN9")
(:LATIN-9 "LATIN-9")
(:ISO-8859-15 "ISO-8859-15")
(:LATIN10 "LATIN10")
(:LATIN-10 "LATIN-10")
(:ISO-8859-16 "ISO-8859-16")
(:UTF-8 "UTF-8")
(:UTF-8B "UTF-8B")
(:UTF-16 "UTF-16")
(:UTF-16/LE "UTF-16/LE")
(:UTF-16LE "UTF-16LE")
(:UTF-16/BE "UTF-16/BE")
(:UTF-16BE "UTF-16BE")
(:UCS-4 "UCS-4")
(:UTF-32 "UTF-32")
(:UCS-4/LE "UCS-4/LE")
(:UCS-4LE "UCS-4LE")
(:UTF-32/LE "UTF-32/LE")
(:UTF-32LE "UTF-32LE")
(:UCS-4/BE "UCS-4/BE")
(:UCS-4BE "UCS-4BE")
(:UTF-32/BE "UTF-32/BE")
(:UTF-32BE "UTF-32BE")
(:UCS-2 "UCS-2" "UCS2")
(:UCS-2/LE "UCS-2/LE")
(:UCS-2LE "UCS-2LE")
(:UCS-2/BE "UCS-2/BE")
(:UCS-2BE "UCS-2BE")
(:WINDOWS-1251 "WINDOWS-1251")
(:CP1251 "CP1251")
(:WINDOWS-1252 "WINDOWS-1252")
(:CP1252 "CP1252")
(:EUCJP "EUCJP")
(:CP932 "CP932")
(:GBK "GBK")
(:KOI8-RU "KOI8-RU")
(:KOI8-R "KOI8-R")
(:KOI8-U "KOI8-U")))
(defun charset-by-name (str)
"Lookup a charset identifier by name. We only support the charsets
supported by babel. We do a lookup by name because we don't want to be
interning strings received from the web server."
(car (find-if (lambda (cs)
(some (lambda (s)
(string-equal s str))
(cdr cs)))
*charsets*)))
(defun get-content-charset (headers)
"Try and get the content charset from the headers. We need this otherwise
babel may not be able to decode the text."
(let ((str (second (find "Content-Type" headers :key #'car :test #'string-equal))))
(when str
(let ((pos (search "charset=" str :test #'string-equal)))
(when pos
(incf pos 8)
(let ((epos (position #\; str :start pos :test #'char=)))
(charset-by-name (string-trim " " (subseq str pos epos)))))))))
(defun http-request (url &key (method :get)
post-data (post-start 0) post-end
rawp headers timeout ignore-certificates-p
statuscb recv-buf (recv-start 0) recv-end)
"Send HTTP request to server.
URL ::= string in format [http|https://][username:password@]hostname[:port][/url]
METHOD ::= HTTP verb e.g. :GET, :POST etc
POST-DATA ::= if specified, is an octet vector sent as post data. Uses region bounded
by POST-START and POST-END.
RAWP ::= if true returns octets otherwise return data is parsed as text.
HEADERS ::= list of (header &optional value)* extra headers to add.
TIMEOUT ::= integer milliseconds to wait for connection and receive.
IGNORE-CERTIFICATES-P ::= if true will set option flags to ignore certificate errors.
STATUSCB ::= if non-nil, is a symbol naming a callback defined using define-status-callback.
This will be invoked to inform various status messages.
RECV-BUF ::= if provided, is an octet vector that receives the reply body.
If not supplied a buffer is allocated. Uses region bounded by RECV-START and RECV-END.
Returns values return-data status-code headers content-length.
"
(let ((comp (crack-url url)))
(with-http (hsession)
(when (eq (getf comp :scheme) :https)
(set-secure-protocols hsession :tls1 t :tls1-1 t :tls1-2 t))
(with-connect (hconn hsession (getf comp :hostname) (getf comp :port))
(with-request (hreq hconn
:verb method
:url (getf comp :url)
:https-p (eq (getf comp :scheme) :https))
(when statuscb
(set-status-callback hreq (get-callback statuscb)))
(let ((user (getf comp :username))
(pass (getf comp :password)))
(when (and user pass)
(set-credentials hreq user pass)))
(dolist (h headers)
(add-request-headers hreq (format nil "~A: ~A"
(first h)
(or (second h) ""))))
(when (eq (getf comp :scheme) :https)
(when ignore-certificates-p
(set-ignore-certificates hreq)))
(when timeout (set-timeouts hreq :connect timeout :recv timeout))
(send-request hreq
(if (stringp post-data)
(babel:string-to-octets post-data)
post-data)
:start post-start :end post-end)
(receive-response hreq)
(let* ((headers (query-headers hreq))
(status (query-status-code hreq))
(len (if (integerp recv-buf) recv-buf (* 32 1024)))
(count 0)
(resp (if (vectorp recv-buf)
recv-buf
(make-array len :element-type '(unsigned-byte 8) :adjustable t)))
(resp-start recv-start)
(resp-end recv-end))
(when (> len 0)
(do ((done nil))
(done)
;; if we have allocated a response buffer, check it is large enough
;; if there isn't enough space, use adjust-array to increase the buffer
(let ((nda (query-data-available hreq)))
(when (and (not (vectorp recv-buf))
(> nda (- (length resp) count)))
(adjust-array resp (+ count nda))))
;; receive response data
(let ((n (read-data hreq resp :start (+ resp-start count) :end resp-end)))
(when (zerop n)
(setf done t))
(incf count n)
(when (and resp-end (> (- resp-end resp-start) count))
(setf done t)))))
(values
(if rawp
resp
(let ((encoding (or (get-content-charset headers) :utf-8)))
(babel:octets-to-string resp :end count :encoding encoding)))
status
headers
count)))))))
| 10,324 | Common Lisp | .lisp | 252 | 32.952381 | 106 | 0.587002 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 46b44c19fb5a4f5de0d98f3532155ff8de7970f45b695df562e22fbfce5caf04 | 42,944 | [
393718
] |
42,945 | ffi.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/winhttp-20200610-git/ffi.lisp | ;;;; Copyright (c) Frank James 2017 <[email protected]>
;;;; This code is licensed under the MIT license.
(in-package #:winhttp)
(define-foreign-library winhttp
(:windows "WinHttp.dll"))
(use-foreign-library winhttp)
(defcfun (%format-message "FormatMessageA" :convention :stdcall)
:uint32
(flags :uint32)
(source :pointer)
(msg-id :uint32)
(lang-id :uint32)
(buffer :pointer)
(size :uint32)
(args :pointer))
(defparameter *winhttp-errors*
'((12001 "Out of Handles")
(12002 "Timeout")
(12004 "Internal Error")
(12005 "Invalid URL")
(12006 "Unrecognised scheme")
(12007 "Name not resolved")
(12009 "Invalid Option")
(12011 "Option not settable")
(12012 "Shutdown")
(12015 "Login failure")
(12017 "Operation cancelled")
(12018 "Incorrect handle type")
(12019 "Incorrect handle state")
(12029 "Cannot connect")
(12030 "Connection error")
(12032 "Resend request")
(12044 "Client auth cert needed")
(12100 "Cannot call before open")
(12101 "Cannot call before send")
(12102 "Cannot call after send")
(12103 "Cannot call after open")
(12150 "Header not found")
(12152 "Invalid server response")
(12153 "Invalid header")
(12154 "Invalid query request")
(12155 "Header already exists")
(12156 "Redirect failed")
(12178 "Auto proxy service error")
(12166 "Bad auto proxy script")
(12167 "Unable to download script")
(12176 "Unhandled script type")
(12177 "Script execution error")
(12172 "Not initialized")
(12175 "Secure failure")
(12037 "Certificate date invalid")
(12038 "Certificate CN invalid")
(12045 "Certificate Invalid CA")
(12057 "Certificate Rev failed")
(12157 "Secure channel error")
(12169 "Invalid certificate")
(12170 "Certificate revoked")
(12179 "Certificate wrong usage")
(12180 "Autodecection failed")
(12181 "Header count execeeded")
(12182 "Header size overflow")
(12183 "Chunked encoding header size overflow")
(12184 "Response drain overflow")
(12185 "Client certificate no private key")
(12186 "Client certificate no access private key")))
(defun winhttp-error-string (code)
(cadr (assoc code *winhttp-errors*)))
(defun format-message (code)
"Use FormatMessage to convert the error code into a system-defined string."
(let ((msg (winhttp-error-string code)))
(when msg (return-from format-message msg)))
(with-foreign-object (buffer :char 1024)
(let ((n (%format-message #x00001000
(null-pointer)
code
0
buffer
1024
(null-pointer))))
(if (= n 0)
(let ((ec (%get-last-error)))
(format nil "Failed to format message ~A: ~A"
ec
(format-message ec)))
(foreign-string-to-lisp buffer :count (- n 2))))))
(define-condition win-error (error)
((code :initform 0 :initarg :code :reader win-error-code))
(:report (lambda (condition stream)
(format stream "ERROR ~A: ~A"
(win-error-code condition)
(format-message (win-error-code condition))))))
(defcfun (%get-last-error "GetLastError" :convention :stdcall) :long)
(defun get-last-error ()
(let ((code (%get-last-error)))
(unless (zerop code)
(error 'win-error :code code))))
(defmacro with-wide-string ((var string) &body body)
`(with-foreign-string (,var ,string :encoding :ucs-2)
,@body))
(defmacro with-buffers (bindings &body body)
`(with-foreign-objects (,@(mapcar (lambda (binding)
(destructuring-bind (var len) binding
`(,var :uint8 ,len)))
bindings))
,@body))
(defun memset (p type &optional (val 0))
(dotimes (i (foreign-type-size type))
(setf (mem-aref p :uint8 i) val)))
;; struct URL_COMPONENTS {
;; DWORD dwStructSize;
;; LPWSTR lpszScheme;
;; DWORD dwSchemeLength;
;; int nScheme;
;; LPWSTR lpszHostName;
;; DWORD dwHostNameLength;
;; INTERNET_PORT nPort;
;; LPWSTR lpszUserName;
;; DWORD dwUserNameLength;
;; LPWSTR lpszPassword;
;; DWORD dwPasswordLength;
;; LPWSTR lpszUrlPath;
;; DWORD dwUrlPathLength;
;; LPWSTR lpszExtraInfo;
;; DWORD dwExtraInfoLength;
;; };
(defcstruct url-components
(size :uint32)
(scheme :pointer)
(scheme-len :uint32)
(nscheme :int32) ;; 1==http 2==https 3==ftp?
(hostname :pointer)
(hostname-len :uint32)
(port :uint16)
(username :pointer)
(username-len :uint32)
(password :pointer)
(password-len :uint32)
(url :pointer)
(url-len :uint32)
(extra :pointer)
(extra-len :uint32))
;; BOOL WINAPI WinHttpCrackUrl(
;; _In_ LPCWSTR pwszUrl,
;; _In_ DWORD dwUrlLength,
;; _In_ DWORD dwFlags,
;; _Inout_ LPURL_COMPONENTS lpUrlComponents
;; );
(defconstant +icu-escape+ #x80000000)
(defconstant +icu-decode+ #x10000000)
(defcfun (%crack-url "WinHttpCrackUrl" :convention :stdcall) :boolean
(url :pointer)
(url-len :uint32)
(flags :uint32)
(components :pointer))
(defun crack-url (url)
"Parse a URL into its components."
(declare (type string url))
(with-foreign-objects ((comp '(:struct url-components)))
(with-wide-string (ustr url)
(with-buffers ((hostname 512)
(scheme 64)
(url 512)
(extra 512)
(user 512)
(pass 512))
(memset comp '(:struct url-components))
(setf (foreign-slot-value comp '(:struct url-components) 'size)
(foreign-type-size '(:struct url-components))
(foreign-slot-value comp '(:struct url-components) 'hostname)
hostname
(foreign-slot-value comp '(:struct url-components) 'hostname-len)
256
(foreign-slot-value comp '(:struct url-components) 'scheme)
scheme
(foreign-slot-value comp '(:struct url-components) 'scheme-len)
32
(foreign-slot-value comp '(:struct url-components) 'url)
url
(foreign-slot-value comp '(:struct url-components) 'url-len)
256
(foreign-slot-value comp '(:struct url-components) 'username)
user
(foreign-slot-value comp '(:struct url-components) 'username-len)
256
(foreign-slot-value comp '(:struct url-components) 'password)
pass
(foreign-slot-value comp '(:struct url-components) 'password-len)
256
(foreign-slot-value comp '(:struct url-components) 'extra)
extra
(foreign-slot-value comp '(:struct url-components) 'extra-len)
256)
(let ((res (%crack-url ustr 0 +icu-escape+ comp)))
(unless res (get-last-error))
(list :scheme (let ((s (foreign-slot-value comp '(:struct url-components) 'nscheme)))
(ecase s
(1 :http)
(2 :https)
(3 :ftp)))
:url (foreign-string-to-lisp url :encoding :ucs-2le)
:hostname (foreign-string-to-lisp hostname :encoding :ucs-2le)
:username (let ((u (foreign-string-to-lisp user :encoding :ucs-2le)))
(unless (string= u "") u))
:password (let ((p (foreign-string-to-lisp pass :encoding :ucs-2le)))
(unless (string= p "") p))
:extra (foreign-string-to-lisp extra :encoding :ucs-2le)
:port (let ((p (foreign-slot-value comp '(:struct url-components) 'port)))
(cond
((zerop p)
(let ((s (foreign-slot-value comp '(:struct url-components) 'nscheme)))
(cond
((= s 1) 80)
((= s 2) 443)
((= s 3) 21)
(t 80))))
(t p)))))))))
(defconstant +access-no-proxy+ 1)
;; HINTERNET WINAPI WinHttpOpen(
;; _In_opt_ LPCWSTR pwszUserAgent,
;; _In_ DWORD dwAccessType,
;; _In_ LPCWSTR pwszProxyName,
;; _In_ LPCWSTR pwszProxyBypass,
;; _In_ DWORD dwFlags
;; );
(defcfun (%http-open "WinHttpOpen" :convention :stdcall) :pointer
(user :pointer)
(access-type :uint32)
(proxy :pointer)
(bypass :pointer)
(flags :uint32))
(defun http-open (&optional user-agent)
(with-wide-string (u (or user-agent "winhttp"))
(let ((h (%http-open u
+access-no-proxy+
(null-pointer)
(null-pointer)
0)))
(when (null-pointer-p h) (get-last-error))
h)))
;; BOOL WINAPI WinHttpCloseHandle(
;; _In_ HINTERNET hInternet
;; );
(defcfun (%close-handle "WinHttpCloseHandle" :convention :stdcall) :bool
(h :pointer))
(defun close-handle (h)
(let ((res (%close-handle h)))
(unless res (get-last-error))))
(defconstant +addreq-add+ #x20000000)
(defconstant +addreq-replace+ #x80000000)
;; BOOL WINAPI WinHttpAddRequestHeaders(
;; _In_ HINTERNET hRequest,
;; _In_ LPCWSTR pwszHeaders,
;; _In_ DWORD dwHeadersLength,
;; _In_ DWORD dwModifiers
;; );
(defcfun (%add-request-headers "WinHttpAddRequestHeaders" :convention :stdcall) :boolean
(hreq :pointer)
(headers :pointer)
(len :uint32)
(modifiers :uint32))
(defun add-request-headers (hreq header)
(with-wide-string (h header)
(let ((res (%add-request-headers hreq
h
#xffffffff
(logior +addreq-add+ +addreq-replace+))))
(unless res (get-last-error)))))
;; HINTERNET WINAPI WinHttpConnect(
;; _In_ HINTERNET hSession,
;; _In_ LPCWSTR pswzServerName,
;; _In_ INTERNET_PORT nServerPort,
;; _Reserved_ DWORD dwReserved
;; );
(defcfun (%http-connect "WinHttpConnect" :convention :stdcall) :pointer
(hsession :pointer)
(server :pointer)
(port :uint16)
(reserved :uint32))
(defun http-connect (hsession hostname &optional port)
(with-wide-string (s hostname)
(let ((res (%http-connect hsession s (or port 80) 0)))
(when (null-pointer-p res) (get-last-error))
res)))
(defconstant +flag-secure+ #x00800000)
;; HINTERNET WINAPI WinHttpOpenRequest(
;; _In_ HINTERNET hConnect,
;; _In_ LPCWSTR pwszVerb,
;; _In_ LPCWSTR pwszObjectName,
;; _In_ LPCWSTR pwszVersion,
;; _In_ LPCWSTR pwszReferrer,
;; _In_ LPCWSTR *ppwszAcceptTypes,
;; _In_ DWORD dwFlags
;; );
(defcfun (%win-http-open-request "WinHttpOpenRequest" :convention :stdcall) :pointer
(hconnect :pointer)
(verb :pointer)
(object :pointer)
(version :pointer)
(referrer :pointer)
(accept-types :pointer)
(flags :uint32))
(defun http-open-request (hconnect &key verb url https-p)
(with-wide-string (ustr (or url ""))
(with-wide-string (vstr (if verb
(string-upcase (string verb))
"GET"))
(let ((hreq (%win-http-open-request hconnect
vstr
ustr
(null-pointer)
(null-pointer)
(null-pointer)
(if https-p +flag-secure+ 0))))
(when (null-pointer-p hreq) (get-last-error))
hreq))))
(defparameter *info-levels*
'((:mime-version 0)
(:content-type 1)
(:content-transfer-encoding 2)
(:content-id 3)
(:content-description 4)
(:content-length 5)
(:content-language 6)
(:allow 7)
(:public 8)
(:date 9)
(:expires 10)
(:last-modified 11)
(:message-id 12)
(:uri 13)
(:derived-from 14)
(:cost 15)
(:link 16)
(:pragma 17)
(:version 18)
(:status-code 19)
(:status-text 20)
(:raw-headers 21)
(:raw-headers-crlf 22)
(:connection 23)
(:accept 24)
(:accept-charset 25)
(:accept-encoding 26)
(:accept-language 27)
(:authorization 28)
(:content-encoding 29)
(:forwarded 30)
(:from 31)
(:if-modified-since 32)
(:location 33)
(:orig-uri 34)
(:referer 35)
(:retry-after 36)
(:server 37)
(:title 38)
(:user-agent 39)
(:www-authenticate 40)
(:proxy-authenticate 41)
(:accept-ranges 42)
(:set-cookie 43)
(:cookie 44)
(:request-method 45)
(:refresh 46)
(:content-disposition 47)
(:age 48)
(:cache-control 49)
(:content-base 50)
(:content-location 51)
(:content-md5 52)
(:content-range 53)
(:etag 54)
(:host 55)
(:if-match 56)
(:if-none-match 57)
(:if-range 58)
(:if-unmodified-since 59)
(:max-forwards 60)
(:proxy-authorization 61)
(:range 62)
(:transfer-encoding 63)
(:upgrade 64)
(:vary 65)
(:via 66)
(:warning 67)
(:expect 68)
(:proxy-connection 69)
(:unless-modified-since 70)
(:proxy-support 75)
(:authentication-info 76)
(:passport-urls 77)
(:passport-config 78)))
(defun query-info-level (name)
(cadr (assoc name *info-levels*)))
;; BOOL WINAPI WinHttpQueryHeaders(
;; _In_ HINTERNET hRequest,
;; _In_ DWORD dwInfoLevel,
;; _In_opt_ LPCWSTR pwszName,
;; _Out_ LPVOID lpBuffer,
;; _Inout_ LPDWORD lpdwBufferLength,
;; _Inout_ LPDWORD lpdwIndex
;; );
(defcfun (%http-query-headers "WinHttpQueryHeaders" :convention :stdcall) :boolean
(hreq :pointer)
(info :uint32)
(name :pointer)
(buf :pointer)
(len :pointer)
(idx :pointer))
(defun query-headers (hreq)
(with-foreign-objects ((buf :uint8 (* 1024 32))
(len :uint32))
(setf (mem-aref len :uint32) (* 1024 32))
(let ((res (%http-query-headers hreq
(query-info-level :raw-headers-crlf)
(null-pointer)
buf
len
(null-pointer))))
(unless res (get-last-error)))
(let ((hstr (foreign-string-to-lisp buf :encoding :ucs-2le :count (mem-aref len :uint32))))
(with-input-from-string (s hstr)
(do ((l (read-line s nil nil) (read-line s nil nil))
(hlist nil))
((null l) (reverse hlist))
(setf l (remove #\return l :test #'char=))
(let ((pos (position #\: l :test #'char=)))
(when pos
(push (list (subseq l 0 pos)
(subseq l (+ pos 2)))
hlist))))))))
(defun query-status-code (hreq)
(with-foreign-objects ((buf :uint8 64)
(len :uint32))
(setf (mem-aref len :uint32) 64)
(let ((res (%http-query-headers hreq
(query-info-level :status-code)
(null-pointer)
buf
len
(null-pointer))))
(unless res (get-last-error)))
(parse-integer (foreign-string-to-lisp buf :encoding :ucs-2le))))
;; BOOL WINAPI WinHttpReadData(
;; _In_ HINTERNET hRequest,
;; _Out_ LPVOID lpBuffer,
;; _In_ DWORD dwNumberOfBytesToRead,
;; _Out_ LPDWORD lpdwNumberOfBytesRead
;; );
(defcfun (%read-data "WinHttpReadData" :convention :stdcall) :boolean
(hreq :pointer)
(buf :pointer)
(len :uint32)
(nbytes :pointer))
(defun read-data (hreq seq &key (start 0) end)
(let ((count (- (or end (length seq)) start)))
(with-foreign-object (buf :uint8 count)
(with-foreign-object (nbytes :uint32)
(let ((res (%read-data hreq buf count nbytes)))
(unless res (get-last-error))
(dotimes (i (mem-aref nbytes :uint32))
(setf (aref seq (+ i start)) (mem-aref buf :uint8 i)))
(mem-aref nbytes :uint32))))))
;; BOOL WINAPI WinHttpReceiveResponse(
;; _In_ HINTERNET hRequest,
;; _Reserved_ LPVOID lpReserved
;; );
(defcfun (%receive-response "WinHttpReceiveResponse" :convention :stdcall) :boolean
(hreq :pointer)
(reserved :pointer))
(defun receive-response (hreq)
(let ((res (%receive-response hreq (null-pointer))))
(unless res (get-last-error))
nil))
;; BOOL WINAPI WinHttpSendRequest(
;; _In_ HINTERNET hRequest,
;; _In_opt_ LPCWSTR pwszHeaders,
;; _In_ DWORD dwHeadersLength,
;; _In_opt_ LPVOID lpOptional,
;; _In_ DWORD dwOptionalLength,
;; _In_ DWORD dwTotalLength,
;; _In_ DWORD_PTR dwContext
;; );
(defcfun (%send-request "WinHttpSendRequest" :convention :stdcall) :boolean
(hreq :pointer)
(headers :pointer)
(hlen :uint32)
(optional :pointer)
(len :uint32)
(total :uint32)
(context :pointer))
(defun send-request (hreq seq &key (start 0) end)
(let ((count (- (or end (length seq)) start)))
(with-foreign-object (buf :uint8 count)
(dotimes (i count)
(setf (mem-aref buf :uint8 i) (aref seq (+ start i))))
(let ((res (%send-request hreq
(null-pointer)
0
buf
count
count
(null-pointer))))
(unless res (get-last-error))
nil))))
;; BOOL WINAPI WinHttpQueryDataAvailable(
;; _In_ HINTERNET hRequest,
;; _Out_ LPDWORD lpdwNumberOfBytesAvailable
;; );
(defcfun (%query-data-available "WinHttpQueryDataAvailable" :convention :stdcall) :boolean
(hreq :pointer)
(nbytes :pointer))
(defun query-data-available (hreq)
(with-foreign-object (nbytes :uint32)
(let ((res (%query-data-available hreq nbytes)))
(unless res (get-last-error))
(mem-aref nbytes :uint32))))
;; BOOL WINAPI WinHttpSetCredentials(
;; _In_ HINTERNET hRequest,
;; _In_ DWORD AuthTargets,
;; _In_ DWORD AuthScheme,
;; _In_ LPCWSTR pwszUserName,
;; _In_ LPCWSTR pwszPassword,
;; _Reserved_ LPVOID pAuthParams
;; );
(defcfun (%set-credentials "WinHttpSetCredentials" :convention :stdcall) :boolean
(hreq :pointer)
(targets :uint32)
(scheme :uint32)
(username :pointer)
(password :pointer)
(params :pointer))
(defun set-credentials (hreq username password &optional (scheme :basic) (target :server))
(with-wide-string (ustr username)
(with-wide-string (pstr password)
(let ((res (%set-credentials hreq
(ecase target
(:server 0)
(:proxy 1))
(ecase scheme
(:basic 1)
(:ntlm 2)
(:passport 4)
(:digest 8)
(:negotiate 16))
(if (eq scheme :negotiate) (null-pointer) ustr)
(if (eq scheme :negotiate) (null-pointer) pstr)
(null-pointer))))
(unless res (get-last-error))
nil))))
;; BOOL WINAPI WinHttpSetOption(
;; _In_ HINTERNET hInternet,
;; _In_ DWORD dwOption,
;; _In_ LPVOID lpBuffer,
;; _In_ DWORD dwBufferLength
;; );
(defcfun (%set-option "WinHttpSetOption" :convention :stdcall) :boolean
(hreq :pointer)
(option :uint32)
(buf :pointer)
(len :uint32))
(defun set-ignore-certificates (hreq)
(with-foreign-object (buf :uint32)
(setf (mem-aref buf :uint32)
(logior #x0100 ;; ignore-unknown-ca
#x2000 ;; ignore-data-invalid
#x1000 ;; ignore-cert-cn-invalid
#x0200 ;; ignore-wrong-usage
;; #x00010000 ;; SECURITY_FLAG_IGNORE_WEAK_SIGNATURE
;; #x10000000 ;; SECURITY_FLAG_STRENGTH_WEAK
;; #x20000000 ;; SECURITY_FLAG_STRENGTH_STRONG
;; #x40000000 ;; SECURITY_FLAG_STRENTH_MEDIUM
0))
(let ((ret (%set-option hreq
31 ;; WINHTTP_OPTION_SECURITY_FLAGS
buf
4)))
(unless ret
(get-last-error))))
nil)
(defun set-secure-protocols (hinternet &key ssl2 ssl3 tls1 tls1-1 tls1-2)
"Set the TLS protocols that can be used for a session.
HINTERNET ::= session handle."
(let ((prots
(logior (if ssl2 #x0008 0)
(if ssl3 #x0020 0)
(if tls1 #x0080 0)
(if tls1-1 #x0200 0)
(if tls1-2 #x0800 0))))
(with-foreign-object (buf :uint32)
(setf (mem-aref buf :uint32) prots)
(let ((ret (%set-option hinternet
84 ;; WINHTTP_OPTION_SECURE_PROTOCOLS
buf 4)))
(unless ret
(get-last-error))))))
;; BOOL WINAPI WinHttpQueryAuthSchemes(
;; _In_ HINTERNET hRequest,
;; _Out_ LPDWORD lpdwSupportedSchemes,
;; _Out_ LPDWORD lpdwFirstScheme,
;; _Out_ LPDWORD pdwAuthTarget
;; );
;; BOOL WINAPI WinHttpSetTimeouts(
;; _In_ HINTERNET hInternet,
;; _In_ int dwResolveTimeout,
;; _In_ int dwConnectTimeout,
;; _In_ int dwSendTimeout,
;; _In_ int dwReceiveTimeout
;; );
(defcfun (%set-timeouts "WinHttpSetTimeouts" :convention :stdcall) :boolean
(hreq :pointer)
(resolve :int32)
(connect :int32)
(send :int32)
(recv :int32))
(defun set-timeouts (hreq &key resolve connect send recv)
(let ((res (%set-timeouts hreq
(or resolve 0)
(or connect 0)
(or send 0)
(or recv 0))))
(unless res (get-last-error))
nil))
;; WINHTTPAPI WINHTTP_STATUS_CALLBACK WinHttpSetStatusCallback(
;; IN HINTERNET hInternet,
;; IN WINHTTP_STATUS_CALLBACK lpfnInternetCallback,
;; IN DWORD dwNotificationFlags,
;; IN DWORD_PTR dwReserved
;; );
(defcfun (%set-status-callback "WinHttpSetStatusCallback" :convention :stdcall)
:pointer
(hinternet :pointer)
(callback :pointer)
(flags :uint32)
(reserved :pointer))
(defun set-status-callback (hinternet callback)
"Set a callback to receive status updates. This can be used to track
progress of an HTTP request.
HINTERNET ::= request handle
CALLBACK ::= foreign callback address.
"
(%set-status-callback hinternet callback #xffffffff (null-pointer)))
;; WINHTTPAPI DWORD WinHttpWebSocketClose(
;; HINTERNET hWebSocket,
;; USHORT usStatus,
;; PVOID pvReason,
;; DWORD dwReasonLength
;; );
(defcfun (%websocket-close "WinHttpWebSocketClose" :convention :stdcall) :uint32
(hwebsocket :pointer)
(status :uint16)
(reason :pointer)
(creason :uint32))
(defun websocket-close (hwebsocket &optional status)
"Close the websocket handle"
(%websocket-close hwebsocket
(or status 0)
(null-pointer)
0))
;; typedef enum _WINHTTP_WEB_SOCKET_CLOSE_STATUS {
;; WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_ENDPOINT_TERMINATED_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_PROTOCOL_ERROR_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_INVALID_DATA_TYPE_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_EMPTY_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_ABORTED_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_INVALID_PAYLOAD_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_POLICY_VIOLATION_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_MESSAGE_TOO_BIG_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_UNSUPPORTED_EXTENSIONS_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_SERVER_ERROR_CLOSE_STATUS,
;; WINHTTP_WEB_SOCKET_SECURE_HANDSHAKE_ERROR_CLOSE_STATUS
;; } WINHTTP_WEB_SOCKET_CLOSE_STATUS;
;; WINHTTPAPI HINTERNET WinHttpWebSocketCompleteUpgrade(
;; HINTERNET hRequest,
;; DWORD_PTR pContext
;; );
(defcfun (%websocket-complete-upgrade "WinHttpWebSocketCompleteUpgrade" :convention :stdcall) :pointer
(hreq :pointer)
(pcxt :pointer))
(defun websocket-complete-upgrade (hrequest)
"Complete the upgrade to the websocket. returns the websocket handle. The request handle can now be closed."
(let ((res (%websocket-complete-upgrade hrequest (null-pointer))))
(if (null-pointer-p res)
(get-last-error)
res)))
;; WINHTTPAPI DWORD WinHttpWebSocketQueryCloseStatus(
;; HINTERNET hWebSocket,
;; USHORT *pusStatus,
;; PVOID pvReason,
;; DWORD dwReasonLength,
;; DWORD *pdwReasonLengthConsumed
;; );
(defcfun (%websocket-query-close-status "WinHttpWebSocketQueryCloseStatus" :convention :stdcall) :uint32
(hwebsocket :pointer)
(status :pointer)
(reason :pointer)
(creason :uint32)
(reasonlength :pointer))
(defun websocket-query-close-status (hwebsocket)
"Get the websocket close status."
(with-foreign-objects ((status :uint16)
(reason :uint8 128)
(count :uint32))
(%websocket-query-close-status hwebsocket
status
reason
128
count)
(values (mem-aref status :uint16)
(foreign-string-to-lisp reason :count (mem-aref count :uint32)))))
;; WINHTTPAPI DWORD WinHttpWebSocketReceive(
;; HINTERNET hWebSocket,
;; PVOID pvBuffer,
;; DWORD dwBufferLength,
;; DWORD *pdwBytesRead,
;; WINHTTP_WEB_SOCKET_BUFFER_TYPE *peBufferType
;; );
(defcfun (%websocket-recv "WinHttpWebSocketReceive" :convention :stdcall) :uint32
(hwebsocket :pointer)
(buffer :pointer)
(cbuffer :uint32)
(nbytes :pointer)
(buffertype :pointer))
(defun websocket-receive (hwebsocket seq &key (start 0) end)
"Receive some data.
HWEBSOCKET ::= the websocket handke
SEQ ::= buffer that receives the data
START, END ::= buffer region to fill in
returns values count buffer-type, where
COUNT ::= number of bytes received
BUFFER-TYPE ::= type of message received
"
(let ((count (- (or end (length seq)) start)))
(with-foreign-objects ((buf :uint8 count)
(nbytes :uint32)
(btype :uint32))
(let ((sts (%websocket-recv hwebsocket
buf
count
nbytes
btype)))
(unless (zerop sts)
(error "Failed ~S" sts)))
(dotimes (i (mem-aref nbytes :uint32))
(setf (aref seq (+ start i)) (mem-aref buf :uint8 i)))
(values (mem-aref nbytes :uint32) (get-buffer-type (mem-aref btype :uint32))))))
;; WINHTTPAPI DWORD WinHttpWebSocketSend(
;; HINTERNET hWebSocket,
;; WINHTTP_WEB_SOCKET_BUFFER_TYPE eBufferType,
;; PVOID pvBuffer,
;; DWORD dwBufferLength
;; );
(defcfun (%websocket-send "WinHttpWebSocketSend" :convention :stdcall) :uint32
(hwebsocket :pointer)
(btype :uint32)
(buf :pointer)
(cbuf :uint32))
(defun websocket-send (hwebsocket seq &key (start 0) end buffer-type)
"Send some data on a websocket.
HWEBSOCKET ::= websocket handle
SEQ ::= buffer
START,END ::= buffer region to send
BUFFER-TYPE ::= type of message"
(let ((count (- (or end (length seq)) start)))
(with-foreign-objects ((buf :uint8 count))
(let ((sts (%websocket-send hwebsocket
(if buffer-type
(get-buffer-type buffer-type)
0)
buf
count)))
(unless (zerop sts)
(error "Failed ~S" sts)))))
nil)
;; WINHTTPAPI DWORD WinHttpWebSocketShutdown(
;; HINTERNET hWebSocket,
;; USHORT usStatus,
;; PVOID pvReason,
;; DWORD dwReasonLength
;; );
(defcfun (%websocket-shutdown "WinHttpWebSocketShutdown" :convention :stdcall) :uint32
(hwebsocket :pointer)
(status :uint16)
(reason :pointer)
(creason :uint32))
(defun websocket-shutdown (hwebsocket &optional status)
"Shutdown a websocket"
(%websocket-shutdown hwebsocket
(or status 0)
(null-pointer)
0))
;; typedef enum _WINHTTP_WEB_SOCKET_BUFFER_TYPE {
;; WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE,
;; WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE,
;; WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE,
;; WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE,
;; WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE
;; } WINHTTP_WEB_SOCKET_BUFFER_TYPE;
(defconstant +websocket-binary-message+ 0)
(defconstant +websocket-binary-fragment+ 1)
(defconstant +websocket-utf8-message+ 2)
(defconstant +websocket-utf8-fragment+ 3)
(defconstant +websocket-close+ 4)
(defun get-buffer-type (buffertype)
(ecase buffertype
(0 :binary)
(1 :binary-fragment)
(2 :utf8)
(3 :utf8-fragment)
(4 :close)
(:binary 0)
(:binary-fragment 1)
(:utf8 2)
(:utf8-fragment 3)
(:close 4)))
(defconstant +WINHTTP-OPTION-UPGRADE-TO-WEB-SOCKET+ 114)
(defun upgrade-to-websocket (hrequest)
"Call this before the initial SEND-REQUEST call."
(%set-option hrequest
+WINHTTP-OPTION-UPGRADE-TO-WEB-SOCKET+
(null-pointer)
0))
(defmacro with-websocket ((var hostname port &key url https-p) &body body)
"Bind VAR to a websocket connected to hostname:port/url."
(let ((ghttp (gensym))
(ghconnect (gensym))
(ghreq (gensym)))
`(with-http (,ghttp)
(with-connect (,ghconnect ,ghttp ,hostname ,port)
(with-request (,ghreq ,ghconnect :url ,url :https-p ,https-p)
(upgrade-to-websocket ,ghreq)
(send-request ,ghreq nil :end 0)
(receive-response ,ghreq)
(let ((,var (websocket-complete-upgrade ,ghreq)))
(unwind-protect (progn ,@body)
(websocket-close ,var))))))))
| 27,592 | Common Lisp | .lisp | 836 | 28.840909 | 110 | 0.647623 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 82d6c81dc6442d81a8cef900428323132912f132ed7b2f2fdec7ad82ddfe07cf | 42,945 | [
381586
] |
42,946 | xmlrpc.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/winhttp-20200610-git/examples/xmlrpc.lisp | ;;;; Most code taken from S-XML-RPC and is licensed under the terms of
;;;; the Lisp Lesser General Public License (LLGPL)
;;;;
(eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload "cl-base64")
(ql:quickload "s-xml"))
(defpackage #:xmlrpc
(:use #:cl)
(:export #:call
#:xmlrpc-struct
#:xmlrpc-member))
(in-package #:xmlrpc)
;;; conditions
(define-condition xml-rpc-condition (error)
()
(:documentation "Parent condition for all conditions thrown by the XML-RPC package"))
(define-condition xml-rpc-fault (xml-rpc-condition)
((code :initarg :code :reader xml-rpc-fault-code)
(string :initarg :string :reader xml-rpc-fault-string))
(:report (lambda (condition stream)
(format stream
"XML-RPC fault with message '~a' and code ~d."
(xml-rpc-fault-string condition)
(xml-rpc-fault-code condition))))
(:documentation "This condition is thrown when the XML-RPC server returns a fault"))
(setf (documentation 'xml-rpc-fault-code 'function) "Get the code from an XML-RPC fault")
(setf (documentation 'xml-rpc-fault-string 'function) "Get the string from an XML-RPC fault")
(define-condition xml-rpc-error (xml-rpc-condition)
((place :initarg :code :reader xml-rpc-error-place)
(data :initarg :data :reader xml-rpc-error-data))
(:report (lambda (condition stream)
(format stream
"XML-RPC error ~a at ~a."
(xml-rpc-error-data condition)
(xml-rpc-error-place condition))))
(:documentation "This condition is thrown when an XML-RPC protocol error occurs"))
(setf (documentation 'xml-rpc-error-place 'function)
"Get the place from an XML-RPC error"
(documentation 'xml-rpc-error-data 'function)
"Get the data from an XML-RPC error")
;;; iso8601 support (the xml-rpc variant)
(defun universal-time->iso8601 (time &optional (stream nil))
"Convert a Common Lisp universal time to a string in the XML-RPC variant of ISO8601"
(multiple-value-bind (second minute hour date month year)
(decode-universal-time time)
(format stream
"~d~2,'0d~2,'0dT~2,'0d:~2,'0d:~2,'0d"
year
month
date
hour
minute
second)))
(defun iso8601->universal-time (string)
"Convert string in the XML-RPC variant of ISO8601 to a Common Lisp universal time"
(let (year month date (hour 0) (minute 0) (second 0))
(when (< (length string) 9)
(error "~s is to short to represent an iso8601" string))
(setf year (parse-integer string :start 0 :end 4)
month (parse-integer string :start 4 :end 6)
date (parse-integer string :start 6 :end 8))
(when (and (>= (length string) 17) (char= #\T (char string 8)))
(setf hour (parse-integer string :start 9 :end 11)
minute (parse-integer string :start 12 :end 14)
second (parse-integer string :start 15 :end 17)))
(encode-universal-time second minute hour date month year)))
(defstruct (xml-rpc-time (:print-function print-xml-rpc-time))
"A wrapper around a Common Lisp universal time to be interpreted as an XML-RPC-TIME"
universal-time)
(setf (documentation 'xml-rpc-time-p 'function)
"Return T when the argument is an XML-RPC time"
(documentation 'xml-rpc-time-universal-time 'function)
"Return the universal time from an XML-RPC time")
(defun print-xml-rpc-time (xml-rpc-time stream depth)
(declare (ignore depth))
(format stream
"#<XML-RPC-TIME ~a>"
(universal-time->iso8601 (xml-rpc-time-universal-time xml-rpc-time))))
(defun xml-rpc-time (&optional (universal-time (get-universal-time)))
"Create a new XML-RPC-TIME struct with the universal time specified, defaulting to now"
(make-xml-rpc-time :universal-time universal-time))
;;; a wrapper for literal strings, where escaping #\< and #\& is not
;;; desired
(defstruct (xml-literal (:print-function print-xml-literal))
"A wrapper around a Common Lisp string that will be sent over
the wire unescaped"
content)
(setf (documentation 'xml-literal-p 'function)
"Return T when the argument is an unescaped xml string"
(documentation 'xml-literal-content 'function)
"Return the content of a literal xml string")
(defun print-xml-literal (xml-literal stream depth)
(declare (ignore depth))
(format stream
"#<XML-LITERAL \"~a\" >"
(xml-literal-content xml-literal)))
(defun xml-literal (content)
"Create a new XML-LITERAL struct with the specified content."
(make-xml-literal :content content))
;;; an extra datatype for xml-rpc structures (associative maps)
(defstruct (xml-rpc-struct (:print-function print-xml-rpc-struct))
"An XML-RPC-STRUCT is an alist mapping member names to values"
alist)
(setf (documentation 'xml-rpc-struct-p 'function)
"Return T when the argument is an XML-RPC struct"
(documentation 'xml-rpc-struct-alist 'function)
"Return the alist of member names and values from an XML-RPC struct")
(defun print-xml-rpc-struct (xml-element stream depth)
(declare (ignore depth))
(format stream "#<XML-RPC-STRUCT :KEYS ~S>"
(mapcar #'car (xml-rpc-struct-alist xml-element))))
(defun (setf xml-rpc-struct-member) (value struct &rest keys)
"Set the value of a specific member of an XML-RPC-STRUCT"
(do ((keys keys (cdr keys))
(obj struct (if (integerp (car keys))
(elt obj (car keys))
(cdr (assoc (car keys) (xml-rpc-struct-alist obj))))))
((null (cdr keys))
(if (integerp (car keys))
(setf (elt obj (car keys)) value)
(setf (cdr (assoc (car keys) (xml-rpc-struct-alist obj))) value))))
value)
(defun xml-rpc-struct-member (struct &rest keys)
"Find a member of a structure."
(do ((keys keys (cdr keys))
(obj struct (let ((key (car keys)))
(if (integerp key)
(elt obj key)
(cdr (assoc key (xml-rpc-struct-alist obj) :test #'string-equal))))))
((null keys) obj)))
(defun xml-rpc-struct (&rest args)
"Create a new XML-RPC-STRUCT from the arguments: alternating member names and values"
(unless (evenp (length args))
(error "~s must contain an even number of elements" args))
(let (alist)
(loop (if (null args)
(return)
(push (cons (pop args) (pop args)) alist)))
(make-xml-rpc-struct :alist alist)))
(defun xml-rpc-struct-equal (struct1 struct2)
"Compare two XML-RPC-STRUCTs for equality"
(equal (xml-rpc-struct-alist struct1)
(xml-rpc-struct-alist struct2)))
;;; encoding support
(defun encode-xml-rpc-struct (struct stream)
(princ "<struct>" stream)
(mapcar (lambda (pair)
(destructuring-bind (key . value) pair
(princ "<member>" stream)
(format stream "<name>~a</name>" key) ; assuming name contains no special characters
(encode-xml-rpc-value value stream)
(princ "</member>" stream)))
(xml-rpc-struct-alist struct))
(princ "</struct>" stream))
(defun encode-xml-rpc-array (sequence stream)
(princ "<array><data>" stream)
(map 'nil #'(lambda (element) (encode-xml-rpc-value element stream)) sequence)
(princ "</data></array>" stream))
(defun encode-xml-rpc-value (arg stream)
(princ "<value>" stream)
(cond ((or (null arg) (eq arg t))
(princ "<boolean>" stream)
(princ (if arg 1 0) stream)
(princ "</boolean>" stream))
((or (stringp arg) (symbolp arg))
(princ "<string>" stream)
(s-xml:print-string-xml (string arg) stream)
(princ "</string>" stream))
((integerp arg) (format stream "<int>~d</int>" arg))
((floatp arg) (format stream "<double>~f</double>" arg))
((and (arrayp arg)
(= (array-rank arg) 1)
(subtypep (array-element-type arg)
'(unsigned-byte 8)))
(princ "<base64>" stream)
(cl-base64:usb8-array-to-base64-stream arg stream)
(princ "</base64>" stream))
((xml-rpc-time-p arg)
(princ "<dateTime.iso8601>" stream)
(universal-time->iso8601 (xml-rpc-time-universal-time arg) stream)
(princ "</dateTime.iso8601>" stream))
((xml-literal-p arg)
(princ (xml-literal-content arg) stream))
((or (listp arg) (vectorp arg)) (encode-xml-rpc-array arg stream))
((xml-rpc-struct-p arg) (encode-xml-rpc-struct arg stream))
;; add generic method call
(t (error "cannot encode ~s" arg)))
(princ "</value>" stream))
(defun encode-xml-rpc-args (args stream)
(princ "<params>" stream)
(dolist (arg args)
(princ "<param>" stream)
(encode-xml-rpc-value arg stream)
(princ "</param>" stream))
(princ "</params>" stream))
(defun encode-xml-rpc-call (name &rest args)
"Encode an XML-RPC call with name and args as an XML string"
(with-output-to-string (stream)
(princ "<methodCall>" stream)
;; Spec says: The string may only contain identifier characters,
;; upper and lower-case A-Z, the numeric characters, 0-9,
;; underscore, dot, colon and slash.
(format stream "<methodName>~a</methodName>" (string name)) ; assuming name contains no special characters
(when args
(encode-xml-rpc-args args stream))
(princ "</methodCall>" stream)))
(defun encode-xml-rpc-result (value)
(with-output-to-string (stream)
(princ "<methodResponse>" stream)
(encode-xml-rpc-args (list value) stream)
(princ "</methodResponse>" stream)))
(defun encode-xml-rpc-fault-value (fault-string &optional (fault-code 0))
;; for system.multicall
(with-output-to-string (stream)
(princ "<struct>" stream)
(format stream "<member><name>faultCode</name><value><int>~d</int></value></member>" fault-code)
(princ "<member><name>faultString</name><value><string>" stream)
(s-xml:print-string-xml fault-string stream)
(princ "</string></value></member>" stream)
(princ "</struct>" stream)))
(defun encode-xml-rpc-fault (fault-string &optional (fault-code 0))
(with-output-to-string (stream)
(princ "<methodResponse><fault><value>" stream)
(princ (encode-xml-rpc-fault-value fault-string fault-code) stream)
(princ "</value></fault></methodResponse>" stream)))
;;; decoding support
(defparameter *decode-value-types* nil)
(defun decode-xml-rpc-new-element (name attributes seed)
(declare (ignore seed name attributes))
'())
(defun decode-xml-rpc-finish-element (name attributes parent-seed seed)
(declare (ignore attributes))
(cons (ecase name
((:|int| :|i4|)
(if *decode-value-types*
:int
(parse-integer seed)))
(:|double|
(if *decode-value-types*
:double
(read-from-string seed)))
(:|boolean|
(if *decode-value-types*
:boolean
(= 1 (parse-integer seed))))
(:|string|
(if *decode-value-types*
:string
(if (null seed) "" seed)))
(:|dateTime.iso8601|
(if *decode-value-types*
:datetime
(xml-rpc-time (iso8601->universal-time seed))))
(:|base64|
(if (null seed)
(make-array 0 :element-type '(unsigned-byte 8))
(cl-base64:base64-string-to-usb8-array seed)))
(:|array| (car seed))
(:|data| (nreverse seed)) ; potential problem with empty data i.e. <data>\n</data> parsed as "\n"
(:|value| (if (stringp seed) seed (car seed)))
(:|struct| (make-xml-rpc-struct :alist seed))
(:|member| (cons (cadr seed) (car seed)))
(:|name| seed) ;;(intern seed :keyword))
(:|params| (nreverse seed)) ; potential problem with empty params <params>\n</params> parsed as "\n"
(:|param| (car seed))
(:|fault| (make-condition 'xml-rpc-fault
:string (xml-rpc-struct-member (car seed) :|faultString|)
:code (xml-rpc-struct-member (car seed) :|faultCode|)))
(:|methodName| seed)
(:|methodCall| (let ((pair (nreverse seed)))
(cons (car pair) (cadr pair))))
(:|methodResponse| (car seed)))
parent-seed))
;; fixes issue with empty params, data
(defun decode-xml-rpc-text (string seed)
(declare (ignore seed))
(if (> (length (string-trim '(#\Space #\Newline #\Return)
string))
0)
string
nil))
(defun decode-xml-rpc (stream)
(car (s-xml:start-parse-xml
stream
(make-instance 's-xml:xml-parser-state
:new-element-hook #'decode-xml-rpc-new-element
:finish-element-hook #'decode-xml-rpc-finish-element
:text-hook #'decode-xml-rpc-text))))
;;;; Copyright (c) Frank James 2017 <[email protected]>
;;;; This code is licensed under the MIT license.
(defun call (url method &rest args)
"Make an XML-RPC call.
URL ::= url of server.
METHOD ::= xmlrpc method name.
ARGS ::= list of arguments.
"
(let ((encoded (apply #'encode-xml-rpc-call method args)))
(multiple-value-bind (resp status-code)
(winhttp:http-request url
:method :post
:post-data encoded
:timeout 5000
:ignore-certificates-p t)
(unless (= status-code 200) (error "HTTP Status ~A" status-code))
(with-input-from-string (s resp)
(let ((ret (decode-xml-rpc s)))
(if (typep ret 'xml-rpc-fault)
(error ret)
(car ret)))))))
(defun xmlrpc-struct (&rest args)
(apply #'xml-rpc-struct args))
(defun xmlrpc-member (struct &rest keys)
(apply #'xml-rpc-struct-member struct keys))
| 12,964 | Common Lisp | .lisp | 313 | 37.054313 | 110 | 0.677276 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | a13570c9649e0b58ba06a8c46234040ed81f3d11ea135842fb50733a6ca7bf48 | 42,946 | [
205365
] |
42,947 | websocket.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/winhttp-20200610-git/examples/websocket.lisp |
(defpackage winhttp-websocket-test
(:use #:cl))
(in-package #:winhttp-websocket-test)
(defparameter *hostname* nil)
(defparameter *port* nil)
(defun client ()
(winhttp:with-websocket (hwebsocket *hostname* *port*)
(let ((seq (make-array 64 :element-type '(unsigned-byte 8))))
(winhttp:websocket-send hwebsocket (babel:string-to-octets "hello"))
(multiple-value-bind (count type) (winhttp:websocket-receive hwebsocket seq)
(format t "Type ~S Msg ~S~%" type (subseq seq 0 count))))))
| 510 | Common Lisp | .lisp | 11 | 42.818182 | 82 | 0.713415 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | f222d1687fe637b2487b92640dfe20ee7c94ba91091e368babb13aca0a24bf59 | 42,947 | [
448393
] |
42,948 | aa-misc.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/aa-misc.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
(defpackage #:net.tuxee.aa-misc
(:use #:common-lisp)
(:nicknames #:aa-misc)
(:export ;; minimal image support (for testing purpose!)
#:make-image
#:image-width
#:image-height
;; Rendering functions.
#:image-put-pixel
#:image-put-span
;; Loading, saving and displaying image.
#:load-image
#:save-image
#:show-image
#:*external-viewer*
))
(in-package #:net.tuxee.aa-misc)
(defvar *external-viewer* "xv"
"Default program to run to display a PNM image.")
(deftype octet () '(unsigned-byte 8))
(defun make-image (width height &optional default-color)
"Create a new image.
width -- width of the image
height -- height of the image
default-color -- if not NIL, then the image is filled with the
specified color. If unspecified, then the contents of the image
is also unspecified.
Return the newly created image."
(let ((image (make-array (list height width 3)
:element-type 'octet)))
(when default-color
(loop for y below height
do (loop for x below width
do (loop for rgb below 3
do (setf (aref image y x rgb) (aref default-color rgb))))))
image))
(defun image-width (image)
(array-dimension image 1))
(defun image-height (image)
(array-dimension image 0))
;;;--[ Rendering ]-----------------------------------------------------------
(declaim (inline blend-value))
(defun blend-value (a b alpha)
(max 0 (min 255 (floor (+ (* (- 256 alpha) a)
(* alpha b))
256))))
(defun alpha/normalized (alpha)
(min 255 (abs alpha)))
(defun alpha/even-odd (alpha)
(min 255 (- 256 (abs (- 256 (mod (abs alpha) 512))))))
(defun image-put-pixel (image &optional (color #(0 0 0)) (opacity 1.0) (alpha-function :normalized))
(check-type image (array octet (* * 3)))
(let ((width (image-width image))
(height (image-height image)))
(case alpha-function
(:normalized
(setf alpha-function #'alpha/normalized))
(:even-odd
(setf alpha-function #'alpha/even-odd)))
(if (/= opacity 1.0)
(lambda (x y alpha)
(declare (optimize speed (safety 0) (debug 0)))
(when (and (<= 0 x (1- width))
(<= 0 y (1- height)))
(loop for rgb below 3
do (setf (aref image y x rgb)
(blend-value (aref image y x rgb)
(aref color rgb)
(floor (* opacity (funcall alpha-function alpha))))))))
(lambda (x y alpha)
(declare (optimize speed (safety 0) (debug 0)))
(when (and (<= 0 x (1- width))
(<= 0 y (1- height)))
(loop for rgb below 3
do (setf (aref image y x rgb)
(blend-value (aref image y x rgb)
(aref color rgb)
(funcall alpha-function alpha)))))))))
(defun image-put-span (image &optional (color #(0 0 0)) (opacity 1.0) (alpha-function :normalized))
(check-type image (array octet (* * 3)))
(let ((width (image-width image))
(height (image-height image)))
(case alpha-function
(:normalized
(setf alpha-function #'alpha/normalized))
(:even-odd
(setf alpha-function #'alpha/even-odd)))
(if (/= opacity 1.0)
(lambda (x1 x2 y alpha)
(declare (optimize speed (safety 0) (debug 0)))
(when (and (< x1 width)
(> x2 0)
(<= 0 y (1- height)))
(setf alpha (funcall alpha-function alpha))
(loop for x from (max 0 x1) below (min x2 width)
do (loop for rgb below 3
do (setf (aref image y x rgb)
(blend-value (aref image y x rgb)
(aref color rgb)
(floor (* opacity alpha))))))))
(lambda (x1 x2 y alpha)
(declare (optimize speed (safety 0) (debug 0)))
(when (and (< x1 width)
(> x2 0)
(<= 0 y (1- height)))
(setf alpha (funcall alpha-function alpha))
(loop for x from (max 0 x1) below (min x2 width)
do (loop for rgb below 3
do (setf (aref image y x rgb)
(blend-value (aref image y x rgb)
(aref color rgb)
alpha)))))))))
;;;--[ load/save/display ]---------------------------------------------------
(defun %load-image/pnm (filename)
(with-open-file (file filename :element-type 'octet)
(flet ((read-word (&optional limit)
"Read the next \"word\" (a sequence of non-space
characters) skipping initial blanks. The first blank
character after the word is also consumed."
(declare (ignore limit)) ; FIXME
(let ((result (make-array 0
:element-type 'octet
:fill-pointer 0
:adjustable t)))
;; skip blanks, extract the word, consume the following
;; blank.
(loop for byte = (read-byte file)
while (member byte '(9 10 13 32))
finally (vector-push-extend byte result))
(loop for byte = (read-byte file)
until (member byte '(9 10 13 32))
do (vector-push-extend byte result))
result))
(parse-ascii-integer (seq)
"Parse an integer represented by the ASCII charset
in the array SEQ."
(let ((result 0))
(loop for digit in (coerce seq 'list)
unless (<= 48 digit 57)
do (error "Invalid ASCII integer")
do (setf result (+ (* 10 result) (- digit 48))))
result)))
(let ((format (read-word 3)))
(unless (equalp format #(80 54))
(error "Expected P6 image format (got ASCII sequence ~S)" (subseq format 0 16)))
(let ((width (parse-ascii-integer (read-word 10)))
(height (parse-ascii-integer (read-word 10)))
(maxval (parse-ascii-integer (read-word 10))))
(when (/= maxval 255)
(error "Expected 24 bits color image"))
(unless (and (<= 1 width 4096)
(<= 1 height 4096))
(error "Cowardly refusing to read an image of size ~Dx~D" width height))
(let* ((image (make-array (list height width 3) :element-type 'octet))
(index 0)
(end-index (apply #'* (array-dimensions image))))
;; skip blanks to find the first byte of data.
(loop for byte = (read-byte file)
while (member byte '(9 10 13 32))
finally (setf (row-major-aref image index) byte))
(incf index)
;; read the rest of the data.
(loop while (< index end-index)
for byte = (read-byte file)
do (setf (row-major-aref image index) byte)
(incf index))
image))))))
(defun load-image (filename format)
(ecase format
(:pnm
(%load-image/pnm filename))))
(defun make-array-flat-displaced (array &optional (start 0))
(make-array (apply #'* (array-dimensions array))
:element-type (array-element-type array)
:displaced-to array
:displaced-index-offset start))
(defun save-image/pnm (filename image)
"Save image with PNM format into the file with filename
FILENAME. IMAGE must be an (UNSIGNED-BYTE 8) array of
dimension (* * 3). Last axis represent the RGB component in that
order."
(with-open-file (file filename
:element-type 'octet
:direction :output
:if-does-not-exist :create
:if-exists :overwrite)
(labels ((write-ascii-integer (n stream)
(when (minusp n)
(write-byte 45 stream) ; #\-
(setf n (- n)))
(write-sequence (loop with digits = ()
for digit = (mod n 10)
do (push (+ 48 digit) digits)
(setf n (floor n 10))
while (plusp n)
finally (return digits))
stream)))
;; "P6" <width> <height> <maxval>
(write-sequence #(80 54) file)
(write-byte 32 file)
(write-ascii-integer (array-dimension image 1) file)
(write-byte 32 file)
(write-ascii-integer (array-dimension image 0) file)
(write-byte 32 file)
(write-ascii-integer 255 file)
(write-byte 10 file)
(write-sequence (make-array-flat-displaced image) file))))
(defun save-image (filename image format)
(ecase format
((:pnm :ppm)
(save-image/pnm filename image)))
(values))
;;; WARNING: Run external program.
(defun show-image (image &optional (external-viewer *external-viewer*))
"Display IMAGE using the specified external viewver."
(uiop:with-temporary-file (:pathname temp-filename :prefix "cl-aa-tmp" :type "pnm")
(save-image temp-filename image :pnm)
(uiop:run-program `(,external-viewer ,(uiop:native-namestring temp-filename))
:output :interactive :error-output :interactive)))
| 9,955 | Common Lisp | .lisp | 222 | 32.207207 | 100 | 0.522196 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 7180fba0470f4494b8b7aa8ba28c85f254e88b56ed126623a4af666213c61ae0 | 42,948 | [
-1
] |
42,949 | paths-package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/paths-package.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
(defpackage #:net.tuxee.paths
(:use #:cl)
(:nicknames #:paths)
(:export ;; 2D points (knot and control points)
#:make-point
#:point-x
#:point-y
#:p+
#:p-
#:p*
#:point-rotate
#:point-angle
#:point-norm
#:point-distance
;; Paths
#:create-path
#:path-clear
#:path-reset
#:path-extend
#:path-concatenate
#:path-replace
#:path-size
#:path-last-knot
#:path-orient
#:path-clone
#:path-reverse
#:path-reversed
#:path-translate
#:path-rotate
#:path-scale
#:path-transform-as-marker
;; Interpolators
#:make-straight-line
#:make-arc
#:make-catmull-rom
#:make-bezier-curve
;; Path iterators
#:path-iterator-reset
#:path-iterator-next
#:path-iterator
#:path-iterator-segmented
#:filter-distinct
;; Misc
#:make-discrete-path
#:make-circle-path
#:make-rectangle-path
#:make-rectangle-path/center
#:make-regular-polygon-path
#:make-simple-path
#:path-annotated
#:make-simple-path
;; Transformations
#:stroke-path
#:dash-path
#:clip-path
#:clip-path/path
;; Variables
#:*bezier-distance-tolerance*
#:*bezier-angle-tolerance*
#:*arc-length-tolerance*
))
(in-package #:net.tuxee.paths)
| 1,888 | Common Lisp | .lisp | 65 | 18.230769 | 71 | 0.49615 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | a1aa0e3abb1b5cd8f3e8273222bc46eeefede519af88f1d68cec64a819170a32 | 42,949 | [
-1
] |
42,950 | paths-annotation.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/paths-annotation.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
(in-package #:net.tuxee.paths)
;;;--[ Path annotation ]-----------------------------------------------------
(defun path-annotated (paths &key (include-tangents nil) (decimate-knots t) (assume-type nil))
"Annotate the path with visual effect (like color for each type
of interpolation, circle to represent knots,..)
path -- a path or a list of path
Return a list of (color . paths)."
(let (layer-surface
layer-lines
layer-arcs
layer-bezier
layer-bezier-cpl
layer-bezier-cp
layer-catmull-rom
layer-catmull-rom-cp
layer-knots
layer-implicit
layer-tangents)
(dolist (path (if (listp paths) paths (list paths)))
(let ((path-type (or assume-type (path-type path))))
(when (plusp (path-size path))
;;
;; Surfaces
;;
(unless (eq path-type :open-polyline)
(push path layer-surface))
;;
;; Interpolations
;;
(loop with iterator = (path-iterator path)
for stop-p = nil then end-p
for k1 = nil then k2
for (interpolation k2 end-p) = (multiple-value-list (path-iterator-next iterator))
until stop-p
when k1
do
;;
;; Tangents
;;
(when include-tangents
(let ((t1 (interpolation-normal interpolation k1 k2 nil))
(t2 (interpolation-normal interpolation k1 k2 t)))
(when t1
(setf layer-tangents
(nconc (stroke-path
(make-simple-path
(list k1 (p+ k1 (p* t1 25.0)))) 1.0)
layer-tangents)))
(when t2
(setf layer-tangents
(nconc (stroke-path
(make-simple-path
(list k2 (p+ k2 (p* t2 25.0)))) 1.0)
layer-tangents)))))
;;
;; Interpolation
;;
(etypecase interpolation
((eql :straight-line)
(setf layer-lines
(nconc (stroke-path (make-simple-path (list k1 k2)) 1.0)
layer-lines)))
(bezier
(let ((control (create-path :open-polyline)))
(path-reset control k1)
(loop for cp across (slot-value interpolation 'control-points)
do (path-extend control (make-straight-line) cp)
(push (make-circle-path (point-x cp) (point-y cp) 5.0)
layer-bezier-cp)
(push (path-reversed (make-circle-path (point-x cp) (point-y cp) 3.5))
layer-bezier-cp))
(path-extend control (make-straight-line) k2)
(push (first (stroke-path control 1.0))
layer-bezier-cpl))
(let ((arc (create-path :open-polyline)))
(path-reset arc k1)
(path-extend arc interpolation k2)
(push (first (stroke-path (make-discrete-path arc) 1.0))
layer-bezier)))
(arc
(let ((arc (create-path :open-polyline)))
(path-reset arc k1)
(path-extend arc interpolation k2)
(setf layer-arcs
(nconc (stroke-path (make-discrete-path arc) 1.0)
layer-arcs))))
(catmull-rom
(loop for cp in (list* (slot-value interpolation 'head)
(slot-value interpolation 'queue)
(coerce (slot-value interpolation 'control-points)
'list))
do
(push (make-circle-path (point-x cp) (point-y cp) 5.0)
layer-catmull-rom-cp)
(push (path-reversed (make-circle-path (point-x cp) (point-y cp) 3.5))
layer-catmull-rom-cp))
(let ((spline (create-path :open-polyline)))
(path-reset spline k1)
(path-extend spline interpolation k2)
(push (first (stroke-path (make-discrete-path spline) 1.0))
layer-catmull-rom)))))
;;
;; Implicit straight line
;;
(unless (eq path-type :open-polyline)
(let ((k1 (aref (path-knots path) (1- (length (path-knots path)))))
(i2 (aref (path-interpolations path) 0))
(k2 (aref (path-knots path) 0))
(path (create-path :open-polyline)))
(path-reset path k1)
(path-extend path i2 k2)
(setf layer-implicit
(nconc (stroke-path (dash-path path #(5 5)) 1.0)
layer-implicit))))
;;
;; Knots (decimated)
;;
(loop with knots = (path-knots path)
with last-added-knot = nil
with first-knot = t
with second-knot = nil
for i below (length knots)
for knot = (aref knots i)
for last-knot = (= i (- (length knots) 1))
do (when (or (not decimate-knots)
last-knot
(null last-added-knot)
(> (point-distance last-added-knot knot) 10))
(when first-knot
(push (make-circle-path (point-x knot) (point-y knot) 8.0)
layer-knots)
(push (path-reversed (make-circle-path (point-x knot) (point-y knot) 6.5))
layer-knots))
(push (make-circle-path (point-x knot) (point-y knot) 5.0)
layer-knots)
(unless second-knot
(push (path-reversed (make-circle-path (point-x knot) (point-y knot) 3.5))
layer-knots))
(setf last-added-knot knot
second-knot first-knot
first-knot nil))))))
;; Put everything together
(list (cons #(230 245 255) (nreverse layer-surface))
(cons #(90 120 180) (nreverse layer-implicit))
(cons #(90 120 180) (nreverse layer-lines))
(cons #(255 0 0) (nreverse layer-tangents))
(cons #(255 0 255) (nreverse layer-arcs))
(cons #(255 0 0) (nreverse layer-bezier))
(cons #(0 255 0) (nreverse layer-catmull-rom))
(cons #(255 128 0) (nreverse layer-bezier-cpl))
(cons #(0 0 255) (nreverse layer-knots))
(cons #(100 100 100) (nreverse layer-catmull-rom-cp))
(cons #(255 0 0) (nreverse layer-bezier-cp)))))
| 7,217 | Common Lisp | .lisp | 156 | 29.557692 | 95 | 0.472923 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 1aa0932e0d08e7f55946a6781235233d14132c69efcf73bf744c3cc447e60ea9 | 42,950 | [
-1
] |
42,951 | doc.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/doc.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
(defpackage #:net.tuxee.vectors-doc
(:use #:cl #:aa #:paths)
(:export #:generate))
(in-package #:net.tuxee.vectors-doc)
(defvar *target* "/home/fred/Devel/cl-vectors/doc-pictures/")
;;;--[ Path annotation ]-----------------------------------------------------
(defun path-map-line (path function)
"Iterate over all the line on the contour of the path."
(loop with iterator = (path-iterator-segmented path)
for previous-knot = nil then knot
for (interpolation knot end-p) = (multiple-value-list (path-iterator-next iterator))
while knot
when previous-knot
do (funcall function previous-knot knot)
until end-p
finally (when knot
(funcall function knot (nth-value 1 (path-iterator-next iterator))))))
(defun rasterize-paths (paths image &optional (color #(0 0 0)) (opacity 1.0) (scale 1.0))
(let ((state (make-state)))
(flet ((do-line (p1 p2)
(line-f state
(* scale (point-x p1)) (* scale (point-y p1))
(* scale (point-x p2)) (* scale (point-y p2)))))
(loop for path in (flatten paths)
do (path-map-line path #'do-line)))
(cells-sweep state (aa-misc:image-put-pixel image color opacity))))
(defun flatten (path)
(if (not (listp path))
(list path)
(loop for item in path nconc (flatten item))))
(defun paths-bounding-box (paths &optional (scale 1.0))
(let ((state (make-state))
min-x max-x
min-y max-y)
(flet ((do-line (p1 p2)
(line-f state
(* scale (point-x p1)) (* scale (point-y p1))
(* scale (point-x p2)) (* scale (point-y p2))))
(do-cell (x y alpha)
(declare (ignore alpha))
(cond
(min-x
(cond
((< x min-x) (setf min-x x))
((> x max-x) (setf max-x x)))
(cond
((< y min-y) (setf min-y y))
((> y max-y) (setf max-y y))))
(t
(setf min-x x
max-x x
min-y y
max-y y)))))
(loop for path in (flatten paths)
do (path-map-line path #'do-line))
(cells-sweep state #'do-cell (lambda (&rest args) (declare (ignore args)))))
(when min-x
(values min-x min-y (1+ max-x) (1+ max-y)))))
(defun show-paths (paths &key (color #(0 0 0)) (opacity 1.0) (width 800) (height 600)
(background #(255 255 255)))
(let ((image (aa-misc:make-image width height background)))
(rasterize-paths paths image color opacity)
(aa-misc:show-image image)))
(defun create-graph (graph &key subgraphs (width 800) (height 600) (auto-size t) (scale 1.0)
(background #(255 255 255)))
(when auto-size
(let (min-x max-x
min-y max-y)
(flet ((update-limits (graph)
(loop for (color . paths) in graph
do (multiple-value-bind (x1 y1 x2 y2) (paths-bounding-box paths scale)
(when x1
(when (or (null min-x) (< x1 min-x)) (setf min-x x1))
(when (or (null max-x) (> x2 max-x)) (setf max-x x2))
(when (or (null min-y) (< y1 min-y)) (setf min-y y1))
(when (or (null max-y) (> y2 max-y)) (setf max-y y2)))))))
(when graph
(update-limits graph))
(when subgraphs
(mapcar #'update-limits subgraphs)))
(ecase auto-size
(:border
(setf width (max 1 (+ (max 0 min-x) max-x))
height (max 1 (+ (max 0 min-y) max-y))))
(t
(setf width (max 1 max-x)
height (max 1 max-y))))))
(let ((image (aa-misc:make-image width height background)))
(when graph
(loop for (color . paths) in graph
do (rasterize-paths paths image color 1.0 scale)))
(dolist (subgraph subgraphs)
(loop for (color . paths) in subgraph
do (rasterize-paths paths image color 0.3 scale)))
image))
(defun generate-annotated-path (path &rest args &key reference &allow-other-keys)
(apply #'create-graph (when path (path-annotated path))
:subgraphs (mapcar #'path-annotated (if (listp reference) reference (list reference)))
:allow-other-keys t
args))
(defun show-annotated-path (&rest args)
(aa-misc:show-image (apply #'generate-annotated-path args)))
(defun show-graph (graph)
(aa-misc:show-image (create-graph graph)))
(defun save-image* (filename image)
(aa-misc:save-image (merge-pathnames filename *target*) image :pnm))
(defun save-graph (filename graph)
(aa-misc:save-image (merge-pathnames filename *target*) (create-graph graph) :pnm))
(defun save-annotated-path (filename &rest args)
(aa-misc:save-image (merge-pathnames filename *target*) (apply #'generate-annotated-path args) :pnm))
;;;--------------------------------------------------------------------------
(defun test ()
(let ((path (create-path :polygon)))
(path-reset path (make-point 25 15))
(path-extend path (make-straight-line) (make-point 250 25))
(path-extend path (make-bezier-curve (list (make-point 300 40)
(make-point 400 150)
(make-point 200 100)))
(make-point 250 250))
(path-extend path (make-arc 100 200 :x-axis-rotation -0.8)
(make-point 25 250))
(path-extend path (make-catmull-rom (make-point 10 270)
(list (make-point 10 200)
(make-point 40 160)
(make-point 25 120)
(make-point 60 90))
(make-point 70 40))
(make-point 55 55))
(show-annotated-path path)))
(defun generate ()
;;
;; Reference path
;;
(let ((path (make-simple-path '((125 . 20)
(75 . 105)
(45 . 110)
(25 . 25)
(200 . 55)
(75 . 155)
(90 . 170)
(240 . 120)
(125 . 90)))))
(save-annotated-path
"pic-main.pnm"
path
:auto-size :border))
;;
;; Interpolations
;;
(let ((path (create-path :polygon)))
(path-reset path (make-point 25 15))
(path-extend path (make-straight-line) (make-point 250 25))
(path-extend path (make-bezier-curve (list (make-point 300 40)
(make-point 400 150)
(make-point 200 100)))
(make-point 250 250))
(path-extend path (make-arc 100 200 :x-axis-rotation -0.8)
(make-point 25 250))
(path-extend path (make-catmull-rom (make-point 10 270)
(list (make-point 10 200)
(make-point 40 160)
(make-point 25 120)
(make-point 60 90))
(make-point 70 40))
(make-point 55 55))
(save-annotated-path
"pic-interpolations.pnm"
path
:auto-size :border))
;;
;; Discrete path - Before
;;
(let ((path (make-simple-path '((80 . 80) (100 . 200) (250 . 80) (300 . 200)))))
(save-annotated-path
"pic-before-discrete.pnm"
(paths:stroke-path path 100.0
:caps :round
:joint :round
:inner-joint :miter)
:reference path
:auto-size :border))
;;
;; Discrete path - After
;;
(let ((path (make-simple-path '((80 . 80) (100 . 200) (250 . 80) (300 . 200)))))
(save-annotated-path
"pic-after-discrete.pnm"
(make-discrete-path (first (paths:stroke-path path 100.0
:caps :round
:joint :round
:inner-joint :miter)))
:reference path
:auto-size :border))
;;
;; Stroke
;;
(let* ((path (make-simple-path '((50 . 50) (70 . 170) (190 . 90) (270 . 170) (300 . 40))))
(stroked (stroke-path path 40.0
:caps :square
:joint :round
:inner-joint :miter
:assume-type :open-polyline)))
(save-annotated-path
"pic-stroke-open.pnm"
stroked
:reference path
:auto-size :border))
(let* ((path (make-simple-path '((50 . 50) (70 . 170) (190 . 90) (270 . 170) (300 . 40))))
(stroked (stroke-path path 40.0
:caps :square
:joint :round
:inner-joint :miter
:assume-type :closed-polyline)))
(save-annotated-path
"pic-stroke-closed.pnm"
stroked
:reference path
:auto-size :border))
(let* ((path (make-simple-path '((50 . 50) (70 . 170) (190 . 90) (270 . 170) (300 . 40))))
(stroked (stroke-path path 40.0
:caps :square
:joint :round
:inner-joint :miter
:assume-type :polygon)))
(save-annotated-path
"pic-stroke-polygon.pnm"
stroked
:reference path
:auto-size :border))
;;
;; Dash
;;
(let ((path (create-path :open-polyline)))
(path-reset path (make-point 30 30))
(path-extend path (make-straight-line) (make-point 180 80))
(path-extend path (make-arc 80 80 :large-arc-flag t :sweep-flag t) (make-point 150 150))
(path-extend path (make-straight-line) (make-point 90 200))
(save-annotated-path
"pic-dash-1.pnm"
(dash-path path #(80 50))
:reference path
:auto-size :border))
;;
;; Clipping
;;
(let ((path (make-simple-path '((50 . 50) (70 . 170) (190 . 30) (270 . 170))))
(clipping (make-rectangle-path/center 140 120 80 80)))
(paths::path-rotate clipping 0.3 (make-point 140 120))
(print (paths::clip-path/path path clipping))
(save-annotated-path
"pic-clipping.pnm"
(paths::clip-path/path path clipping)
:reference (list path clipping)
:auto-size :border))
;;
;; Rotate
;;
(let* ((paths (stroke-path (make-simple-path '((50 . 50) (70 . 170) (190 . 30) (270 . 170)))
40.0 :caps :round :inner-joint :miter :joint :round))
(paths-copy (mapcar #'path-clone paths)))
(dolist (path paths)
(path-rotate path 0.4 (make-point 100 80)))
(save-annotated-path
"pic-rotate.pnm"
paths
:reference (list paths-copy)
:auto-size :border))
;;
;; Circle example
;;
(let ((path (make-circle-path 100 50 90 40 0.2)))
(save-annotated-path
"pic-circle.pnm"
path
:auto-size :border))
;;
;; Rectangle example
;;
(let ((path (make-rectangle-path 10 10 300 100 :round-x 20 :round-y 30)))
(save-annotated-path
"pic-rectangle.pnm"
path
:auto-size :border))
;;
;; Arc example
;;
(let ((path (create-path :open-polyline)))
(path-reset path (make-point 20 300))
(path-extend path (make-straight-line) (make-point 70 275))
(path-extend path (make-arc 25 25 :x-axis-rotation -0.5 :sweep-flag t)
(make-point 120 250))
(path-extend path (make-straight-line) (make-point 170 225))
(path-extend path (make-arc 25 50 :x-axis-rotation -0.5 :sweep-flag t)
(make-point 220 200))
(path-extend path (make-straight-line) (make-point 270 175))
(path-extend path (make-arc 25 75 :x-axis-rotation -0.5 :sweep-flag t)
(make-point 320 150))
(path-extend path (make-straight-line) (make-point 370 125))
(path-extend path (make-arc 25 100 :x-axis-rotation -0.5 :sweep-flag t)
(make-point 420 100))
(path-extend path (make-straight-line) (make-point 470 75))
(paths::path-scale path 0.7 0.7)
(save-annotated-path
"pic-arc.pnm"
path
:auto-size :border))
;;
;; Catmull-Rom example
;;
(let ((path (create-path :open-polyline)))
(path-reset path (make-point 30 40))
(path-extend path (make-catmull-rom (make-point 20 20)
(list (make-point 80 20)
(make-point 140 190)
(make-point 200 140)
(make-point 130 30))
(make-point 300 90))
(make-point 270 40))
(save-annotated-path
"pic-catmull-rom.pnm"
path
:auto-size :border))
;;
;; Bezier example
;;
(let ((path (create-path :open-polyline)))
(path-reset path (make-point 10 100))
(path-extend path (make-bezier-curve (list (make-point 80 10)
(make-point 140 250)
(make-point 200 200)
(make-point 250 90)))
(make-point 300 100))
(save-annotated-path
"pic-bezier.pnm"
path
:auto-size :border))
;;
;; list marker
;;
(let ((path (create-path :polygon)))
(path-extend path (make-arc 50 50) (make-point 0 0))
(path-extend path (make-arc 34 34) (make-point 20 20))
(path-extend path (make-arc 34 34) (make-point 0 40))
(path-reverse path)
(save-graph "pic-list.pnm" (list (list #(120 120 120) (stroke-path path 2))
(list #(0 0 0) path))))
;;
;; black triangle antialiased
;;
(let ((state (aa:make-state)))
(aa:line-f state 200 50 250 150)
(aa:line-f state 250 150 50 100)
(aa:line-f state 50 100 200 50)
(let* ((image (aa-misc:make-image 300 200 #(255 255 255)))
(put-pixel (aa-misc:image-put-pixel image #(0 0 0))))
(aa:cells-sweep state put-pixel)
(save-image* "pic-tut1.pnm" image)))
;; 2 overlapping triangles
(let ((state (aa:make-state))) ; create the state
;; the 1st triangle
(aa:line-f state 200 50 250 150) ; describe the 3 sides
(aa:line-f state 250 150 50 100) ; of the first triangle
(aa:line-f state 50 100 200 50)
;; the 2nd triangle
(aa:line-f state 75 25 10 75) ; describe the 3 sides
(aa:line-f state 10 75 175 100) ; of the second triangle
(aa:line-f state 175 100 75 25)
(let* ((image (aa-misc:make-image 300 200 #(255 255 255)))
(put-pixel (aa-misc:image-put-pixel image #(0 0 0))))
(aa:cells-sweep state put-pixel) ; render it
(save-image* "pic-tut2.pnm" image)))
;; 2 overlapping triangles red/blue
(let ((state1 (aa:make-state))
(state2 (aa:make-state)))
;; the 1st triangle
(aa:line-f state1 200 50 250 150) ; describe the 3 sides
(aa:line-f state1 250 150 50 100) ; of the first triangle
(aa:line-f state1 50 100 200 50)
;; the 2nd triangle
(aa:line-f state2 75 25 10 75) ; describe the 3 sides
(aa:line-f state2 10 75 175 100) ; of the second triangle
(aa:line-f state2 175 100 75 25)
(let ((image (aa-misc:make-image 300 200 #(255 255 255))))
(aa:cells-sweep state1 (aa-misc:image-put-pixel image #(255 0 0)))
(aa:cells-sweep state2 (aa-misc:image-put-pixel image #(0 0 255)))
(save-image* "pic-tut3.pnm" image)))
)
#|
(defun path-extend-with-waves (path knot width frequency)
;; generate a serie of arc to represent a wave up to knot
)
|#
| 15,908 | Common Lisp | .lisp | 395 | 30.035443 | 103 | 0.533923 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b7e374f0fe9be80c847b2a97e9950160c9cad99de44e733edd7e2de6365cc400 | 42,951 | [
145817
] |
42,952 | vectors.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/vectors.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
(defpackage #:net.tuxee.vectors
(:use #:cl #:net.tuxee.aa #:net.tuxee.paths)
(:nicknames #:vectors)
(:export #:update-state))
(in-package #:net.tuxee.vectors)
(defun update-state (state paths)
(if (listp paths)
(dolist (path paths)
(update-state state path))
(let ((iterator (path-iterator-segmented paths)))
(multiple-value-bind (i1 k1 e1) (path-iterator-next iterator)
(declare (ignore i1))
(when (and k1 (not e1))
;; at least 2 knots
(let ((first-knot k1))
(loop
(multiple-value-bind (i2 k2 e2) (path-iterator-next iterator)
(declare (ignore i2))
(line-f state
(point-x k1) (point-y k1)
(point-x k2) (point-y k2))
(setf k1 k2)
(when e2
(return))))
(line-f state
(point-x k1) (point-y k1)
(point-x first-knot) (point-y first-knot)))))))
state)
| 1,256 | Common Lisp | .lisp | 31 | 28.967742 | 78 | 0.530328 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 60b76f1b708013d26115f96b8485f4377a43601cd315c2766630f4aac648c959 | 42,952 | [
-1
] |
42,953 | paths-ttf.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/paths-ttf.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
(defpackage #:net.tuxee.paths-ttf
(:use #:cl #:net.tuxee.paths #:zpb-ttf)
(:nicknames #:paths-ttf)
(:export #:paths-from-glyph
#:paths-from-string
#:make-string-path))
(in-package #:net.tuxee.paths-ttf)
(defun paths-from-glyph (glyph &key (offset (make-point 0 0))
(scale-x 1.0) (scale-y 1.0)
(auto-orient nil))
"Extract paths from a glyph."
(flet ((point (p) (p+ (make-point (* (x p) scale-x)
(* (y p) scale-y))
offset)))
(let (result)
(do-contours (contour glyph)
(let ((path (create-path :polygon))
(last-point nil))
(do-contour-segments (a b c) contour
(let ((pa (point a))
(pb (when b (point b)))
(pc (point c)))
(if last-point
(assert (and (= (point-x last-point) (point-x pa))
(= (point-y last-point) (point-y pa))))
(path-reset path pa))
(path-extend path
(if b
(make-bezier-curve (list pb))
(make-straight-line))
pc)
(setq last-point pc)))
(when (minusp (* scale-x scale-y))
(path-reverse path))
(push path result)))
(setq result (nreverse result))
(when (and auto-orient result)
(path-orient (car result) auto-orient (cdr result)))
result)))
(defun paths-from-string (font-loader text &key (offset (make-point 0 0))
(scale-x 1.0) (scale-y 1.0)
(kerning t) (auto-orient nil))
"Extract paths from a string."
(let (result)
(loop
for previous-char = nil then char
for char across text
for previous-glyph = nil then glyph
for glyph = (find-glyph char font-loader)
do (when previous-char
(setf offset
(p+ offset
(make-point (* scale-x
(+ (advance-width previous-glyph)
(if kerning
(kerning-offset previous-char
char
font-loader)
0)))
0))))
(let ((glyph-paths (paths-from-glyph glyph
:offset offset :auto-orient auto-orient
:scale-x scale-x :scale-y scale-y)))
(push glyph-paths result)))
(apply #'nconc (nreverse result))))
(defun make-string-path (font-loader text &key (position (make-point 0 0)) (size 12)
(halign :left) (valign :baseline)
(inverted t) (kerning t))
(let* ((em (units/em font-loader))
(scale (/ size em))
(scale-x scale)
(scale-y scale))
(when inverted
(setq scale-y (- scale-y)))
(let ((bb (string-bounding-box text font-loader :kerning kerning)))
(setq position (p- position
(p* (make-point
(ecase halign
(:none
0)
(:left
(aref bb 0))
(:right
(aref bb 2))
(:center
(/ (+ (aref bb 0) (aref bb 2)) 2.0)))
(ecase valign
(:baseline
0)
(:top
(aref bb 1))
(:bottom
(aref bb 3))
(:center
(/ (+ (aref bb 1) (aref bb 3)) 2.0))))
scale))))
(paths-from-string font-loader text :offset position
:scale-x scale-x :scale-y scale-y
:kerning kerning
:auto-orient :cw)))
| 4,674 | Common Lisp | .lisp | 103 | 24.84466 | 84 | 0.396363 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | ab9fb122965e2efd03c8293cf92fd319740086a32c49688d0c4488bdc609bbc5 | 42,953 | [
-1
] |
42,954 | aa.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/aa.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
;;;; This file implement the AA algorithm from the AntiGrain project
;;;; (http://antigrain.com/).
;;;;
;;;; Changelogs:
;;;;
;;;; 2007-03-11: Extended the protocol to provide a way to sweep only
;;;; a rectangular zone of the resulting state. This was
;;;; done with some new functions: FREEZE-STATE,
;;;; SCANLINE-SWEEP, SCANLINE-Y and CELLS-SWEEP/RECTANGLE.
;;;; The function CELLS-SWEEP is now based on them.
;;;;
;;;; 2007-02-25: Released under LLGPL this time. Future changes made
;;;; in this file will be thus covered by this license.
;;;;
;;;; 2007-01-20: Minors updates to comments and code.
;;;;
;;;; 2007-01-11: I chose to release the code in this file in public
;;;; domain. You can do whatever you want with the code.
;;;;
;;;; 2007-01-07: fixed 2 bugs related to cells reuse. The first bug
;;;; was that the cell after the last reused one was kept
;;;; in the list. The second bug occured when the latest
;;;; cell (the current one) was empty. The code was
;;;; failing to correctly eliminate unused cells in such
;;;; case.
;;;;
;;;; 2007-01-05: +cell-width+ is no longer passed as parameter to let
;;;; the CL compiler optimize various computation
;;;; involving this value. Added docstrings and
;;;; (hopefully) clarified some points.
;;;;
;;;; 2006-12-31: moved examples to a separate file
;;;;
;;;; 2006-12-30: added animated GIF (using Skippy) example
;;;;
;;;; 2006-12-30: cleaned the code, factorized, simplified
;;;;
;;;; 2006-12-30: map-grid-spans rewritten in term of map-line-spans
;;;;
;;;; 2006-12-30: first release
;;;;
;;;; About AntiGrain: "Anti-Grain Geometry (AGG) is an Open Source,
;;;; free of charge graphic library, written in industrially standard
;;;; C++." "A High Quality Rendering Engine for C++". Its main author
;;;; is Maxim Shemanarev. Project home page is at http://antigrain.com/
;;;;
;;;; How to use it:
;;;;
;;;; 1) create a state with MAKE-STATE, or reuse a previous state by
;;;; calling STATE-RESET on it.
;;;;
;;;; 2) call LINE-F (or LINE) to draw each line of one or several
;;;; closed polygons. It is very important to close them to get a
;;;; coherent result. Note that nothing is really drawn at this
;;;; stage (not until the call to CELLS-SWEEP.)
;;;;
;;;; 3) finally, call CELLS-SWEEP to let it call your own function for
;;;; each pixels covered by the polygon(s), where the callback
;;;; function take 3 arguments: x, y, alpha. Pixels are scanned on
;;;; increasing y, then on increasing x. Optionnaly, CELLS-SWEEP
;;;; can take another callback function as parameter. See its
;;;; documentation for details.
;;;;
;;;; The alpha value passed to the callback function can be used in
;;;; various way. Usually you want:
;;;;
;;;; (defun normalize-alpha (alpha)
;;;; (min 255 (abs alpha)))
;;;;
;;;; to get a normalized alpha value between 0 and 255. But you may
;;;; also be interested by:
;;;;
;;;; (defun even-odd-alpha (alpha)
;;;; (let ((value (mod alpha 512)))
;;;; (min 255 (if (< value 256) value (- 512 value)))))
;;;;
;;;; to simulate "even/odd" fill. You can also use the alpha value
;;;; to render polygons without anti-aliasing by using:
;;;;
;;;; (defun bool-alpha (value)
;;;; (if (>= (abs value) 128) 255 0))
;;;;
;;;; or, for "even/odd" fill:
;;;;
;;;; (defun bool-even-odd-alpha (value)
;;;; (if (<= 128 (mod (abs value) 256) 384) 255 0))
;;;;
;;;; Note: Drawing direction (clockwise or counter-clockwise) is only
;;;; important if polygons overlap during a single
;;;; cells-state. Opposite directions produce hole at the intersection
;;;; (coverage is canceled), while identical directions does not
;;;; (coverage overflow.)
;;;;
;;;; The latest version can be downloaded from:
;;;;
;;;; http://tuxee.net/cl-aa.lisp
;;;; http://tuxee.net/cl-aa-sample.lisp
;;;;
;;;; See also:
;;;;
;;;; http://projects.tuxee.net/cl-aa-path/
;;;;
;;;; See examples of output at:
;;;;
;;;; http://tuxee.net/cl-aa-1.png
;;;; http://tuxee.net/cl-aa-2.png (this one was a bug.)
;;;; http://tuxee.net/cl-aa-3.png
;;;; http://tuxee.net/cl-aa-4.png
;;;; http://tuxee.net/cl-aa-5.png (when testing transparency, but looks bad.)
;;;; http://tuxee.net/cl-aa-6.png
;;;; http://tuxee.net/cl-aa-7.png
;;;; http://tuxee.net/cl-aa-8.png
;;;; http://tuxee.net/cl-aa-stroke-0.png (using stroke functions not provided here.)
;;;; http://tuxee.net/cl-aa-stroke-1.png
;;;; http://tuxee.net/cl-aa-stroke-2.png
;;;; http://tuxee.net/cl-aa-skippy-1.gif (animated GIF, thanks to Skippy library)
;;;; http://tuxee.net/cl-aa-skippy-2.gif
;;;;
;;;; The code is absolutely NOT optimized in any way. It was mainly to
;;;; figure how the algorithm was working. Also, I don't have tested
;;;; many corner cases. It is absolutely NOT for production use.
;;;;
;;;; About the example, note that the resulting image is exported as a
;;;; PNM file. Not great, but no need for any external lib. You can
;;;; use pnmtopng to convert it to PNG afterward.
;;;;
;;;; Inspiration come from agg/include/agg_rasterizer_cells_aa.h and
;;;; agg/include/agg_rasterizer_scanline_aa.h sources files from the
;;;; AntiGrain project (version 2.5 at this date.)
;;;;
;;;; For animated GIF, see Zach Beane's Skippy project at:
;;;; http://www.cliki.net/Skippy
;;;; Naming convention:
;;;; foo-m for fixed-point mantissa,
;;;; foo-f for fixed-point fractional part.
#+nil(error "This file assume that #+NIL is never defined.")
(defpackage #:net.tuxee.aa
(:use #:common-lisp)
(:nicknames #:aa)
(:export #:make-state
#:state-reset
#:line
#:line-f
#:freeze-state
#:scanline-y
#:scanline-sweep
#:cells-sweep
#:cells-sweep/rectangle))
(in-package #:net.tuxee.aa)
;;;--[ Utility function ]-----------------------------------------------------
(defconstant +cell-width+ 256
"A cell represent a pixel square, and the width is the
fractional part of the fixed-point coordinate. A large value
increase precision. 256 should be enough though. Note that
smaller value should NOT increase performance.")
;;; This function is used to split a line at each pixel boundaries
;;; (when using sub-pixel coordinates.) Since the function only cut
;;; along one axis, it must be called twice (with the second call with
;;; coordinates swapped) to split along X and Y axis.
;;;
;;; In the comments below, by "main axis" I mean the X axis if A1 and
;;; A2 are the X coordinates, or the Y axis otherwise.
(declaim (inline map-line-spans))
(defun map-line-spans (function a1 b1 a2 b2)
"Call FUNCTION for each segment of a line with integer
coordinates (A1,B1)-(A2,B2) cut by a grid of spacing
+CELL-WIDTH+."
(multiple-value-bind (b1-m b1-f) (floor b1 +cell-width+)
(multiple-value-bind (b2-m b2-f) (floor b2 +cell-width+)
(cond
;; The line doesn't cross the grid in the main axis. We have a
;; single segment. Just call FUNCTION.
((= b1-m b2-m)
(funcall function b1-m a1 b1-f a2 b2-f))
;; The line cross the grid in the main axis. We have at least
;; 2 segments.
(t
(let* ((b-m b1-m)
(delta-a (- a2 a1))
(delta-b (abs (- b2 b1)))
(b-increment (signum (- b2 b1)))
(from-boundary (if (< b1 b2) 0 +cell-width+))
(to-boundary (if (< b1 b2) +cell-width+ 0)))
(multiple-value-bind (a ma) (floor (+ (* delta-a (if (< b1 b2)
(- +cell-width+ b1-f)
b1-f))
;; a littre change compared to
;; AntiGrain AA algorithm. Used
;; to round to the nearest integer
;; instead of the "floor" one.
(floor delta-b 2))
delta-b)
(incf a a1)
;; The first segment (to reach the first grid boundary)
(funcall function b1-m a1 b1-f a to-boundary)
(incf b-m b-increment)
(when (/= b-m b2-m)
(multiple-value-bind (step mod) (floor (* +cell-width+ delta-a) delta-b)
(loop
do (let ((prev-a a))
(incf a step)
(incf ma mod)
(when (>= ma delta-b)
(incf a)
(decf ma delta-b))
;; A segment from one grid boundary to the other.
(funcall function b-m prev-a from-boundary a to-boundary)
(incf b-m b-increment))
while (/= b-m b2-m))))
;; The last segment (from the latest grid boundary up to
;; the final coordinates.)
(funcall function b-m a from-boundary a2 b2-f))))))))
(defun map-grid-spans (function x1 y1 x2 y2)
"Call FUNCTION for each segments of the line from (X1,Y1)
to (X2,Y2) cut by a grid with spacing +CELL-WIDTH+."
(check-type x1 integer)
(check-type y1 integer)
(check-type x2 integer)
(check-type y2 integer)
(flet ((hline (y-m x1 y1-f x2 y2-f)
(declare (integer y-m x1 y1-f x2 y2-f))
(flet ((pixel (x-m y1-f x1-f y2-f x2-f)
(declare (integer x-m y1-f x1-f y2-f x2-f))
(funcall function x-m y-m x1-f y1-f x2-f y2-f)))
;; further split along Y axis
(map-line-spans #'pixel y1-f x1 y2-f x2))))
;; first split along X axis
(map-line-spans #'hline x1 y1 x2 y2)))
;;;--[ cell ]-----------------------------------------------------------------
;;; Note that cover and area are unbound and could take any value
;;; while drawing polygons (even negative values), especially when
;;; drawing multiple overlapping polygons. However, for non
;;; overlapping polygons, cover is in the range (-width,width) and
;;; area in the range (-2*width*width,2*width*width), where width is
;;; +cell-width+ defined above.
(defstruct cell
"A cell used to represent the partial area covered by a line
passing by a corresponding pixel. The cell alone doesn't hold all
the information to calculate the area."
(x 0 :type integer)
(y 0 :type integer)
(cover 0 :type integer)
(area 0 :type integer))
(declaim (inline cell-empty-p))
(defun cell-empty-p (cell)
"Test if the cell is empty. A cell is empty when COVER and AREA
are both zero."
(and (zerop (cell-cover cell))
(zerop (cell-area cell))))
(declaim (inline cell-reset))
(defun cell-reset (cell)
"Reset the cell such that CELL-EMPTY-P is true."
(setf (cell-area cell) 0
(cell-cover cell) 0))
(declaim (inline compare-cells))
(defun compare-cells (a b)
"Compare coordinates between 2 cells. Used to sort cells by Y,
then by X."
(or (< (cell-y a) (cell-y b))
(and (= (cell-y a) (cell-y b))
(< (cell-x a) (cell-x b)))))
(declaim (inline update-cell))
(defun update-cell (cell fx1 fy1 fx2 fy2)
"Update COVER and AREA given a segment inside the corresponding
cell. FX1, FY1, FX2 and FY2 must be subpixel coordinates between
0 and +CELL-WIDTH+ included."
(let ((delta (- fy2 fy1)))
(incf (cell-cover cell) delta)
;; Note: increase by twice the area, for optimization
;; purpose. Will be divided by 2 in the final pass.
(incf (cell-area cell) (* (+ fx1 fx2) delta))))
;;;-------------------------------------------------------------------------
(defconstant +alpha-range+ 256
"For non overlapping polygons, the alpha value will be in the
range (-limit,limit) where limit is +alpha-range+. The value is
negative or positive accordingly to the polygon
orientation (clockwise or counter-clockwise.)")
(defconstant +alpha-divisor+ (floor (* 2 +cell-width+ +cell-width+)
+alpha-range+)
"Constant used to translate value computed by AREA and COVER to
an alpha value.")
(defstruct state
"AA state. Hold all the cells generated when drawing lines."
(current-cell (make-cell) :type cell)
(cells nil)
(scanlines nil)
;; these slots for reusing cells with state-reset
(end-of-lines nil)
(dropped-cells nil)
(recycling-cells (cons nil nil)))
(defun state-reset (state)
"Reset the state, losing all accumulated cells. It can be
faster or less memory consuming to reset a state and reuse it,
rather than creating a new state."
(cell-reset (state-current-cell state))
(when (state-end-of-lines state)
;; join back the scanlines to form a single list
(loop for line in (rest (state-scanlines state))
for eol in (state-end-of-lines state)
do (setf (cdr eol) line)))
(let ((cells (nconc (state-dropped-cells state)
(state-cells state))))
(setf (state-recycling-cells state) (cons nil cells)
(state-scanlines state) nil
(state-end-of-lines state) nil
(state-dropped-cells state) nil
(state-cells state) cells)))
(declaim (inline state-push-current-cell))
(defun state-push-cell (state cell)
"Store a copy of the current cell into the cells list. If the
state was reset, possibly reuse previous cells."
(unless (cell-empty-p cell)
(let ((recycling-cells (cdr (state-recycling-cells state))))
(cond
(recycling-cells
(let ((target-cell (car recycling-cells)))
(setf (cell-x target-cell) (cell-x cell)
(cell-y target-cell) (cell-y cell)
(cell-cover target-cell) (cell-cover cell)
(cell-area target-cell) (cell-area cell)))
(setf (state-recycling-cells state) recycling-cells))
(t
(push (copy-cell cell) (state-cells state)))))))
(defun state-finalize (state)
"Finalize the state."
;; Ensure that the current cell is stored with other cells and that
;; old cells (before the last reset) that were not reused are
;; correctly removed from the result.
(let ((current-cell (state-current-cell state)))
(unless (cell-empty-p current-cell)
(state-push-cell state current-cell)
(cell-reset current-cell))
(when (cdr (state-recycling-cells state))
(setf (cdr (state-recycling-cells state)) nil)
(unless (car (state-recycling-cells state))
(setf (state-cells state) nil)))))
(defun set-current-cell (state x y)
"Ensure current cell is one at coordinate X and Y. If not,
the current cell is stored, then reset accordingly to new
coordinate.
Returns the current cell."
(let ((current-cell (state-current-cell state)))
(declare (cell current-cell))
(when (or (/= x (cell-x current-cell))
(/= y (cell-y current-cell)))
;; Store the current cell, then reset it.
(state-push-cell state current-cell)
(setf (cell-x current-cell) x
(cell-y current-cell) y
(cell-cover current-cell) 0
(cell-area current-cell) 0))
current-cell))
(defun state-sort-cells (state)
"Sort the cells by Y, then by X."
(setf (state-cells state)
(sort (state-cells state) #'compare-cells)))
(defun line (state x1 y1 x2 y2)
"Draw a line from (X1,Y1) to (X2,Y2). All coordinates are
integers with subpixel accuracy (a pixel width is given by
+CELL-WIDTH+.) The line must be part of a closed polygon."
(declare (integer x1 y1 x2 y2))
(map-grid-spans (lambda (x y fx1 fy1 fx2 fy2)
(update-cell (set-current-cell state x y)
fx1 fy1 fx2 fy2))
x1 y1 x2 y2))
(defun line-f (state x1 y1 x2 y2)
"Draw a line, whose coordinates are translated to fixed-point
as expected by function LINE. This is a convenient function to
not depend on +CELL-WIDTH+."
(labels ((float-to-fixed (n)
(values (round (* +cell-width+ n)))))
(line state
(float-to-fixed x1) (float-to-fixed y1)
(float-to-fixed x2) (float-to-fixed y2))))
(declaim (inline compute-alpha))
(defun compute-alpha (cover area)
"Compute the alpha value given the accumulated cover and the
actual area of a cell."
(truncate (- (* 2 +cell-width+ cover) area)
+alpha-divisor+))
(defun freeze-state (state)
"Freeze the state and return a list of scanlines. A scanline is
an object which can be examined with SCANLINE-Y and processed
with SCANLINE-SWEEP."
(unless (state-scanlines state)
(state-finalize state)
(state-sort-cells state)
(let (lines
end-of-lines
dropped-cells
(cells (state-cells state)))
(when cells
(push cells lines)
(let ((previous-cell (first cells)))
(loop
(unless (rest cells)
(return))
(let ((cell (second cells))
(rest (cdr cells)))
(cond
((/= (cell-y previous-cell) (cell-y cell))
;; different y, break the cells list, begin a new
;; line.
(push cells end-of-lines)
(push rest lines)
(setf (cdr cells) nil
previous-cell cell)
(setf cells rest))
((/= (cell-x previous-cell) (cell-x cell))
;; same y, different x, do nothing special, move to
;; the next cell.
(setf previous-cell cell)
(setf cells rest))
(t
;; same coordinates, accumulate current cell into
;; the previous, and remove current from the list.
(incf (cell-cover previous-cell) (cell-cover cell))
(incf (cell-area previous-cell) (cell-area cell))
(push cell dropped-cells)
(setf (cdr cells) (cdr rest))))))))
(setf (state-scanlines state) (nreverse lines)
(state-end-of-lines state) (nreverse end-of-lines)
(state-dropped-cells state) dropped-cells)))
(state-scanlines state))
(declaim (inline scanline-y))
(defun scanline-y (scanline)
"Get the Y position of SCANLINE."
(cell-y (first scanline)))
(defun scanline-sweep (scanline function function-span &key start end)
"Call FUNCTION for each pixel on the polygon covered by
SCANLINE. The pixels are scanned in increasing X. The sweep can
be limited to a range by START (included) or/and END (excluded)."
(declare (optimize speed (debug 0) (safety 0) (space 2)))
(let ((cover 0)
(y (scanline-y scanline))
(cells scanline)
(last-x nil))
(when start
;; skip initial cells that are before START
(loop while (and cells (< (cell-x (car cells)) start))
do (incf cover (cell-cover (car cells)))
(setf last-x (cell-x (car cells))
cells (cdr cells))))
(when cells
(dolist (cell cells)
(let ((x (cell-x cell)))
(when (and last-x (> x (1+ last-x)))
(let ((alpha (compute-alpha cover 0)))
(unless (zerop alpha)
(let ((start-x (if start (max start (1+ last-x)) (1+ last-x)))
(end-x (if end (min end x) x)))
(if function-span
(funcall function-span start-x end-x y alpha)
(loop for ix from start-x below end-x
do (funcall function ix y alpha)))))))
(when (and end (>= x end))
(return))
(incf cover (cell-cover cell))
(let ((alpha (compute-alpha cover (cell-area cell))))
(unless (zerop alpha)
(funcall function x y alpha)))
(setf last-x x))))))
(defun cells-sweep/rectangle (state x1 y1 x2 y2 function &optional function-span)
"Call FUNCTION for each pixel on the polygon described by
previous call to LINE or LINE-F. The pixels are scanned in
increasing Y, then on increasing X. This is limited to the
rectangle region specified with (X1,Y1)-(X2,Y2) (where X2 must be
greater than X1 and Y2 must be greater than Y1, to describe a
non-empty region.)
For optimization purpose, the optional FUNCTION-SPAN, if
provided, is called for a full span of identical alpha pixel. If
not provided, a call is made to FUNCTION for each pixel in the
span."
(let ((scanlines (freeze-state state)))
(dolist (scanline scanlines)
(when (<= y1 (scanline-y scanline) (1- y2))
(scanline-sweep scanline function function-span :start x1 :end x2))))
(values))
(defun cells-sweep (state function &optional function-span)
"Call FUNCTION for each pixel on the polygon described by
previous call to LINE or LINE-F. The pixels are scanned in
increasing Y, then on increasing X.
For optimization purpose, the optional FUNCTION-SPAN, if
provided, is called for a full span of identical alpha pixel. If
not provided, a call is made to FUNCTION for each pixel in the
span."
(let ((scanlines (freeze-state state)))
(dolist (scanline scanlines)
(scanline-sweep scanline function function-span)))
(values))
| 21,643 | Common Lisp | .lisp | 493 | 37.261663 | 88 | 0.610951 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 2c598ad806f34d72c61a3b99d86288b3a55893d2c7822b56c27db6b764189978 | 42,954 | [
-1
] |
42,955 | aa-bin.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/aa-bin.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
;;;; See http://projects.tuxee.net/cl-vectors/
;;;; The name 'cl-aa-bin' is derived from 'cl-aa' which is the library
;;;; used to rasterize antialiased polygons. The '-bin' version
;;;; doesn't perform antialiasing (the alpha value is always a
;;;; multiple of 256), but support the same protocol (drop-in
;;;; replacement) hence the choice of the name.
;;;; The aa-bin algorithm is faster and more accurate than when using
;;;; the original 'cl-aa' algorithm as a non-antialiasing rasterizer.
;;;; The algorithm compute all the pixels whose "center" (assuming a
;;;; "pixel is a little square"..) are inside the polygon to
;;;; rasterize.
(defpackage #:net.tuxee.aa-bin
(:use #:cl)
(:nicknames #:aa-bin)
(:export #:make-state
#:line
#:line-f
#:cells-sweep))
(in-package #:net.tuxee.aa-bin)
(defconstant +cell-width+ 256
"A cell represent a pixel square, and the width is the
fractional part of the fixed-point coordinate. A large value
increase precision. 256 should be enough though. Note that
smaller value should NOT increase performance.")
(defconstant +alpha-range+ 256
"For non overlapping polygons, the alpha value will be in the
range (-limit,limit) where limit is +alpha-range+. The value is
negative or positive accordingly to the polygon
orientation (clockwise or counter-clockwise.)")
(defun map-line-intersections (function x1 y1 x2 y2)
(declare (optimize speed (safety 0) (debug 0)))
(when (/= y1 y2)
(when (> y1 y2)
(rotatef y1 y2)
(rotatef x1 x2))
(let ((dx (- x2 x1))
(dy (- y2 y1)))
;; FIXME: optimize the loop with the usual Bresenham integer
;; algorithm
(loop for n from (* +cell-width+ (ceiling y1 +cell-width+))
upto (* +cell-width+ (floor (1- y2) +cell-width+))
by +cell-width+
do (funcall function
(+ x1 (floor (* dx (- n y1)) dy))
n)))))
(defstruct cell
x y (value 0))
(defstruct state
"AA state. Hold all the cells generated when drawing lines."
(cells nil))
(defun state-reset (state)
"Reset the state, losing all accumulated cells. It can be
faster or less memory consuming to reset a state and reuse it,
rather than creating a new state."
(setf (state-cells state) nil))
(declaim (inline set-current-cell))
(defun set-current-cell (state x y)
(let ((cells (state-cells state)))
(if (and cells
(= (cell-x (first cells)) x)
(= (cell-y (first cells)) y))
(first cells)
(let ((cell (make-cell :x x :y y)))
(push cell (state-cells state))
cell))))
(defun line (state x1 y1 x2 y2)
(when (/= y1 y2)
(map-line-intersections (lambda (x y)
(let ((x-m (ceiling x +cell-width+))
(y-m (floor y +cell-width+)))
(incf (cell-value (set-current-cell state x-m y-m))
(if (< y1 y2) 1 -1))))
(- x1 (floor +cell-width+ 2))
(- y1 (floor +cell-width+ 2))
(- x2 (floor +cell-width+ 2))
(- y2 (floor +cell-width+ 2)))))
(defun line-f (state x1 y1 x2 y2)
"Draw a line, whose coordinates are translated to fixed-point
as expected by function LINE. This is a convenient function to
not depend on +CELL-WIDTH+."
(labels ((float-to-fixed (n)
(values (round (* +cell-width+ n)))))
(line state
(float-to-fixed x1) (float-to-fixed y1)
(float-to-fixed x2) (float-to-fixed y2))))
(declaim (inline compare-cells))
(defun compare-cells (a b)
"Compare coordinates between 2 cells. Used to sort cells by Y,
then by X."
(or (< (cell-y a) (cell-y b))
(and (= (cell-y a) (cell-y b))
(< (cell-x a) (cell-x b)))))
(defun cells-sweep (state function &optional span-function)
"Call FUNCTION for each pixel on the polygon path described by
previous call to LINE or LINE-F. The pixels are scanned in
increasing Y, then on increasing X. For optimization purpose, the
optional FUNCTION-SPAN, if provided, is called for a full span of
identical alpha pixel. If not provided, a call is made to
FUNCTION for each pixel in the span."
(setf (state-cells state) (sort (state-cells state) #'compare-cells))
(let (x y value)
(flet ((call ()
(unless (zerop value)
(funcall function x y (* +alpha-range+ value)))))
(dolist (cell (state-cells state))
(cond
((null value)
;; first cell
(setf x (cell-x cell)
y (cell-y cell)
value (cell-value cell)))
((/= (cell-y cell) y)
;; different y
(call)
(setf x (cell-x cell)
y (cell-y cell)
value (cell-value cell)))
((/= (cell-x cell) x)
;; same y, different x
(call)
(unless (zerop value)
(let ((scaled-value (* +alpha-range+ value)))
(if (and (> (- (cell-x cell) x) 1)
span-function)
(funcall span-function (1+ x) (cell-x cell) y scaled-value)
(loop for ix from (1+ x) below (cell-x cell)
do (funcall function ix y scaled-value)))))
(setf x (cell-x cell))
(incf value (cell-value cell)))
(t
;; same cell, accumulate
(incf value (cell-value cell)))))
(when value
(call)))))
| 5,783 | Common Lisp | .lisp | 137 | 33.817518 | 83 | 0.587347 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 0983b0e8a330488c00cb8339e8047be22be1d32ba140a95e2c072194d206d8df | 42,955 | [
-1
] |
42,956 | paths.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-vectors-20180228-git/paths.lisp | ;;;; cl-vectors -- Rasterizer and paths manipulation library
;;;; Copyright (C) 2007-2013 Frédéric Jolliton <[email protected]>
;;;; This code is licensed under the MIT license.
;;;; This file provides facilities to create and manipulate vectorial paths.
#+nil(error "This file assume that #+NIL is never defined.")
(in-package #:net.tuxee.paths)
(defvar *bezier-distance-tolerance* 0.5
"The default distance tolerance used when rendering Bezier
curves.")
(defvar *bezier-angle-tolerance* 0.05
"The default angle tolerance (in radian) used when rendering
Bezier curves")
(defvar *arc-length-tolerance* 1.0
"The maximum length of segment describing an arc.")
(defvar *miter-limit* 4.0
"Miter limit before reverting to bevel joint. Must be >=1.0.")
;;;--[ Math utilities ]------------------------------------------------------
;;; http://mathworld.wolfram.com/Line-LineIntersection.html
(defun line-intersection (x1 y1 x2 y2
x3 y3 x4 y4)
"Compute the intersection between 2 lines (x1,y1)-(x2,y2)
and (x3,y3)-(x4,y4). Return the coordinates of the intersection
points as 2 values. If the 2 lines are colinears, return NIL."
(flet ((det (a b c d)
(- (* a d)
(* b c))))
(let* ((dx1 (- x2 x1))
(dy1 (- y2 y1))
(dx2 (- x4 x3))
(dy2 (- y4 y3))
(d (det dx2 dy2 dx1 dy1)))
(unless (zerop d)
(let ((a (det x1 y1 x2 y2))
(b (det x3 y3 x4 y4)))
(values (/ (det a dx1 b dx2) d)
(/ (det a dy1 b dy2) d)))))))
(defun line-intersection/delta (x1 y1 dx1 dy1
x2 y2 dx2 dy2)
"Compute the intersection between the line by (x1,y1) and
direction (dx1,dy1) and the line by (x2,y2) and
direction (dx2,dy2). Return the coordinates of the intersection
points as 2 values. If the 2 lines are colinears, return NIL."
(flet ((det (a b c d)
(- (* a d)
(* b c))))
(let ((d (det dx2 dy2 dx1 dy1)))
(unless (zerop d)
(let ((a (det x1 y1 (+ x1 dx1) (+ y1 dy1)))
(b (det x2 y2 (+ x2 dx2) (+ y2 dy2))))
(values (/ (det a dx1 b dx2) d)
(/ (det a dy1 b dy2) d)))))))
(defun normalize (x y &optional (length 1.0))
"Normalize the vector (X,Y) such that its length is LENGTH (or
1.0 if unspecified.) Return the component of the resulting vector
as 2 values. Return NIL if the input vector had a null length."
(if (zerop length)
(values 0.0 0.0)
(let ((norm (/ (sqrt (+ (* x x) (* y y))) length)))
(unless (zerop norm)
(values (/ x norm) (/ y norm))))))
(defun line-normal (x1 y1 x2 y2)
"Normalize the vector (X2-X1,Y2-Y1). See NORMALIZE."
(normalize (- x2 x1) (- y2 y1)))
;;;--[ Points ]--------------------------------------------------------------
;;; Points are supposed to be immutable
(declaim (inline make-point point-x point-y))
(defun make-point (x y) (cons x y))
(defun point-x (point) (car point))
(defun point-y (point) (cdr point))
;;; Utility functions for points
(defun p+ (p1 p2)
(make-point (+ (point-x p1) (point-x p2))
(+ (point-y p1) (point-y p2))))
(defun p- (p1 p2)
(make-point (- (point-x p1) (point-x p2))
(- (point-y p1) (point-y p2))))
(defun p* (point scale &optional (scale-y scale))
(make-point (* (point-x point) scale)
(* (point-y point) scale-y)))
(defun point-rotate (point angle)
"Rotate POINT by ANGLE radian around the origin."
(let ((x (point-x point))
(y (point-y point)))
(make-point (- (* x (cos angle)) (* y (sin angle)))
(+ (* y (cos angle)) (* x (sin angle))))))
(defun point-angle (point)
"Compute the angle of POINT relatively to the X axis."
(atan (point-y point) (point-x point)))
(defun point-norm (point)
"Compute the distance of POINT from origin."
(sqrt (+ (expt (point-x point) 2)
(expt (point-y point) 2))))
;; (point-norm (p- p2 p1))
(defun point-distance (p1 p2)
"Compute the distance between P1 and P2."
(sqrt (+ (expt (- (point-x p2) (point-x p1)) 2)
(expt (- (point-y p2) (point-y p1)) 2))))
;; (p* (p+ p1 p2) 0.5)
(defun point-middle (p1 p2)
"Compute the point between P1 and P2."
(make-point (/ (+ (point-x p1) (point-x p2)) 2.0)
(/ (+ (point-y p1) (point-y p2)) 2.0)))
;;;--[ Paths ]---------------------------------------------------------------
(defstruct path
(type :open-polyline :type (member :open-polyline :closed-polyline :polygon))
(orientation :unknown :type (member :unknown :cw :ccw))
(knots (make-array 0 :adjustable t :fill-pointer 0))
(interpolations (make-array 0 :adjustable t :fill-pointer 0)))
(defun create-path (type)
"Create a new path of the given type. The type must be one of
the following keyword:
:open-polyline -- An open polyline path,
:closed-polyline -- A closed polyline path,
:polygon -- Like :closed-polyline, but implicitly filled."
(assert (member type '(:open-polyline :closed-polyline :polygon)))
(make-path :type type))
(defun path-clear (path)
"Clear the path such that it is empty."
(setf (path-orientation path) :unknown
(fill-pointer (path-knots path)) 0
(fill-pointer (path-interpolations path)) 0))
(defun path-reset (path knot)
"Reset the path such that it is a single knot."
(path-clear path)
(vector-push-extend knot (path-knots path))
(vector-push-extend (make-straight-line) (path-interpolations path)))
(defun path-extend (path interpolation knot)
"Extend the path to KNOT, with INTERPOLATION."
(vector-push-extend interpolation (path-interpolations path))
(vector-push-extend knot (path-knots path))
;; Extending the path can change how the orientation is
;; auto-detected.
(setf (path-orientation path) :unknown))
(defun path-concatenate (path interpolation other-path)
"Append OTHER-PATH to PATH, joined by INTERPOLATION."
(let ((interpolations (path-interpolations other-path))
(knots (path-knots other-path)))
(loop for i below (length knots)
do (path-extend path
(interpolation-clone (if (and (zerop i) interpolation)
interpolation
(aref interpolations i)))
(aref knots i)))))
(defun path-replace (path other-path)
"Replace PATH with contents of OTHER-PATH."
(path-clear path)
(path-concatenate path nil other-path))
(defun path-size (path)
"Return the number of knots on the path."
(length (path-knots path)))
(defun path-last-knot (path)
"Return the last knot of the path. Return NIL if the path is
empty."
(let ((knots (path-knots path)))
(when (plusp (length knots))
(aref knots (1- (length knots))))))
(defun path-guess-orientation (path)
"Guess the orientation of the path.
This is implemented loosely because we don't take care about
interpolations. We only consider a polygon described by the
knots. However, it should work..
Update path orientation flag, and returns either :CW or :CCW."
(let ((knots (path-knots path)))
(let ((loose-area (loop for last-knot-index = (1- (length knots)) then knot-index
for knot-index below (length knots)
sum (- (* (point-x (aref knots last-knot-index))
(point-y (aref knots knot-index)))
(* (point-x (aref knots knot-index))
(point-y (aref knots last-knot-index)))))))
(setf (path-orientation path) (if (plusp loose-area) :ccw :cw)))))
(defun path-orient (path orientation &optional other-paths)
"Orient the path in the given orientation.
If OTHER-PATHS is specified, then the paths are reversed
inconditionnaly if PATH is also reversed."
(assert (member orientation '(:cw :ccw)) (orientation) "Expected either :CW or :CCW")
(when (eq (path-orientation path) :unknown)
(path-guess-orientation path))
(unless (eq (path-orientation path) orientation)
(path-reverse path)
(map nil #'path-reverse other-paths))
(values))
;;; Iterators
(defgeneric path-iterator-reset (iterator)
(:documentation "Reset the iterator before the first knot."))
(defgeneric path-iterator-next (iterator)
(:documentation "Move the iterator to the next knot, and return
3 values: INTERPOLATION, KNOT and END-P. INTERPOLATION is the
interpolation between the previous knot and the current one. For
the first iteration, INTERPOLATION is usually the implicit
straight line between the last knot and the first knot. KNOT and
INTERPOLATION are null if the path is empty. END-P is true if the
knot is the last on the path or if the path is empty."))
(defun path-from-iterator (iterator type)
"Construct a new path from the given iterator."
(let ((path (create-path type)))
(loop
(multiple-value-bind (iterator knot end-p) (path-iterator-next iterator)
(path-extend path iterator knot)
(when end-p
(return path))))))
;;; Classic iterator
(defstruct path-iterator-state
path index)
(defun path-iterator (path)
(make-path-iterator-state :path path :index nil))
(defmethod path-iterator-reset ((iterator path-iterator-state))
(setf (path-iterator-state-index iterator) nil))
(defmethod path-iterator-next ((iterator path-iterator-state))
(let* ((index (path-iterator-state-index iterator))
(path (path-iterator-state-path iterator))
(knots (path-knots path))
(interpolations (path-interpolations path)))
(cond
((zerop (length knots))
(values nil nil t))
(t
;; Update index to the next place
(setf index
(setf (path-iterator-state-index iterator)
(if (null index) 0 (mod (1+ index) (length knots)))))
(values (aref interpolations index)
(aref knots index)
(= index (1- (length knots))))))))
;;; Segmented iterator
;;;
;;; This iterator iterate over segmented interpolation, if the
;;; interpolation is matched by the predicate. This is useful for
;;; algorithms that doesn't handle certain type of interpolations.
;;; The predicate could test the type, but also certain type of
;;; interpolation (such as arc of circle vs arc of ellipse, or degree
;;; of the Bezier curves.)
;;; Note: I use PI prefix instead of PATH-ITERATOR to shorten names.
(defstruct pi-segmented-state
path index predicate end-p queue)
(defun path-iterator-segmented (path &optional (predicate (constantly t)))
(make-pi-segmented-state :path path :index nil
:predicate predicate
:end-p nil :queue nil))
(defmethod path-iterator-reset ((iterator pi-segmented-state))
(setf (pi-segmented-state-index iterator) nil
(pi-segmented-state-queue iterator) nil))
(defmethod path-iterator-next ((iterator pi-segmented-state))
(flet ((update-queue (interpolation k1 k2 last-p)
(let (new-queue)
(interpolation-segment interpolation k1 k2 (lambda (p) (push p new-queue)))
(push k2 new-queue)
(setf (pi-segmented-state-end-p iterator) last-p
(pi-segmented-state-queue iterator) (nreverse new-queue))))
(dequeue ()
(let* ((knot (pop (pi-segmented-state-queue iterator)))
(end-p (and (pi-segmented-state-end-p iterator)
(null (pi-segmented-state-queue iterator)))))
(values (make-straight-line) knot (when end-p t)))))
(cond
((pi-segmented-state-queue iterator)
;; Queue is not empty, process it first.
(dequeue))
(t
;; Either refill the queue, or return the next straight line
;; from the sub iterator.
(let* ((index (pi-segmented-state-index iterator))
(path (pi-segmented-state-path iterator))
(knots (path-knots path))
(interpolations (path-interpolations path)))
(cond
((zerop (length knots))
;; Empty path.
(values nil nil t))
(t
;; Update index to the next place
(setf index
(setf (pi-segmented-state-index iterator)
(if (null index) 0 (mod (1+ index) (length knots)))))
(let ((interpolation (aref interpolations index))
(knot (aref knots index))
(end-p (= index (1- (length knots)))))
;; Check if we have to segment the next interpolation
(if (funcall (pi-segmented-state-predicate iterator)
interpolation)
(let ((previous-index (mod (1- index) (length knots))))
(update-queue interpolation
(aref knots previous-index)
knot end-p)
(dequeue))
(values interpolation knot end-p))))))))))
;;; Iterate distinct
;;; This iterator filter out identical knots. That is, the knots with
;;; the same positions, with any interpolation. (All interpolations
;;; currently implemented are empty when knot around them are not
;;; distinct.)
;;; When cyclic-p is true, the first knot of the iterator is the first
;;; knot distinct from the first knot of the reference iterator.
;;; When cyclic-p is false, the first knot of the iterator if the
;;; first knot of the reference iterator, and if the path ends with a
;;; knot which is not distinct from the first, it is kept.
(defclass filter-distinct-state ()
((iterator :initarg :iterator)
(cyclic-p :initarg :cyclic-p)
(fixed :initarg :fixed)
(next :initarg :next)
(next-is-end-p)))
(defun filter-distinct (iterator &optional (preserve-cyclic-end-p nil))
(make-instance 'filter-distinct-state
:iterator iterator
:cyclic-p (not preserve-cyclic-end-p)
:fixed nil
:next nil))
(defmethod path-iterator-reset ((iterator filter-distinct-state))
(with-slots ((sub iterator) next next-is-end-p) iterator
(path-iterator-reset sub)
(setf next nil
next-is-end-p nil)))
(defmethod path-iterator-next ((iterator filter-distinct-state))
(with-slots ((sub iterator) cyclic-p fixed next next-is-end-p) iterator
(when fixed
;; constant result cached
(return-from path-iterator-next (values-list fixed)))
(labels ((get-next ()
"Get the next knot information as a list (not as
multiple values)."
(multiple-value-list (path-iterator-next sub)))
(distinct-p (a b)
"Test if A and B have distinct knots."
(not (zerop (point-distance (second a) (second b)))))
(move-to-next (previous loop-p)
"Move iterator to find a knot distinct from the
PREVIOUS. Also indicate if the resulting knot is
the first of the sub iterator, and if end of path
was encountered. This is needed to compute the
effective END-P flag for the resulting iterator."
(loop
with first-p = (third previous)
with end-encountered-p = (third previous)
for current = (get-next)
until (or (distinct-p previous current)
(and (not loop-p) first-p))
do (setf first-p (third current))
when (third current)
do (setf end-encountered-p t)
finally (return (values current first-p end-encountered-p)))))
(let (result)
(unless next
;; First time we iterate.
(setf next-is-end-p nil)
(let ((first (get-next)))
(cond
((or (not (second first))
(third first))
;; It was an empty path or a single knot path. Cache it
;; and returns it for each further iterations.
(setf fixed first
result first))
(cyclic-p
(multiple-value-bind (first-in-cycle first-p end-p) (move-to-next first nil)
(declare (ignore first-p))
(cond
(end-p
(setf (third first) t
fixed first
result first))
(t
(setf next first-in-cycle)))))
(t
(setf next first)))))
(unless result
;; We copy NEXT because we need to modify RESULT, and since
;; NEXT is kept for the next iteration, we take care of not
;; modifying it.
(setf result (copy-seq next)
(third result) next-is-end-p)
(multiple-value-bind (current first-p end-encountered-p) (move-to-next next cyclic-p)
(setf next current)
;; Set end marker
(cond
(cyclic-p
(setf next-is-end-p first-p)
(when (and end-encountered-p (not first-p))
(setf (third result) t)))
(t
(setf (third result) end-encountered-p)))))
(values-list result)))))
;;; Misc
(defun path-clone (path)
(let ((new-interpolations (copy-seq (path-interpolations path))))
(loop for i below (length new-interpolations)
do (setf (aref new-interpolations i)
(interpolation-clone (aref new-interpolations i))))
(let ((new-path (create-path (path-type path))))
(setf (path-knots new-path) (copy-seq (path-knots path))
(path-interpolations new-path) new-interpolations
(path-orientation new-path) (path-orientation path))
new-path)))
(defun path-reverse (path)
;; reverse the order of knots
(setf (path-knots path) (nreverse (path-knots path)))
;; reverse the order of interpolations 1..n (not the first one,
;; which is the implicit straight line.)
(loop with interpolations = (path-interpolations path)
with length = (length interpolations)
for i from 1 upto (floor (1- length) 2)
do (rotatef (aref interpolations i)
(aref interpolations (- length i))))
;; reverse each interpolation
(loop for interpolation across (path-interpolations path)
do (interpolation-reverse interpolation))
(unless (eq (path-orientation path) :unknown)
(setf (path-orientation path) (ecase (path-orientation path)
(:cw :ccw)
(:ccw :cw))))
path)
(defun path-reversed (path)
(let ((new-path (path-clone path)))
(path-reverse new-path)
new-path))
(defmacro do-path ((path interpolation knot) &body body)
(let ((path-sym (gensym))
(knots (gensym))
(interpolations (gensym))
(index (gensym)))
`(symbol-macrolet ((,interpolation (aref ,interpolations ,index))
(,knot (aref ,knots ,index)))
(loop
with ,path-sym = ,path
with ,knots = (path-knots ,path-sym)
with ,interpolations = (path-interpolations ,path-sym)
for ,index below (length ,knots)
do (progn ,@body)))))
(defun path-translate (path vector)
"Translate the whole path accordingly to VECTOR."
(if (listp path)
(dolist (path-item path)
(path-translate path-item vector))
(unless (and (zerop (point-x vector))
(zerop (point-y vector)))
(do-path (path interpolation knot)
(setf knot (p+ knot vector))
(interpolation-translate interpolation vector))))
path)
(defun path-rotate (path angle &optional center)
"Rotate the whole path by ANGLE radian around CENTER (which is
the origin if unspecified.)"
(if (listp path)
(dolist (path-item path)
(path-rotate path-item angle center))
(unless (zerop angle)
(when center
(path-translate path (p* center -1.0)))
(do-path (path interpolation knot)
(setf knot (point-rotate knot angle))
(interpolation-rotate interpolation angle))
(when center
(path-translate path center))))
path)
(defun path-scale (path scale-x scale-y &optional center)
"Scale the whole path by (SCALE-X,SCALE-Y) from CENTER (which
is the origin if unspecified.) Warning: not all interpolations
support non uniform scaling (when scale-x /= scale-y)."
;;; FIXME: What to do about path-orientation?
(if (listp path)
(dolist (path-item path)
(path-scale path-item scale-x scale-y center))
(progn
(when center
(path-translate path (p* center -1.0)))
(do-path (path interpolation knot)
(setf knot (p* knot scale-x scale-y))
(interpolation-scale interpolation scale-x scale-y))
(when center
(path-translate path center))
(when (minusp (* scale-x scale-y))
(path-reverse path))))
path)
(defun path-end-info (path side)
(when (>= (path-size path) 2)
(if (not side)
(values (aref (path-knots path) 0)
(interpolation-normal (aref (path-interpolations path) 1)
(aref (path-knots path) 0)
(aref (path-knots path) 1)
nil))
(let ((ks (length (path-knots path)))
(is (length (path-interpolations path))))
(values (aref (path-knots path) (1- ks))
(interpolation-normal (aref (path-interpolations path) (1- is))
(aref (path-knots path) (- is 2))
(aref (path-knots path) (- is 1))
t))))))
(defun path-transform-as-marker (path path-reference side &key (offset 0.0) (scale 1.0) (angle 0.0))
"Translate, rotate and scale PATH representing a marker such
that it is adapted to the PATH-REFERENCE. If SIDE is false, it is
placed at the start of the path, otherwise it is placed at the
end of the path."
(multiple-value-bind (knot normal) (path-end-info path-reference side)
(when knot
(path-rotate path (+ (/ pi -2) angle (point-angle normal)))
(path-scale path scale scale)
(path-translate path (p+ knot (p* normal offset)))
path)))
;;;--[ Interpolations ]------------------------------------------------------
(defgeneric interpolation-segment (interpolation k1 k2 function)
(:documentation "Segment the path between K1 and K2 described
by the INTERPOLATION. Call FUNCTION for each generated point on
the interpolation path."))
(defgeneric interpolation-normal (interpolation k1 k2 side)
(:documentation "Compute the normal, going \"outside\" at
either K1 (if SIDE is false) or K2 (if SIDE is true). Return NIL
if the normal cannot be computed. Return a point otherwise."))
(defgeneric interpolation-clone (interpolation)
(:documentation "Duplicate INTERPOLATION."))
(defgeneric interpolation-reverse (interpolation)
(:documentation "Reverse the path described by INTERPOLATION
in-place."))
(defgeneric interpolation-reversed (interpolation)
(:method (interpolation)
(let ((cloned-interpolation (interpolation-clone interpolation)))
(interpolation-reversed cloned-interpolation)
cloned-interpolation))
(:documentation "Duplicate and reverse the INTERPOLATION."))
(defgeneric interpolation-translate (interpolation vector))
(defgeneric interpolation-rotate (interpolation angle))
(defgeneric interpolation-scale (interpolation scale-x scale-y))
;;; Straight lines
(defun make-straight-line ()
:straight-line)
(defun straight-line-p (value)
(eq value :straight-line))
(defmethod interpolation-segment ((interpolation (eql :straight-line)) k1 k2 function)
(declare (ignore interpolation k1 k2 function)))
(defmethod interpolation-normal ((interpolation (eql :straight-line)) k1 k2 side)
(let* ((x1 (point-x k1))
(y1 (point-y k1))
(x2 (point-x k2))
(y2 (point-y k2))
(dx (- x2 x1))
(dy (- y2 y1))
(dist (sqrt (+ (expt dx 2) (expt dy 2)))))
(when (plusp dist)
(if side
(make-point (/ dx dist)
(/ dy dist))
(make-point (- (/ dx dist))
(- (/ dy dist)))))))
(defmethod interpolation-clone ((interpolation (eql :straight-line)))
(make-straight-line))
(defmethod interpolation-reverse ((interpolation (eql :straight-line)))
(declare (ignore interpolation)))
(defmethod interpolation-translate ((interpolation (eql :straight-line)) vector)
(declare (ignore interpolation vector)))
(defmethod interpolation-rotate ((interpolation (eql :straight-line)) angle)
(declare (ignore interpolation angle)))
(defmethod interpolation-scale ((interpolation (eql :straight-line)) scale-x scale-y)
(declare (ignore interpolation scale-x scale-y)))
;;; Arc (SVG style)
(defclass arc ()
((rx :initarg rx)
(ry :initarg ry)
(x-axis-rotation :initarg x-axis-rotation)
(large-arc-flag :initarg large-arc-flag) ; t = choose the longest arc, nil = choose the smallest arc
(sweep-flag :initarg sweep-flag))) ; t = arc on the right, nil = arc on the left
(defun make-arc (rx ry &key (x-axis-rotation 0.0) (large-arc-flag nil) (sweep-flag nil))
(make-instance 'arc
'rx rx
'ry ry
'x-axis-rotation x-axis-rotation
'large-arc-flag large-arc-flag
'sweep-flag sweep-flag))
(defun svg-arc-parameters/reverse (center rx ry rotation start-angle delta-angle)
"Conversion from center to endpoint parameterization of SVG arc.
Returns values P1, P2, LARGE-ARC-FLAG-P, SWEEP-FLAG-P."
(let ((p1 (point-rotate (make-point rx 0) start-angle))
(p2 (point-rotate (make-point rx 0) (+ start-angle delta-angle))))
(flet ((transform (p)
(p+
(point-rotate
(p* p 1.0 (/ rx ry))
rotation)
center)))
(values (transform p1) (transform p2)
(> (abs delta-angle) pi)
(plusp delta-angle)))))
(defun svg-arc-parameters (p1 p2 rx ry rotation large-arc-flag-p sweep-flag-p)
"Conversion from endpoint to center parameterization of SVG arc.
Returns values RC, RX, RY, START-ANGLE and DELTA-ANGLE, where RC is
the center of the ellipse, RX and RY are the normalized
radii (needed if scaling was necessary)."
(when (and (/= rx 0)
(/= ry 0))
;; [SVG] "If rX or rY have negative signs, these are dropped; the
;; absolute value is used instead."
(setf rx (abs rx)
ry (abs ry))
;; normalize boolean value to nil/t
(setf large-arc-flag-p (when large-arc-flag-p t)
sweep-flag-p (when sweep-flag-p t))
;; rp1 and rp2 are p1 and p2 into the coordinate system such
;; that rotation is cancelled and ellipse ratio is 1 (a circle.)
(let* ((rp1 (p* (point-rotate p1 (- rotation)) 1.0 (/ rx ry)))
(rp2 (p* (point-rotate p2 (- rotation)) 1.0 (/ rx ry)))
(rm (point-middle rp1 rp2))
(drp1 (p- rm rp1))
(dist (point-norm drp1)))
(when (plusp dist)
(let ((diff-sq (- (expt rx 2) (expt dist 2)))
rc)
(cond
((not (plusp diff-sq))
;; a/ scale the arc if it is too small to touch the points
(setf ry (* dist (/ ry rx))
rx dist
rc rm))
(t
;; b/ otherwise compute the center of the circle
(let ((d (/ (sqrt diff-sq) dist)))
(unless (eq large-arc-flag-p sweep-flag-p)
(setf d (- d)))
(setf rc (make-point (+ (point-x rm) (* (point-y drp1) d))
(- (point-y rm) (* (point-x drp1) d)))))))
(let* ((start-angle (point-angle (p- rp1 rc)))
(end-angle (point-angle (p- rp2 rc)))
(delta-angle (- end-angle start-angle)))
(when (minusp delta-angle)
(incf delta-angle (* 2 pi)))
(unless sweep-flag-p
(decf delta-angle (* 2 pi)))
(values (point-rotate (p* rc 1.0 (/ ry rx)) rotation) rx ry start-angle delta-angle)))))))
(defmethod interpolation-segment ((interpolation arc) k1 k2 function)
(let ((rotation (slot-value interpolation 'x-axis-rotation)))
(multiple-value-bind (rc rx ry start-angle delta-angle)
(svg-arc-parameters k1 k2
(slot-value interpolation 'rx)
(slot-value interpolation 'ry)
rotation
(slot-value interpolation 'large-arc-flag)
(slot-value interpolation 'sweep-flag))
(when rc
(loop with n = (max 3 (* (max rx ry) (abs delta-angle)))
for i from 1 below n
for angle = (+ start-angle (/ (* delta-angle i) n))
for p = (p+ (point-rotate
(p*
(make-point (* rx (cos angle))
(* rx (sin angle)))
1.0 (/ ry rx))
rotation)
rc)
do (funcall function p))))))
(defmethod interpolation-normal ((interpolation arc) k1 k2 side)
(let ((rotation (slot-value interpolation 'x-axis-rotation)))
(multiple-value-bind (rc rx ry start-angle delta-angle)
(svg-arc-parameters k1 k2
(slot-value interpolation 'rx)
(slot-value interpolation 'ry)
rotation
(slot-value interpolation 'large-arc-flag)
(slot-value interpolation 'sweep-flag))
(flet ((adjust (normal)
(let* ((p (point-rotate (p* normal 1.0 (/ ry rx)) rotation))
(d (point-norm p)))
(when (plusp delta-angle)
(setf d (- d)))
(make-point (/ (point-x p) d) (/ (point-y p) d)))))
(when rc
(let ((end-angle (+ start-angle delta-angle)))
(adjust (if side
(make-point (sin end-angle)
(- (cos end-angle)))
(make-point (- (sin start-angle))
(cos start-angle))))))))))
(defmethod interpolation-clone ((interpolation arc))
(make-arc (slot-value interpolation 'rx)
(slot-value interpolation 'ry)
:x-axis-rotation (slot-value interpolation 'x-axis-rotation)
:large-arc-flag (slot-value interpolation 'large-arc-flag)
:sweep-flag (slot-value interpolation 'sweep-flag)))
(defmethod interpolation-reverse ((interpolation arc))
(setf (slot-value interpolation 'sweep-flag)
(not (slot-value interpolation 'sweep-flag))))
(defmethod interpolation-translate ((interpolation arc) vector)
(declare (ignore interpolation vector)))
(defmethod interpolation-rotate ((interpolation arc) angle)
(incf (slot-value interpolation 'x-axis-rotation) angle))
(defmethod interpolation-scale ((interpolation arc) scale-x scale-y)
;; FIXME: Return :segment-me if scaling is not possible?
(assert (and (not (zerop scale-x))
(= scale-x scale-y)))
(with-slots (rx ry) interpolation
(setf rx (* rx scale-x)
ry (* ry scale-y))))
;;; Catmull-Rom
(defclass catmull-rom ()
((head
:initarg head)
(control-points
:initform (make-array 0)
:initarg control-points)
(queue
:initarg queue)))
(defun make-catmull-rom (head control-points queue)
(make-instance 'catmull-rom
'head head
'control-points (coerce control-points 'vector)
'queue queue))
(defmethod interpolation-segment ((interpolation catmull-rom) k1 k2 function)
(let* ((control-points (slot-value interpolation 'control-points))
(points (make-array (+ (length control-points) 4))))
(replace points control-points :start1 2)
(setf (aref points 0) (slot-value interpolation 'head)
(aref points 1) k1
(aref points (- (length points) 2)) k2
(aref points (- (length points) 1)) (slot-value interpolation 'queue))
(labels ((eval-catmull-rom (a b c d p)
;; http://www.mvps.org/directx/articles/catmull/
(* 0.5
(+ (* 2 b)
(* (+ (- a) c) p)
(* (+ (* 2 a) (* -5 b) (* 4 c) (- d)) (expt p 2))
(* (+ (- a) (* 3 b) (* -3 c) d) (expt p 3))))))
(loop for s below (- (length points) 3)
for a = (aref points (+ s 0)) then b
for b = (aref points (+ s 1)) then c
for c = (aref points (+ s 2)) then d
for d = (aref points (+ s 3))
do (funcall function b)
(loop with n = 32
for i from 1 below n
for p = (/ (coerce i 'float) n)
for x = (eval-catmull-rom (point-x a)
(point-x b)
(point-x c)
(point-x d)
p)
for y = (eval-catmull-rom (point-y a)
(point-y b)
(point-y c)
(point-y d)
p)
do (funcall function (make-point x y)))
(funcall function c)))))
(defmethod interpolation-normal ((interpolation catmull-rom) k1 k2 side)
(with-slots (head control-points queue) interpolation
(let (a b)
(if (zerop (length control-points))
(if side
(setf a k1
b queue)
(setf a k2
b head))
(if side
(setf a (aref control-points (1- (length control-points)))
b queue)
(setf a (aref control-points 0)
b head)))
(let* ((x1 (point-x a))
(y1 (point-y a))
(x2 (point-x b))
(y2 (point-y b))
(dx (- x2 x1))
(dy (- y2 y1))
(dist (sqrt (+ (expt dx 2) (expt dy 2)))))
(when (plusp dist)
(make-point (/ dx dist)
(/ dy dist)))))))
(defmethod interpolation-clone ((interpolation catmull-rom))
(make-catmull-rom (slot-value interpolation 'head)
(copy-seq (slot-value interpolation 'control-points))
(slot-value interpolation 'queue)))
(defmethod interpolation-reverse ((interpolation catmull-rom))
(rotatef (slot-value interpolation 'head)
(slot-value interpolation 'queue))
(nreverse (slot-value interpolation 'control-points)))
(defmethod interpolation-translate ((interpolation catmull-rom) vector)
(with-slots (head control-points queue) interpolation
(setf head (p+ head vector)
queue (p+ queue vector))
(loop for i below (length control-points)
do (setf (aref control-points i) (p+ (aref control-points i) vector)))))
(defmethod interpolation-rotate ((interpolation catmull-rom) angle)
(with-slots (head control-points queue) interpolation
(setf head (point-rotate head angle)
queue (point-rotate queue angle))
(loop for i below (length control-points)
do (setf (aref control-points i) (point-rotate (aref control-points i) angle)))))
(defmethod interpolation-scale ((interpolation catmull-rom) scale-x scale-y)
(with-slots (head control-points queue) interpolation
(setf head (p* head scale-x scale-y)
queue (p* queue scale-x scale-y))
(loop for i below (length control-points)
do (setf (aref control-points i) (p* (aref control-points i)
scale-x scale-y)))))
;;; Bezier curves
;;; [http://www.fho-emden.de/~hoffmann/bezier18122002.pdf]
(defclass bezier ()
((control-points
:initform (make-array 0)
:initarg control-points)))
(defun make-bezier-curve (control-points)
(make-instance 'bezier
'control-points (make-array (length control-points)
:initial-contents control-points)))
(defun split-bezier (points &optional (position 0.5))
"Split the Bezier curve described by POINTS at POSITION into
two Bezier curves of the same degree. Returns the curves as 2
values."
(let* ((size (length points))
(stack (make-array size))
(current points))
(setf (aref stack 0) points)
(loop for j from 1 below size
for next-size from (1- size) downto 1
do (let ((next (make-array next-size)))
(loop for i below next-size
for a = (aref current i)
for b = (aref current (1+ i))
do (setf (aref next i)
(make-point (+ (* (- 1.0 position) (point-x a))
(* position (point-x b)))
(+ (* (- 1.0 position) (point-y a))
(* position (point-y b))))))
(setf (aref stack j) next
current next)))
(let ((left (make-array (length points)))
(right (make-array (length points))))
(loop for i from 0 below size
for j from (1- size) downto 0
do (setf (aref left i) (aref (aref stack i) 0)
(aref right i) (aref (aref stack j) i)))
(values left right))))
(defun evaluate-bezier (points position)
"Evaluate the point at POSITION on the Bezier curve described
by POINTS."
(let* ((size (length points))
(temp (make-array (1- size))))
(loop for current = points then temp
for i from (length temp) downto 1
do (loop for j below i
for a = (aref current j)
for b = (aref current (1+ j))
do (setf (aref temp j)
(make-point (+ (* (- 1.0 position) (point-x a))
(* position (point-x b)))
(+ (* (- 1.0 position) (point-y a))
(* position (point-y b)))))))
(let ((p (aref temp 0)))
(values (point-x p) (point-y p)))))
(defun discrete-bezier-curve (points function
&key
(include-ends t)
(min-subdivide nil)
(max-subdivide 10)
(distance-tolerance *bezier-distance-tolerance*)
(angle-tolerance *bezier-angle-tolerance*))
"Subdivize Bezier curve up to certain criterions."
;; FIXME: Handle cusps correctly!
(unless min-subdivide
(setf min-subdivide (floor (log (1+ (length points)) 2))))
(labels ((norm (a b)
(sqrt (+ (expt a 2) (expt b 2))))
(refine-bezier (points depth)
(let* ((a (aref points 0))
(b (aref points (1- (length points))))
(middle-straight (point-middle a b)))
(multiple-value-bind (bx by) (evaluate-bezier points 0.5)
(when (or (< depth min-subdivide)
(and (<= depth max-subdivide)
(or (> (norm (- bx (point-x middle-straight))
(- by (point-y middle-straight)))
distance-tolerance)
(> (abs (- (atan (- by (point-y a)) (- bx (point-x a)))
(atan (- (point-y b) by) (- (point-x b) bx))))
angle-tolerance))))
(multiple-value-bind (a b) (split-bezier points 0.5)
(refine-bezier a (1+ depth))
(funcall function bx by)
(refine-bezier b (1+ depth))))))))
(when include-ends
(let ((p (aref points 0)))
(funcall function (point-x p) (point-y p))))
(refine-bezier points 0)
(when include-ends
(let ((p (aref points (1- (length points)))))
(funcall function (point-x p) (point-y p)))))
(values))
(defmethod interpolation-segment ((interpolation bezier) k1 k2 function)
(with-slots (control-points) interpolation
(let ((points (make-array (+ 2 (length control-points)))))
(replace points control-points :start1 1)
(setf (aref points 0) k1
(aref points (1- (length points))) k2)
(discrete-bezier-curve points
(lambda (x y) (funcall function (make-point x y)))
:include-ends nil))))
(defmethod interpolation-normal ((interpolation bezier) k1 k2 side)
(let ((control-points (slot-value interpolation 'control-points))
a b)
(if (zerop (length control-points))
(if side
(setf a k1
b k2)
(setf a k2
b k1))
(if side
(setf a (aref control-points (1- (length control-points)))
b k2)
(setf a (aref control-points 0)
b k1)))
(let* ((x1 (point-x a))
(y1 (point-y a))
(x2 (point-x b))
(y2 (point-y b))
(dx (- x2 x1))
(dy (- y2 y1))
(dist (sqrt (+ (expt dx 2) (expt dy 2)))))
(when (plusp dist)
(make-point (/ dx dist)
(/ dy dist))))))
(defmethod interpolation-clone ((interpolation bezier))
(let ((control-points (copy-seq (slot-value interpolation 'control-points))))
(loop for i below (length control-points)
do (setf (aref control-points i) (aref control-points i)))
(make-bezier-curve control-points)))
(defmethod interpolation-reverse ((interpolation bezier))
(nreverse (slot-value interpolation 'control-points)))
(defmethod interpolation-translate ((interpolation bezier) vector)
(with-slots (control-points) interpolation
(loop for i below (length control-points)
do (setf (aref control-points i) (p+ (aref control-points i) vector)))))
(defmethod interpolation-rotate ((interpolation bezier) angle)
(with-slots (control-points) interpolation
(loop for i below (length control-points)
do (setf (aref control-points i) (point-rotate (aref control-points i) angle)))))
(defmethod interpolation-scale ((interpolation bezier) scale-x scale-y)
(with-slots (control-points) interpolation
(loop for i below (length control-points)
do (setf (aref control-points i) (p* (aref control-points i)
scale-x scale-y)))))
;;;--[ Building paths ]------------------------------------------------------
(defun make-discrete-path (path)
"Construct a path with only straight lines."
(let ((result (create-path (path-type path)))
(knots (path-knots path))
(interpolations (path-interpolations path)))
(when (plusp (length knots))
;; nicer, but slower too.. (But not profiled. Premature optimization?)
#+nil(loop with iterator = (path-iterator-segmented path)
for (interpolation knot end-p) = (multiple-value-list (path-iterator-next iterator))
do (path-extend result interpolation knot)
until end-p)
(path-reset result (aref knots 0))
(loop
for i below (1- (length knots))
for k1 = (aref knots i)
for k2 = (aref knots (1+ i))
for interpolation = (aref interpolations (1+ i))
do (interpolation-segment interpolation k1 k2
(lambda (knot)
(path-extend result
(make-straight-line)
knot)))
do (path-extend result (make-straight-line) k2)
finally (unless (eq (path-type path) :open-polyline)
(interpolation-segment (aref interpolations 0) k2 (aref knots 0)
(lambda (knot)
(path-extend result
(make-straight-line)
knot))))))
result))
(defun make-circle-path (cx cy radius &optional (radius-y radius) (x-axis-rotation 0.0))
"Construct a path to represent a circle centered at CX,CY of
the specified RADIUS."
;; Note: We represent the circle with 2 arcs
(let ((path (create-path :polygon)))
(setf radius (abs radius)
radius-y (abs radius-y))
(when (= radius radius-y)
(setf x-axis-rotation 0.0))
(when (and (plusp radius) (plusp radius-y))
(let* ((center (make-point cx cy))
(p (point-rotate (make-point radius 0) x-axis-rotation))
(left (p+ center p))
(right (p- center p)))
(path-extend path (make-arc radius radius-y :x-axis-rotation x-axis-rotation) left)
(path-extend path (make-arc radius radius-y :x-axis-rotation x-axis-rotation) right)))
path))
(defun make-rectangle-path (x1 y1 x2 y2
&key (round nil) (round-x nil) (round-y nil))
;; FIXME: Instead: center + width + height + rotation ?
;; FIXME: Round corners? (rx, ry)
(when (> x1 x2)
(rotatef x1 x2))
(when (> y1 y2)
(rotatef y1 y2))
(let ((path (create-path :closed-polyline))
(round-x (or round-x round))
(round-y (or round-y round)))
(cond
((and round-x (plusp round-x)
round-y (plusp round-y))
(path-reset path (make-point (+ x1 round-x) y1))
(path-extend path (make-arc round-x round-y) (make-point x1 (+ y1 round-y)))
(path-extend path (make-straight-line) (make-point x1 (- y2 round-y)))
(path-extend path (make-arc round-x round-y) (make-point (+ x1 round-x) y2))
(path-extend path (make-straight-line) (make-point (- x2 round-x) y2))
(path-extend path (make-arc round-x round-y) (make-point x2 (- y2 round-y)))
(path-extend path (make-straight-line) (make-point x2 (+ y1 round-y)))
(path-extend path (make-arc round-x round-y) (make-point (- x2 round-x) y1)))
(t
(path-reset path (make-point x1 y1))
(path-extend path (make-straight-line) (make-point x1 y2))
(path-extend path (make-straight-line) (make-point x2 y2))
(path-extend path (make-straight-line) (make-point x2 y1))))
path))
(defun make-rectangle-path/center (x y dx dy &rest args)
(apply #'make-rectangle-path (- x dx) (- y dy) (+ x dx) (+ y dy) args))
(defun make-regular-polygon-path (x y radius sides &optional (start-angle 0.0))
(let ((path (create-path :closed-polyline)))
(loop for i below sides
for angle = (+ start-angle (/ (* i 2 pi) sides))
do (path-extend path (make-straight-line)
(make-point (+ x (* (cos angle) radius))
(- y (* (sin angle) radius)))))
path))
(defun make-simple-path (points &optional (type :open-polyline))
"Create a path with only straight line, by specifying only knots."
(let ((path (create-path type)))
(dolist (point points)
(path-extend path (make-straight-line) point))
path))
;;;--[ Transformations ]-----------------------------------------------------
(defmacro define-for-multiple-paths (name-multiple name-single &optional documentation)
"Define a new function named by NAME-MULTIPLE which accepts
either a single path or a list of paths as input from a function
named by NAME-SINGLE accepting only a single path and producing a
list of paths."
`(defun ,name-multiple (paths &rest args)
,@(when documentation (list documentation))
(loop for path in (if (listp paths) paths (list paths))
nconc (apply #',name-single path args))))
;;; Stroke
(defun stroke-path/1 (path thickness
&key (caps :butt) (joint :none) (inner-joint :none)
assume-type)
"Stroke the path."
(setf thickness (abs thickness))
(let ((half-thickness (/ thickness 2.0))
target)
;; TARGET is the path updated by the function LINE-TO and
;; EXTEND-TO below.
(labels ((filter-interpolation (interpolation)
;; We handle only straight-line and arc of circle. The
;; rest will be segmented.
(not (or (straight-line-p interpolation)
(and (typep interpolation 'arc)
(= (slot-value interpolation 'rx)
(slot-value interpolation 'ry))))))
(det (a b c d)
(- (* a d) (* b c)))
(arc (model)
"Make a new arc similar to MODEL but with a radius
updated to match the stroke."
(assert (= (slot-value model 'rx)
(slot-value model 'ry)))
(let ((shift (if (slot-value model 'sweep-flag)
(- half-thickness)
half-thickness)))
(make-arc (+ (slot-value model 'rx) shift)
(+ (slot-value model 'ry) shift)
:sweep-flag (slot-value model 'sweep-flag)
:large-arc-flag (slot-value model 'large-arc-flag))))
(line-to (p)
"Extend the path to knot P with a straight line."
(path-extend target (make-straight-line) p))
(extend-to (i p)
"EXtend the path to knot P with the given interpolation."
(path-extend target i p))
(do-single (k1)
"Produce the resulting path when the input path
contains a single knot."
(ecase caps
(:butt
nil)
(:square
(path-replace target
(make-rectangle-path/center (point-x k1)
(point-y k1)
half-thickness
half-thickness)))
(:round
(path-replace target
(make-circle-path (point-x k1)
(point-y k1)
half-thickness)))))
(do-first (k1 i2 k2)
"Process the first interpolation."
(let* ((normal (interpolation-normal i2 k1 k2 nil))
(n (p* normal half-thickness))
(d (point-rotate n (/ pi 2))))
(ecase caps
(:butt
(line-to (p- k1 d)))
(:square
(line-to (p+ (p+ k1 d) n))
(line-to (p+ (p- k1 d) n))
(unless (straight-line-p i2)
(line-to (p- k1 d))))
(:round
(extend-to (make-arc half-thickness half-thickness) (p- k1 d))))))
(do-last (k1 i2 k2)
"Process the last interpolation."
(let* ((normal (interpolation-normal i2 k1 k2 t))
(d (p* (point-rotate normal (/ pi 2)) half-thickness)))
(cond
((typep i2 'arc)
(extend-to (arc i2) (p+ k2 d)))
((straight-line-p i2)
(unless (eq caps :square)
(line-to (p+ k2 d))))
(t
(error "unexpected interpolation")))))
(do-segment (k1 i2 k2 i3 k3)
"Process intermediate interpolation."
(let* ((normal-a (interpolation-normal i2 k1 k2 t))
(normal-b (interpolation-normal i3 k2 k3 nil))
(outer-p (plusp (det (point-x normal-a) (point-y normal-a)
(point-x normal-b) (point-y normal-b))))
(d-a (p* (point-rotate normal-a (/ pi 2)) half-thickness))
(d-b (p* (point-rotate normal-b (/ pi -2)) half-thickness)))
(cond
((and (not outer-p)
(eq inner-joint :miter)
(straight-line-p i2)
(straight-line-p i3))
;; Miter inner joint between 2 straight lines
(multiple-value-bind (xi yi)
(line-intersection/delta
(point-x (p+ k2 d-a)) (point-y (p+ k2 d-a))
(point-x normal-a) (point-y normal-a)
(point-x (p+ k2 d-b)) (point-y (p+ k2 d-b))
(point-x normal-b) (point-y normal-b))
(cond
((and xi
(plusp (+ (* (- xi (point-x k1))
(point-x normal-a))
(* (- yi (point-y k1))
(point-y normal-a))))
(plusp (+ (* (- xi (point-x k3))
(point-x normal-b))
(* (- yi (point-y k3))
(point-y normal-b)))))
;; ok, intersection point
;; is behind segments
;; ends
(extend-to (make-straight-line) (make-point xi yi)))
(t
;; revert to basic joint
(line-to (p+ k2 d-a))
(line-to (p+ k2 d-b))))))
((and outer-p
(eq joint :miter)
(straight-line-p i2)
(straight-line-p i3))
;; Miter outer joint between 2 straight lines
(multiple-value-bind (xi yi)
(line-intersection/delta
(point-x (p+ k2 d-a)) (point-y (p+ k2 d-a))
(point-x normal-a) (point-y normal-a)
(point-x (p+ k2 d-b)) (point-y (p+ k2 d-b))
(point-x normal-b) (point-y normal-b))
(let ((i (make-point xi yi)))
(cond
((and xi
(<= (point-distance i k2)
(* half-thickness *miter-limit*)))
(line-to (make-point xi yi)))
(t
;; FIXME: Ugh. My math skill show its
;; limits. This is probably possible to
;; compute the same thing with less steps.
(let* ((p (p+ k2 (point-middle d-a d-b)))
(a (point-distance (p+ k2 d-a) i))
(b (- (* half-thickness *miter-limit*)
(point-distance k2 p)))
(c (point-distance p i))
(d (/ (* a b) c))
(p1 (p+ (p+ k2 d-a) (p* normal-a d)))
(p2 (p+ (p+ k2 d-b) (p* normal-b d))))
(line-to p1)
(line-to p2)))))))
(t
(extend-to (if (typep i2 'arc)
(arc i2)
(make-straight-line))
(p+ k2 d-a))
;; joint
(if outer-p
(ecase joint
((:none :miter)
(line-to (p+ k2 d-b)))
(:round
(extend-to (make-arc half-thickness half-thickness
:sweep-flag nil)
(p+ k2 d-b))))
(ecase inner-joint
((:none :miter)
(line-to (p+ k2 d-b)))
(:round
(extend-to (make-arc half-thickness half-thickness
:sweep-flag t)
(p+ k2 d-b)))))))))
(do-contour-half (path new-target first-half-p)
(setf target new-target)
(let ((iterator (filter-distinct (path-iterator-segmented path #'filter-interpolation)
t)))
(flet ((next ()
(path-iterator-next iterator)))
(multiple-value-bind (i1 k1 e1) (next)
(when k1
(cond
(e1
(when first-half-p
(do-single k1)))
(t
;; at least 2 knots
(multiple-value-bind (i2 k2 e2) (next)
(do-first k1 i2 k2)
;; rest of the path
(unless e2
(loop
(multiple-value-bind (i3 k3 e3) (next)
(do-segment k1 i2 k2 i3 k3)
(shiftf i1 i2 i3)
(shiftf k1 k2 k3)
(when e3
(return)))))
(do-last k1 i2 k2)))))))))
(do-contour-polygon (path new-target first-p)
(setf target new-target)
(let ((iterator (filter-distinct (path-iterator-segmented path #'filter-interpolation))))
(flet ((next ()
(path-iterator-next iterator)))
(multiple-value-bind (i1 k1 e1) (next)
(when k1
(cond
(e1
(when first-p
(do-single k1)))
(t
;; at least 2 knots
(multiple-value-bind (i2 k2 e2) (next)
;; rest of the path
(let (extra-iteration)
(when e2
(setf extra-iteration 2))
(loop
(multiple-value-bind (i3 k3 e3) (next)
(when (and extra-iteration (zerop extra-iteration))
(return))
(do-segment k1 i2 k2 i3 k3)
(shiftf i1 i2 i3)
(shiftf k1 k2 k3)
(cond
(extra-iteration
(decf extra-iteration))
(e3
(setf extra-iteration 2)))))))))))))))
(when (plusp half-thickness)
(ecase (or assume-type (path-type path))
(:open-polyline
(let ((result (create-path :polygon)))
(do-contour-half path result t)
(do-contour-half (path-reversed path) result nil)
(list result)))
(:closed-polyline
(let ((result-a (create-path :polygon))
(result-b (create-path :polygon)))
;; FIXME: What happen for single knot path?
(do-contour-polygon path result-a t)
(do-contour-polygon (path-reversed path) result-b nil)
(list result-a result-b)))
(:polygon
(let ((result (create-path :polygon)))
(do-contour-polygon path result t)
(list result))))))))
(define-for-multiple-paths stroke-path stroke-path/1)
;;; Dash
(defun dash-path/1 (path sizes &key (toggle-p nil) (cycle-index 0))
"Dash path. If TOGGLE-P is true, segments of odd indices are
kept, while if TOGGLE-P is false, segments of even indices are
kept. CYCLE indicate where to cycle the SIZES once the end is
reached."
(assert (<= 0 cycle-index (1- (length sizes)))
(cycle-index) "Invalid cycle index")
(assert (loop for size across sizes never (minusp size))
(sizes) "All sizes must be non-negative.")
(assert (loop for size across sizes thereis (plusp size))
(sizes) "At least one size must be positive.")
(flet ((interpolation-filter (interpolation)
(or (not (typep interpolation 'arc))
(/= (slot-value interpolation 'rx)
(slot-value interpolation 'ry)))))
(let (result
(current (create-path :open-polyline))
(current-length 0.0)
(toggle (not toggle-p))
(index 0)
(size (aref sizes 0))
(iterator (path-iterator-segmented path #'interpolation-filter)))
(flet ((flush ()
(when toggle
(push current result))
(setf toggle (not toggle))
(setf current (create-path :open-polyline)
current-length 0.0)
(incf index)
(when (= index (length sizes))
(setf index cycle-index))
(setf size (aref sizes index)))
(extend (interpolation knot length)
(path-extend current interpolation knot)
(incf current-length length)))
(loop
for previous-knot = nil then knot
for stop-p = nil then end-p
for (interpolation knot end-p) = (multiple-value-list (path-iterator-next iterator))
if (not previous-knot)
do (path-reset current knot)
else
do (etypecase interpolation
((eql :straight-line)
(let* ((delta (p- knot previous-knot))
(length (point-norm delta))
(pos 0.0))
(loop
(let ((missing (- size current-length))
(available (- length pos)))
(when (> missing available)
(extend (make-straight-line) knot available)
(return))
(incf pos missing)
(let ((end (p+ previous-knot (p* delta (/ pos length)))))
(extend (make-straight-line) end missing)
(flush)
(path-reset current end))))))
(arc
(with-slots (rx ry x-axis-rotation large-arc-flag sweep-flag) interpolation
(assert (= rx ry))
(multiple-value-bind (rc nrx nry start-angle delta-angle)
(svg-arc-parameters previous-knot knot rx ry
x-axis-rotation
large-arc-flag
sweep-flag)
(let* ((length (* (abs delta-angle) nrx))
(pos 0.0))
(loop
(let ((missing (- size current-length))
(available (- length pos)))
(when (> missing available)
(extend (make-arc nrx nry
:x-axis-rotation x-axis-rotation
:large-arc-flag (>= (/ available nrx) pi)
:sweep-flag sweep-flag)
knot
available)
(return))
(incf pos missing)
(let ((end (p+
(point-rotate (make-point nrx 0)
(+ x-axis-rotation
(if (plusp delta-angle)
(+ start-angle (/ pos nrx))
(- start-angle (/ pos nrx)))))
rc)))
(extend (make-arc nrx nry
:x-axis-rotation x-axis-rotation
:large-arc-flag (>= (/ missing nrx) pi)
:sweep-flag sweep-flag)
end
missing)
(flush)
(path-reset current end)))))))))
until (if (eq (path-type path) :open-polyline) end-p stop-p))
(flush))
(nreverse result))))
(define-for-multiple-paths dash-path dash-path/1)
;;; Clip path
(defun clip-path/1 (path x y dx dy)
(let (result
(current (create-path (path-type path)))
(iterator (path-iterator-segmented path)))
(labels ((next ()
(path-iterator-next iterator))
(det (a b c d)
(- (* a d) (* b c)))
(inside-p (p)
(plusp (det (- (point-x p) x)
(- (point-y p) y)
dx dy)))
(clip-left (k1 k2)
(let ((k1-inside-p (when (inside-p k1) t))
(k2-inside-p (when (inside-p k2) t)))
(when k1-inside-p
(path-extend current (make-straight-line) k1))
(when (not (eq k1-inside-p k2-inside-p))
(multiple-value-bind (xi yi)
(line-intersection/delta x y dx dy
(point-x k1) (point-y k1)
(- (point-x k2) (point-x k1))
(- (point-y k2) (point-y k1)))
(when xi
(path-extend current (make-straight-line) (make-point xi yi))))))))
(multiple-value-bind (i1 k1 e1) (next)
(let ((first-knot k1))
(when k1
(cond
(e1
(when (inside-p k1)
(path-reset current k1)))
(t
(loop
(multiple-value-bind (i2 k2 e2) (next)
(clip-left k1 k2)
(when e2
(if (eq (path-type path) :open-polyline)
(when (inside-p k2)
(path-extend current (make-straight-line) k2))
(clip-left k2 first-knot))
(return))
(setf i1 i2)
(setf k1 k2)))))))))
(push current result)
result))
(define-for-multiple-paths clip-path clip-path/1)
(defun clip-path/path/1 (path limit)
(let ((iterator (filter-distinct (path-iterator-segmented limit)))
(result (list path)))
(multiple-value-bind (i1 k1 e1) (path-iterator-next iterator)
(declare (ignore i1))
(when (and k1 (not e1))
(let ((stop-p nil))
(loop
(multiple-value-bind (i2 k2 e2) (path-iterator-next iterator)
(declare (ignore i2))
(setq result (loop for path in result
nconc (clip-path path
(point-x k1) (point-y k1)
(point-x (p- k2 k1)) (point-y (p- k2 k1)))))
(when stop-p
(return result))
(when e2
(setf stop-p t))
(setf k1 k2))))))))
(define-for-multiple-paths clip-path/path clip-path/path/1)
#|
;;; Round path
(defun round-path/1 (path &optional max-radius)
(declare (ignore max-radius))
(list path))
(define-for-multiple-paths round-path round-path/1)
|#
| 68,905 | Common Lisp | .lisp | 1,458 | 33.474623 | 104 | 0.522261 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | bf4cb3f1d99560f4f9e8c81fe9a189db6a69975ffe8a689ca50edc2a879cd747 | 42,956 | [
-1
] |
42,957 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/grovel/package.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; package.lisp --- Groveler DEFPACKAGE.
;;;
;;; 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.
;;;
(uiop:define-package #:cffi-grovel
(:mix #:cffi-toolchain #:asdf #:uiop #:alexandria #:common-lisp)
(:export
;; Class name
#:grovel-file
#:process-grovel-file
#:wrapper-file
#:process-wrapper-file
;; Error conditions
#:grovel-error
#:missing-definition))
| 1,483 | Common Lisp | .lisp | 35 | 40.542857 | 70 | 0.736006 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 37994ebfeb1c14f6bf1aed7efe4d85a62459827166848195814b61de6229a8ac | 42,957 | [
124820,
135841
] |
42,958 | asdf.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/grovel/asdf.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; asdf.lisp --- ASDF components for cffi-grovel.
;;;
;;; Copyright (C) 2005-2006, Dan Knap <[email protected]>
;;; Copyright (C) 2005-2006, Emily Backes <[email protected]>
;;; Copyright (C) 2007, Stelian Ionescu <[email protected]>
;;; Copyright (C) 2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-grovel)
(defclass cc-flags-mixin ()
((cc-flags :initform nil :accessor cc-flags-of :initarg :cc-flags)))
(defclass process-op (downward-operation)
()
(:documentation "This ASDF operation performs the steps necessary
to generate a compilable and loadable lisp file from a
PROCESS-OP-INPUT component."))
(defclass process-op-input (cl-source-file)
((generated-lisp-file-type
:initarg :generated-lisp-file-type
:accessor generated-lisp-file-type
:documentation "The :TYPE argument to use for the generated lisp file."))
(:default-initargs
:generated-lisp-file-type "generated-lisp-file")
(:documentation "This ASDF component represents a file that is
used as input to a function that generates lisp source file. This
component acts as if it is a CL-SOURCE-FILE by applying the
COMPILE-OP and LOAD-SOURCE-OP operations to the file generated by
PROCESS-OP."))
(defmethod perform :around ((op process-op) (file cc-flags-mixin))
(let ((*cc-flags* (append (ensure-list (cc-flags-of file))
*cc-flags*)))
(call-next-method)))
(defmethod input-files ((op process-op) (c process-op-input))
(list (component-pathname c)))
(defmethod input-files ((op compile-op) (c process-op-input))
(list (first (output-files 'process-op c))))
(defmethod component-depends-on ((op process-op) (c process-op-input))
`((prepare-op ,c) ,@(call-next-method)))
(defmethod component-depends-on ((op compile-op) (c process-op-input))
`((process-op ,c) ,@(call-next-method)))
(defmethod component-depends-on ((op load-source-op) (c process-op-input))
`((process-op ,c) ,@(call-next-method)))
;;;# ASDF component: GROVEL-FILE
(defclass grovel-file (process-op-input cc-flags-mixin)
()
(:default-initargs
:generated-lisp-file-type "processed-grovel-file")
(:documentation
"This ASDF component represents an input file that is processed
by PROCESS-GROVEL-FILE."))
(defmethod output-files ((op process-op) (c grovel-file))
(let* ((input-file (first (input-files op c)))
(output-file (make-pathname :type (generated-lisp-file-type c)
:defaults input-file))
(c-file (make-c-file-name output-file "__grovel")))
(list output-file
c-file
(make-exe-file-name c-file))))
(defmethod perform ((op process-op) (c grovel-file))
(let* ((output-file (first (output-files op c)))
(input-file (first (input-files op c)))
(tmp-file (process-grovel-file input-file output-file)))
(rename-file-overwriting-target tmp-file output-file)))
;;;# ASDF component: WRAPPER-FILE
(defclass wrapper-file (process-op-input cc-flags-mixin)
((soname :initform nil :initarg :soname :accessor soname-of))
(:default-initargs
:generated-lisp-file-type "processed-wrapper-file")
(:documentation
"This ASDF component represents an input file that is processed
by PROCESS-WRAPPER-FILE. This generates a foreign library and
matching CFFI bindings that are subsequently compiled and
loaded."))
(defun wrapper-soname (c)
(or (soname-of c)
(component-name c)))
(defmethod output-files ((op process-op) (c wrapper-file))
(let* ((input-file (first (input-files op c)))
(output-file (make-pathname :type (generated-lisp-file-type c)
:defaults input-file))
(c-file (make-c-file-name output-file "__wrapper"))
(o-file (make-o-file-name output-file "__wrapper"))
(lib-soname (wrapper-soname c)))
(list output-file
(make-so-file-name (make-soname lib-soname output-file))
c-file
o-file)))
;;; Declare the .o and .so files as compilation outputs,
;;; so they get picked up by bundle operations.
#.(when (version<= "3.1.6" (asdf-version))
'(defmethod output-files ((op compile-op) (c wrapper-file))
(destructuring-bind (generated-lisp lib-file c-file o-file) (output-files 'process-op c)
(declare (ignore generated-lisp c-file))
(multiple-value-bind (files translatedp) (call-next-method)
(values (append files (list lib-file o-file)) translatedp)))))
(defmethod perform ((op process-op) (c wrapper-file))
(let* ((output-file (first (output-files op c)))
(input-file (first (input-files op c)))
(tmp-file (process-wrapper-file
input-file
:output-defaults output-file
:lib-soname (wrapper-soname c))))
(unwind-protect
(alexandria:copy-file tmp-file output-file :if-to-exists :supersede)
(delete-file tmp-file))))
;; Allow for naked :cffi-grovel-file and :cffi-wrapper-file in asdf definitions.
(setf (find-class 'asdf::cffi-grovel-file) (find-class 'grovel-file))
(setf (find-class 'asdf::cffi-wrapper-file) (find-class 'wrapper-file))
| 6,337 | Common Lisp | .lisp | 129 | 44.116279 | 94 | 0.690865 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | af964719ca4bff43f33bad223330c4cadb56ee529dc8dd8a9ceb986b8777c123 | 42,958 | [
80667
] |
42,959 | main-example.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/examples/main-example.lisp | (in-package #:cffi-example)
(defcfun "puts" :int
"Put a string to standard output, return non-negative length output, or EOF"
(string :string))
(defun check-groveller ()
(assert (equal (list +a0+ +a1+ +a2+ +a3+ +a4+) '(2 4 8 16 32)))
(assert (equal (bn 1) 32)))
(defun entry-point ()
(when uiop:*command-line-arguments*
(uiop:format! t "Arguments: ~A~%" (uiop:escape-command uiop:*command-line-arguments*)))
(puts "hello, world!")
(check-groveller)
(uiop:finish-outputs)
(uiop:quit 0))
| 511 | Common Lisp | .lisp | 14 | 33.714286 | 91 | 0.672065 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 791bd5b62636e70fb19da6d3f02dbfcf52e815df864c3513fd36f4430c35b118 | 42,959 | [
177537,
430943
] |
42,961 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/examples/package.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; package.lisp --- CFFI-EXAMPLES package definition.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(defpackage #:cffi-example
(:use #:cl #:cffi #:cffi-sys)
(:export #:check-groveller #:entry-point))
| 1,387 | Common Lisp | .lisp | 29 | 46.655172 | 70 | 0.740604 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | f829d728d15812e4078b63a0ec494b2bf8387fcd5e8cea13dd5aa7b52f441d33 | 42,961 | [
21427,
428905
] |
42,964 | run-examples.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/examples/run-examples.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; run-examples.lisp --- Simple script to run the examples.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; 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.
;;;
(setf *load-verbose* nil *compile-verbose* nil)
#-asdf
(ignore-errors (require "asdf"))
#-asdf
(load "~/common-lisp/asdf/build/asdf.lisp")
(asdf:load-system 'cffi-examples :verbose nil)
(cffi-examples:run-examples)
(force-output)
(quit)
| 1,529 | Common Lisp | .lisp | 35 | 42.571429 | 70 | 0.746309 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | fbcac6fa869c2f0333e242de2faf542d3dec499f41186ca371674ae0a6ae7194 | 42,964 | [
309833
] |
42,965 | grovel-example.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/examples/grovel-example.lisp | (in-package #:cffi-example)
(define "a0(x)" "+x+x")
(define "a1(x)" "a0(+x+x)")
(define "a2(x)" "a1(+x+x)")
(define "a3(x)" "a2(+x+x)")
(define "a4(x)" "a3(+x+x)")
(define "a5(x)" "a4(+x+x)")
(define "A0" "a0(1)")
(define "A1" "a1(1)")
(define "A2" "a2(1)")
(define "A3" "a3(1)")
(define "A4" "a4(1)")
(constant (+a0+ "A0"))
(constant (+a1+ "A1"))
(constant (+a2+ "A2"))
(constant (+a3+ "A3"))
(constant (+a4+ "A4"))
| 420 | Common Lisp | .lisp | 17 | 23.529412 | 27 | 0.5275 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 733d5486d5ba94914615ede21670cf3ca1594d2f97c73c78389154f6d4e82fdf | 42,965 | [
433247
] |
42,967 | wrapper-example.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/examples/wrapper-example.lisp | (in-package #:cffi-example)
(defwrapper* "b0" :long ((x :long)) "return x;")
(defwrapper* "b1" :long ((x :long)) "return x;")
(defwrapper* "b2" :long ((x :long)) "return x;")
(defwrapper* "b3" :long ((x :long)) "return x;")
(defwrapper* "b4" :long ((x :long)) "return x;")
(define "b0_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(define "b1_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(define "b2_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
;;(define "b3_cffi_wrap(x)"
;; "b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
;;(define "b4_cffi_wrap(x)"
;; "b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(defwrapper* "bn" :long ((x :long)) "return b0_cffi_wrap(x);")
| 877 | Common Lisp | .lisp | 17 | 50.058824 | 81 | 0.633606 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 8f548a8084712f786f57dbba2e67fd0fd09fe389542fd2c36f29b59ef8225c41 | 42,967 | [
191353,
261001
] |
42,971 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/package.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; package.lisp --- Package definition for CFFI.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cl-user)
(defpackage #:cffi
(:use #:common-lisp #:cffi-sys #:babel-encodings)
(:import-from #:alexandria
#:compose
#:ensure-list
#:featurep
#:format-symbol
#:hash-table-values
#:if-let
#:ignore-some-conditions
#:lastcar
#:make-gensym-list
#:make-keyword
#:mappend
#:once-only
#:parse-body
#:simple-style-warning
#:symbolicate
#:unwind-protect-case
#:when-let
#:with-unique-names)
(:export
;; Types.
#:foreign-pointer
;; FIXME: the following types are undocumented. They should
;; probably be replaced with a proper type introspection API
;; though.
#:*built-in-foreign-types*
#:*other-builtin-types*
#:*built-in-integer-types*
#:*built-in-float-types*
;; Primitive pointer operations.
#:foreign-free
#:foreign-alloc
#:mem-aptr
#:mem-aref
#:mem-ref
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:incf-pointer
#:with-foreign-pointer
#:make-pointer
#:pointer-address
;; Shareable vectors.
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
;; Foreign string operations.
#:*default-foreign-encoding*
#:foreign-string-alloc
#:foreign-string-free
#:foreign-string-to-lisp
#:lisp-string-to-foreign
#:with-foreign-string
#:with-foreign-strings
#:with-foreign-pointer-as-string
;; Foreign array operations.
;; TODO: document these
#:foreign-array-alloc
#:foreign-array-free
#:foreign-array-to-lisp
#:lisp-array-to-foreign
#:with-foreign-array
#:foreign-aref
;; Foreign function operations.
#:defcfun
#:foreign-funcall
#:foreign-funcall-pointer
#:foreign-funcall-varargs
#:foreign-funcall-pointer-varargs
#:translate-camelcase-name
#:translate-name-from-foreign
#:translate-name-to-foreign
#:translate-underscore-separated-name
;; Foreign library operations.
#:*foreign-library-directories*
#:*darwin-framework-directories*
#:foreign-library
#:foreign-library-load-state
#:foreign-library-name
#:foreign-library-pathname
#:foreign-library-type
#:foreign-library-loaded-p
#:list-foreign-libraries
#:define-foreign-library
#:load-foreign-library
#:load-foreign-library-error
#:use-foreign-library
#:close-foreign-library
#:reload-foreign-libraries
;; Callbacks.
#:callback
#:get-callback
#:defcallback
;; Foreign type operations.
#:defcstruct
#:defcunion
#:defctype
#:defcenum
#:defbitfield
#:define-foreign-type
#:define-parse-method
#:define-c-struct-wrapper
#:foreign-enum-keyword
#:foreign-enum-keyword-list
#:foreign-enum-value
#:foreign-bitfield-symbol-list
#:foreign-bitfield-symbols
#:foreign-bitfield-value
#:foreign-slot-pointer
#:foreign-slot-value
#:foreign-slot-type
#:foreign-slot-offset
#:foreign-slot-count
#:foreign-slot-names
#:foreign-type-alignment
#:foreign-type-size
#:with-foreign-object
#:with-foreign-objects
#:with-foreign-slots
#:convert-to-foreign
#:convert-from-foreign
#:convert-into-foreign-memory
#:free-converted-object
#:translation-forms-for-class
;; Extensible foreign type operations.
#:define-translation-method ; FIXME: undocumented
#:translate-to-foreign
#:translate-from-foreign
#:translate-into-foreign-memory
#:free-translated-object
#:expand-to-foreign-dyn
#:expand-to-foreign
#:expand-from-foreign
#:expand-into-foreign-memory
;; Foreign globals.
#:defcvar
#:get-var-pointer
#:foreign-symbol-pointer
))
| 5,136 | Common Lisp | .lisp | 169 | 25.443787 | 70 | 0.678442 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 50683680b9c0f6b89f854ca9f9ee5b61c3b298626f95af83a71489aebc7c7306 | 42,971 | [
66453
] |
42,972 | cffi-clasp.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/cffi-clasp.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-clasp.lisp --- CFFI-SYS implementation for Clasp.
;;;
;;; Copyright (C) 2017 Frank Goenninger <[email protected]>
;;;
;;; 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.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:alexandria)
(:export
#:canonicalize-symbol-name-case
#:foreign-pointer
#:pointerp
#:pointer-eq
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%mem-ref
#:%mem-set
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:native-namestring
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:%defcallback
#:%callback
#:%foreign-symbol-pointer))
(in-package #:cffi-sys)
;;;# Mis-features
(pushnew 'flat-namespace cl:*features*)
;;;# Symbol Case
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Allocation
(defun %foreign-alloc (size)
"Allocate SIZE bytes of foreign-addressable memory."
(clasp-ffi:%foreign-alloc size))
(defun foreign-free (ptr)
"Free a pointer PTR allocated by FOREIGN-ALLOC."
(clasp-ffi:%foreign-free ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let* ((,size-var ,size)
(,var (%foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var))))
;;;# Misc. Pointer Operations
(deftype foreign-pointer ()
'clasp-ffi:foreign-data)
(defun null-pointer-p (ptr)
"Test if PTR is a null pointer."
(clasp-ffi:%null-pointer-p ptr))
(defun null-pointer ()
"Construct and return a null pointer."
(clasp-ffi:%make-nullpointer))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(clasp-ffi:%make-pointer address))
(defun inc-pointer (ptr offset)
"Return a pointer OFFSET bytes past PTR."
(clasp-ffi:%inc-pointer ptr offset))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(clasp-ffi:%foreign-data-address ptr))
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(typep ptr 'clasp-ffi:foreign-data))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(check-type ptr1 clasp-ffi:foreign-data)
(check-type ptr2 clasp-ffi:foreign-data)
(eql (pointer-address ptr1) (pointer-address ptr2)))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes that can passed to
WITH-POINTER-TO-VECTOR-DATA."
(make-array size :element-type '(unsigned-byte 8)))
;; frgo, 2016-07-02: TODO: Implemenent!
;; (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
;; "Bind PTR-VAR to a foreign pointer to the data in VECTOR."
;; `(let ((,ptr-var (si:make-foreign-data-from-array ,vector)))
;; ,@body))
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(clasp-ffi:%foreign-type-size type-keyword))
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
(clasp-ffi:%foreign-type-alignment type-keyword))
;;;# Dereferencing
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference an object of TYPE at OFFSET bytes from PTR."
(clasp-ffi:%mem-ref ptr type offset))
(defun %mem-set (value ptr type &optional (offset 0))
"Set an object of TYPE at OFFSET bytes from PTR."
(clasp-ffi:%mem-set ptr type value offset))
(defmacro %foreign-funcall (name args &key library convention)
"Call a foreign function."
(declare (ignore library convention))
`(clasp-ffi:%foreign-funcall ,name ,@args))
(defmacro %foreign-funcall-pointer (ptr args &key convention)
"Funcall a pointer to a foreign function."
(declare (ignore convention))
`(clasp-ffi:%foreign-funcall-pointer ,ptr ,@args))
;;;# Foreign Libraries
(defun %load-foreign-library (name path)
"Load a foreign library."
(clasp-ffi:%load-foreign-library name path))
(defun %close-foreign-library (handle)
"Close a foreign library."
(clasp-ffi:%close-foreign-library handle))
(defun %foreign-symbol-pointer (name library)
"Returns a pointer to a foreign symbol NAME."
(clasp-ffi:%foreign-symbol-pointer name library))
(defun native-namestring (pathname)
(namestring pathname))
;;;# Callbacks
(defmacro %defcallback (name rettype arg-names arg-types body
&key convention)
`(clasp-ffi:%defcallback (,name ,@(when convention `(:convention ,convention)))
,rettype ,arg-names ,arg-types ,body))
(defun %callback (name)
(clasp-ffi:%get-callback name))
| 6,322 | Common Lisp | .lisp | 162 | 36.111111 | 81 | 0.723084 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 77c9fb876efa22f5a3fdc24d4b20142ec00d78037945723ffd583c9277cbd402 | 42,972 | [
226386
] |
42,974 | types.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/types.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; types.lisp --- User-defined CFFI types.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2005-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
;;;# Built-In Types
;; NOTE: In the C standard there's a "signed-char":
;; https://stackoverflow.com/questions/436513/char-signed-char-char-unsigned-char
;; and "char" may be either signed or unsigned, i.e. treating it as a small int
;; is not wise. At the level of CFFI we can safely ignore this and assume that
;; :char is mapped to "signed-char" by the CL implementation under us.
(define-built-in-foreign-type :char)
(define-built-in-foreign-type :unsigned-char)
(define-built-in-foreign-type :short)
(define-built-in-foreign-type :unsigned-short)
(define-built-in-foreign-type :int)
(define-built-in-foreign-type :unsigned-int)
(define-built-in-foreign-type :long)
(define-built-in-foreign-type :unsigned-long)
(define-built-in-foreign-type :float)
(define-built-in-foreign-type :double)
(define-built-in-foreign-type :void)
#-cffi-sys::no-long-long
(progn
(define-built-in-foreign-type :long-long)
(define-built-in-foreign-type :unsigned-long-long))
;;; Define emulated LONG-LONG types. Needs checking whether we're
;;; using the right sizes on various platforms.
;;;
;;; A possibly better, certainly faster though more intrusive,
;;; alternative is available here:
;;; <http://article.gmane.org/gmane.lisp.cffi.devel/1091>
#+cffi-sys::no-long-long
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass emulated-llong-type (foreign-type) ())
(defmethod foreign-type-size ((tp emulated-llong-type)) 8)
(defmethod foreign-type-alignment ((tp emulated-llong-type))
;; better than assuming that the alignment is 8
(foreign-type-alignment :long))
(defmethod aggregatep ((tp emulated-llong-type)) nil)
(define-foreign-type emulated-llong (emulated-llong-type)
()
(:simple-parser :long-long))
(define-foreign-type emulated-ullong (emulated-llong-type)
()
(:simple-parser :unsigned-long-long))
(defmethod canonicalize ((tp emulated-llong)) :long-long)
(defmethod unparse-type ((tp emulated-llong)) :long-long)
(defmethod canonicalize ((tp emulated-ullong)) :unsigned-long-long)
(defmethod unparse-type ((tp emulated-ullong)) :unsigned-long-long)
(defun %emulated-mem-ref-64 (ptr type offset)
(let ((value #+big-endian
(+ (ash (mem-ref ptr :unsigned-long offset) 32)
(mem-ref ptr :unsigned-long (+ offset 4)))
#+little-endian
(+ (mem-ref ptr :unsigned-long offset)
(ash (mem-ref ptr :unsigned-long (+ offset 4)) 32))))
(if (and (eq type :long-long) (logbitp 63 value))
(lognot (logxor value #xFFFFFFFFFFFFFFFF))
value)))
(defun %emulated-mem-set-64 (value ptr type offset)
(when (and (eq type :long-long) (minusp value))
(setq value (lognot (logxor value #xFFFFFFFFFFFFFFFF))))
(%mem-set (ldb (byte 32 0) value) ptr :unsigned-long
#+big-endian (+ offset 4) #+little-endian offset)
(%mem-set (ldb (byte 32 32) value) ptr :unsigned-long
#+big-endian offset #+little-endian (+ offset 4))
value))
;;; When some lisp other than SCL supports :long-double we should
;;; use #-cffi-sys::no-long-double here instead.
#+(and scl long-float) (define-built-in-foreign-type :long-double)
(defparameter *possible-float-types* '(:float :double :long-double))
(defparameter *other-builtin-types* '(:pointer :void)
"List of types other than integer or float built in to CFFI.")
(defparameter *built-in-integer-types*
(set-difference
cffi:*built-in-foreign-types*
(append *possible-float-types* *other-builtin-types*))
"List of integer types supported by CFFI.")
(defparameter *built-in-float-types*
(set-difference
cffi:*built-in-foreign-types*
(append *built-in-integer-types* *other-builtin-types*))
"List of real float types supported by CFFI.")
;;;# Foreign Pointers
(define-compiler-macro inc-pointer (&whole form pointer offset)
(if (and (constantp offset)
(eql 0 (eval offset)))
pointer
form))
(define-modify-macro incf-pointer (&optional (offset 1)) inc-pointer)
(defun mem-ref (ptr type &optional (offset 0))
"Return the value of TYPE at OFFSET bytes from PTR. If TYPE is aggregate,
we don't return its 'value' but a pointer to it, which is PTR itself."
(let* ((parsed-type (parse-type type))
(ctype (canonicalize parsed-type)))
#+cffi-sys::no-long-long
(when (member ctype '(:long-long :unsigned-long-long))
(return-from mem-ref
(translate-from-foreign (%emulated-mem-ref-64 ptr ctype offset)
parsed-type)))
;; normal branch
(if (aggregatep parsed-type)
(if (bare-struct-type-p parsed-type)
(inc-pointer ptr offset)
(translate-from-foreign (inc-pointer ptr offset) parsed-type))
(translate-from-foreign (%mem-ref ptr ctype offset) parsed-type))))
(define-compiler-macro mem-ref (&whole form ptr type &optional (offset 0))
"Compiler macro to open-code MEM-REF when TYPE is constant."
(if (constantp type)
(let* ((parsed-type (parse-type (eval type)))
(ctype (canonicalize parsed-type)))
;; Bail out when using emulated long long types.
#+cffi-sys::no-long-long
(when (member ctype '(:long-long :unsigned-long-long))
(return-from mem-ref form))
(if (aggregatep parsed-type)
(if (bare-struct-type-p parsed-type)
`(inc-pointer ,ptr ,offset)
(expand-from-foreign `(inc-pointer ,ptr ,offset) parsed-type))
(expand-from-foreign `(%mem-ref ,ptr ,ctype ,offset) parsed-type)))
form))
(defun mem-set (value ptr type &optional (offset 0))
"Set the value of TYPE at OFFSET bytes from PTR to VALUE."
(let* ((ptype (parse-type type))
(ctype (canonicalize ptype)))
#+cffi-sys::no-long-long
(when (or (eq ctype :long-long) (eq ctype :unsigned-long-long))
(return-from mem-set
(%emulated-mem-set-64 (translate-to-foreign value ptype)
ptr ctype offset)))
(if (aggregatep ptype) ; XXX: backwards incompatible?
(translate-into-foreign-memory value ptype (inc-pointer ptr offset))
(%mem-set (translate-to-foreign value ptype) ptr ctype offset))))
(define-setf-expander mem-ref (ptr type &optional (offset 0) &environment env)
"SETF expander for MEM-REF that doesn't rebind TYPE.
This is necessary for the compiler macro on MEM-SET to be able
to open-code (SETF MEM-REF) forms."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion ptr env)
(declare (ignore setter newval))
;; if either TYPE or OFFSET are constant, we avoid rebinding them
;; so that the compiler macros on MEM-SET and %MEM-SET work.
(with-unique-names (store type-tmp offset-tmp)
(values
(append (unless (constantp type) (list type-tmp))
(unless (constantp offset) (list offset-tmp))
dummies)
(append (unless (constantp type) (list type))
(unless (constantp offset) (list offset))
vals)
(list store)
`(progn
(mem-set ,store ,getter
,@(if (constantp type) (list type) (list type-tmp))
,@(if (constantp offset) (list offset) (list offset-tmp)))
,store)
`(mem-ref ,getter
,@(if (constantp type) (list type) (list type-tmp))
,@(if (constantp offset) (list offset) (list offset-tmp)))))))
(define-compiler-macro mem-set
(&whole form value ptr type &optional (offset 0))
"Compiler macro to open-code (SETF MEM-REF) when type is constant."
(if (constantp type)
(let* ((parsed-type (parse-type (eval type)))
(ctype (canonicalize parsed-type)))
;; Bail out when using emulated long long types.
#+cffi-sys::no-long-long
(when (member ctype '(:long-long :unsigned-long-long))
(return-from mem-set form))
(if (aggregatep parsed-type)
(expand-into-foreign-memory
value parsed-type `(inc-pointer ,ptr ,offset))
`(%mem-set ,(expand-to-foreign value parsed-type)
,ptr ,ctype ,offset)))
form))
;;;# Dereferencing Foreign Arrays
;;; Maybe this should be named MEM-SVREF? [2007-02-28 LO]
(defun mem-aref (ptr type &optional (index 0))
"Like MEM-REF except for accessing 1d arrays."
(mem-ref ptr type (* index (foreign-type-size type))))
(define-compiler-macro mem-aref (&whole form ptr type &optional (index 0))
"Compiler macro to open-code MEM-AREF when TYPE (and eventually INDEX)."
(if (constantp type)
(if (constantp index)
`(mem-ref ,ptr ,type
,(* (eval index) (foreign-type-size (eval type))))
`(mem-ref ,ptr ,type (* ,index ,(foreign-type-size (eval type)))))
form))
(define-setf-expander mem-aref (ptr type &optional (index 0) &environment env)
"SETF expander for MEM-AREF."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion ptr env)
(declare (ignore setter newval))
;; we avoid rebinding type and index, if possible (and if type is not
;; constant, we don't bother about the index), so that the compiler macros
;; on MEM-SET or %MEM-SET can work.
(with-unique-names (store type-tmp index-tmp)
(values
(append (unless (constantp type)
(list type-tmp))
(unless (and (constantp type) (constantp index))
(list index-tmp))
dummies)
(append (unless (constantp type)
(list type))
(unless (and (constantp type) (constantp index))
(list index))
vals)
(list store)
;; Here we'll try to calculate the offset from the type and index,
;; or if not possible at least get the type size early.
`(progn
,(if (constantp type)
(if (constantp index)
`(mem-set ,store ,getter ,type
,(* (eval index) (foreign-type-size (eval type))))
`(mem-set ,store ,getter ,type
(* ,index-tmp ,(foreign-type-size (eval type)))))
`(mem-set ,store ,getter ,type-tmp
(* ,index-tmp (foreign-type-size ,type-tmp))))
,store)
`(mem-aref ,getter
,@(if (constantp type)
(list type)
(list type-tmp))
,@(if (and (constantp type) (constantp index))
(list index)
(list index-tmp)))))))
(defmethod translate-into-foreign-memory
(value (type foreign-pointer-type) pointer)
(setf (mem-aref pointer :pointer) value))
(defmethod translate-into-foreign-memory
(value (type foreign-built-in-type) pointer)
(setf (mem-aref pointer (unparse-type type)) value))
(defun mem-aptr (ptr type &optional (index 0))
"The pointer to the element."
(inc-pointer ptr (* index (foreign-type-size type))))
(define-compiler-macro mem-aptr (&whole form ptr type &optional (index 0))
"The pointer to the element."
(cond ((not (constantp type))
form)
((not (constantp index))
`(inc-pointer ,ptr (* ,index ,(foreign-type-size (eval type)))))
((zerop (eval index))
ptr)
(t
`(inc-pointer ,ptr ,(* (eval index)
(foreign-type-size (eval type)))))))
(define-foreign-type foreign-array-type ()
((dimensions :reader dimensions :initarg :dimensions)
(element-type :reader element-type :initarg :element-type))
(:actual-type :pointer))
(defmethod aggregatep ((type foreign-array-type))
t)
(defmethod print-object ((type foreign-array-type) stream)
"Print a FOREIGN-ARRAY-TYPE instance to STREAM unreadably."
(print-unreadable-object (type stream :type t :identity nil)
(format stream "~S ~S" (element-type type) (dimensions type))))
(defun array-element-size (array-type)
(foreign-type-size (element-type array-type)))
(defmethod foreign-type-size ((type foreign-array-type))
(* (array-element-size type) (reduce #'* (dimensions type))))
(defmethod foreign-type-alignment ((type foreign-array-type))
(foreign-type-alignment (element-type type)))
(define-parse-method :array (element-type &rest dimensions)
(assert (plusp (length dimensions)))
(make-instance 'foreign-array-type
:element-type element-type
:dimensions dimensions))
(defun indexes-to-row-major-index (dimensions &rest subscripts)
(apply #'+ (maplist (lambda (x y)
(* (car x) (apply #'* (cdr y))))
subscripts
dimensions)))
(defun row-major-index-to-indexes (index dimensions)
(loop with idx = index
with rank = (length dimensions)
with indexes = (make-list rank)
for dim-index from (- rank 1) downto 0 do
(setf (values idx (nth dim-index indexes))
(floor idx (nth dim-index dimensions)))
finally (return indexes)))
(defun foreign-alloc (type &key (initial-element nil initial-element-p)
(initial-contents nil initial-contents-p)
(count 1 count-p) null-terminated-p)
"Allocate enough memory to hold COUNT objects of type TYPE. If
INITIAL-ELEMENT is supplied, each element of the newly allocated
memory is initialized with its value. If INITIAL-CONTENTS is supplied,
each of its elements will be used to initialize the contents of the
newly allocated memory."
(let (contents-length)
;; Some error checking, etc...
(when (and null-terminated-p
(not (eq (canonicalize-foreign-type type) :pointer)))
(error "Cannot use :NULL-TERMINATED-P with non-pointer types."))
(when (and initial-element-p initial-contents-p)
(error "Cannot specify both :INITIAL-ELEMENT and :INITIAL-CONTENTS"))
(when initial-contents-p
(setq contents-length (length initial-contents))
(if count-p
(assert (>= count contents-length))
(setq count contents-length)))
;; Everything looks good.
(let ((ptr (%foreign-alloc (* (foreign-type-size type)
(if null-terminated-p (1+ count) count)))))
(when initial-element-p
(dotimes (i count)
(setf (mem-aref ptr type i) initial-element)))
(when initial-contents-p
(dotimes (i contents-length)
(setf (mem-aref ptr type i) (elt initial-contents i))))
(when null-terminated-p
(setf (mem-aref ptr :pointer count) (null-pointer)))
ptr)))
;;; Simple compiler macro that kicks in when TYPE is constant and only
;;; the COUNT argument is passed. (Note: hard-coding the type's size
;;; into the fasl will likely break CLISP fasl cross-platform
;;; compatibilty.)
(define-compiler-macro foreign-alloc (&whole form type &rest args
&key (count 1 count-p) &allow-other-keys)
(if (or (and count-p (<= (length args) 2)) (null args))
(cond
((and (constantp type) (constantp count))
`(%foreign-alloc ,(* (eval count) (foreign-type-size (eval type)))))
((constantp type)
`(%foreign-alloc (* ,count ,(foreign-type-size (eval type)))))
(t form))
form))
(defun lisp-array-to-foreign (array pointer array-type)
"Copy elements from a Lisp array to POINTER. ARRAY-TYPE must be a CFFI array
type."
(let* ((type (ensure-parsed-base-type array-type))
(el-type (element-type type))
(dimensions (dimensions type)))
(loop with foreign-type-size = (array-element-size type)
with size = (reduce #'* dimensions)
for i from 0 below size
for offset = (* i foreign-type-size)
for element = (apply #'aref array
(row-major-index-to-indexes i dimensions))
do (setf (mem-ref pointer el-type offset) element))))
(defun foreign-array-to-lisp (pointer array-type &rest make-array-args)
"Copy elements from pointer into a Lisp array. ARRAY-TYPE must be a CFFI array
type; the type of the resulting Lisp array can be defined in MAKE-ARRAY-ARGS
that are then passed to MAKE-ARRAY. If POINTER is a null pointer, returns NIL."
(unless (null-pointer-p pointer)
(let* ((type (ensure-parsed-base-type array-type))
(el-type (element-type type))
(dimensions (dimensions type))
(array (apply #'make-array dimensions make-array-args)))
(loop with foreign-type-size = (array-element-size type)
with size = (reduce #'* dimensions)
for i from 0 below size
for offset = (* i foreign-type-size)
for element = (mem-ref pointer el-type offset)
do (setf (apply #'aref array
(row-major-index-to-indexes i dimensions))
element))
array)))
(defun foreign-array-alloc (array array-type)
"Allocate a foreign array containing the elements of lisp array.
The foreign array must be freed with foreign-array-free."
(check-type array array)
(let* ((type (ensure-parsed-base-type array-type))
(ptr (foreign-alloc (element-type type)
:count (reduce #'* (dimensions type)))))
(lisp-array-to-foreign array ptr array-type)
ptr))
(defun foreign-array-free (ptr)
"Free a foreign array allocated by foreign-array-alloc."
(foreign-free ptr))
(defmacro with-foreign-array ((var lisp-array array-type) &body body)
"Bind var to a foreign array containing lisp-array elements in body."
(with-unique-names (type)
`(let ((,type (ensure-parsed-base-type ,array-type)))
(with-foreign-pointer (,var (* (reduce #'* (dimensions ,type))
(array-element-size ,type)))
(lisp-array-to-foreign ,lisp-array ,var ,array-type)
,@body))))
(defun foreign-aref (ptr array-type &rest indexes)
(let* ((type (ensure-parsed-base-type array-type))
(offset (* (array-element-size type)
(apply #'indexes-to-row-major-index
(dimensions type) indexes))))
(mem-ref ptr (element-type type) offset)))
(defun (setf foreign-aref) (value ptr array-type &rest indexes)
(let* ((type (ensure-parsed-base-type array-type))
(offset (* (array-element-size type)
(apply #'indexes-to-row-major-index
(dimensions type) indexes))))
(setf (mem-ref ptr (element-type type) offset) value)))
;;; Automatic translations for the :ARRAY type. Notice that these
;;; translators will also invoke the appropriate translators for for
;;; each of the array's elements since that's the normal behaviour of
;;; the FOREIGN-ARRAY-* operators, but there's a FIXME: **it doesn't
;;; free them yet**
;;; This used to be in a separate type but let's experiment with just
;;; one type for a while. [2008-12-30 LO]
;;; FIXME: those ugly invocations of UNPARSE-TYPE suggest that these
;;; foreign array operators should take the type and dimention
;;; arguments "unboxed". [2008-12-31 LO]
(defmethod translate-to-foreign (array (type foreign-array-type))
(foreign-array-alloc array (unparse-type type)))
(defmethod translate-aggregate-to-foreign (ptr value (type foreign-array-type))
(lisp-array-to-foreign value ptr (unparse-type type)))
(defmethod translate-from-foreign (pointer (type foreign-array-type))
(foreign-array-to-lisp pointer (unparse-type type)))
(defmethod free-translated-object (pointer (type foreign-array-type) param)
(declare (ignore param))
(foreign-array-free pointer))
;;;# Foreign Structures
;;;## Foreign Structure Slots
(defgeneric foreign-struct-slot-pointer (ptr slot)
(:documentation
"Get the address of SLOT relative to PTR."))
(defgeneric foreign-struct-slot-pointer-form (ptr slot)
(:documentation
"Return a form to get the address of SLOT in PTR."))
(defgeneric foreign-struct-slot-value (ptr slot)
(:documentation
"Return the value of SLOT in structure PTR."))
(defgeneric (setf foreign-struct-slot-value) (value ptr slot)
(:documentation
"Set the value of a SLOT in structure PTR."))
(defgeneric foreign-struct-slot-value-form (ptr slot)
(:documentation
"Return a form to get the value of SLOT in struct PTR."))
(defgeneric foreign-struct-slot-set-form (value ptr slot)
(:documentation
"Return a form to set the value of SLOT in struct PTR."))
(defclass foreign-struct-slot ()
((name :initarg :name :reader slot-name)
(offset :initarg :offset :accessor slot-offset)
;; FIXME: the type should probably be parsed?
(type :initarg :type :accessor slot-type))
(:documentation "Base class for simple and aggregate slots."))
(defmethod foreign-struct-slot-pointer (ptr (slot foreign-struct-slot))
"Return the address of SLOT relative to PTR."
(inc-pointer ptr (slot-offset slot)))
(defmethod foreign-struct-slot-pointer-form (ptr (slot foreign-struct-slot))
"Return a form to get the address of SLOT relative to PTR."
(let ((offset (slot-offset slot)))
(if (zerop offset)
ptr
`(inc-pointer ,ptr ,offset))))
(defun foreign-slot-names (type)
"Returns a list of TYPE's slot names in no particular order."
(loop for value being the hash-values
in (slots (ensure-parsed-base-type type))
collect (slot-name value)))
;;;### Simple Slots
(defclass simple-struct-slot (foreign-struct-slot)
()
(:documentation "Non-aggregate structure slots."))
(defmethod foreign-struct-slot-value (ptr (slot simple-struct-slot))
"Return the value of a simple SLOT from a struct at PTR."
(mem-ref ptr (slot-type slot) (slot-offset slot)))
(defmethod foreign-struct-slot-value-form (ptr (slot simple-struct-slot))
"Return a form to get the value of a slot from PTR."
`(mem-ref ,ptr ',(slot-type slot) ,(slot-offset slot)))
(defmethod (setf foreign-struct-slot-value) (value ptr (slot simple-struct-slot))
"Set the value of a simple SLOT to VALUE in PTR."
(setf (mem-ref ptr (slot-type slot) (slot-offset slot)) value))
(defmethod foreign-struct-slot-set-form (value ptr (slot simple-struct-slot))
"Return a form to set the value of a simple structure slot."
`(setf (mem-ref ,ptr ',(slot-type slot) ,(slot-offset slot)) ,value))
;;;### Aggregate Slots
(defclass aggregate-struct-slot (foreign-struct-slot)
((count :initarg :count :accessor slot-count))
(:documentation "Aggregate structure slots."))
;;; Since MEM-REF returns a pointer for struct types we are able to
;;; chain together slot names when accessing slot values in nested
;;; structures.
(defmethod foreign-struct-slot-value (ptr (slot aggregate-struct-slot))
"Return a pointer to SLOT relative to PTR."
(convert-from-foreign (inc-pointer ptr (slot-offset slot))
(slot-type slot)))
(defmethod foreign-struct-slot-value-form (ptr (slot aggregate-struct-slot))
"Return a form to get the value of SLOT relative to PTR."
`(convert-from-foreign (inc-pointer ,ptr ,(slot-offset slot))
',(slot-type slot)))
(defmethod translate-aggregate-to-foreign (ptr value (type foreign-struct-type))
;;; FIXME: use the block memory interface instead.
(loop for i below (foreign-type-size type)
do (%mem-set (%mem-ref value :char i) ptr :char i)))
(defmethod (setf foreign-struct-slot-value)
(value ptr (slot aggregate-struct-slot))
"Set the value of an aggregate SLOT to VALUE in PTR."
(translate-aggregate-to-foreign (inc-pointer ptr (slot-offset slot))
value
(parse-type (slot-type slot))))
(defmethod foreign-struct-slot-set-form (value ptr (slot aggregate-struct-slot))
"Return a form to get the value of an aggregate SLOT relative to PTR."
`(translate-aggregate-to-foreign (inc-pointer ,ptr ,(slot-offset slot))
,value
,(parse-type (slot-type slot))))
;;;## Defining Foreign Structures
(defun make-struct-slot (name offset type count)
"Make the appropriate type of structure slot."
;; If TYPE is an aggregate type or COUNT is >1, create an
;; AGGREGATE-STRUCT-SLOT, otherwise a SIMPLE-STRUCT-SLOT.
(if (or (> count 1) (aggregatep (parse-type type)))
(make-instance 'aggregate-struct-slot :offset offset :type type
:name name :count count)
(make-instance 'simple-struct-slot :offset offset :type type
:name name)))
(defun parse-deprecated-struct-type (name struct-or-union)
(check-type struct-or-union (member :struct :union))
(let* ((struct-type-name `(,struct-or-union ,name))
(struct-type (parse-type struct-type-name)))
(simple-style-warning
"bare references to struct types are deprecated. ~
Please use ~S or ~S instead."
`(:pointer ,struct-type-name) struct-type-name)
(make-instance (class-of struct-type)
:alignment (alignment struct-type)
:size (size struct-type)
:slots (slots struct-type)
:name (name struct-type)
:bare t)))
;;; Regarding structure alignment, the following ABIs were checked:
;;; - System-V ABI: x86, x86-64, ppc, arm, mips and itanium. (more?)
;;; - Mac OS X ABI Function Call Guide: ppc32, ppc64 and x86.
;;;
;;; Rules used here:
;;;
;;; 1. "An entire structure or union object is aligned on the same
;;; boundary as its most strictly aligned member."
;;;
;;; 2. "Each member is assigned to the lowest available offset with
;;; the appropriate alignment. This may require internal
;;; padding, depending on the previous member."
;;;
;;; 3. "A structure's size is increased, if necessary, to make it a
;;; multiple of the alignment. This may require tail padding,
;;; depending on the last member."
;;;
;;; Special cases from darwin/ppc32's ABI:
;;; http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/index.html
;;;
;;; 4. "The embedding alignment of the first element in a data
;;; structure is equal to the element's natural alignment."
;;;
;;; 5. "For subsequent elements that have a natural alignment
;;; greater than 4 bytes, the embedding alignment is 4, unless
;;; the element is a vector." (note: this applies for
;;; structures too)
;; FIXME: get a better name for this. --luis
(defun get-alignment (type alignment-type firstp)
"Return alignment for TYPE according to ALIGNMENT-TYPE."
(declare (ignorable firstp))
(ecase alignment-type
(:normal #-(and darwin ppc)
(foreign-type-alignment type)
#+(and darwin ppc)
(if firstp
(foreign-type-alignment type)
(min 4 (foreign-type-alignment type))))))
(defun adjust-for-alignment (type offset alignment-type firstp)
"Return OFFSET aligned properly for TYPE according to ALIGNMENT-TYPE."
(let* ((align (get-alignment type alignment-type firstp))
(rem (mod offset align)))
(if (zerop rem)
offset
(+ offset (- align rem)))))
(defmacro with-tentative-type-definition ((name value namespace) &body body)
(once-only (name namespace)
`(unwind-protect-case ()
(progn
(notice-foreign-type ,name ,value ,namespace)
,@body)
(:abort (undefine-foreign-type ,name ,namespace)))))
(defun notice-foreign-struct-definition (name options slots)
"Parse and install a foreign structure definition."
(destructuring-bind (&key size (class 'foreign-struct-type))
options
(let ((struct (make-instance class :name name))
(current-offset 0)
(max-align 1)
(firstp t))
(with-tentative-type-definition (name struct :struct)
;; determine offsets
(dolist (slotdef slots)
(destructuring-bind (slotname type &key (count 1) offset) slotdef
(when (eq (canonicalize-foreign-type type) :void)
(simple-foreign-type-error type :struct
"In struct ~S: void type not allowed in field ~S"
name slotdef))
(setq current-offset
(or offset
(adjust-for-alignment type current-offset :normal firstp)))
(let* ((slot (make-struct-slot slotname current-offset type count))
(align (get-alignment (slot-type slot) :normal firstp)))
(setf (gethash slotname (slots struct)) slot)
(when (> align max-align)
(setq max-align align)))
(incf current-offset (* count (foreign-type-size type))))
(setq firstp nil))
;; calculate padding and alignment
(setf (alignment struct) max-align) ; See point 1 above.
(let ((tail-padding (- max-align (rem current-offset max-align))))
(unless (= tail-padding max-align) ; See point 3 above.
(incf current-offset tail-padding)))
(setf (size struct) (or size current-offset))))))
(defun generate-struct-accessors (name conc-name slot-names)
(loop with pointer-arg = (symbolicate '#:pointer-to- name)
for slot in slot-names
for accessor = (symbolicate conc-name slot)
collect `(defun ,accessor (,pointer-arg)
(foreign-slot-value ,pointer-arg '(:struct ,name) ',slot))
collect `(defun (setf ,accessor) (value ,pointer-arg)
(foreign-slot-set value ,pointer-arg '(:struct ,name) ',slot))))
(define-parse-method :struct (name)
(funcall (find-type-parser name :struct)))
(defvar *defcstruct-hook* nil)
(defmacro defcstruct (name-and-options &body fields)
"Define the layout of a foreign structure."
(discard-docstring fields)
(destructuring-bind (name . options)
(ensure-list name-and-options)
(let ((conc-name (getf options :conc-name)))
(remf options :conc-name)
(unless (getf options :class) (setf (getf options :class) (symbolicate name '-tclass)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
;; m-f-s-t could do with this with mop:ensure-class.
,(when-let (class (getf options :class))
`(defclass ,class (foreign-struct-type
translatable-foreign-type)
()))
(notice-foreign-struct-definition ',name ',options ',fields)
,@(when conc-name
(generate-struct-accessors name conc-name
(mapcar #'car fields)))
,@(when *defcstruct-hook*
;; If non-nil, *defcstruct-hook* should be a function
;; of the arguments that returns NIL or a list of
;; forms to include in the expansion.
(apply *defcstruct-hook* name-and-options fields))
(define-parse-method ,name ()
(parse-deprecated-struct-type ',name :struct))
'(:struct ,name)))))
;;;## Accessing Foreign Structure Slots
(defun get-slot-info (type slot-name)
"Return the slot info for SLOT-NAME or raise an error."
(let* ((struct (ensure-parsed-base-type type))
(info (gethash slot-name (slots struct))))
(unless info
(simple-foreign-type-error type :struct
"Undefined slot ~A in foreign type ~A."
slot-name type))
info))
(defun foreign-slot-pointer (ptr type slot-name)
"Return the address of SLOT-NAME in the structure at PTR."
(foreign-struct-slot-pointer ptr (get-slot-info type slot-name)))
(define-compiler-macro foreign-slot-pointer (&whole whole ptr type slot-name)
(if (and (constantp type) (constantp slot-name))
(foreign-struct-slot-pointer-form
ptr (get-slot-info (eval type) (eval slot-name)))
whole))
(defun foreign-slot-type (type slot-name)
"Return the type of SLOT in a struct TYPE."
(slot-type (get-slot-info type slot-name)))
(defun foreign-slot-offset (type slot-name)
"Return the offset of SLOT in a struct TYPE."
(slot-offset (get-slot-info type slot-name)))
(defun foreign-slot-count (type slot-name)
"Return the number of items in SLOT in a struct TYPE."
(slot-count (get-slot-info type slot-name)))
(defun foreign-slot-value (ptr type slot-name)
"Return the value of SLOT-NAME in the foreign structure at PTR."
(foreign-struct-slot-value ptr (get-slot-info type slot-name)))
(define-compiler-macro foreign-slot-value (&whole form ptr type slot-name)
"Optimizer for FOREIGN-SLOT-VALUE when TYPE is constant."
(if (and (constantp type) (constantp slot-name))
(foreign-struct-slot-value-form
ptr (get-slot-info (eval type) (eval slot-name)))
form))
(define-setf-expander foreign-slot-value (ptr type slot-name &environment env)
"SETF expander for FOREIGN-SLOT-VALUE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion ptr env)
(declare (ignore setter newval))
(if (and (constantp type) (constantp slot-name))
;; if TYPE and SLOT-NAME are constant we avoid rebinding them
;; so that the compiler macro on FOREIGN-SLOT-SET works.
(with-unique-names (store)
(values
dummies
vals
(list store)
`(progn
(foreign-slot-set ,store ,getter ,type ,slot-name)
,store)
`(foreign-slot-value ,getter ,type ,slot-name)))
;; if not...
(with-unique-names (store slot-name-tmp type-tmp)
(values
(list* type-tmp slot-name-tmp dummies)
(list* type slot-name vals)
(list store)
`(progn
(foreign-slot-set ,store ,getter ,type-tmp ,slot-name-tmp)
,store)
`(foreign-slot-value ,getter ,type-tmp ,slot-name-tmp))))))
(defun foreign-slot-set (value ptr type slot-name)
"Set the value of SLOT-NAME in a foreign structure."
(setf (foreign-struct-slot-value ptr (get-slot-info type slot-name)) value))
(define-compiler-macro foreign-slot-set
(&whole form value ptr type slot-name)
"Optimizer when TYPE and SLOT-NAME are constant."
(if (and (constantp type) (constantp slot-name))
(foreign-struct-slot-set-form
value ptr (get-slot-info (eval type) (eval slot-name)))
form))
(defmacro with-foreign-slots ((vars ptr type) &body body)
"Create local symbol macros for each var in VARS to reference
foreign slots in PTR of TYPE. Similar to WITH-SLOTS.
Each var can be of the form:
name name bound to slot of same name
(:pointer name) name bound to pointer to slot of same name
(name slot-name) name bound to slot-name
(name :pointer slot-name) name bound to pointer to slot-name"
(let ((ptr-var (gensym "PTR")))
`(let ((,ptr-var ,ptr))
(symbol-macrolet
,(loop :for var :in vars
:collect
(if (listp var)
(let ((p1 (first var)) (p2 (second var)) (p3 (third var)))
(if (eq p1 :pointer)
`(,p2 (foreign-slot-pointer ,ptr-var ',type ',p2))
(if (eq p2 :pointer)
`(,p1 (foreign-slot-pointer ,ptr-var ',type ',p3))
`(,p1 (foreign-slot-value ,ptr-var ',type ',p2)))))
`(,var (foreign-slot-value ,ptr-var ',type ',var))))
,@body))))
;;; We could add an option to define a struct instead of a class, in
;;; the unlikely event someone needs something like that.
(defmacro define-c-struct-wrapper (class-and-type supers &optional slots)
"Define a new class with CLOS slots matching those of a foreign
struct type. An INITIALIZE-INSTANCE method is defined which
takes a :POINTER initarg that is used to store the slots of a
foreign object. This pointer is only used for initialization and
it is not retained.
CLASS-AND-TYPE is either a list of the form (class-name
struct-type) or a single symbol naming both. The class will
inherit SUPERS. If a list of SLOTS is specified, only those
slots will be defined and stored."
(destructuring-bind (class-name &optional (struct-type (list :struct class-name)))
(ensure-list class-and-type)
(let ((slots (or slots (foreign-slot-names struct-type))))
`(progn
(defclass ,class-name ,supers
,(loop for slot in slots collect
`(,slot :reader ,(format-symbol t "~A-~A" class-name slot))))
;; This could be done in a parent class by using
;; FOREIGN-SLOT-NAMES when instantiating but then the compiler
;; macros wouldn't kick in.
(defmethod initialize-instance :after ((inst ,class-name) &key pointer)
(with-foreign-slots (,slots pointer ,struct-type)
,@(loop for slot in slots collect
`(setf (slot-value inst ',slot) ,slot))))
',class-name))))
;;;# Foreign Unions
;;;
;;; A union is a subclass of FOREIGN-STRUCT-TYPE in which all slots
;;; have an offset of zero.
;;; See also the notes regarding ABI requirements in
;;; NOTICE-FOREIGN-STRUCT-DEFINITION
(defun notice-foreign-union-definition (name-and-options slots)
"Parse and install a foreign union definition."
(destructuring-bind (name &key size)
(ensure-list name-and-options)
(let ((union (make-instance 'foreign-union-type :name name))
(max-size 0)
(max-align 0))
(with-tentative-type-definition (name union :union)
(dolist (slotdef slots)
(destructuring-bind (slotname type &key (count 1)) slotdef
(when (eq (canonicalize-foreign-type type) :void)
(simple-foreign-type-error name :struct
"In union ~S: void type not allowed in field ~S"
name slotdef))
(let* ((slot (make-struct-slot slotname 0 type count))
(size (* count (foreign-type-size type)))
(align (foreign-type-alignment (slot-type slot))))
(setf (gethash slotname (slots union)) slot)
(when (> size max-size)
(setf max-size size))
(when (> align max-align)
(setf max-align align)))))
(setf (size union) (or size max-size))
(setf (alignment union) max-align)))))
(define-parse-method :union (name)
(funcall (find-type-parser name :union)))
(defmacro defcunion (name-and-options &body fields)
"Define the layout of a foreign union."
(discard-docstring fields)
(destructuring-bind (name &key size)
(ensure-list name-and-options)
(declare (ignore size))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-union-definition ',name-and-options ',fields)
(define-parse-method ,name ()
(parse-deprecated-struct-type ',name :union))
'(:union ,name))))
;;;# Operations on Types
(defmethod foreign-type-alignment (type)
"Return the alignment in bytes of a foreign type."
(foreign-type-alignment (parse-type type)))
(defmacro with-foreign-object ((var type &optional (count 1)) &body body)
"Bind VAR to a pointer to COUNT objects of TYPE during BODY.
The buffer has dynamic extent and may be stack allocated."
`(with-foreign-pointer
(,var ,(if (constantp type)
;; with-foreign-pointer may benefit from constant folding:
(if (constantp count)
(* (eval count) (foreign-type-size (eval type)))
`(* ,count ,(foreign-type-size (eval type))))
`(* ,count (foreign-type-size ,type))))
,@body))
(defmacro with-foreign-objects (bindings &body body)
(if bindings
`(with-foreign-object ,(car bindings)
(with-foreign-objects ,(cdr bindings)
,@body))
`(progn ,@body)))
;;;## Anonymous Type Translators
;;;
;;; (:wrapper :to-c some-function :from-c another-function)
;;;
;;; TODO: We will need to add a FREE function to this as well I think.
;;; --james
(define-foreign-type foreign-type-wrapper ()
((to-c :initarg :to-c :reader wrapper-to-c)
(from-c :initarg :from-c :reader wrapper-from-c))
(:documentation "Wrapper type."))
(define-parse-method :wrapper (base-type &key to-c from-c)
(make-instance 'foreign-type-wrapper
:actual-type (parse-type base-type)
:to-c (or to-c 'identity)
:from-c (or from-c 'identity)))
(defmethod translate-to-foreign (value (type foreign-type-wrapper))
(translate-to-foreign
(funcall (slot-value type 'to-c) value) (actual-type type)))
(defmethod translate-from-foreign (value (type foreign-type-wrapper))
(funcall (slot-value type 'from-c)
(translate-from-foreign value (actual-type type))))
;;;# Other types
;;; Boolean type. Maps to an :int by default. Only accepts integer types.
(define-foreign-type foreign-boolean-type ()
())
(define-parse-method :boolean (&optional (base-type :int))
(make-instance
'foreign-boolean-type :actual-type
(ecase (canonicalize-foreign-type base-type)
((:char :unsigned-char :int :unsigned-int :long :unsigned-long
#-cffi-sys::no-long-long :long-long
#-cffi-sys::no-long-long :unsigned-long-long) base-type))))
(defmethod translate-to-foreign (value (type foreign-boolean-type))
(if value 1 0))
(defmethod translate-from-foreign (value (type foreign-boolean-type))
(not (zerop value)))
(defmethod expand-to-foreign (value (type foreign-boolean-type))
"Optimization for the :boolean type."
(if (constantp value)
(if (eval value) 1 0)
`(if ,value 1 0)))
(defmethod expand-from-foreign (value (type foreign-boolean-type))
"Optimization for the :boolean type."
(if (constantp value) ; very unlikely, heh
(not (zerop (eval value)))
`(not (zerop ,value))))
;;; Boolean type that represents C99 _Bool
(defctype :bool (:boolean :char))
;;;# Typedefs for built-in types.
(defctype :uchar :unsigned-char)
(defctype :ushort :unsigned-short)
(defctype :uint :unsigned-int)
(defctype :ulong :unsigned-long)
(defctype :llong :long-long)
(defctype :ullong :unsigned-long-long)
(defmacro defctype-matching (name size-or-type base-types &key (match-by '=))
(let* ((target-size (typecase size-or-type
(integer size-or-type)
(t (foreign-type-size size-or-type))))
(matching-type (loop for type in base-types
for size = (foreign-type-size type)
when (funcall match-by target-size size)
return type)))
(if matching-type
`(defctype ,name ,matching-type)
`(warn "Found no matching type of size ~d in~% ~a"
,target-size ',base-types))))
;;; We try to define the :[u]int{8,16,32,64} types by looking at
;;; the sizes of the built-in integer types and defining typedefs.
(macrolet ((match-types (sized-types base-types)
`(progn ,@(loop for (name size-or-type) in sized-types
collect `(defctype-matching ,name ,size-or-type ,base-types)))))
;; signed
(match-types ((:int8 1) (:int16 2) (:int32 4) (:int64 8)
(:intptr :pointer))
(:char :short :int :long :long-long))
;; unsigned
(match-types ((:uint8 1) (:uint16 2) (:uint32 4) (:uint64 8)
(:uintptr :pointer))
(:unsigned-char :unsigned-short :unsigned-int :unsigned-long
:unsigned-long-long)))
;;; Pretty safe bets.
(defctype :size #+64-bit :uint64 #+32-bit :uint32)
(defctype :ssize #+64-bit :int64 #+32-bit :int32)
(defctype :ptrdiff :ssize)
(defctype :offset #+(or 64-bit bsd) :int64 #-(or 64-bit bsd) :int32)
| 45,461 | Common Lisp | .lisp | 937 | 41.013874 | 93 | 0.646497 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 734311f0a14210c25049d4f557b8bb967a3609aba46753bd932cccc9beaae486 | 42,974 | [
361746
] |
42,977 | enum.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/enum.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; enum.lisp --- Defining foreign constants as Lisp keywords.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
;; TODO the accessors names are rather inconsistent:
;; FOREIGN-ENUM-VALUE FOREIGN-BITFIELD-VALUE
;; FOREIGN-ENUM-KEYWORD FOREIGN-BITFIELD-SYMBOLS
;; FOREIGN-ENUM-KEYWORD-LIST FOREIGN-BITFIELD-SYMBOL-LIST
;; I'd rename them to: FOREIGN-*-KEY(S) and FOREIGN-*-ALL-KEYS -- attila
;; TODO bitfield is a confusing name, because the C standard calls
;; the "int foo : 3" type as a bitfield. Maybe rename to defbitmask?
;; -- attila
;;;# Foreign Constants as Lisp Keywords
;;;
;;; This module defines the DEFCENUM macro, which provides an
;;; interface for defining a type and associating a set of integer
;;; constants with keyword symbols for that type.
;;;
;;; The keywords are automatically translated to the appropriate
;;; constant for the type by a type translator when passed as
;;; arguments or a return value to a foreign function.
(defclass foreign-enum (named-foreign-type enhanced-foreign-type)
((keyword-values
:initform (error "Must specify KEYWORD-VALUES.")
:initarg :keyword-values
:reader keyword-values)
(value-keywords
:initform (error "Must specify VALUE-KEYWORDS.")
:initarg :value-keywords
:reader value-keywords)
(allow-undeclared-values
:initform nil
:initarg :allow-undeclared-values
:reader allow-undeclared-values))
(:documentation "Describes a foreign enumerated type."))
(deftype enum-key ()
'(and symbol (not null)))
(defparameter +valid-enum-base-types+ *built-in-integer-types*)
(defun parse-foreign-enum-like (type-name base-type values
&optional field-mode-p)
(let ((keyword-values (make-hash-table :test 'eq))
(value-keywords (make-hash-table))
(field-keywords (list))
(bit-index->keyword (make-array 0 :adjustable t
:element-type t))
(default-value (if field-mode-p 1 0))
(most-extreme-value 0)
(has-negative-value? nil))
(dolist (pair values)
(destructuring-bind (keyword &optional (value default-value valuep))
(ensure-list pair)
(check-type keyword enum-key)
;;(check-type value integer)
(when (> (abs value) (abs most-extreme-value))
(setf most-extreme-value value))
(when (minusp value)
(setf has-negative-value? t))
(if field-mode-p
(if valuep
(when (and (>= value default-value)
(single-bit-p value))
(setf default-value (ash value 1)))
(setf default-value (ash default-value 1)))
(setf default-value (1+ value)))
(if (gethash keyword keyword-values)
(error "A foreign enum cannot contain duplicate keywords: ~S."
keyword)
(setf (gethash keyword keyword-values) value))
;; This is completely arbitrary behaviour: we keep the last
;; value->keyword mapping. I suppose the opposite would be
;; just as good (keeping the first). Returning a list with all
;; the keywords might be a solution too? Suggestions
;; welcome. --luis
(setf (gethash value value-keywords) keyword)
(when (and field-mode-p
(single-bit-p value))
(let ((bit-index (1- (integer-length value))))
(push keyword field-keywords)
(when (<= (array-dimension bit-index->keyword 0)
bit-index)
(setf bit-index->keyword
(adjust-array bit-index->keyword (1+ bit-index)
:initial-element nil)))
(setf (aref bit-index->keyword bit-index)
keyword)))))
(if base-type
(progn
(setf base-type (canonicalize-foreign-type base-type))
;; I guess we don't lose much by not strictly adhering to
;; the C standard here, and some libs out in the wild are
;; already using e.g. :double.
#+nil
(assert (member base-type +valid-enum-base-types+ :test 'eq) ()
"Invalid base type ~S for enum type ~S. Must be one of ~S."
base-type type-name +valid-enum-base-types+))
;; details: https://stackoverflow.com/questions/1122096/what-is-the-underlying-type-of-a-c-enum
(let ((bits (integer-length most-extreme-value)))
(setf base-type
(let ((most-uint-bits (load-time-value (* (foreign-type-size :unsigned-int) 8)))
(most-ulong-bits (load-time-value (* (foreign-type-size :unsigned-long) 8)))
(most-ulonglong-bits (load-time-value (* (foreign-type-size :unsigned-long-long) 8))))
(or (if has-negative-value?
(cond
((<= (1+ bits) most-uint-bits)
:int)
((<= (1+ bits) most-ulong-bits)
:long)
((<= (1+ bits) most-ulonglong-bits)
:long-long))
(cond
((<= bits most-uint-bits)
:unsigned-int)
((<= bits most-ulong-bits)
:unsigned-long)
((<= bits most-ulonglong-bits)
:unsigned-long-long)))
(error "Enum value ~S of enum ~S is too large to store."
most-extreme-value type-name))))))
(values base-type keyword-values value-keywords
field-keywords (when field-mode-p
(alexandria:copy-array
bit-index->keyword :adjustable nil
:fill-pointer nil)))))
(defun make-foreign-enum (type-name base-type values &key allow-undeclared-values)
"Makes a new instance of the foreign-enum class."
(multiple-value-bind
(base-type keyword-values value-keywords)
(parse-foreign-enum-like type-name base-type values)
(make-instance 'foreign-enum
:name type-name
:actual-type (parse-type base-type)
:keyword-values keyword-values
:value-keywords value-keywords
:allow-undeclared-values allow-undeclared-values)))
(defun %defcenum-like (name-and-options enum-list type-factory)
(discard-docstring enum-list)
(destructuring-bind (name &optional base-type &rest args)
(ensure-list name-and-options)
(let ((type (apply type-factory name base-type enum-list args)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-type ',name
;; ,type is not enough here, someone needs to
;; define it when we're being loaded from a fasl.
(,type-factory ',name ',base-type ',enum-list ,@args))
,@(remove nil
(mapcar (lambda (key)
(unless (keywordp key)
`(defconstant ,key ,(foreign-enum-value type key))))
(foreign-enum-keyword-list type)))))))
(defmacro defcenum (name-and-options &body enum-list)
"Define an foreign enumerated type."
(%defcenum-like name-and-options enum-list 'make-foreign-enum))
(defun hash-keys-to-list (ht)
(loop for k being the hash-keys in ht collect k))
(defun foreign-enum-keyword-list (enum-type)
"Return a list of KEYWORDS defined in ENUM-TYPE."
(hash-keys-to-list (keyword-values (ensure-parsed-base-type enum-type))))
;;; These [four] functions could be good canditates for compiler macros
;;; when the value or keyword is constant. I am not going to bother
;;; until someone has a serious performance need to do so though. --jamesjb
(defun %foreign-enum-value (type keyword &key errorp)
(check-type keyword enum-key)
(or (gethash keyword (keyword-values type))
(when errorp
(error "~S is not defined as a keyword for enum type ~S."
keyword type))))
(defun foreign-enum-value (type keyword &key (errorp t))
"Convert a KEYWORD into an integer according to the enum TYPE."
(let ((type-obj (ensure-parsed-base-type type)))
(if (not (typep type-obj 'foreign-enum))
(error "~S is not a foreign enum type." type)
(%foreign-enum-value type-obj keyword :errorp errorp))))
(defun %foreign-enum-keyword (type value &key errorp)
(check-type value integer)
(or (gethash value (value-keywords type))
(when errorp
(error "~S is not defined as a value for enum type ~S."
value type))))
(defun foreign-enum-keyword (type value &key (errorp t))
"Convert an integer VALUE into a keyword according to the enum TYPE."
(let ((type-obj (ensure-parsed-base-type type)))
(if (not (typep type-obj 'foreign-enum))
(error "~S is not a foreign enum type." type)
(%foreign-enum-keyword type-obj value :errorp errorp))))
(defmethod translate-to-foreign (value (type foreign-enum))
(if (typep value 'enum-key)
(%foreign-enum-value type value :errorp t)
value))
(defmethod translate-into-foreign-memory
(value (type foreign-enum) pointer)
(setf (mem-aref pointer (unparse-type (actual-type type)))
(translate-to-foreign value type)))
(defmethod translate-from-foreign (value (type foreign-enum))
(if (allow-undeclared-values type)
(or (%foreign-enum-keyword type value :errorp nil)
value)
(%foreign-enum-keyword type value :errorp t)))
(defmethod expand-to-foreign (value (type foreign-enum))
(once-only (value)
`(if (typep ,value 'enum-key)
(%foreign-enum-value ,type ,value :errorp t)
,value)))
;;; There are two expansions necessary for an enum: first, the enum
;;; keyword needs to be translated to an int, and then the int needs
;;; to be made indirect.
(defmethod expand-to-foreign-dyn-indirect (value var body (type foreign-enum))
(expand-to-foreign-dyn-indirect ; Make the integer indirect
(with-unique-names (feint)
(call-next-method value feint (list feint) type)) ; TRANSLATABLE-FOREIGN-TYPE method
var
body
(actual-type type)))
;;;# Foreign Bitfields as Lisp keywords
;;;
;;; DEFBITFIELD is an abstraction similar to the one provided by DEFCENUM.
;;; With some changes to DEFCENUM, this could certainly be implemented on
;;; top of it.
(defclass foreign-bitfield (foreign-enum)
((field-keywords
:initform (error "Must specify FIELD-KEYWORDS.")
:initarg :field-keywords
:reader field-keywords)
(bit-index->keyword
:initform (error "Must specify BIT-INDEX->KEYWORD")
:initarg :bit-index->keyword
:reader bit-index->keyword))
(:documentation "Describes a foreign bitfield type."))
(defun make-foreign-bitfield (type-name base-type values)
"Makes a new instance of the foreign-bitfield class."
(multiple-value-bind
(base-type keyword-values value-keywords
field-keywords bit-index->keyword)
(parse-foreign-enum-like type-name base-type values t)
(make-instance 'foreign-bitfield
:name type-name
:actual-type (parse-type base-type)
:keyword-values keyword-values
:value-keywords value-keywords
:field-keywords field-keywords
:bit-index->keyword bit-index->keyword)))
(defmacro defbitfield (name-and-options &body masks)
"Define an foreign enumerated type."
(%defcenum-like name-and-options masks 'make-foreign-bitfield))
(defun foreign-bitfield-symbol-list (bitfield-type)
"Return a list of SYMBOLS defined in BITFIELD-TYPE."
(field-keywords (ensure-parsed-base-type bitfield-type)))
(defun %foreign-bitfield-value (type symbols)
(declare (optimize speed))
(labels ((process-one (symbol)
(check-type symbol symbol)
(or (gethash symbol (keyword-values type))
(error "~S is not a valid symbol for bitfield type ~S."
symbol type))))
(declare (dynamic-extent #'process-one))
(cond
((consp symbols)
(reduce #'logior symbols :key #'process-one))
((null symbols)
0)
(t
(process-one symbols)))))
(defun foreign-bitfield-value (type symbols)
"Convert a list of symbols into an integer according to the TYPE bitfield."
(let ((type-obj (ensure-parsed-base-type type)))
(assert (typep type-obj 'foreign-bitfield) ()
"~S is not a foreign bitfield type." type)
(%foreign-bitfield-value type-obj symbols)))
(define-compiler-macro foreign-bitfield-value (&whole form type symbols)
"Optimize for when TYPE and SYMBOLS are constant."
(declare (notinline foreign-bitfield-value))
(if (and (constantp type) (constantp symbols))
(foreign-bitfield-value (eval type) (eval symbols))
form))
(defun %foreign-bitfield-symbols (type value)
(check-type value integer)
(check-type type foreign-bitfield)
(loop
:with bit-index->keyword = (bit-index->keyword type)
:for bit-index :from 0 :below (array-dimension bit-index->keyword 0)
:for mask = 1 :then (ash mask 1)
:for key = (aref bit-index->keyword bit-index)
:when (and key
(= (logand value mask) mask))
:collect key))
(defun foreign-bitfield-symbols (type value)
"Convert an integer VALUE into a list of matching symbols according to
the bitfield TYPE."
(let ((type-obj (ensure-parsed-base-type type)))
(if (not (typep type-obj 'foreign-bitfield))
(error "~S is not a foreign bitfield type." type)
(%foreign-bitfield-symbols type-obj value))))
(define-compiler-macro foreign-bitfield-symbols (&whole form type value)
"Optimize for when TYPE and SYMBOLS are constant."
(declare (notinline foreign-bitfield-symbols))
(if (and (constantp type) (constantp value))
`(quote ,(foreign-bitfield-symbols (eval type) (eval value)))
form))
(defmethod translate-to-foreign (value (type foreign-bitfield))
(if (integerp value)
value
(%foreign-bitfield-value type (ensure-list value))))
(defmethod translate-from-foreign (value (type foreign-bitfield))
(%foreign-bitfield-symbols type value))
(defmethod expand-to-foreign (value (type foreign-bitfield))
(flet ((expander (value type)
`(if (integerp ,value)
,value
(%foreign-bitfield-value ,type (ensure-list ,value)))))
(if (constantp value)
(eval (expander value type))
(expander value type))))
(defmethod expand-from-foreign (value (type foreign-bitfield))
(flet ((expander (value type)
`(%foreign-bitfield-symbols ,type ,value)))
(if (constantp value)
(eval (expander value type))
(expander value type))))
| 16,214 | Common Lisp | .lisp | 340 | 39.185294 | 108 | 0.638252 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 5013db8ff43fcfda1a425134c3b2d5f040c9c13e547209fedaf32de83ede6cad | 42,977 | [
283045
] |
42,978 | strings.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/strings.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; strings.lisp --- Operations on foreign strings.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2005-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
;;;# Foreign String Conversion
;;;
;;; Functions for converting NULL-terminated C-strings to Lisp strings
;;; and vice versa. The string functions accept an ENCODING keyword
;;; argument which is used to specify the encoding to use when
;;; converting to/from foreign strings.
(defvar *default-foreign-encoding* :utf-8
"Default foreign encoding.")
;;; TODO: refactor, sigh. Also, this should probably be a function.
(defmacro bget (ptr off &optional (bytes 1) (endianness :ne))
(let ((big-endian (member endianness
'(:be #+big-endian :ne #+little-endian :re))))
(once-only (ptr off)
(ecase bytes
(1 `(mem-ref ,ptr :uint8 ,off))
(2 (if big-endian
#+big-endian
`(mem-ref ,ptr :uint16 ,off)
#-big-endian
`(dpb (mem-ref ,ptr :uint8 ,off) (byte 8 8)
(mem-ref ,ptr :uint8 (1+ ,off)))
#+little-endian
`(mem-ref ,ptr :uint16 ,off)
#-little-endian
`(dpb (mem-ref ,ptr :uint8 (1+ ,off)) (byte 8 8)
(mem-ref ,ptr :uint8 ,off))))
(4 (if big-endian
#+big-endian
`(mem-ref ,ptr :uint32 ,off)
#-big-endian
`(dpb (mem-ref ,ptr :uint8 ,off) (byte 8 24)
(dpb (mem-ref ,ptr :uint8 (1+ ,off)) (byte 8 16)
(dpb (mem-ref ,ptr :uint8 (+ ,off 2)) (byte 8 8)
(mem-ref ,ptr :uint8 (+ ,off 3)))))
#+little-endian
`(mem-ref ,ptr :uint32 ,off)
#-little-endian
`(dpb (mem-ref ,ptr :uint8 (+ ,off 3)) (byte 8 24)
(dpb (mem-ref ,ptr :uint8 (+ ,off 2)) (byte 8 16)
(dpb (mem-ref ,ptr :uint8 (1+ ,off)) (byte 8 8)
(mem-ref ,ptr :uint8 ,off))))))))))
(defmacro bset (val ptr off &optional (bytes 1) (endianness :ne))
(let ((big-endian (member endianness
'(:be #+big-endian :ne #+little-endian :re))))
(ecase bytes
(1 `(setf (mem-ref ,ptr :uint8 ,off) ,val))
(2 (if big-endian
#+big-endian
`(setf (mem-ref ,ptr :uint16 ,off) ,val)
#-big-endian
`(setf (mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 0) ,val)
(mem-ref ,ptr :uint8 ,off) (ldb (byte 8 8) ,val))
#+little-endian
`(setf (mem-ref ,ptr :uint16 ,off) ,val)
#-little-endian
`(setf (mem-ref ,ptr :uint8 ,off) (ldb (byte 8 0) ,val)
(mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 8) ,val))))
(4 (if big-endian
#+big-endian
`(setf (mem-ref ,ptr :uint32 ,off) ,val)
#-big-endian
`(setf (mem-ref ,ptr :uint8 (+ 3 ,off)) (ldb (byte 8 0) ,val)
(mem-ref ,ptr :uint8 (+ 2 ,off)) (ldb (byte 8 8) ,val)
(mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 16) ,val)
(mem-ref ,ptr :uint8 ,off) (ldb (byte 8 24) ,val))
#+little-endian
`(setf (mem-ref ,ptr :uint32 ,off) ,val)
#-little-endian
`(setf (mem-ref ,ptr :uint8 ,off) (ldb (byte 8 0) ,val)
(mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 8) ,val)
(mem-ref ,ptr :uint8 (+ ,off 2)) (ldb (byte 8 16) ,val)
(mem-ref ,ptr :uint8 (+ ,off 3)) (ldb (byte 8 24) ,val)))))))
;;; TODO: tackle optimization notes.
(defparameter *foreign-string-mappings*
(instantiate-concrete-mappings
;; :optimize ((speed 3) (debug 0) (compilation-speed 0) (safety 0))
:octet-seq-getter bget
:octet-seq-setter bset
:octet-seq-type foreign-pointer
:code-point-seq-getter babel::string-get
:code-point-seq-setter babel::string-set
:code-point-seq-type babel:simple-unicode-string))
(defun null-terminator-len (encoding)
(length (enc-nul-encoding (get-character-encoding encoding))))
(defun lisp-string-to-foreign (string buffer bufsize &key (start 0) end offset
(encoding *default-foreign-encoding*))
(check-type string string)
(when offset
(setq buffer (inc-pointer buffer offset)))
(with-checked-simple-vector ((string (coerce string 'babel:unicode-string))
(start start) (end end))
(declare (type simple-string string))
(let ((mapping (lookup-mapping *foreign-string-mappings* encoding))
(nul-len (null-terminator-len encoding)))
(assert (plusp bufsize))
(multiple-value-bind (size end)
(funcall (octet-counter mapping) string start end (- bufsize nul-len))
(funcall (encoder mapping) string start end buffer 0)
(dotimes (i nul-len)
(setf (mem-ref buffer :char (+ size i)) 0))))
buffer))
;;; Expands into a loop that calculates the length of the foreign
;;; string at PTR plus OFFSET, using ACCESSOR and looking for a null
;;; terminator of LENGTH bytes.
(defmacro %foreign-string-length (ptr offset type length)
(once-only (ptr offset)
`(do ((i 0 (+ i ,length)))
((zerop (mem-ref ,ptr ,type (+ ,offset i))) i)
(declare (fixnum i)))))
;;; Return the length in octets of the null terminated foreign string
;;; at POINTER plus OFFSET octets, assumed to be encoded in ENCODING,
;;; a CFFI encoding. This should be smart enough to look for 8-bit vs
;;; 16-bit null terminators, as appropriate for the encoding.
(defun foreign-string-length (pointer &key (encoding *default-foreign-encoding*)
(offset 0))
(ecase (null-terminator-len encoding)
(1 (%foreign-string-length pointer offset :uint8 1))
(2 (%foreign-string-length pointer offset :uint16 2))
(4 (%foreign-string-length pointer offset :uint32 4))))
(defun foreign-string-to-lisp (pointer &key (offset 0) count
(max-chars (1- array-total-size-limit))
(encoding *default-foreign-encoding*))
"Copy at most COUNT bytes from POINTER plus OFFSET encoded in
ENCODING into a Lisp string and return it. If POINTER is a null
pointer, NIL is returned."
(unless (null-pointer-p pointer)
(let ((count (or count
(foreign-string-length
pointer :encoding encoding :offset offset)))
(mapping (lookup-mapping *foreign-string-mappings* encoding)))
(assert (plusp max-chars))
(multiple-value-bind (size new-end)
(funcall (code-point-counter mapping)
pointer offset (+ offset count) max-chars)
(let ((string (make-string size :element-type 'babel:unicode-char)))
(funcall (decoder mapping) pointer offset new-end string 0)
(values string (- new-end offset)))))))
;;;# Using Foreign Strings
(defun foreign-string-alloc (string &key (encoding *default-foreign-encoding*)
(null-terminated-p t) (start 0) end)
"Allocate a foreign string containing Lisp string STRING.
The string must be freed with FOREIGN-STRING-FREE."
(check-type string string)
(with-checked-simple-vector ((string (coerce string 'babel:unicode-string))
(start start) (end end))
(declare (type simple-string string))
(let* ((mapping (lookup-mapping *foreign-string-mappings* encoding))
(count (funcall (octet-counter mapping) string start end 0))
(nul-length (if null-terminated-p
(null-terminator-len encoding)
0))
(length (+ count nul-length))
(ptr (foreign-alloc :char :count length)))
(unwind-protect-case ()
(funcall (encoder mapping) string start end ptr 0)
(:abort (foreign-free ptr)))
(dotimes (i nul-length)
(setf (mem-ref ptr :char (+ count i)) 0))
(values ptr length))))
(defun foreign-string-free (ptr)
"Free a foreign string allocated by FOREIGN-STRING-ALLOC."
(foreign-free ptr))
(defmacro with-foreign-string ((var-or-vars lisp-string &rest args) &body body)
"VAR-OR-VARS is not evaluated and should be a list of the form
\(VAR &OPTIONAL BYTE-SIZE-VAR) or just a VAR symbol. VAR is
bound to a foreign string containing LISP-STRING in BODY. When
BYTE-SIZE-VAR is specified then bind the C buffer size
\(including the possible null terminator\(s)) to this variable."
(destructuring-bind (var &optional size-var)
(ensure-list var-or-vars)
`(multiple-value-bind (,var ,@(when size-var (list size-var)))
(foreign-string-alloc ,lisp-string ,@args)
(unwind-protect
(progn ,@body)
(foreign-string-free ,var)))))
(defmacro with-foreign-strings (bindings &body body)
"See WITH-FOREIGN-STRING's documentation."
(if bindings
`(with-foreign-string ,(first bindings)
(with-foreign-strings ,(rest bindings)
,@body))
`(progn ,@body)))
(defmacro with-foreign-pointer-as-string
((var-or-vars size &rest args) &body body)
"VAR-OR-VARS is not evaluated and should be a list of the form
\(VAR &OPTIONAL SIZE-VAR) or just a VAR symbol. VAR is bound to
a foreign buffer of size SIZE within BODY. The return value is
constructed by calling FOREIGN-STRING-TO-LISP on the foreign
buffer along with ARGS." ; fix wording, sigh
(destructuring-bind (var &optional size-var)
(ensure-list var-or-vars)
`(with-foreign-pointer (,var ,size ,size-var)
(progn
,@body
(values (foreign-string-to-lisp ,var ,@args))))))
;;;# Automatic Conversion of Foreign Strings
(define-foreign-type foreign-string-type ()
(;; CFFI encoding of this string.
(encoding :initform nil :initarg :encoding :reader encoding)
;; Should we free after translating from foreign?
(free-from-foreign :initarg :free-from-foreign
:reader fst-free-from-foreign-p
:initform nil :type boolean)
;; Should we free after translating to foreign?
(free-to-foreign :initarg :free-to-foreign
:reader fst-free-to-foreign-p
:initform t :type boolean))
(:actual-type :pointer)
(:simple-parser :string))
;;; describe me
(defun fst-encoding (type)
(or (encoding type) *default-foreign-encoding*))
;;; Display the encoding when printing a FOREIGN-STRING-TYPE instance.
(defmethod print-object ((type foreign-string-type) stream)
(print-unreadable-object (type stream :type t)
(format stream "~S" (fst-encoding type))))
(defmethod translate-to-foreign ((s string) (type foreign-string-type))
(values (foreign-string-alloc s :encoding (fst-encoding type))
(fst-free-to-foreign-p type)))
(defmethod translate-to-foreign (obj (type foreign-string-type))
(cond
((pointerp obj)
(values obj nil))
;; FIXME: we used to support UB8 vectors but not anymore.
;; ((typep obj '(array (unsigned-byte 8)))
;; (values (foreign-string-alloc obj) t))
(t (error "~A is not a Lisp string or pointer." obj))))
(defmethod translate-from-foreign (ptr (type foreign-string-type))
(unwind-protect
(values (foreign-string-to-lisp ptr :encoding (fst-encoding type)))
(when (fst-free-from-foreign-p type)
(foreign-free ptr))))
(defmethod free-translated-object (ptr (type foreign-string-type) free-p)
(when free-p
(foreign-string-free ptr)))
(defmethod expand-to-foreign-dyn-indirect
(value var body (type foreign-string-type))
(alexandria:with-gensyms (str)
(expand-to-foreign-dyn
value
str
(list
(expand-to-foreign-dyn-indirect str var body (parse-type :pointer)))
type)))
;;;# STRING+PTR
(define-foreign-type foreign-string+ptr-type (foreign-string-type)
()
(:simple-parser :string+ptr))
(defmethod translate-from-foreign (value (type foreign-string+ptr-type))
(list (call-next-method) value))
| 13,345 | Common Lisp | .lisp | 278 | 39.996403 | 81 | 0.625173 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 5e8ae95200e5473ba06611dc894b13c4d5c1c776568ffee9e9371075e6b4f01f | 42,978 | [
216650
] |
42,979 | utils.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/utils.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; utils.lisp --- Various utilities.
;;;
;;; Copyright (C) 2005-2008, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; 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.
;;;
(in-package #:cffi)
(defmacro discard-docstring (body-var)
"Discards the first element of the list in body-var if it's a
string."
`(when (stringp (car ,body-var))
(pop ,body-var)))
(defun single-bit-p (integer)
"Answer whether INTEGER, which must be an integer, is a single
set twos-complement bit."
(if (<= integer 0)
nil ; infinite set bits for negatives
(loop until (logbitp 0 integer)
do (setf integer (ash integer -1))
finally (return (zerop (ash integer -1))))))
;;; This function is here because it needs to be defined early. It's
;;; used by DEFINE-PARSE-METHOD and DEFCTYPE to warn users when
;;; they're defining types whose names belongs to the KEYWORD or CL
;;; packages. CFFI itself gets to use keywords without a warning.
(defun warn-if-kw-or-belongs-to-cl (name)
(let ((package (symbol-package name)))
(when (and (not (eq *package* (find-package '#:cffi)))
(member package '(#:common-lisp #:keyword)
:key #'find-package))
(warn "Defining a foreign type named ~S. This symbol belongs to the ~A ~
package and that may interfere with other code using CFFI."
name (package-name package)))))
(define-condition obsolete-argument-warning (style-warning)
((old-arg :initarg :old-arg :reader old-arg)
(new-arg :initarg :new-arg :reader new-arg))
(:report (lambda (c s)
(format s "Keyword ~S is obsolete, please use ~S"
(old-arg c) (new-arg c)))))
(defun warn-obsolete-argument (old-arg new-arg)
(warn 'obsolete-argument-warning
:old-arg old-arg :new-arg new-arg))
(defun split-if (test seq &optional (dir :before))
(remove-if #'(lambda (x) (equal x (subseq seq 0 0)))
(loop for start fixnum = 0
then (if (eq dir :before)
stop
(the fixnum (1+ (the fixnum stop))))
while (< start (length seq))
for stop = (position-if test seq
:start (if (eq dir :elide)
start
(the fixnum (1+ start))))
collect (subseq seq start
(if (and stop (eq dir :after))
(the fixnum (1+ (the fixnum stop)))
stop))
while stop)))
| 3,824 | Common Lisp | .lisp | 77 | 40.636364 | 79 | 0.608021 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 6d1dd1d9011592a2c61e6f1c9cca0e5df43383bfcfa0d5f5cd6226b3f28d5d50 | 42,979 | [
73946
] |
42,980 | cffi-sbcl.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/cffi-sbcl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-sbcl.lisp --- CFFI-SYS implementation for SBCL.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; 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.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:sb-alien)
(:import-from #:alexandria
#:once-only #:with-unique-names #:when-let #:removef)
(:export
#:canonicalize-symbol-name-case
#:foreign-pointer
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-funcall-varargs
#:%foreign-funcall-pointer-varargs
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:native-namestring
#:%mem-ref
#:%mem-set
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:%foreign-symbol-pointer
#:%defcallback
#:%callback))
(in-package #:cffi-sys)
;;;# Misfeatures
(pushnew 'flat-namespace *features*)
;;;# Symbol Case
(declaim (inline canonicalize-symbol-name-case))
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Basic Pointer Operations
(deftype foreign-pointer ()
'sb-sys:system-area-pointer)
(declaim (inline pointerp))
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(sb-sys:system-area-pointer-p ptr))
(declaim (inline pointer-eq))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(declare (type system-area-pointer ptr1 ptr2))
(sb-sys:sap= ptr1 ptr2))
(declaim (inline null-pointer))
(defun null-pointer ()
"Construct and return a null pointer."
(sb-sys:int-sap 0))
(declaim (inline null-pointer-p))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(declare (type system-area-pointer ptr))
(zerop (sb-sys:sap-int ptr)))
(declaim (inline inc-pointer))
(defun inc-pointer (ptr offset)
"Return a pointer pointing OFFSET bytes past PTR."
(declare (type system-area-pointer ptr)
(type integer offset))
(sb-sys:sap+ ptr offset))
(declaim (inline make-pointer))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
;; (declare (type (unsigned-byte 32) address))
(sb-sys:int-sap address))
(declaim (inline pointer-address))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(declare (type system-area-pointer ptr))
(sb-sys:sap-int ptr))
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage
;;; when the memory has dynamic extent.
(declaim (inline %foreign-alloc))
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
;; (declare (type (unsigned-byte 32) size))
(alien-sap (make-alien (unsigned 8) size)))
(declaim (inline foreign-free))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(declare (type system-area-pointer ptr)
(optimize speed))
(free-alien (sap-alien ptr (* (unsigned 8)))))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
;; If the size is constant we can stack-allocate.
(if (constantp size)
(let ((alien-var (gensym "ALIEN")))
`(with-alien ((,alien-var (array (unsigned 8) ,(eval size))))
(let ((,size-var ,(eval size))
(,var (alien-sap ,alien-var)))
(declare (ignorable ,size-var))
,@body)))
`(let* ((,size-var ,size)
(,var (%foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var)))))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
(declaim (inline make-shareable-byte-vector))
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes that can be passed to
WITH-POINTER-TO-VECTOR-DATA."
; (declare (type sb-int:index size))
(make-array size :element-type '(unsigned-byte 8)))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a foreign pointer to the data in VECTOR."
(let ((vector-var (gensym "VECTOR")))
`(let ((,vector-var ,vector))
(declare (type (sb-kernel:simple-unboxed-array (*)) ,vector-var))
(sb-sys:with-pinned-objects (,vector-var)
(let ((,ptr-var (sb-sys:vector-sap ,vector-var)))
,@body)))))
;;;# Dereferencing
;;; Define the %MEM-REF and %MEM-SET functions, as well as compiler
;;; macros that optimize the case where the type keyword is constant
;;; at compile-time.
(defmacro define-mem-accessors (&body pairs)
`(progn
(defun %mem-ref (ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (,fn ptr offset)))))
(defun %mem-set (value ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (setf (,fn ptr offset) value)))))
(define-compiler-macro %mem-ref
(&whole form ptr type &optional (offset 0))
(if (constantp type)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(,',fn ,ptr ,offset))))
form))
(define-compiler-macro %mem-set
(&whole form value ptr type &optional (offset 0))
(if (constantp type)
(once-only (value)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(setf (,',fn ,ptr ,offset)
,value)))))
form))))
;;; Look up alien type information and build both define-mem-accessors form
;;; and convert-foreign-type function definition.
(defmacro define-type-mapping (accessor-table alien-table)
(let* ((accessible-types
(remove 'void alien-table :key #'second))
(size-and-signedp-forms
(mapcar (lambda (name)
(list (eval `(alien-size ,(second name)))
(typep -1 `(alien ,(second name)))))
accessible-types)))
`(progn
(define-mem-accessors
,@(loop for (cffi-keyword alien-type fixed-accessor)
in accessible-types
and (alien-size signedp)
in size-and-signedp-forms
for (signed-ref unsigned-ref)
= (cdr (assoc alien-size accessor-table))
collect
`(,cffi-keyword
,(or fixed-accessor
(if signedp signed-ref unsigned-ref)
(error "No accessor found for ~S"
alien-type)))))
(defun convert-foreign-type (type-keyword)
(ecase type-keyword
,@(loop for (cffi-keyword alien-type) in alien-table
collect `(,cffi-keyword (quote ,alien-type))))))))
(define-type-mapping
((8 sb-sys:signed-sap-ref-8 sb-sys:sap-ref-8)
(16 sb-sys:signed-sap-ref-16 sb-sys:sap-ref-16)
(32 sb-sys:signed-sap-ref-32 sb-sys:sap-ref-32)
(64 sb-sys:signed-sap-ref-64 sb-sys:sap-ref-64))
((:char char)
(:unsigned-char unsigned-char)
(:short short)
(:unsigned-short unsigned-short)
(:int int)
(:unsigned-int unsigned-int)
(:long long)
(:unsigned-long unsigned-long)
(:long-long long-long)
(:unsigned-long-long unsigned-long-long)
(:float single-float
sb-sys:sap-ref-single)
(:double double-float
sb-sys:sap-ref-double)
(:pointer system-area-pointer
sb-sys:sap-ref-sap)
(:void void)))
;;;# Calling Foreign Functions
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(/ (sb-alien-internals:alien-type-bits
(sb-alien-internals:parse-alien-type
(convert-foreign-type type-keyword) nil)) 8))
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
#+(and darwin ppc (not ppc64))
(case type-keyword
((:double :long-long :unsigned-long-long)
(return-from %foreign-type-alignment 8)))
;; No override necessary for other types...
(/ (sb-alien-internals:alien-type-alignment
(sb-alien-internals:parse-alien-type
(convert-foreign-type type-keyword) nil)) 8))
(defun foreign-funcall-type-and-args (args)
"Return an SB-ALIEN function type for ARGS."
(let ((return-type 'void)
types
fargs)
(loop while args
do (let ((type (pop args)))
(cond ((eq type '&optional)
(push type types))
((not args)
(setf return-type (convert-foreign-type type)))
(t
(push (convert-foreign-type type) types)
(push (pop args) fargs)))))
(values (nreverse types)
(nreverse fargs)
return-type)))
(defmacro %%foreign-funcall (name types fargs rettype)
"Internal guts of %FOREIGN-FUNCALL."
`(alien-funcall
(extern-alien ,name (function ,rettype ,@types))
,@fargs))
(defmacro %foreign-funcall (name args &key library convention)
"Perform a foreign function call, document it more later."
(declare (ignore library convention))
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall ,name ,types ,fargs ,rettype)))
(defmacro %foreign-funcall-pointer (ptr args &key convention)
"Funcall a pointer to a foreign function."
(declare (ignore convention))
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
(with-unique-names (function)
`(with-alien ((,function (* (function ,rettype ,@types)) ,ptr))
(alien-funcall ,function ,@fargs)))))
(defmacro %foreign-funcall-varargs (name fixed-args varargs
&rest args &key convention library)
(declare (ignore convention library))
`(%foreign-funcall ,name ,(append fixed-args (and varargs
;; All SBCL platforms would understand this
;; but this is the only one where it's required.
;; Omitting elsewhere makes it work on older
;; versions of SBCL.
(append #+(and darwin arm64)
'(&optional)
varargs)))
,@args))
(defmacro %foreign-funcall-pointer-varargs (pointer fixed-args varargs
&rest args &key convention)
(declare (ignore convention))
`(%foreign-funcall-pointer ,pointer ,(append fixed-args
(and varargs
(append #+(and darwin arm64)
'(&optional)
varargs)))
,@args))
;;;# Callbacks
;;; The *CALLBACKS* hash table contains a direct mapping of CFFI
;;; callback names to SYSTEM-AREA-POINTERs obtained by ALIEN-LAMBDA.
;;; SBCL will maintain the addresses of the callbacks across saved
;;; images, so it is safe to store the pointers directly.
(defvar *callbacks* (make-hash-table))
(defmacro %defcallback (name rettype arg-names arg-types body
&key convention)
(check-type convention (member :stdcall :cdecl))
`(setf (gethash ',name *callbacks*)
(alien-sap
(sb-alien::alien-lambda
(,convention ,(convert-foreign-type rettype))
,(mapcar (lambda (sym type)
(list sym (convert-foreign-type type)))
arg-names arg-types)
,body))))
(defun %callback (name)
(or (gethash name *callbacks*)
(error "Undefined callback: ~S" name)))
;;;# Loading and Closing Foreign Libraries
#+darwin
(defun call-within-initial-thread (fn &rest args)
(let (result
error
(sem (sb-thread:make-semaphore)))
(sb-thread:interrupt-thread
sb-thread::*initial-thread*
(lambda ()
(multiple-value-setq (result error)
(ignore-errors (apply fn args)))
(sb-thread:signal-semaphore sem)))
(sb-thread:wait-on-semaphore sem)
(if error
(signal error)
result)))
(declaim (inline %load-foreign-library))
(defun %load-foreign-library (name path)
"Load a foreign library."
(declare (ignore name))
;; As of MacOS X 10.6.6, loading things like CoreFoundation from a
;; thread other than the initial one results in a crash.
#+(and darwin sb-thread) (call-within-initial-thread 'load-shared-object path)
#-(and darwin sb-thread) (load-shared-object path))
;;; SBCL 1.0.21.15 renamed SB-ALIEN::SHARED-OBJECT-FILE but introduced
;;; SB-ALIEN:UNLOAD-SHARED-OBJECT which we can use instead.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun unload-shared-object-present-p ()
(multiple-value-bind (foundp kind)
(find-symbol "UNLOAD-SHARED-OBJECT" "SB-ALIEN")
(if (and foundp (eq kind :external))
'(:and)
'(:or)))))
(defun %close-foreign-library (handle)
"Closes a foreign library."
#+#.(cffi-sys::unload-shared-object-present-p)
(sb-alien:unload-shared-object handle)
#-#.(cffi-sys::unload-shared-object-present-p)
(sb-thread:with-mutex (sb-alien::*shared-objects-lock*)
(let ((obj (find (sb-ext:native-namestring handle)
sb-alien::*shared-objects*
:key #'sb-alien::shared-object-file
:test #'string=)))
(when obj
(sb-alien::dlclose-or-lose obj)
(removef sb-alien::*shared-objects* obj)
#-win32
(sb-alien::update-linkage-table)))))
(defun native-namestring (pathname)
(sb-ext:native-namestring pathname))
;;;# Foreign Globals
(defun %foreign-symbol-pointer (name library)
"Returns a pointer to a foreign symbol NAME."
(declare (ignore library))
(when-let (address (sb-sys:find-foreign-symbol-address name))
(sb-sys:int-sap address)))
| 16,339 | Common Lisp | .lisp | 390 | 33.953846 | 100 | 0.618302 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | d48f6756ef085cc31c7c55a2922d174f03c6f15781d54648e4f0fff3e886e8e5 | 42,980 | [
350019
] |
42,982 | early-types.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/early-types.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; early-types.lisp --- Low-level foreign type operations.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2005-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
;;;# Early Type Definitions
;;;
;;; This module contains basic operations on foreign types. These
;;; definitions are in a separate file because they may be used in
;;; compiler macros defined later on.
(in-package #:cffi)
;;;# Foreign Types
;;;
;;; Type specifications are of the form (type {args}*). The type
;;; parser can specify how its arguments should look like through a
;;; lambda list.
;;;
;;; "type" is a shortcut for "(type)", ie, no args were specified.
;;;
;;; Examples of such types: boolean, (boolean), (boolean :int) If the
;;; boolean type parser specifies the lambda list: &optional
;;; (base-type :int), then all of the above three type specs would be
;;; parsed to an identical type.
;;;
;;; Type parsers, defined with DEFINE-PARSE-METHOD should return a
;;; subtype of the foreign-type class.
(defvar *default-type-parsers* (make-hash-table)
"Hash table for :DEFAULT namespace")
(defvar *struct-type-parsers* (make-hash-table)
"Hash table for :STRUCT namespace")
(defvar *union-type-parsers* (make-hash-table)
"Hash table for :UNION namespace")
(define-condition cffi-error (error)
())
(define-condition foreign-type-error (cffi-error)
((type-name :initarg :type-name
:initform (error "Must specify TYPE-NAME.")
:accessor foreign-type-error/type-name)
(namespace :initarg :namespace
:initform :default
:accessor foreign-type-error/namespace)))
(defun foreign-type-error/compound-name (e)
(let ((name (foreign-type-error/type-name e))
(namespace (foreign-type-error/namespace e)))
(if (eq namespace :default)
name
`(,namespace ,name))))
(define-condition simple-foreign-type-error (simple-error foreign-type-error)
())
(defun simple-foreign-type-error (type-name namespace format-control &rest format-arguments)
(error 'simple-foreign-type-error
:type-name type-name :namespace namespace
:format-control format-control :format-arguments format-arguments))
(define-condition undefined-foreign-type-error (foreign-type-error)
()
(:report (lambda (e stream)
(format stream "Unknown CFFI type ~S" (foreign-type-error/compound-name e)))))
(defun undefined-foreign-type-error (type-name &optional (namespace :default))
(error 'undefined-foreign-type-error :type-name type-name :namespace namespace))
;; TODO this is not according to the C namespace rules,
;; see bug: https://github.com/cffi/cffi/issues/266
(deftype c-namespace-name ()
'(member :default :struct :union))
(defun namespace-table (namespace)
(ecase namespace
(:default *default-type-parsers*)
(:struct *struct-type-parsers*)
(:union *union-type-parsers*)))
;; for C namespaces read: https://stackoverflow.com/questions/12579142/type-namespace-in-c
;; (section 6.2.3 Name spaces of identifiers)
;; NOTE: :struct is probably an unfortunate name for the tagged (?) namespace
(defun find-type-parser (symbol &optional (namespace :default))
"Return the type parser for SYMBOL. NAMESPACE is either :DEFAULT (for
variables, functions, and typedefs) or :STRUCT (for structs, unions, and enums)."
(check-type symbol (and symbol (not null)))
(or (gethash symbol (namespace-table namespace))
(undefined-foreign-type-error symbol namespace)))
(defun find-default-type-parser (symbol)
(check-type symbol (and symbol (not null)))
(or (gethash symbol *default-type-parsers*)
(undefined-foreign-type-error symbol :default)))
(defun (setf find-type-parser) (func symbol &optional (namespace :default))
"Set the type parser for SYMBOL."
(check-type symbol (and symbol (not null)))
;; TODO Shall we signal a redefinition warning here?
(setf (gethash symbol (namespace-table namespace)) func))
(defun undefine-foreign-type (symbol &optional (namespace :default))
(remhash symbol (namespace-table namespace))
(values))
;;; Using a generic function would have been nicer but generates lots
;;; of style warnings in SBCL. (Silly reason, yes.)
(defmacro define-parse-method (name lambda-list &body body)
"Define a type parser on NAME and lists whose CAR is NAME."
(discard-docstring body)
(warn-if-kw-or-belongs-to-cl name)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (find-type-parser ',name)
(lambda ,lambda-list ,@body))
',name))
;;; Utility function for the simple case where the type takes no
;;; arguments.
(defun notice-foreign-type (name type &optional (namespace :default))
(setf (find-type-parser name namespace) (lambda () type))
name)
;;;# Generic Functions on Types
(defgeneric canonicalize (foreign-type)
(:documentation
"Return the most primitive foreign type for FOREIGN-TYPE, either a built-in
type--a keyword--or a struct/union type--a list of the form (:STRUCT/:UNION name).
Signals an error if FOREIGN-TYPE is undefined."))
(defgeneric aggregatep (foreign-type)
(:documentation
"Return true if FOREIGN-TYPE is an aggregate type."))
(defgeneric foreign-type-alignment (foreign-type)
(:documentation
"Return the structure alignment in bytes of a foreign type."))
(defgeneric foreign-type-size (foreign-type)
(:documentation
"Return the size in bytes of a foreign type."))
(defgeneric unparse-type (foreign-type)
(:documentation
"Unparse FOREIGN-TYPE to a type specification (symbol or list)."))
;;;# Foreign Types
(defclass foreign-type ()
()
(:documentation "Base class for all foreign types."))
(defmethod make-load-form ((type foreign-type) &optional env)
"Return the form used to dump types to a FASL file."
(declare (ignore env))
`(parse-type ',(unparse-type type)))
(defmethod foreign-type-size (type)
"Return the size in bytes of a foreign type."
(foreign-type-size (parse-type type)))
(defclass named-foreign-type (foreign-type)
((name
;; Name of this foreign type, a symbol.
:initform (error "Must specify a NAME.")
:initarg :name
:accessor name)))
(defmethod print-object ((type named-foreign-type) stream)
"Print a FOREIGN-TYPEDEF instance to STREAM unreadably."
(print-unreadable-object (type stream :type t :identity nil)
(format stream "~S" (name type))))
;;; Return the type's name which can be passed to PARSE-TYPE. If
;;; that's not the case for some subclass of NAMED-FOREIGN-TYPE then
;;; it should specialize UNPARSE-TYPE.
(defmethod unparse-type ((type named-foreign-type))
(name type))
;;;# Built-In Foreign Types
(defclass foreign-built-in-type (foreign-type)
((type-keyword
;; Keyword in CFFI-SYS representing this type.
:initform (error "A type keyword is required.")
:initarg :type-keyword
:accessor type-keyword))
(:documentation "A built-in foreign type."))
(defmethod canonicalize ((type foreign-built-in-type))
"Return the built-in type keyword for TYPE."
(type-keyword type))
(defmethod aggregatep ((type foreign-built-in-type))
"Returns false, built-in types are never aggregate types."
nil)
(defmethod foreign-type-alignment ((type foreign-built-in-type))
"Return the alignment of a built-in type."
(%foreign-type-alignment (type-keyword type)))
(defmethod foreign-type-size ((type foreign-built-in-type))
"Return the size of a built-in type."
(%foreign-type-size (type-keyword type)))
(defmethod unparse-type ((type foreign-built-in-type))
"Returns the symbolic representation of a built-in type."
(type-keyword type))
(defmethod print-object ((type foreign-built-in-type) stream)
"Print a FOREIGN-TYPE instance to STREAM unreadably."
(print-unreadable-object (type stream :type t :identity nil)
(format stream "~S" (type-keyword type))))
(defvar *built-in-foreign-types* nil)
(defmacro define-built-in-foreign-type (keyword)
"Defines a built-in foreign-type."
`(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew ,keyword *built-in-foreign-types*)
(notice-foreign-type
,keyword (make-instance 'foreign-built-in-type :type-keyword ,keyword))))
;;;# Foreign Pointer Types
(defclass foreign-pointer-type (foreign-built-in-type)
((pointer-type
;; Type of object pointed at by this pointer, or nil for an
;; untyped (void) pointer.
:initform nil
:initarg :pointer-type
:accessor pointer-type))
(:default-initargs :type-keyword :pointer))
;;; Define the type parser for the :POINTER type. If no type argument
;;; is provided, a void pointer will be created.
(let ((void-pointer (make-instance 'foreign-pointer-type)))
(define-parse-method :pointer (&optional type)
(if type
(make-instance 'foreign-pointer-type :pointer-type (parse-type type))
;; A bit of premature optimization here.
void-pointer)))
;;; Unparse a foreign pointer type when dumping to a fasl.
(defmethod unparse-type ((type foreign-pointer-type))
(if (pointer-type type)
`(:pointer ,(unparse-type (pointer-type type)))
:pointer))
;;; Print a foreign pointer type unreadably in unparsed form.
(defmethod print-object ((type foreign-pointer-type) stream)
(print-unreadable-object (type stream :type t :identity nil)
(format stream "~S" (unparse-type type))))
;;;# Structure Type
(defgeneric bare-struct-type-p (foreign-type)
(:documentation
"Return true if FOREIGN-TYPE is a bare struct type or an alias of a bare struct type. "))
(defmethod bare-struct-type-p ((type foreign-type))
"Return true if FOREIGN-TYPE is a bare struct type or an alias of a bare struct type. "
nil)
(defclass foreign-struct-type (named-foreign-type)
((slots
;; Hash table of slots in this structure, keyed by name.
:initform (make-hash-table)
:initarg :slots
:accessor slots)
(size
;; Cached size in bytes of this structure.
:initarg :size
:accessor size)
(alignment
;; This struct's alignment requirements
:initarg :alignment
:accessor alignment)
(bare
;; we use this flag to support the (old, deprecated) semantics of
;; bare struct types. FOO means (:POINTER (:STRUCT FOO) in
;; functions declarations whereas FOO in a structure definition is
;; a proper aggregate type: (:STRUCT FOO), etc.
:initform nil
:initarg :bare
:reader bare-struct-type-p)))
(defun slots-in-order (structure-type)
"A list of the structure's slots in order."
(sort (loop for slots being the hash-value of (structure-slots structure-type)
collect slots)
#'<
:key 'slot-offset))
(defmethod canonicalize ((type foreign-struct-type))
(if (bare-struct-type-p type)
:pointer
`(:struct ,(name type))))
(defmethod unparse-type ((type foreign-struct-type))
(if (bare-struct-type-p type)
(name type)
(canonicalize type)))
(defmethod aggregatep ((type foreign-struct-type))
"Returns true, structure types are aggregate."
t)
(defmethod foreign-type-size ((type foreign-struct-type))
"Return the size in bytes of a foreign structure type."
(size type))
(defmethod foreign-type-alignment ((type foreign-struct-type))
"Return the alignment requirements for this struct."
(alignment type))
(defclass foreign-union-type (foreign-struct-type) ())
(defmethod canonicalize ((type foreign-union-type))
(if (bare-struct-type-p type)
:pointer
`(:union ,(name type))))
;;;# Foreign Typedefs
(defclass foreign-type-alias (foreign-type)
((actual-type
;; The FOREIGN-TYPE instance this type is an alias for.
:initarg :actual-type
:accessor actual-type
:initform (error "Must specify an ACTUAL-TYPE.")))
(:documentation "A type that aliases another type."))
(defmethod canonicalize ((type foreign-type-alias))
"Return the built-in type keyword for TYPE."
(canonicalize (actual-type type)))
(defmethod aggregatep ((type foreign-type-alias))
"Return true if TYPE's actual type is aggregate."
(aggregatep (actual-type type)))
(defmethod foreign-type-alignment ((type foreign-type-alias))
"Return the alignment of a foreign typedef."
(foreign-type-alignment (actual-type type)))
(defmethod foreign-type-size ((type foreign-type-alias))
"Return the size in bytes of a foreign typedef."
(foreign-type-size (actual-type type)))
(defclass foreign-typedef (foreign-type-alias named-foreign-type)
())
(defun follow-typedefs (type)
(if (typep type 'foreign-typedef)
(follow-typedefs (actual-type type))
type))
(defmethod bare-struct-type-p ((type foreign-typedef))
(bare-struct-type-p (follow-typedefs type)))
(defun structure-slots (type)
"The hash table of slots for the structure type."
(slots (follow-typedefs type)))
;;;# Type Translators
;;;
;;; Type translation is done with generic functions at runtime for
;;; subclasses of TRANSLATABLE-FOREIGN-TYPE.
;;;
;;; The main interface for defining type translations is through the
;;; generic functions TRANSLATE-{TO,FROM}-FOREIGN and
;;; FREE-TRANSLATED-OBJECT.
(defclass translatable-foreign-type (foreign-type) ())
;;; ENHANCED-FOREIGN-TYPE is used to define translations on top of
;;; previously defined foreign types.
(defclass enhanced-foreign-type (translatable-foreign-type
foreign-type-alias)
((unparsed-type :accessor unparsed-type)))
;;; If actual-type isn't parsed already, let's parse it. This way we
;;; don't have to export PARSE-TYPE and users don't have to worry
;;; about this in DEFINE-FOREIGN-TYPE or DEFINE-PARSE-METHOD.
(defmethod initialize-instance :after ((type enhanced-foreign-type) &key)
(unless (typep (actual-type type) 'foreign-type)
(setf (actual-type type) (parse-type (actual-type type)))))
(defmethod unparse-type ((type enhanced-foreign-type))
(unparsed-type type))
;;; Checks NAMEs, not object identity.
(defun check-for-typedef-cycles (type)
(labels ((%check (cur-type seen)
(when (typep cur-type 'foreign-typedef)
(when (member (name cur-type) seen)
(simple-foreign-type-error type :default
"Detected cycle in type ~S." type))
(%check (actual-type cur-type)
(cons (name cur-type) seen)))))
(%check type nil)))
;;; Only now we define PARSE-TYPE because it needs to do some extra
;;; work for ENHANCED-FOREIGN-TYPES.
(defun parse-type (type)
(let* ((spec (ensure-list type))
(ptype (apply (find-default-type-parser (car spec)) (cdr spec))))
(when (typep ptype 'foreign-typedef)
(check-for-typedef-cycles ptype))
(when (typep ptype 'enhanced-foreign-type)
(setf (unparsed-type ptype) type))
ptype))
(defun ensure-parsed-base-type (type)
(follow-typedefs
(if (typep type 'foreign-type)
type
(parse-type type))))
(defun canonicalize-foreign-type (type)
"Convert TYPE to a built-in type by following aliases.
Signals an error if the type cannot be resolved."
(canonicalize (parse-type type)))
;;; Translate VALUE to a foreign object of the type represented by
;;; TYPE, which will be a subclass of TRANSLATABLE-FOREIGN-TYPE.
;;; Returns the foreign value and an optional second value which will
;;; be passed to FREE-TRANSLATED-OBJECT as the PARAM argument.
(defgeneric translate-to-foreign (value type)
(:method (value type)
(declare (ignore type))
value))
(defgeneric translate-into-foreign-memory (value type pointer)
(:documentation
"Translate the Lisp value into the foreign memory location given by pointer. Return value is not used.")
(:argument-precedence-order type value pointer))
;;; Similar to TRANSLATE-TO-FOREIGN, used exclusively by
;;; (SETF FOREIGN-STRUCT-SLOT-VALUE).
(defgeneric translate-aggregate-to-foreign (ptr value type))
;;; Translate the foreign object VALUE from the type repsented by
;;; TYPE, which will be a subclass of TRANSLATABLE-FOREIGN-TYPE.
;;; Returns the converted Lisp value.
(defgeneric translate-from-foreign (value type)
(:argument-precedence-order type value)
(:method (value type)
(declare (ignore type))
value))
;;; Free an object allocated by TRANSLATE-TO-FOREIGN. VALUE is a
;;; foreign object of the type represented by TYPE, which will be a
;;; TRANSLATABLE-FOREIGN-TYPE subclass. PARAM, if present, contains
;;; the second value returned by TRANSLATE-TO-FOREIGN, and is used to
;;; communicate between the two functions.
;;;
;;; FIXME: I don't think this PARAM argument is necessary anymore
;;; because the TYPE object can contain that information. [2008-12-31 LO]
(defgeneric free-translated-object (value type param)
(:method (value type param)
(declare (ignore value type param))))
;;;## Macroexpansion Time Translation
;;;
;;; The following EXPAND-* generic functions are similar to their
;;; TRANSLATE-* counterparts but are usually called at macroexpansion
;;; time. They offer a way to optimize the runtime translators.
;;; This special variable is bound by the various :around methods
;;; below to the respective form generated by the above %EXPAND-*
;;; functions. This way, an expander can "bail out" by calling the
;;; next method. All 6 of the below-defined GFs have a default method
;;; that simply answers the rtf bound by the default :around method.
(defvar *runtime-translator-form*)
;;; EXPAND-FROM-FOREIGN
(defgeneric expand-from-foreign (value type)
(:method (value type)
(declare (ignore type))
value))
(defmethod expand-from-foreign :around (value (type translatable-foreign-type))
(let ((*runtime-translator-form* `(translate-from-foreign ,value ,type)))
(call-next-method)))
(defmethod expand-from-foreign (value (type translatable-foreign-type))
(declare (ignore value))
*runtime-translator-form*)
;;; EXPAND-TO-FOREIGN
;; The second return value is used to tell EXPAND-TO-FOREIGN-DYN that
;; an unspecialized method was called.
(defgeneric expand-to-foreign (value type)
(:method (value type)
(declare (ignore type))
(values value t)))
(defmethod expand-to-foreign :around (value (type translatable-foreign-type))
(let ((*runtime-translator-form* `(translate-to-foreign ,value ,type)))
(call-next-method)))
(defmethod expand-to-foreign (value (type translatable-foreign-type))
(declare (ignore value))
(values *runtime-translator-form* t))
;;; EXPAND-INTO-FOREIGN-MEMORY
(defgeneric expand-into-foreign-memory (value type ptr)
(:method (value type ptr)
(declare (ignore type ptr))
value))
(defmethod expand-into-foreign-memory :around
(value (type translatable-foreign-type) ptr)
(let ((*runtime-translator-form*
`(translate-into-foreign-memory ,value ,type ,ptr)))
(call-next-method)))
(defmethod expand-into-foreign-memory (value (type translatable-foreign-type) ptr)
(declare (ignore value ptr))
*runtime-translator-form*)
;;; EXPAND-TO-FOREIGN-DYN
(defgeneric expand-to-foreign-dyn (value var body type)
(:method (value var body type)
(declare (ignore type))
`(let ((,var ,value)) ,@body)))
(defmethod expand-to-foreign-dyn :around
(value var body (type enhanced-foreign-type))
(let ((*runtime-translator-form*
(with-unique-names (param)
`(multiple-value-bind (,var ,param)
(translate-to-foreign ,value ,type)
(unwind-protect
(progn ,@body)
(free-translated-object ,var ,type ,param))))))
(call-next-method)))
;;; If this method is called it means the user hasn't defined a
;;; to-foreign-dyn expansion, so we use the to-foreign expansion.
;;;
;;; However, we do so *only* if there's a specialized
;;; EXPAND-TO-FOREIGN for TYPE because otherwise we want to use the
;;; above *RUNTIME-TRANSLATOR-FORM* which includes a call to
;;; FREE-TRANSLATED-OBJECT. (Or else there would occur no translation
;;; at all.)
(defun foreign-expand-runtime-translator-or-binding (value var body type)
(multiple-value-bind (expansion default-etp-p)
(expand-to-foreign value type)
(if default-etp-p
*runtime-translator-form*
`(let ((,var ,expansion))
,@body))))
(defmethod expand-to-foreign-dyn (value var body (type enhanced-foreign-type))
(foreign-expand-runtime-translator-or-binding value var body type))
;;; EXPAND-TO-FOREIGN-DYN-INDIRECT
;;; Like expand-to-foreign-dyn, but always give form that returns a
;;; pointer to the object, even if it's directly representable in
;;; CL, e.g. numbers.
(defgeneric expand-to-foreign-dyn-indirect (value var body type)
(:method (value var body type)
(declare (ignore type))
`(let ((,var ,value)) ,@body)))
(defmethod expand-to-foreign-dyn-indirect :around
(value var body (type translatable-foreign-type))
(let ((*runtime-translator-form*
`(with-foreign-object (,var ',(unparse-type type))
(translate-into-foreign-memory ,value ,type ,var)
,@body)))
(call-next-method)))
(defmethod expand-to-foreign-dyn-indirect
(value var body (type foreign-pointer-type))
`(with-foreign-object (,var :pointer)
(translate-into-foreign-memory ,value ,type ,var)
,@body))
(defmethod expand-to-foreign-dyn-indirect
(value var body (type foreign-built-in-type))
`(with-foreign-object (,var ,type)
(translate-into-foreign-memory ,value ,type ,var)
,@body))
(defmethod expand-to-foreign-dyn-indirect
(value var body (type translatable-foreign-type))
(foreign-expand-runtime-translator-or-binding value var body type))
(defmethod expand-to-foreign-dyn-indirect (value var body (type foreign-type-alias))
(expand-to-foreign-dyn-indirect value var body (actual-type type)))
;;; User interface for converting values from/to foreign using the
;;; type translators. The compiler macros use the expanders when
;;; possible.
(defun convert-to-foreign (value type)
(translate-to-foreign value (parse-type type)))
(define-compiler-macro convert-to-foreign (value type)
(if (constantp type)
(expand-to-foreign value (parse-type (eval type)))
`(translate-to-foreign ,value (parse-type ,type))))
(defun convert-from-foreign (value type)
(translate-from-foreign value (parse-type type)))
(define-compiler-macro convert-from-foreign (value type)
(if (constantp type)
(expand-from-foreign value (parse-type (eval type)))
`(translate-from-foreign ,value (parse-type ,type))))
(defun convert-into-foreign-memory (value type ptr)
(translate-into-foreign-memory value (parse-type type) ptr))
(define-compiler-macro convert-into-foreign-memory (value type ptr)
(if (constantp type)
(expand-into-foreign-memory value (parse-type (eval type)) ptr)
`(translate-into-foreign-memory ,value (parse-type ,type) ,ptr)))
(defun free-converted-object (value type param)
(free-translated-object value (parse-type type) param))
;;;# Enhanced typedefs
(defclass enhanced-typedef (foreign-typedef)
())
(defmethod translate-to-foreign (value (type enhanced-typedef))
(translate-to-foreign value (actual-type type)))
(defmethod translate-into-foreign-memory (value (type enhanced-typedef) pointer)
(translate-into-foreign-memory value (actual-type type) pointer))
(defmethod translate-from-foreign (value (type enhanced-typedef))
(translate-from-foreign value (actual-type type)))
(defmethod free-translated-object (value (type enhanced-typedef) param)
(free-translated-object value (actual-type type) param))
(defmethod expand-from-foreign (value (type enhanced-typedef))
(expand-from-foreign value (actual-type type)))
(defmethod expand-to-foreign (value (type enhanced-typedef))
(expand-to-foreign value (actual-type type)))
(defmethod expand-to-foreign-dyn (value var body (type enhanced-typedef))
(expand-to-foreign-dyn value var body (actual-type type)))
(defmethod expand-into-foreign-memory (value (type enhanced-typedef) ptr)
(expand-into-foreign-memory value (actual-type type) ptr))
;;;# User-defined Types and Translations.
(defmacro define-foreign-type (name supers slots &rest options)
(multiple-value-bind (new-options simple-parser actual-type initargs)
(let ((keywords '(:simple-parser :actual-type :default-initargs)))
(apply #'values
(remove-if (lambda (opt) (member (car opt) keywords)) options)
(mapcar (lambda (kw) (cdr (assoc kw options))) keywords)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass ,name ,(or supers '(enhanced-foreign-type))
,slots
(:default-initargs ,@(when actual-type `(:actual-type ',actual-type))
,@initargs)
,@new-options)
,(when simple-parser
`(define-parse-method ,(car simple-parser) (&rest args)
(apply #'make-instance ',name args)))
',name)))
(defmacro defctype (name base-type &optional documentation)
"Utility macro for simple C-like typedefs."
(declare (ignore documentation))
(warn-if-kw-or-belongs-to-cl name)
(let* ((btype (parse-type base-type))
(dtype (if (typep btype 'enhanced-foreign-type)
'enhanced-typedef
'foreign-typedef)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-type
',name (make-instance ',dtype :name ',name :actual-type ,btype)))))
;;; For Verrazano. We memoize the type this way to help detect cycles.
(defmacro defctype* (name base-type)
"Like DEFCTYPE but defers instantiation until parse-time."
`(eval-when (:compile-toplevel :load-toplevel :execute)
(let (memoized-type)
(define-parse-method ,name ()
(unless memoized-type
(setf memoized-type (make-instance 'foreign-typedef :name ',name
:actual-type nil)
(actual-type memoized-type) (parse-type ',base-type)))
memoized-type))))
| 27,093 | Common Lisp | .lisp | 594 | 41.636364 | 108 | 0.718143 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 3ef67635332dc4e7bd7d108b56fcff64ad7cdcbbc18fffbf2b4d39f022466890 | 42,982 | [
458054
] |
42,984 | features.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/features.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; features.lisp --- CFFI-specific features (DEPRECATED).
;;;
;;; Copyright (C) 2006-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew :cffi *features*))
;;; CFFI-SYS backends take care of pushing the appropriate features to
;;; *features*. See each cffi-*.lisp file.
;;;
;;; Not anymore, I think we should use TRIVIAL-FEATURES for the
;;; platform features instead. Less pain. CFFI-FEATURES is now
;;; deprecated and this code will stay here for a while for backwards
;;; compatibility purposes, to be removed in a future release.
(defpackage #:cffi-features
(:use #:cl)
(:export
#:cffi-feature-p
;; Features related to the CFFI-SYS backend. Why no-*? This
;; reflects the hope that these symbols will go away completely
;; meaning that at some point all lisps will support long-longs,
;; the foreign-funcall primitive, etc...
#:no-long-long
#:no-foreign-funcall
#:no-stdcall
#:flat-namespace
;; Only SCL supports long-double...
;;#:no-long-double
;; Features related to the operating system.
;; More should be added.
#:darwin
#:unix
#:windows
;; Features related to the processor.
;; More should be added.
#:ppc32
#:x86
#:x86-64
#:sparc
#:sparc64
#:hppa
#:hppa64))
(in-package #:cffi-features)
(defun cffi-feature-p (feature-expression)
"Matches a FEATURE-EXPRESSION against those symbols in *FEATURES*
that belong to the CFFI-FEATURES package."
(when (eql feature-expression t)
(return-from cffi-feature-p t))
(let ((features-package (find-package '#:cffi-features)))
(flet ((cffi-feature-eq (name feature-symbol)
(and (eq (symbol-package feature-symbol) features-package)
(string= name (symbol-name feature-symbol)))))
(etypecase feature-expression
(symbol
(not (null (member (symbol-name feature-expression) *features*
:test #'cffi-feature-eq))))
(cons
(ecase (first feature-expression)
(:and (every #'cffi-feature-p (rest feature-expression)))
(:or (some #'cffi-feature-p (rest feature-expression)))
(:not (not (cffi-feature-p (cadr feature-expression))))))))))
;;; for backwards compatibility
(mapc (lambda (sym) (pushnew sym *features*))
'(#+darwin darwin
#+unix unix
#+windows windows
#+ppc ppc32
#+x86 x86
#+x86-64 x86-64
#+sparc sparc
#+sparc64 sparc64
#+hppa hppa
#+hppa64 hppa64
#+cffi-sys::no-long-long no-long-long
#+cffi-sys::flat-namespace flat-namespace
#+cffi-sys::no-foreign-funcall no-foreign-funcall
#+cffi-sys::no-stdcall no-stdcall
))
| 3,965 | Common Lisp | .lisp | 100 | 35.09 | 72 | 0.682148 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 0ee7b1a3d46a8ab59f11bf777798b97a122ab59c0c3ab0e9a57ef8e60b5b8c66 | 42,984 | [
18504,
436312
] |
42,986 | functions.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/functions.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; functions.lisp --- High-level interface to foreign functions.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2005-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
;;;# Calling Foreign Functions
;;;
;;; FOREIGN-FUNCALL is the main primitive for calling foreign
;;; functions. It converts each argument based on the installed
;;; translators for its type, then passes the resulting list to
;;; CFFI-SYS:%FOREIGN-FUNCALL.
;;;
;;; For implementation-specific reasons, DEFCFUN doesn't use
;;; FOREIGN-FUNCALL directly and might use something else (passed to
;;; TRANSLATE-OBJECTS as the CALL-FORM argument) instead of
;;; CFFI-SYS:%FOREIGN-FUNCALL to call the foreign-function.
(defun translate-objects (syms args types rettype call-form &optional indirect)
"Helper function for FOREIGN-FUNCALL and DEFCFUN. If 'indirect is T, all arguments are represented by foreign pointers, even those that can be represented by CL objects."
(if (null args)
(expand-from-foreign call-form (parse-type rettype))
(funcall
(if indirect
#'expand-to-foreign-dyn-indirect
#'expand-to-foreign-dyn)
(car args) (car syms)
(list (translate-objects (cdr syms) (cdr args)
(cdr types) rettype call-form indirect))
(parse-type (car types)))))
(defun parse-args-and-types (args)
"Returns 4 values: types, canonicalized types, args and return type."
(let* ((len (length args))
(return-type (if (oddp len) (lastcar args) :void)))
(loop repeat (floor len 2)
for (type arg) on args by #'cddr
collect type into types
collect (canonicalize-foreign-type type) into ctypes
collect arg into fargs
finally (return (values types ctypes fargs return-type)))))
;;; While the options passed directly to DEFCFUN/FOREIGN-FUNCALL have
;;; precedence, we also grab its library's options, if possible.
(defun parse-function-options (options &key pointer)
(destructuring-bind (&key (library :default libraryp)
(cconv nil cconv-p)
(calling-convention cconv calling-convention-p)
(convention calling-convention))
options
(when cconv-p
(warn-obsolete-argument :cconv :convention))
(when calling-convention-p
(warn-obsolete-argument :calling-convention :convention))
(list* :convention
(or convention
(when libraryp
(let ((lib-options (foreign-library-options
(get-foreign-library library))))
(getf lib-options :convention)))
:cdecl)
;; Don't pass the library option if we're dealing with
;; FOREIGN-FUNCALL-POINTER.
(unless pointer
(list :library library)))))
(defun structure-by-value-p (ctype)
"A structure or union is to be called or returned by value."
(let ((actual-type (ensure-parsed-base-type ctype)))
(or (and (typep actual-type 'foreign-struct-type)
(not (bare-struct-type-p actual-type)))
#+cffi::no-long-long (typep actual-type 'emulated-llong-type))))
(defun fn-call-by-value-p (argument-types return-type)
"One or more structures in the arguments or return from the function are called by value."
(or (some 'structure-by-value-p argument-types)
(structure-by-value-p return-type)))
(defvar *foreign-structures-by-value*
(lambda (&rest args)
(declare (ignore args))
(restart-case
(error "Unable to call structures by value without cffi-libffi loaded.")
(load-cffi-libffi () :report "Load cffi-libffi."
(asdf:operate 'asdf:load-op 'cffi-libffi))))
"A function that produces a form suitable for calling structures by value.")
(defun foreign-funcall-form (thing options args pointerp)
(multiple-value-bind (types ctypes fargs rettype)
(parse-args-and-types args)
(let ((syms (make-gensym-list (length fargs)))
(fsbvp (fn-call-by-value-p ctypes rettype)))
(if fsbvp
;; Structures by value call through *foreign-structures-by-value*
(funcall *foreign-structures-by-value*
thing
fargs
syms
types
rettype
ctypes
pointerp)
(translate-objects
syms fargs types rettype
`(,(if pointerp '%foreign-funcall-pointer '%foreign-funcall)
;; No structures by value, direct call
,thing
(,@(mapcan #'list ctypes syms)
,(canonicalize-foreign-type rettype))
,@(parse-function-options options :pointer pointerp)))))))
(defmacro foreign-funcall (name-and-options &rest args)
"Wrapper around %FOREIGN-FUNCALL that translates its arguments."
(let ((name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
(foreign-funcall-form name options args nil)))
(defmacro foreign-funcall-pointer (pointer options &rest args)
(foreign-funcall-form pointer options args t))
(defun promote-varargs-type (builtin-type)
"Default argument promotions."
(case builtin-type
(:float :double)
((:char :short) :int)
((:unsigned-char :unsigned-short) :unsigned-int)
(t builtin-type)))
;; If cffi-sys doesn't provide a %foreign-funcall-varargs macros we
;; define one that use %foreign-funcall.
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp '%foreign-funcall-varargs)
(defmacro %foreign-funcall-varargs (name fixed-args varargs
&rest args &key convention library)
(declare (ignore convention library))
`(%foreign-funcall ,name ,(append fixed-args varargs) ,@args)))
(unless (fboundp '%foreign-funcall-pointer-varargs)
(defmacro %foreign-funcall-pointer-varargs (pointer fixed-args varargs
&rest args &key convention)
(declare (ignore convention))
`(%foreign-funcall-pointer ,pointer ,(append fixed-args varargs) ,@args))))
(defun foreign-funcall-varargs-form (thing options fixed-args varargs pointerp)
(multiple-value-bind (fixed-types fixed-ctypes fixed-fargs)
(parse-args-and-types fixed-args)
(multiple-value-bind (varargs-types varargs-ctypes varargs-fargs rettype)
(parse-args-and-types varargs)
(let ((fixed-syms (make-gensym-list (length fixed-fargs)))
(varargs-syms (make-gensym-list (length varargs-fargs))))
(translate-objects
(append fixed-syms varargs-syms)
(append fixed-fargs varargs-fargs)
(append fixed-types varargs-types)
rettype
`(,(if pointerp '%foreign-funcall-pointer-varargs '%foreign-funcall-varargs)
,thing
,(mapcan #'list fixed-ctypes fixed-syms)
,(append
(mapcan #'list
(mapcar #'promote-varargs-type varargs-ctypes)
(loop for sym in varargs-syms
and type in varargs-ctypes
if (eq type :float)
collect `(float ,sym 1.0d0)
else collect sym))
(list (canonicalize-foreign-type rettype)))
,@options))))))
(defmacro foreign-funcall-varargs (name-and-options fixed-args
&rest varargs)
"Wrapper around %FOREIGN-FUNCALL that translates its arguments
and does type promotion for the variadic arguments."
(let ((name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
(foreign-funcall-varargs-form name options fixed-args varargs nil)))
(defmacro foreign-funcall-pointer-varargs (pointer options fixed-args
&rest varargs)
"Wrapper around %FOREIGN-FUNCALL-POINTER that translates its
arguments and does type promotion for the variadic arguments."
(foreign-funcall-varargs-form pointer options fixed-args varargs t))
;;;# Defining Foreign Functions
;;;
;;; The DEFCFUN macro provides a declarative interface for defining
;;; Lisp functions that call foreign functions.
;; If cffi-sys doesn't provide a defcfun-helper-forms,
;; we define one that uses %foreign-funcall.
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp 'defcfun-helper-forms)
(defun defcfun-helper-forms (name lisp-name rettype args types options)
(declare (ignore lisp-name))
(values
'()
`(%foreign-funcall ,name ,(append (mapcan #'list types args)
(list rettype))
,@options)))))
(defun %defcfun (lisp-name foreign-name return-type args options docstring)
(let* ((arg-names (mapcar #'first args))
(arg-types (mapcar #'second args))
(syms (make-gensym-list (length args)))
(call-by-value (fn-call-by-value-p arg-types return-type)))
(multiple-value-bind (prelude caller)
(if call-by-value
(values nil nil)
(defcfun-helper-forms
foreign-name lisp-name (canonicalize-foreign-type return-type)
syms (mapcar #'canonicalize-foreign-type arg-types) options))
`(progn
,prelude
(defun ,lisp-name ,arg-names
,@(ensure-list docstring)
,(if call-by-value
`(foreign-funcall
,(cons foreign-name options)
,@(append (mapcan #'list arg-types arg-names)
(list return-type)))
(translate-objects
syms arg-names arg-types return-type caller)))))))
(defun %defcfun-varargs (lisp-name foreign-name return-type args options doc)
(with-unique-names (varargs)
(let ((arg-names (mapcar #'car args)))
`(defmacro ,lisp-name (,@arg-names &rest ,varargs)
,@(ensure-list doc)
`(foreign-funcall-varargs
,'(,foreign-name ,@options)
,,`(list ,@(loop for (name type) in args
collect `',type collect name))
,@,varargs
,',return-type)))))
(defgeneric translate-underscore-separated-name (name)
(:method ((name string))
(values (intern (canonicalize-symbol-name-case (substitute #\- #\_ name)))))
(:method ((name symbol))
(substitute #\_ #\- (string-downcase (symbol-name name)))))
(defun collapse-prefix (l special-words)
(unless (null l)
(multiple-value-bind (newpre skip) (check-prefix l special-words)
(cons newpre (collapse-prefix (nthcdr skip l) special-words)))))
(defun check-prefix (l special-words)
(let ((pl (loop for i from (1- (length l)) downto 0
collect (apply #'concatenate 'simple-string (butlast l i)))))
(loop for w in special-words
for p = (position-if #'(lambda (s) (string= s w)) pl)
when p do (return-from check-prefix (values (nth p pl) (1+ p))))
(values (first l) 1)))
(defgeneric translate-camelcase-name (name &key upper-initial-p special-words)
(:method ((name string) &key upper-initial-p special-words)
(declare (ignore upper-initial-p))
(values (intern (reduce #'(lambda (s1 s2)
(concatenate 'simple-string s1 "-" s2))
(mapcar #'string-upcase
(collapse-prefix
(split-if #'(lambda (ch)
(or (upper-case-p ch)
(digit-char-p ch)))
name)
special-words))))))
(:method ((name symbol) &key upper-initial-p special-words)
(apply #'concatenate
'string
(loop for str in (split-if #'(lambda (ch) (eq ch #\-))
(string name)
:elide)
for first-word-p = t then nil
for e = (member str special-words
:test #'equal :key #'string-upcase)
collect (cond
((and first-word-p (not upper-initial-p))
(string-downcase str))
(e (first e))
(t (string-capitalize str)))))))
(defgeneric translate-name-from-foreign (foreign-name package &optional varp)
(:method (foreign-name package &optional varp)
(declare (ignore package))
(let ((sym (translate-underscore-separated-name foreign-name)))
(if varp
(values (intern (format nil "*~A*"
(canonicalize-symbol-name-case
(symbol-name sym)))))
sym))))
(defgeneric translate-name-to-foreign (lisp-name package &optional varp)
(:method (lisp-name package &optional varp)
(declare (ignore package))
(let ((name (translate-underscore-separated-name lisp-name)))
(if varp
(string-trim '(#\*) name)
name))))
(defun lisp-name (spec varp)
(check-type spec string)
(translate-name-from-foreign spec *package* varp))
(defun foreign-name (spec varp)
(check-type spec (and symbol (not null)))
(translate-name-to-foreign spec *package* varp))
(defun foreign-options (opts varp)
(if varp
(funcall 'parse-defcvar-options opts)
(parse-function-options opts)))
(defun lisp-name-p (name)
(and name (symbolp name) (not (keywordp name))))
(defun %parse-name-and-options (spec varp)
(cond
((stringp spec)
(values (lisp-name spec varp) spec nil))
((symbolp spec)
(assert (not (null spec)))
(values spec (foreign-name spec varp) nil))
((and (consp spec) (stringp (first spec)))
(destructuring-bind (foreign-name &rest options)
spec
(cond
((or (null options)
(keywordp (first options)))
(values (lisp-name foreign-name varp) foreign-name options))
(t
(assert (lisp-name-p (first options)))
(values (first options) foreign-name (rest options))))))
((and (consp spec) (lisp-name-p (first spec)))
(destructuring-bind (lisp-name &rest options)
spec
(cond
((or (null options)
(keywordp (first options)))
(values lisp-name (foreign-name spec varp) options))
(t
(assert (stringp (first options)))
(values lisp-name (first options) (rest options))))))
(t
(error "Not a valid foreign function specifier: ~A" spec))))
;;; DEFCFUN's first argument has can have the following syntax:
;;;
;;; 1. string
;;; 2. symbol
;;; 3. \( string [symbol] options* )
;;; 4. \( symbol [string] options* )
;;;
;;; The string argument denotes the foreign function's name. The
;;; symbol argument is used to name the Lisp function. If one isn't
;;; present, its name is derived from the other. See the user
;;; documentation for an explanation of the derivation rules.
(defun parse-name-and-options (spec &optional varp)
(multiple-value-bind (lisp-name foreign-name options)
(%parse-name-and-options spec varp)
(values lisp-name foreign-name (foreign-options options varp))))
;;; If we find a &REST token at the end of ARGS, it means this is a
;;; varargs foreign function therefore we define a lisp macro using
;;; %DEFCFUN-VARARGS. Otherwise, a lisp function is defined with
;;; %DEFCFUN.
(defmacro defcfun (name-and-options return-type &body args)
"Defines a Lisp function that calls a foreign function."
(let ((docstring (when (stringp (car args)) (pop args))))
(multiple-value-bind (lisp-name foreign-name options)
(parse-name-and-options name-and-options)
(if (eq (lastcar args) '&rest)
(%defcfun-varargs lisp-name foreign-name return-type
(butlast args) options docstring)
(%defcfun lisp-name foreign-name return-type args options
docstring)))))
;;;# Defining Callbacks
(defun inverse-translate-objects (args types declarations rettype call)
`(let (,@(loop for arg in args and type in types
collect (list arg (expand-from-foreign
arg (parse-type type)))))
,@declarations
,(expand-to-foreign call (parse-type rettype))))
(defun parse-defcallback-options (options)
(destructuring-bind (&key (cconv :cdecl cconv-p)
(calling-convention cconv calling-convention-p)
(convention calling-convention))
options
(when cconv-p
(warn-obsolete-argument :cconv :convention))
(when calling-convention-p
(warn-obsolete-argument :calling-convention :convention))
(list :convention convention)))
(defmacro defcallback (name-and-options return-type args &body body)
(multiple-value-bind (body declarations)
(parse-body body :documentation t)
(let ((arg-names (mapcar #'car args))
(arg-types (mapcar #'cadr args))
(name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
`(progn
(%defcallback ,name ,(canonicalize-foreign-type return-type)
,arg-names ,(mapcar #'canonicalize-foreign-type arg-types)
,(inverse-translate-objects
arg-names arg-types declarations return-type
`(block ,name ,@body))
,@(parse-defcallback-options options))
',name))))
(declaim (inline get-callback))
(defun get-callback (symbol)
(%callback symbol))
(defmacro callback (name)
`(%callback ',name))
| 19,030 | Common Lisp | .lisp | 402 | 38.047264 | 173 | 0.625531 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | a6f6385385cdbbca6db2aac382482262e12746e002db1ad76b96a42ea7dfc926 | 42,986 | [
188309
] |
42,987 | libraries.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/libraries.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; libraries.lisp --- Finding and loading foreign libraries.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2006-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
;;;# Finding Foreign Libraries
;;;
;;; We offer two ways for the user of a CFFI library to define
;;; his/her own library directories: *FOREIGN-LIBRARY-DIRECTORIES*
;;; for regular libraries and *DARWIN-FRAMEWORK-DIRECTORIES* for
;;; Darwin frameworks.
;;;
;;; These two special variables behave similarly to
;;; ASDF:*CENTRAL-REGISTRY* as its arguments are evaluated before
;;; being used. We used our MINI-EVAL instead of the full-blown EVAL
;;; and the evaluated form should yield a single pathname or a list of
;;; pathnames.
;;;
;;; Only after failing to find a library through the normal ways
;;; (eg: on Linux LD_LIBRARY_PATH, /etc/ld.so.cache, /usr/lib/, /lib)
;;; do we try to find the library ourselves.
(defun explode-path-environment-variable (name)
(mapcar #'uiop:ensure-directory-pathname
(split-if (lambda (c) (eql #\: c))
(uiop:getenv name)
:elide)))
(defun darwin-fallback-library-path ()
(or (explode-path-environment-variable "DYLD_FALLBACK_LIBRARY_PATH")
(list (merge-pathnames #p"lib/" (user-homedir-pathname))
#+arm64 #p"/opt/homebrew/lib/"
#p"/opt/local/lib/"
#p"/usr/local/lib/"
#p"/usr/lib/")))
(defvar *foreign-library-directories*
(if (featurep :darwin)
'((explode-path-environment-variable "LD_LIBRARY_PATH")
(explode-path-environment-variable "DYLD_LIBRARY_PATH")
(uiop:getcwd)
(darwin-fallback-library-path))
'())
"List onto which user-defined library paths can be pushed.")
(defun fallback-darwin-framework-directories ()
(or (explode-path-environment-variable "DYLD_FALLBACK_FRAMEWORK_PATH")
(list (uiop:getcwd)
(merge-pathnames #p"Library/Frameworks/" (user-homedir-pathname))
#p"/Library/Frameworks/"
#p"/System/Library/Frameworks/")))
(defvar *darwin-framework-directories*
'((explode-path-environment-variable "DYLD_FRAMEWORK_PATH")
(fallback-darwin-framework-directories))
"List of directories where Frameworks are searched for.")
(defun mini-eval (form)
"Simple EVAL-like function to evaluate the elements of
*FOREIGN-LIBRARY-DIRECTORIES* and *DARWIN-FRAMEWORK-DIRECTORIES*."
(typecase form
(cons (apply (car form) (mapcar #'mini-eval (cdr form))))
(symbol (symbol-value form))
(t form)))
(defun parse-directories (list)
(mappend (compose #'ensure-list #'mini-eval) list))
(defun find-file (path directories)
"Searches for PATH in a list of DIRECTORIES and returns the first it finds."
(some (lambda (directory) (probe-file (merge-pathnames path directory)))
directories))
(defun find-darwin-framework (framework-name)
"Searches for FRAMEWORK-NAME in *DARWIN-FRAMEWORK-DIRECTORIES*."
(dolist (directory (parse-directories *darwin-framework-directories*))
(let ((framework-directory
(merge-pathnames (format nil "~A.framework/" framework-name)
directory)))
(when (probe-file framework-directory)
(let ((path (merge-pathnames framework-name framework-directory)))
(return-from find-darwin-framework path))))))
;;;# Defining Foreign Libraries
;;;
;;; Foreign libraries can be defined using the
;;; DEFINE-FOREIGN-LIBRARY macro. Example usage:
;;;
;;; (define-foreign-library opengl
;;; (:darwin (:framework "OpenGL"))
;;; (:unix (:or "libGL.so" "libGL.so.1"
;;; #p"/myhome/mylibGL.so"))
;;; (:windows "opengl32.dll")
;;; ;; an hypothetical example of a particular platform
;;; ((:and :some-system :some-cpu) "libGL-support.lib")
;;; ;; if no other clauses apply, this one will and a type will be
;;; ;; automagically appended to the name passed to :default
;;; (t (:default "libGL")))
;;;
;;; This information is stored in the *FOREIGN-LIBRARIES* hashtable
;;; and when the library is loaded through LOAD-FOREIGN-LIBRARY (or
;;; USE-FOREIGN-LIBRARY) the first clause matched by FEATUREP is
;;; processed.
(defvar *foreign-libraries* (make-hash-table :test 'eq)
"Hashtable of defined libraries.")
(defclass foreign-library ()
((name :initform nil :initarg :name :accessor foreign-library-name)
(type :initform :system :initarg :type)
(spec :initarg :spec)
(options :initform nil :initarg :options)
(load-state :initform nil :initarg :load-state :accessor foreign-library-load-state)
(handle :initform nil :initarg :handle :accessor foreign-library-handle)
(pathname :initform nil)))
(defmethod print-object ((library foreign-library) stream)
(with-slots (name pathname) library
(print-unreadable-object (library stream :type t)
(when name
(format stream "~A" name))
(when pathname
(format stream " ~S" (file-namestring pathname))))))
(define-condition foreign-library-undefined-error (error)
((name :initarg :name :reader fl-name))
(:report (lambda (c s)
(format s "Undefined foreign library: ~S"
(fl-name c)))))
(defun get-foreign-library (lib)
"Look up a library by NAME, signalling an error if not found."
(if (typep lib 'foreign-library)
lib
(or (gethash lib *foreign-libraries*)
(error 'foreign-library-undefined-error :name lib))))
(defun (setf get-foreign-library) (value name)
(setf (gethash name *foreign-libraries*) value))
(defun foreign-library-type (lib)
(slot-value (get-foreign-library lib) 'type))
(defun foreign-library-pathname (lib)
(slot-value (get-foreign-library lib) 'pathname))
(defun %foreign-library-spec (lib)
(assoc-if (lambda (feature)
(or (eq feature t)
(featurep feature)))
(slot-value lib 'spec)))
(defun foreign-library-spec (lib)
(second (%foreign-library-spec lib)))
(defun foreign-library-options (lib)
(append (cddr (%foreign-library-spec lib))
(slot-value lib 'options)))
(defun foreign-library-search-path (lib)
(loop for (opt val) on (foreign-library-options lib) by #'cddr
when (eql opt :search-path)
append (ensure-list val) into search-path
finally (return (mapcar #'pathname search-path))))
(defun foreign-library-loaded-p (lib)
(not (null (foreign-library-load-state (get-foreign-library lib)))))
(defun list-foreign-libraries (&key (loaded-only t) type)
"Return a list of defined foreign libraries.
If LOADED-ONLY is non-null only loaded libraries are returned.
TYPE restricts the output to a specific library type: if NIL
all libraries are returned."
(let ((libs (hash-table-values *foreign-libraries*)))
(remove-if (lambda (lib)
(or (and type
(not (eql type (foreign-library-type lib))))
(and loaded-only
(not (foreign-library-loaded-p lib)))))
libs)))
;; :CONVENTION, :CALLING-CONVENTION and :CCONV are coalesced,
;; the former taking priority
;; options with NULL values are removed
(defun clean-spec-up (spec)
(mapcar (lambda (x)
(list* (first x) (second x)
(let* ((opts (cddr x))
(cconv (getf opts :cconv))
(calling-convention (getf opts :calling-convention))
(convention (getf opts :convention))
(search-path (getf opts :search-path)))
(remf opts :cconv) (remf opts :calling-convention)
(when cconv
(warn-obsolete-argument :cconv :convention))
(when calling-convention
(warn-obsolete-argument :calling-convention
:convention))
(setf (getf opts :convention)
(or convention calling-convention cconv))
(setf (getf opts :search-path)
(mapcar #'pathname (ensure-list search-path)))
(loop for (opt val) on opts by #'cddr
when val append (list opt val) into new-opts
finally (return new-opts)))))
spec))
(defmethod initialize-instance :after
((lib foreign-library) &key canary search-path
(cconv :cdecl cconv-p)
(calling-convention cconv calling-convention-p)
(convention calling-convention))
(with-slots (type options spec) lib
(check-type type (member :system :test :grovel-wrapper))
(setf spec (clean-spec-up spec))
(let ((all-options
(apply #'append options (mapcar #'cddr spec))))
(assert (subsetp (loop for (key . nil) on all-options by #'cddr
collect key)
'(:convention :search-path)))
(when cconv-p
(warn-obsolete-argument :cconv :convention))
(when calling-convention-p
(warn-obsolete-argument :calling-convention :convention))
(flet ((set-option (key value)
(when value (setf (getf options key) value))))
(set-option :convention convention)
(set-option :search-path
(mapcar #'pathname (ensure-list search-path)))
(set-option :canary canary)))))
(defun register-foreign-library (name spec &rest options)
(let ((old-handle
(when-let ((old-lib (gethash name *foreign-libraries*)))
(foreign-library-handle old-lib))))
(setf (get-foreign-library name)
(apply #'make-instance 'foreign-library
:name name
:spec spec
:handle old-handle
options))
name))
(defmacro define-foreign-library (name-and-options &body pairs)
"Defines a foreign library NAME that can be posteriorly used with
the USE-FOREIGN-LIBRARY macro."
(destructuring-bind (name . options)
(ensure-list name-and-options)
(check-type name symbol)
`(register-foreign-library ',name ',pairs ,@options)))
;;;# LOAD-FOREIGN-LIBRARY-ERROR condition
;;;
;;; The various helper functions that load foreign libraries can
;;; signal this error when something goes wrong. We ignore the host's
;;; error. We should probably reuse its error message.
(define-condition load-foreign-library-error (simple-error)
())
(defun read-new-value ()
(format *query-io* "~&Enter a new value (unevaluated): ")
(force-output *query-io*)
(read *query-io*))
(defun fl-error (control &rest arguments)
(error 'load-foreign-library-error
:format-control control
:format-arguments arguments))
;;;# Loading Foreign Libraries
(defun load-darwin-framework (name framework-name)
"Tries to find and load a darwin framework in one of the directories
in *DARWIN-FRAMEWORK-DIRECTORIES*. If unable to find FRAMEWORK-NAME,
it signals a LOAD-FOREIGN-LIBRARY-ERROR."
(let ((framework (find-darwin-framework framework-name)))
(if framework
(load-foreign-library-path name (native-namestring framework))
(fl-error "Unable to find framework ~A" framework-name))))
(defun report-simple-error (name error)
(fl-error "Unable to load foreign library (~A).~% ~A"
name
(format nil "~?" (simple-condition-format-control error)
(simple-condition-format-arguments error))))
;;; FIXME: haven't double checked whether all Lisps signal a
;;; SIMPLE-ERROR on %load-foreign-library failure. In any case they
;;; should be throwing a more specific error.
(defun load-foreign-library-path (name path &optional search-path)
"Tries to load PATH using %LOAD-FOREIGN-LIBRARY which should try and
find it using the OS's usual methods. If that fails we try to find it
ourselves."
(handler-case
(values (%load-foreign-library name path)
(pathname path))
(simple-error (error)
(let ((dirs (parse-directories *foreign-library-directories*)))
(if-let (file (find-file path (append search-path dirs)))
(handler-case
(values (%load-foreign-library name (native-namestring file))
file)
(simple-error (error)
(report-simple-error name error)))
(report-simple-error name error))))))
(defun try-foreign-library-alternatives (name library-list &optional search-path)
"Goes through a list of alternatives and only signals an error when
none of alternatives were successfully loaded."
(dolist (lib library-list)
(multiple-value-bind (handle pathname)
(ignore-errors (load-foreign-library-helper name lib search-path))
(when handle
(return-from try-foreign-library-alternatives
(values handle pathname)))))
;; Perhaps we should show the error messages we got for each
;; alternative if we can figure out a nice way to do that.
(fl-error "Unable to load any of the alternatives:~% ~S" library-list))
(defparameter *cffi-feature-suffix-map*
'((:windows . ".dll")
(:darwin . ".dylib")
(:unix . ".so")
(t . ".so"))
"Mapping of OS feature keywords to shared library suffixes.")
(defun default-library-suffix ()
"Return a string to use as default library suffix based on the
operating system. This is used to implement the :DEFAULT option.
This will need to be extended as we test on more OSes."
(or (cdr (assoc-if #'featurep *cffi-feature-suffix-map*))
(fl-error "Unable to determine the default library suffix on this OS.")))
(defun load-foreign-library-helper (name thing &optional search-path)
(etypecase thing
((or pathname string)
(load-foreign-library-path name (filter-pathname thing) search-path))
(cons
(ecase (first thing)
(:framework (load-darwin-framework name (second thing)))
(:default
(unless (stringp (second thing))
(fl-error "Argument to :DEFAULT must be a string."))
(let ((library-path
(concatenate 'string
(second thing)
(default-library-suffix))))
(load-foreign-library-path name library-path search-path)))
(:or (try-foreign-library-alternatives name (rest thing) search-path))))))
(defun %do-load-foreign-library (library search-path)
(flet ((%do-load (lib name spec)
(let ((canary (getf (foreign-library-options lib) :canary)))
(cond
((and canary (foreign-symbol-pointer canary))
;; Do nothing because the library is already loaded.
(setf (foreign-library-load-state lib) :static))
((foreign-library-spec lib)
(with-slots (handle pathname) lib
(setf (values handle pathname)
(load-foreign-library-helper
name spec (foreign-library-search-path lib)))
(setf (foreign-library-load-state lib) :external)))))
lib))
(etypecase library
(symbol
(let* ((lib (get-foreign-library library))
(spec (foreign-library-spec lib)))
(%do-load lib library spec)))
((or string list)
(let* ((lib-name (gensym
(format nil "~:@(~A~)-"
(if (listp library)
(first library)
(file-namestring library)))))
(lib (make-instance 'foreign-library
:type :system
:name lib-name
:spec `((t ,library))
:search-path search-path)))
;; first try to load the anonymous library
;; and register it only if that worked
(%do-load lib lib-name library)
(setf (get-foreign-library lib-name) lib))))))
(defun filter-pathname (thing)
(typecase thing
(pathname (namestring thing))
(t thing)))
(defun load-foreign-library (library &key search-path)
"Loads a foreign LIBRARY which can be a symbol denoting a library defined
through DEFINE-FOREIGN-LIBRARY; a pathname or string in which case we try to
load it directly first then search for it in *FOREIGN-LIBRARY-DIRECTORIES*;
or finally list: either (:or lib1 lib2) or (:framework <framework-name>).
The option :CANARY can specify a symbol that will be searched to detect if
the library is already loaded, in which case DEFINE-FOREIGN-LIBRARY will mark
the library as loaded and return."
(let ((library (filter-pathname library)))
(restart-case
(progn
;; dlopen/dlclose does reference counting, but the CFFI-SYS
;; API has no infrastructure to track that. Therefore if we
;; want to avoid increasing the internal dlopen reference
;; counter, and thus thwarting dlclose, then we need to try
;; to call CLOSE-FOREIGN-LIBRARY and ignore any signaled
;; errors.
(ignore-some-conditions (foreign-library-undefined-error)
(close-foreign-library library))
(%do-load-foreign-library library search-path))
;; Offer these restarts that will retry the call to
;; %LOAD-FOREIGN-LIBRARY.
(retry ()
:report "Try loading the foreign library again."
(load-foreign-library library :search-path search-path))
(use-value (new-library)
:report "Use another library instead."
:interactive read-new-value
(load-foreign-library new-library :search-path search-path)))))
(defmacro use-foreign-library (name)
`(load-foreign-library ',name))
;;;# Closing Foreign Libraries
(defun close-foreign-library (library)
"Closes a foreign library."
(let* ((library (filter-pathname library))
(lib (get-foreign-library library))
(handle (foreign-library-handle lib)))
(when handle
(%close-foreign-library handle)
(setf (foreign-library-handle lib) nil)
;; Reset the load state only when the library was externally loaded.
(setf (foreign-library-load-state lib) nil)
t)))
(defun reload-foreign-libraries (&key (test #'foreign-library-loaded-p))
"(Re)load all currently loaded foreign libraries."
(let ((libs (list-foreign-libraries)))
(loop for l in libs
for name = (foreign-library-name l)
when (funcall test name)
do (load-foreign-library name))
libs))
| 19,702 | Common Lisp | .lisp | 422 | 39.113744 | 87 | 0.65221 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 06d3c2bde65dfc7d5f5bb51ec2c30595800969ce06891f61337fbdc4b36219cc | 42,987 | [
389687
] |
42,988 | cffi-allegro.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/cffi-allegro.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-allegro.lisp --- CFFI-SYS implementation for Allegro CL.
;;;
;;; Copyright (C) 2005-2009, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; 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.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp)
(:import-from #:alexandria #:if-let #:with-unique-names #:once-only)
(:export
#:canonicalize-symbol-name-case
#:foreign-pointer
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:native-namestring
#:%mem-ref
#:%mem-set
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:%foreign-symbol-pointer
#:defcfun-helper-forms
#:%defcallback
#:%callback))
(in-package #:cffi-sys)
;;;# Mis-features
#-64bit (pushnew 'no-long-long *features*)
(pushnew 'flat-namespace *features*)
;;;# Symbol Case
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(if (eq excl:*current-case-mode* :case-sensitive-lower)
(string-downcase name)
(string-upcase name)))
;;;# Basic Pointer Operations
(deftype foreign-pointer ()
'ff:foreign-address)
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(ff:foreign-address-p ptr))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(eql ptr1 ptr2))
(defun null-pointer ()
"Return a null pointer."
0)
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(zerop ptr))
(defun inc-pointer (ptr offset)
"Return a pointer pointing OFFSET bytes past PTR."
(+ ptr offset))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(check-type address ff:foreign-address)
address)
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(check-type ptr ff:foreign-address)
ptr)
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage
;;; when the memory has dynamic extent.
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(ff:allocate-fobject :char :c size))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(ff:free-fobject ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
#+(version>= 8 1)
(when (and (constantp size) (<= (eval size) ff:*max-stack-fobject-bytes*))
(return-from with-foreign-pointer
`(let ((,size-var ,(eval size)))
(declare (ignorable ,size-var))
(ff:with-static-fobject (,var '(:array :char ,(eval size))
:allocation :foreign-static-gc)
;; (excl::stack-allocated-p var) => T
(let ((,var (ff:fslot-address ,var)))
,@body)))))
`(let* ((,size-var ,size)
(,var (ff:allocate-fobject :char :c ,size-var)))
(unwind-protect
(progn ,@body)
(ff:free-fobject ,var))))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes can passed to
WITH-POINTER-TO-VECTOR-DATA."
(make-array size :element-type '(unsigned-byte 8)
:allocation :static-reclaimable))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a foreign pointer to the data in VECTOR."
;; An array allocated in static-reclamable is a non-simple array in
;; the normal Lisp allocation area, pointing to a simple array in
;; the static-reclaimable allocation area. Therefore we have to get
;; out the simple-array to find the pointer to the actual contents.
(with-unique-names (simple-vec)
`(excl:with-underlying-simple-vector (,vector ,simple-vec)
(let ((,ptr-var (ff:fslot-address-typed :unsigned-char :lisp
,simple-vec)))
,@body))))
;;;# Dereferencing
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to an Allegro type."
(ecase type-keyword
(:char :char)
(:unsigned-char :unsigned-char)
(:short :short)
(:unsigned-short :unsigned-short)
(:int :int)
(:unsigned-int :unsigned-int)
(:long :long)
(:unsigned-long :unsigned-long)
(:long-long
#+64bit :nat
#-64bit (error "this platform does not support :long-long."))
(:unsigned-long-long
#+64bit :unsigned-nat
#-64bit (error "this platform does not support :unsigned-long-long"))
(:float :float)
(:double :double)
(:pointer :unsigned-nat)
(:void :void)))
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference an object of TYPE at OFFSET bytes from PTR."
(unless (zerop offset)
(setf ptr (inc-pointer ptr offset)))
(ff:fslot-value-typed (convert-foreign-type type) :c ptr))
;;; Compiler macro to open-code the call to FSLOT-VALUE-TYPED when the
;;; CFFI type is constant. Allegro does its own transformation on the
;;; call that results in efficient code.
(define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
(if (constantp type)
(let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off))))
`(ff:fslot-value-typed ',(convert-foreign-type (eval type))
:c ,ptr-form))
form))
(defun %mem-set (value ptr type &optional (offset 0))
"Set the object of TYPE at OFFSET bytes from PTR."
(unless (zerop offset)
(setf ptr (inc-pointer ptr offset)))
(setf (ff:fslot-value-typed (convert-foreign-type type) :c ptr) value))
;;; Compiler macro to open-code the call to (SETF FSLOT-VALUE-TYPED)
;;; when the CFFI type is constant. Allegro does its own
;;; transformation on the call that results in efficient code.
(define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
(if (constantp type)
(once-only (val)
(let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off))))
`(setf (ff:fslot-value-typed ',(convert-foreign-type (eval type))
:c ,ptr-form) ,val)))
form))
;;;# Calling Foreign Functions
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(ff:sizeof-fobject (convert-foreign-type type-keyword)))
(defun %foreign-type-alignment (type-keyword)
"Returns the alignment in bytes of a foreign type."
#+(and powerpc macosx32)
(when (eq type-keyword :double)
(return-from %foreign-type-alignment 8))
;; No override necessary for the remaining types....
(ff::sized-ftype-prim-align
(ff::iforeign-type-sftype
(ff:get-foreign-type
(convert-foreign-type type-keyword)))))
(defun foreign-funcall-type-and-args (args)
"Returns a list of types, list of args and return type."
(let ((return-type :void))
(loop for (type arg) on args by #'cddr
if arg collect type into types
and collect arg into fargs
else do (setf return-type type)
finally (return (values types fargs return-type)))))
(defun convert-to-lisp-type (type)
(ecase type
((:char :short :int :long :nat)
`(signed-byte ,(* 8 (ff:sizeof-fobject type))))
((:unsigned-char :unsigned-short :unsigned-int :unsigned-long :unsigned-nat)
`(unsigned-byte ,(* 8 (ff:sizeof-fobject type))))
(:float 'single-float)
(:double 'double-float)
(:void 'null)))
(defun allegro-type-pair (cffi-type)
;; the :FOREIGN-ADDRESS pseudo-type accepts both pointers and
;; arrays. We need the latter for shareable byte vector support.
(if (eq cffi-type :pointer)
(list :foreign-address)
(let ((ftype (convert-foreign-type cffi-type)))
(list ftype (convert-to-lisp-type ftype)))))
#+ignore
(defun note-named-foreign-function (symbol name types rettype)
"Give Allegro's compiler a hint to perform a direct call."
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (get ',symbol 'system::direct-ff-call)
(list '(,name :language :c)
t ; callback
:c ; convention
;; return type '(:c-type lisp-type)
',(allegro-type-pair rettype)
;; arg types '({(:c-type lisp-type)}*)
'(,@(mapcar #'allegro-type-pair types))
nil ; arg-checking
ff::ep-flag-never-release))))
(defmacro %foreign-funcall (name args &key convention library)
(declare (ignore convention library))
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(system::ff-funcall
(load-time-value (excl::determine-foreign-address
'(,name :language :c)
#-(version>= 8 1) ff::ep-flag-never-release
#+(version>= 8 1) ff::ep-flag-always-release
nil ; method-index
))
;; arg types {'(:c-type lisp-type) argN}*
,@(mapcan (lambda (type arg)
`(',(allegro-type-pair type) ,arg))
types fargs)
;; return type '(:c-type lisp-type)
',(allegro-type-pair rettype))))
(defun defcfun-helper-forms (name lisp-name rettype args types options)
"Return 2 values for DEFCFUN. A prelude form and a caller form."
(declare (ignore options))
(let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name))))
(values
`(ff:def-foreign-call (,ff-name ,name)
,(loop for type in types
collect (list* (gensym) (allegro-type-pair type)))
:returning ,(allegro-type-pair rettype)
;; Don't use call-direct when there are no arguments.
,@(unless (null args) '(:call-direct t))
:arg-checking nil
:strings-convert nil
#+(version>= 8 1) ,@'(:release-heap :when-ok
:release-heap-ignorable t)
#+smp ,@'(:release-heap-implies-allow-gc t))
`(,ff-name ,@args))))
;;; See doc/allegro-internals.txt for a clue about entry-vec.
(defmacro %foreign-funcall-pointer (ptr args &key convention)
(declare (ignore convention))
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
(with-unique-names (entry-vec)
`(let ((,entry-vec (excl::make-entry-vec-boa)))
(setf (aref ,entry-vec 1) ,ptr) ; set jump address
(system::ff-funcall
,entry-vec
;; arg types {'(:c-type lisp-type) argN}*
,@(mapcan (lambda (type arg)
`(',(allegro-type-pair type) ,arg))
types fargs)
;; return type '(:c-type lisp-type)
',(allegro-type-pair rettype))))))
;;;# Callbacks
;;; The *CALLBACKS* hash table contains information about a callback
;;; for the Allegro FFI. The key is the name of the CFFI callback,
;;; and the value is a cons, the car containing the symbol the
;;; callback was defined on in the CFFI-CALLBACKS package, the cdr
;;; being an Allegro FFI pointer (a fixnum) that can be passed to C
;;; functions.
;;;
;;; These pointers must be restored when a saved Lisp image is loaded.
;;; The RESTORE-CALLBACKS function is added to *RESTART-ACTIONS* to
;;; re-register the callbacks during Lisp startup.
(defvar *callbacks* (make-hash-table))
;;; Register a callback in the *CALLBACKS* hash table.
(defun register-callback (cffi-name callback-name)
(setf (gethash cffi-name *callbacks*)
(cons callback-name (ff:register-foreign-callable
callback-name :reuse t))))
;;; Restore the saved pointers in *CALLBACKS* when loading an image.
(defun restore-callbacks ()
(maphash (lambda (key value)
(register-callback key (car value)))
*callbacks*))
;;; Arrange for RESTORE-CALLBACKS to run when a saved image containing
;;; CFFI is restarted.
(eval-when (:load-toplevel :execute)
(pushnew 'restore-callbacks excl:*restart-actions*))
;;; Create a package to contain the symbols for callback functions.
(defpackage #:cffi-callbacks
(:use))
(defun intern-callback (name)
(intern (format nil "~A::~A"
(if-let (package (symbol-package name))
(package-name package)
"#")
(symbol-name name))
'#:cffi-callbacks))
(defun convert-calling-convention (convention)
(ecase convention
(:cdecl :c)
(:stdcall :stdcall)))
(defmacro %defcallback (name rettype arg-names arg-types body
&key convention)
(declare (ignore rettype))
(let ((cb-name (intern-callback name)))
`(progn
(ff:defun-foreign-callable ,cb-name
,(mapcar (lambda (sym type) (list sym (convert-foreign-type type)))
arg-names arg-types)
(declare (:convention ,(convert-calling-convention convention)))
,body)
(register-callback ',name ',cb-name))))
;;; Return the saved Lisp callback pointer from *CALLBACKS* for the
;;; CFFI callback named NAME.
(defun %callback (name)
(or (cdr (gethash name *callbacks*))
(error "Undefined callback: ~S" name)))
;;;# Loading and Closing Foreign Libraries
(defun %load-foreign-library (name path)
"Load a foreign library."
;; ACL 8.0 honors the :FOREIGN option and always tries to foreign load
;; the argument. However, previous versions do not and will only
;; foreign load the argument if its type is a member of the
;; EXCL::*LOAD-FOREIGN-TYPES* list. Therefore, we bind that special
;; to a list containing whatever type NAME has.
(declare (ignore name))
(let ((excl::*load-foreign-types*
(list (pathname-type (parse-namestring path)))))
(handler-case
(progn
#+(version>= 7) (load path :foreign t)
#-(version>= 7) (load path))
(file-error (fe)
(error (change-class fe 'simple-error))))
path))
(defun %close-foreign-library (name)
"Close the foreign library NAME."
(ff:unload-foreign-library name))
(defun native-namestring (pathname)
(namestring pathname))
;;;# Foreign Globals
(defun convert-external-name (name)
"Add an underscore to NAME if necessary for the ABI."
#+macosx (concatenate 'string "_" name)
#-macosx name)
(defun %foreign-symbol-pointer (name library)
"Returns a pointer to a foreign symbol NAME."
(declare (ignore library))
(prog1 (ff:get-entry-point (convert-external-name name))))
| 16,300 | Common Lisp | .lisp | 390 | 36.184615 | 80 | 0.657626 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 28cf7279a09c42eb724ea30424e1c3d8bda494a3283a610e8c7c99e7a929c8a2 | 42,988 | [
303325,
333054
] |
42,990 | structures.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/structures.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; structures.lisp --- Methods for translating foreign structures.
;;;
;;; Copyright (C) 2011, Liam M. Healy <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
;;; Definitions for conversion of foreign structures.
(defmethod translate-into-foreign-memory ((object list)
(type foreign-struct-type)
p)
(unless (bare-struct-type-p type)
(loop for (name value) on object by #'cddr
do (setf (foreign-slot-value p (unparse-type type) name)
(let ((slot (gethash name (structure-slots type))))
(convert-to-foreign value (slot-type slot)))))))
(defmethod translate-to-foreign (value (type foreign-struct-type))
(let ((ptr (foreign-alloc type)))
(translate-into-foreign-memory value type ptr)
ptr))
(defmethod translate-from-foreign (p (type foreign-struct-type))
;; Iterate over slots, make plist
(if (bare-struct-type-p type)
p
(let ((plist (list)))
(loop for slot being the hash-value of (structure-slots type)
for name = (slot-name slot)
do (setf (getf plist name)
(foreign-struct-slot-value p slot)))
plist)))
(defmethod free-translated-object (ptr (type foreign-struct-type) freep)
(unless (bare-struct-type-p type)
;; Look for any pointer slots and free them first
(loop for slot being the hash-value of (structure-slots type)
when (and (listp (slot-type slot)) (eq (first (slot-type slot)) :pointer))
do
;; Free if the pointer is to a specific type, not generic :pointer
(free-translated-object
(foreign-slot-value ptr type (slot-name slot))
(rest (slot-type slot))
freep))
(foreign-free ptr)))
(defmacro define-translation-method ((object type method) &body body)
"Define a translation method for the foreign structure type; 'method is one of :into, :from, or :to, meaning relation to foreign memory. If :into, the variable 'pointer is the foreign pointer. Note: type must be defined and loaded before this macro is expanded, and just the bare name (without :struct) should be specified."
(let ((tclass (class-name (class-of (cffi::parse-type `(:struct ,type))))))
(when (eq tclass 'foreign-struct-type)
(error "Won't replace existing translation method for foreign-struct-type"))
`(defmethod
,(case method
(:into 'translate-into-foreign-memory)
(:from 'translate-from-foreign)
(:to 'translate-to-foreign))
;; Arguments to the method
(,object
(type ,tclass)
,@(when (eq method :into) '(pointer))) ; is intentional variable capture a good idea?
;; The body
(declare (ignorable type)) ; I can't think of a reason why you'd want to use this
,@body)))
(defmacro translation-forms-for-class (class type-class)
"Make forms for translation of foreign structures to and from a standard class. The class slots are assumed to have the same name as the foreign structure."
;; Possible improvement: optional argument to map structure slot names to/from class slot names.
`(progn
(defmethod translate-from-foreign (pointer (type ,type-class))
;; Make the instance from the plist
(apply 'make-instance ',class (call-next-method)))
(defmethod translate-into-foreign-memory ((object ,class) (type ,type-class) pointer)
(call-next-method
;; Translate into a plist and call the general method
(loop for slot being the hash-value of (structure-slots type)
for name = (slot-name slot)
append (list slot-name (slot-value object slot-name)))
type
pointer))))
;;; For a class already defined and loaded, and a defcstruct already defined, use
;;; (translation-forms-for-class class type-class)
;;; to connnect the two. It would be nice to have a macro to do all three simultaneously.
;;; (defmacro define-foreign-structure (class ))
#|
(defmacro define-structure-conversion
(value-symbol type lisp-class slot-names to-form from-form &optional (struct-name type))
"Define the functions necessary to convert to and from a foreign structure. The to-form sets each of the foreign slots in succession, assume the foreign object exists. The from-form creates the Lisp object, making it with the correct value by reference to foreign slots."
`(flet ((map-slots (fn val)
(maphash
(lambda (name slot-struct)
(funcall fn (foreign-slot-value val ',type name) (slot-type slot-struct)))
(slots (follow-typedefs (parse-type ',type))))))
;; Convert this to a separate function so it doesn't have to be recomputed on the fly each time.
(defmethod translate-to-foreign ((,value-symbol ,lisp-class) (type ,type))
(let ((p (foreign-alloc ',struct-name)))
;;(map-slots #'translate-to-foreign ,value-symbol) ; recursive translation of slots
(with-foreign-slots (,slot-names p ,struct-name)
,to-form)
(values p t))) ; second value is passed to FREE-TRANSLATED-OBJECT
(defmethod free-translated-object (,value-symbol (p ,type) freep)
(when freep
;; Is this redundant?
(map-slots #'free-translated-object value) ; recursively free slots
(foreign-free ,value-symbol)))
(defmethod translate-from-foreign (,value-symbol (type ,type))
(with-foreign-slots (,slot-names ,value-symbol ,struct-name)
,from-form))))
|#
| 6,764 | Common Lisp | .lisp | 123 | 47.943089 | 328 | 0.673503 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | e79ef63626f4a01d21d8121ecd41fef5cb44acc881ef1ffe67f4af2b264dc0fb | 42,990 | [
287673
] |
42,991 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/c2ffi/package.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; Copyright (C) 2015, Attila Lendvai <[email protected]>
;;;
;;; 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.
;;;
(uiop:define-package #:cffi/c2ffi
(:mix #:uiop
#:alexandria
#:common-lisp)
(:import-from :asdf
#:cl-source-file
#:find-system
#:output-file
#:output-files
#:input-files
#:operation-done-p
#:perform
#:compile-op
#:load-op
#:load-source-op
#:prepare-op
#:component-pathname
#:component-depends-on
#:operation
#:downward-operation
#:selfward-operation
#:load-system
#:component-loaded-p)
(:export
#:c2ffi-file
#:camelcased?
#:camelcase-to-dash-separated
#:change-case-to-readtable-case
#:default-ffi-name-transformer
#:default-ffi-type-transformer
#:generate-spec
#:maybe-camelcase-to-dash-separated))
| 2,152 | Common Lisp | .lisp | 56 | 31.446429 | 70 | 0.640095 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 6214c831a518746218dc9f3554eb6e3a1ca8202d91f5055dec643672a6557756 | 42,991 | [
318718
] |
42,992 | generator.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/c2ffi/generator.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; generator.lisp --- Generate CFFI bindings for a c2ffi output.
;;;
;;; Copyright (C) 2015, Attila Lendvai <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi/c2ffi)
;;; Output generation happens in one phase, straight into the output
;;; stream. There's minimal look-ahead (for source-location and name)
;;; which is needed to apply user specified filters in time.
;;;
;;; Each CFFI form is also EVAL'd during generation because the CFFI
;;; type lookup/parsing mechanism is used while generating the output.
;;;
;;; Nomenclature:
;;;
;;; - variable names in this file are to be interpreted in the
;;; C,c2ffi,json context, and 'cffi' is added to names that denote
;;; the cffi name.
;;;
;;; Possible improvments:
;;;
;;; - generate an additional grovel file for C inline function
;;; declarations found in header files
;;;
;;; - generate struct-by-value DEFCFUN's into a separate file so that
;;; users can decide whether to depend on libffi, or they can make do
;;; without those definitions
(defvar *allow-pointer-type-simplification* t)
(defvar *allow-skipping-struct-fields* t)
(defvar *assume-struct-by-value-support* t)
;; Called on the json name and may return a symbol to be used, or a string.
(defvar *ffi-name-transformer* 'default-ffi-name-transformer)
;; Called on the already transformed name to decide whether to export it
(defvar *ffi-name-export-predicate* 'default-ffi-name-export-predicate)
;; Called on the CFFI type, e.g. to turn (:pointer :char) into a :string.
(defvar *ffi-type-transformer* 'default-ffi-type-transformer)
;; May return up to two closures using VALUES. The first one will be called
;; with each emitted form, and the second one once, at the end. They both may
;; return a list of forms that will be emitted using OUTPUT/CODE.
(defvar *callback-factory* 'default-callback-factory)
(define-constant +generated-file-header+
";;; -*- Mode: lisp -*-~%~
;;;~%~
;;; This file has been automatically generated by cffi/c2ffi. Editing it by hand is not wise.~%~
;;;~%~%"
:test 'equal)
(defvar *c2ffi-output-stream*)
(defun output/export (names package)
(let ((names (uiop:ensure-list names)))
;; Make sure we have something PRINT-READABLY as a package name,
;; i.e. not a SIMPLE-BASE-STRING on SBCL.
(output/code `(export ',names ',(make-symbol (package-name package))))))
(defun output/code (form)
(check-type form cons)
(format *c2ffi-output-stream* "~&")
(write form
:stream *c2ffi-output-stream*
:circle t
:pretty t
:escape t
:readably t)
(format *c2ffi-output-stream* "~%~%")
(unless (member (first form) '(cffi:defcfun alexandria:define-constant) :test 'eq)
(eval form)))
(defun output/string (message-control &rest message-arguments)
(apply 'format *c2ffi-output-stream* message-control message-arguments))
;; NOTE: as per c2ffi json output. A notable difference to
;; CFFI::*BUILT-IN-FOREIGN-TYPES* is the presence of :SIGNED-CHAR.
(define-constant +c-builtin-types+ '(":void" ":_Bool" ":char" ":signed-char" ":unsigned-char" ":short"
":unsigned-short" ":int" ":unsigned-int" ":long" ":unsigned-long"
":long-long" ":unsigned-long-long" ":float" ":double" ":long-double")
:test 'equal)
(define-condition unsupported-type (cffi::foreign-type-error)
((json-definition :initarg :json-definition
:accessor json-definition-of)))
(defun unsupported-type (json-entry)
(error 'unsupported-type :type-name nil :json-definition json-entry))
;;;;;;
;;; Utilities
(defun compile-rules (rules)
(case rules
(:all rules)
(t (mapcar (lambda (pattern)
(check-type pattern string "Patterns in the inclusion/exclusion rules must be strings.")
(let ((scanner (cl-ppcre:create-scanner pattern)))
(named-lambda cffi/c2ffi/cl-ppcre-rule-matcher
(string)
(funcall scanner string 0 (length string)))))
rules))))
(defun include-definition? (name source-location
include-definitions exclude-definitions
include-sources exclude-sources)
(labels
((covered-by-a-rule? (name rules)
(or (eq rules :all)
(not (null (some (rcurry #'funcall name) rules)))))
(weak? (rules)
(eq :all rules))
(strong? (name rules)
(and name
(not (weak? rules))
(covered-by-a-rule? name rules))))
(let* ((excl-def/weak (weak? exclude-definitions))
(excl-def/strong (strong? name exclude-definitions))
(incl-def/weak (weak? include-definitions))
(incl-def/strong (strong? name include-definitions))
(excl-src/weak (weak? exclude-sources))
(excl-src/strong (strong? source-location exclude-sources))
(incl-src/weak (weak? include-sources))
(incl-src/strong (strong? source-location include-sources))
(incl/strong (or incl-def/strong
incl-src/strong))
(excl/strong (or excl-def/strong
excl-src/strong))
(incl/weak (or incl-def/weak
incl-src/weak))
(excl/weak (or excl-def/weak
excl-src/weak)))
(or incl-def/strong
(and (not excl/strong)
(or incl/strong
(and incl/weak
;; we want src exclude rules to be stronger
(not excl-src/weak))
(not excl/weak)))))))
(defun coerce-to-byte-size (bit-size)
(let ((byte-size (/ bit-size 8)))
(unless (integerp byte-size)
(error "Non-byte size encountered where it wasn't expected (~A bits)" bit-size))
byte-size))
(defmacro assume (condition &optional format-control &rest format-arguments)
"Similar to ASSERT, but WARN's only."
`(unless ,condition
,(if format-control
`(warn ,format-control ,@format-arguments)
`(warn "ASSUME failed: ~S" ',condition))))
(defun canonicalize-transformer-hook (hook)
(etypecase hook
((and (or function symbol)
(not null))
hook)
(string
(the symbol (safe-read-from-string hook)))))
;;;;;;
;;; Json access
(defun json-value (alist key &key (otherwise nil otherwise?))
(check-type alist list)
(check-type key (and symbol (not null)))
(let* ((entry (assoc key alist))
(result (cond
(entry
(cdr entry))
(otherwise?
otherwise)
(t (error "Key ~S not found in json entry ~S." key alist)))))
(if (equal result "")
nil
result)))
(defmacro with-json-values ((json-entry &rest args) &body body)
(if (null args)
`(progn
,@body)
(once-only (json-entry)
`(let (,@(loop
:for entry :in args
:collect (let* ((args (ensure-list entry))
(name (pop args))
(key (or (pop args)
(make-keyword (symbol-name name)))))
(destructuring-bind
;; using &optional would trigger a warning (on SBCL)
(&key (otherwise nil otherwise?))
args
`(,name
(json-value ,json-entry ,key ,@(when otherwise?
`(:otherwise ,otherwise))))))))
,@body))))
(defun expected-json-keys (alist &rest keys)
(let* ((keys (list* :location keys))
(outliers (remove-if (lambda (el)
(member (car el) keys :test 'eq))
alist)))
(when outliers
(warn "Unexpected key(s) in json entry ~S: ~S" alist outliers))))
;;;;;;
;;; Namespaces, names and conversions
;; an alist of (name . hashtable)
(defvar *generated-names*)
(defvar *anon-name-counter*)
(defvar *anon-entities*)
(defun register-anon-entity (id name)
(check-type id integer)
(check-type name string)
(assert (not (zerop (length name))))
(setf (gethash id *anon-entities*) name)
name)
(defun lookup-anon-entity (id)
(or (gethash id *anon-entities*)
(error "Could not find anonymous entity with id ~S." id)))
(defun generate-anon-name (base-name)
(format nil "~A"
(strcat (symbol-name base-name)
(princ-to-string (incf *anon-name-counter*)))))
(defun valid-name-or-die (name)
;; checks for valid json names (*not* CFFI names)
(etypecase name
(string
(assert (not (zerop (length name)))))
(cons
(assert (= 2 (length name)))
(assert (member (first name) '(:struct :union :enum)))
(valid-name-or-die (second name)))))
(defun call-hook (hook &rest args)
(apply hook
;; indiscriminately add one keyword arg entry to warn
(append args '(just-a-warning "Make sure your transformer hook has &key &allow-other-keys for future extendability."))))
(defun find-cffi-type-or-die (type-name &optional (namespace :default))
(when (eq namespace :enum)
;; TODO FIXME this should be cleaned up in CFFI. more about namespace confusion at:
;; https://github.com/cffi/cffi/issues/266
(setf namespace :default))
(cffi::find-type-parser type-name namespace))
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-constant +name-kinds+ '(:struct :union :function :variable :type
:constant :field :argument :enum :member)
:test 'equal))
(deftype ffi-name-kind ()
'#.(list* 'member +name-kinds+))
(defun json-name-to-cffi-name (name kind &optional anonymous)
(check-type name string)
(check-type kind ffi-name-kind)
(when *ffi-name-transformer*
(setf name (call-hook *ffi-name-transformer* name kind))
(unless (or (and (symbolp name)
(not (null name)))
(stringp name))
(error "The FFI-NAME-TRANSFORMER ~S returned with ~S which is not a valid name."
*ffi-name-transformer* name)))
(let ((cffi-name (if (symbolp name)
name
(intern name))))
(when (and (not anonymous)
(boundp '*generated-names*))
;; TODO FIXME this function also gets called for e.g. argument types of a function. and
;; if the function ends up *not* getting emitted, e.g. because of a missing type, then
;; we wrongly record here the missing type in the *generated-names* registry.
(setf (gethash name (cdr (assoc kind *generated-names*)))
cffi-name))
cffi-name))
(defun default-callback-factory (&key &allow-other-keys)
(values))
(defun default-ffi-name-transformer (name kind &key &allow-other-keys)
(check-type name string)
(case kind
#+nil
((:constant :member)
(assert (not (symbolp name)))
(format nil "+~A+" name))
(t name)))
(defun change-case-to-readtable-case (name &optional (reatable *readtable*))
(ecase (readtable-case reatable)
(:upcase (string-upcase name))
(:downcase (string-downcase name))
(:preserve name)
;; (:invert no, you don't)
))
(defun camelcased? (name)
(and (>= (length name) 3)
(let ((lower 0)
(upper 0))
(loop
:for char :across name
:do (cond
((upper-case-p char)
(incf upper))
((lower-case-p char)
(incf lower))))
(unless (or (zerop lower)
(zerop upper))
(let ((ratio (/ upper lower)))
(and (<= 0.05 ratio 0.5)))))))
(defun camelcase-to-dash-separated (name)
(coerce (loop
:for char :across name
:for index :from 0
:when (and (upper-case-p char)
(not (zerop index)))
:collect #\-
:collect (char-downcase char))
'string))
(defun maybe-camelcase-to-dash-separated (name)
(if (camelcased? name)
(camelcase-to-dash-separated name)
name))
(defun default-ffi-name-export-predicate (symbol &key &allow-other-keys)
(declare (ignore symbol))
nil)
(defun default-ffi-type-transformer (type context &key &allow-other-keys)
(declare (ignore context))
(cond
((and (consp type)
(eq :pointer (first type)))
(let ((pointed-to-type (second type)))
(if (eq pointed-to-type :char)
:string
type)))
(t
type)))
(defun function-pointer-type-name ()
(symbolicate '#:function-pointer))
(defmacro with-allowed-foreign-type-errors ((on-failure-form &key (enabled t)) &body body)
(with-unique-names (type-block)
`(block ,type-block
(handler-bind
((cffi::foreign-type-error
(lambda (_)
(declare (ignore _))
(when ,enabled
(return-from ,type-block ,on-failure-form)))))
,@body))))
(defun %json-type-to-cffi-type (json-entry)
(with-json-values (json-entry tag)
(let ((cffi-type
(cond
((switch (tag :test 'equal)
(":void" :void)
(":_Bool" :bool)
;; regarding :signed-char see https://stackoverflow.com/questions/436513/char-signed-char-char-unsigned-char
(":char" :char)
(":signed-char" :char)
(":unsigned-char" :unsigned-char)
(":short" :short)
(":unsigned-short" :unsigned-short)
(":int" :int)
(":unsigned-int" :unsigned-int)
(":long" :long)
(":unsigned-long" :unsigned-long)
(":long-long" :long-long)
(":unsigned-long-long" :unsigned-long-long)
(":float" :float)
(":double" :double)
;; TODO FIXME
;;(":long-double" :long-double)
)
;; return the result of the condition expression
)
((or (progn
(assert (not (member tag +c-builtin-types+ :test 'equal)) ()
"Not all C basic types are covered! The outlier is: ~S" tag)
nil)
(equal tag ":struct")
(equal tag ":union"))
;; ":struct" is a "struct foo-struct var" kind of reference
(expected-json-keys json-entry :name :tag :id)
(with-json-values (json-entry name id)
(let* ((kind (if (equal tag ":struct")
:struct
:union))
(cffi-name (if name
(json-name-to-cffi-name name kind)
(lookup-anon-entity id))))
(find-cffi-type-or-die cffi-name kind)
`(,kind ,cffi-name))))
((or (equal tag "struct")
(equal tag "union"))
;; "struct" denotes a "struct {} var", or "typedef struct {} my_type"
;; kind of inline anonymous declaration. Let's call PROCESS-C2FFI-ENTRY
;; to emit it for us, and return with the generated name (first value)
;; as if it was a standalone toplevel struct definition.
;; TODO is it a problem that we don't invoke the CALLBACK-FACTORY stuff here?
(let ((form (process-c2ffi-entry json-entry))
(kind (if (equal tag "struct")
:struct
:union)))
(assert (and (consp form)
(member (first form) '(cffi:defcstruct cffi:defcunion))))
`(,kind ,(first (ensure-list (second form))))))
((equal tag ":enum")
;; ":enum" is an "enum foo var" kind of reference
(expected-json-keys json-entry :name :tag :id)
(with-json-values (json-entry name id)
(let ((cffi-name (json-name-to-cffi-name (or name
(lookup-anon-entity id))
:enum)))
(find-cffi-type-or-die cffi-name :enum)
;; TODO FIXME this would be the proper one, but CFFI is broken: `(:enum ,cffi-name)
cffi-name)))
((equal tag "enum")
;; "enum" is an inline "typedef enum {m1, m2} var" kind of inline declaration
(expected-json-keys json-entry :name :tag :id)
;; TODO FIXME similarly to struct, but it would be nice to see an example
(error "not yet implemented"))
((equal tag ":array")
(expected-json-keys json-entry :tag :type :size)
(with-json-values (json-entry type size)
(check-type size integer)
`(:array ,(json-type-to-cffi-type type) ,size)))
((equal tag ":pointer")
(expected-json-keys json-entry :tag :type :id)
(with-json-values (json-entry type)
`(:pointer ,(with-allowed-foreign-type-errors
(:void :enabled *allow-pointer-type-simplification*)
(json-type-to-cffi-type type)))))
((equal tag ":function-pointer")
(expected-json-keys json-entry :tag)
(function-pointer-type-name))
((equal tag ":function")
(unsupported-type json-entry))
(t
(assert (not (starts-with #\: tag)))
(let ((cffi-name (json-name-to-cffi-name tag :type)))
;; TODO FIXME json-name-to-cffi-name collects the mentioned
;; types to later emit +TYPE-NAMES+, but if this next
;; find-cffi-type-or-die dies then the entire function is
;; skipped.
(find-cffi-type-or-die cffi-name)
cffi-name)))))
(assert cffi-type () "Failed to map ~S to a cffi type" json-entry)
cffi-type)))
(defun should-export-p (symbol)
(and symbol
(symbolp symbol)
(not (keywordp symbol))
*ffi-name-export-predicate*
(call-hook *ffi-name-export-predicate* symbol)))
(defun json-type-to-cffi-type (json-entry &optional (context nil context?))
(let ((cffi-type (%json-type-to-cffi-type json-entry)))
(if context?
(call-hook *ffi-type-transformer* cffi-type context)
cffi-type)))
;;;;;;
;;; Entry point, the "API"
(defun process-c2ffi-spec-file (c2ffi-spec-file package-name
&key
(allow-pointer-type-simplification *allow-pointer-type-simplification*)
(allow-skipping-struct-fields *allow-skipping-struct-fields*)
(assume-struct-by-value-support *assume-struct-by-value-support*)
;; either a pathname or a string (will be copied as is),
;; or a function that will be funcall'd with one argument
;; to emit a form (i.e. OUTPUT/CODE).
prelude
(output (make-pathname :name (strcat (pathname-name c2ffi-spec-file) ".cffi-tmp")
:type "lisp" :defaults c2ffi-spec-file))
(output-encoding asdf:*default-encoding*)
;; The args following this point are mirrored in the ASDF
;; component on the same name.
(ffi-name-transformer *ffi-name-transformer*)
(ffi-name-export-predicate *ffi-name-export-predicate*)
;; as per CFFI:DEFINE-FOREIGN-LIBRARY and CFFI:LOAD-FOREIGN-LIBRARY
(ffi-type-transformer *ffi-type-transformer*)
(callback-factory *callback-factory*)
foreign-library-name
foreign-library-spec
(emit-generated-name-mappings t)
(include-sources :all)
exclude-sources
(include-definitions :all)
exclude-definitions)
"Generates a lisp file with CFFI definitions from C2FFI-SPEC-FILE.
PACKAGE-NAME will be overwritten, it assumes full control over the
target package."
(check-type c2ffi-spec-file (or pathname string))
(macrolet ((@ (var)
`(setf ,var (compile-rules ,var))))
(@ include-sources)
(@ exclude-sources)
(@ include-definitions)
(@ exclude-definitions))
(with-standard-io-syntax
(with-input-from-file (in c2ffi-spec-file :external-format (uiop:encoding-external-format :utf-8))
(with-output-to-file (*c2ffi-output-stream* output :if-exists :supersede
:external-format (uiop:encoding-external-format output-encoding))
(let* ((*package* (or (find-package package-name)
(make-package package-name)))
;; Make sure we use an uninterned symbol, so that it's neutral to READTABLE-CASE.
(package-name (make-symbol (package-name *package*)))
;; Let's rebind a copy, so that when we are done with
;; the generation (which also EVAL's the forms) then
;; the CFFI type repository is also reverted back to
;; the previous state. This avoids redefinition warning
;; when the generated file gets compiled and loaded
;; later.
(cffi::*default-type-parsers* (copy-hash-table cffi::*default-type-parsers*))
(cffi::*struct-type-parsers* (copy-hash-table cffi::*struct-type-parsers*))
(cffi::*union-type-parsers* (copy-hash-table cffi::*union-type-parsers*))
(*anon-name-counter* 0)
(*anon-entities* (make-hash-table))
(*generated-names* (mapcar (lambda (key)
`(,key . ,(make-hash-table :test 'equal)))
+name-kinds+))
(*allow-pointer-type-simplification* allow-pointer-type-simplification)
(*allow-skipping-struct-fields* allow-skipping-struct-fields)
(*assume-struct-by-value-support* assume-struct-by-value-support)
(*ffi-name-transformer* (canonicalize-transformer-hook ffi-name-transformer))
(*ffi-name-export-predicate* (canonicalize-transformer-hook ffi-name-export-predicate))
(*ffi-type-transformer* (canonicalize-transformer-hook ffi-type-transformer))
(*callback-factory* (canonicalize-transformer-hook callback-factory))
(*read-default-float-format* 'double-float)
(json (json:decode-json in)))
(output/string +generated-file-header+)
;; some forms that are always emitted
(mapc 'output/code
;; Make sure the package exists. We don't even want to :use COMMON-LISP here,
;; to avoid any possible name clashes.
`((uiop:define-package ,package-name (:use))
(in-package ,package-name)
(cffi:defctype ,(function-pointer-type-name) :pointer)))
(when (and foreign-library-name
foreign-library-spec)
(when (stringp foreign-library-name)
(setf foreign-library-name (safe-read-from-string foreign-library-name)))
(output/code `(cffi:define-foreign-library ,foreign-library-name
,@foreign-library-spec))
;; TODO: Unconditionally emitting a USE-FOREIGN-LIBRARY may not be smart.
;; For details see: https://github.com/cffi/cffi/issues/272
(output/code `(cffi:use-foreign-library ,foreign-library-name)))
(etypecase prelude
(null)
(string
(output/string prelude))
(pathname
(with-input-from-file (prelude-stream prelude)
(alexandria:copy-stream prelude-stream *c2ffi-output-stream*
:element-type 'character)))
((or symbol function)
(funcall prelude 'output/code)))
;;
;; Let's enumerate the entries
(multiple-value-bind (form-callback epilogue-callback)
(funcall *callback-factory*)
(dolist (json-entry json)
(with-json-values (json-entry name location)
(let ((source-location-file (subseq location
0
(or (position #\: location)
0))))
(if (include-definition?
name source-location-file
include-definitions exclude-definitions
include-sources exclude-sources)
(progn
(output/string "~&~%;; ~S" location)
(let ((emitted-definition (process-c2ffi-entry json-entry)))
;;
;; Call the plugin to let the user emit a form after the given
;; definition
(when (and emitted-definition
form-callback)
(map nil 'output/code (call-hook form-callback emitted-definition)))))
(output/string "~&;; Skipped ~S due to filters" name)))))
;;
;; Call the plugin to let the user append multiple forms after the
;; emitted definitions
(when epilogue-callback
(map nil 'output/code (call-hook epilogue-callback))))
;;
;; emit optional exports
(maphash
(lambda (package-name symbols)
(output/export (sort (remove-if-not #'should-export-p symbols) #'string<)
package-name))
(get-all-names-by-package *generated-names*))
;;
;; emit optional mappings
(when emit-generated-name-mappings
(mapcar (lambda (entry)
(destructuring-bind (kind variable-name) entry
(output/code `(defparameter
,(intern (symbol-name variable-name))
',(hash-table-alist (cdr (assoc kind *generated-names*)))))))
`((:function #:+function-names+)
(:struct #:+struct-names+)
(:union #:+union-names+)
(:variable #:+variable-names+)
(:type #:+type-names+)
(:constant #:+constant-names+)
(:argument #:+argument-names+)
(:field #:+field-names+))))))))
output)
(defun get-all-names-by-package (name-collection)
(let ((tables (mapcar #'cdr name-collection))
all
(grouped (make-hash-table)))
(loop :for table :in tables :do
(loop :for s :being :the :hash-values :of table :do
(push s all)))
(remove-duplicates all :test #'eq)
(loop :for name :in all
:for package-name := (package-name (symbol-package name))
:do (setf (gethash package-name grouped)
(cons name (gethash package-name grouped))))
grouped))
;;;;;;
;;; Processors for various definitions
(defvar *c2ffi-entry-processors* (make-hash-table :test 'equal))
(defun process-c2ffi-entry (json-entry)
(let* ((kind (json-value json-entry :tag))
(processor (gethash kind *c2ffi-entry-processors*)))
(if processor
(let ((definition-form
(handler-bind
((unsupported-type
(lambda (e)
(warn "Skip definition because cannot map ~S to any CFFI type. The definition is ~S"
(json-definition-of e) json-entry)
(return-from process-c2ffi-entry (values))))
(cffi::undefined-foreign-type-error
(lambda (e)
(output/string "~&;; Skipping definition ~S because of missing type ~S"
json-entry (cffi::foreign-type-error/compound-name e))
(return-from process-c2ffi-entry (values)))))
(funcall processor json-entry))))
(when definition-form
(output/code definition-form)
definition-form))
(progn
(warn "No cffi/c2ffi processor defined for ~A" json-entry)
(values)))))
(defmacro define-processor (kind args &body body)
`(setf (gethash ,(string-downcase kind) *c2ffi-entry-processors*)
(named-lambda ,(symbolicate 'c2ffi-processor/ kind) (-json-entry-)
(with-json-values (-json-entry- ,@args)
,@body))))
(defun %process-struct-like (json-entry kind definer anon-base-name)
(expected-json-keys json-entry :tag :ns :name :id :bit-size :bit-alignment :fields)
(with-json-values (json-entry tag (struct-name :name) fields bit-size id)
(assert (member tag '(":struct" "struct" ":union" "union") :test 'equal))
(flet ((process-field (json-entry)
(with-json-values (json-entry (field-name :name) bit-offset type)
(let ((cffi-type (with-allowed-foreign-type-errors
('failed :enabled *allow-skipping-struct-fields*)
(json-type-to-cffi-type type `(,kind ,struct-name ,field-name)))))
(if (eq cffi-type 'failed)
(output/string "~&;; skipping field due to missing type ~S, full json entry: ~S" type json-entry)
`(,(json-name-to-cffi-name field-name :field)
,cffi-type
,@(unless (eq kind :union)
`(:offset ,(coerce-to-byte-size bit-offset)))))))))
`(,definer (,(json-name-to-cffi-name (or struct-name
(register-anon-entity
id
(generate-anon-name anon-base-name)))
kind
(null struct-name))
:size ,(coerce-to-byte-size bit-size))
,@(remove nil (mapcar #'process-field fields))))))
(define-processor struct ()
(%process-struct-like -json-entry- :struct 'cffi:defcstruct '#:anon-struct-))
(define-processor union ()
(%process-struct-like -json-entry- :union 'cffi:defcunion '#:anon-union-))
(define-processor typedef (name type)
(expected-json-keys -json-entry- :tag :name :ns :type)
`(cffi:defctype ,(json-name-to-cffi-name name :type)
,(json-type-to-cffi-type type `(:typedef ,name))))
(define-processor function (return-type (function-name :name) parameters inline variadic storage-class)
(declare (ignore storage-class))
;; TODO does storage-class matter for FFI accessibility?
#+nil
(assume (equal "extern" storage-class)
"Unexpected function STORAGE-CLASS: ~S for function ~S" storage-class function-name)
(expected-json-keys -json-entry- :tag :name :return-type :parameters :variadic :inline :storage-class :ns)
(let ((uses-struct-by-value? nil))
(flet ((process-arg (json-entry index)
(expected-json-keys json-entry :tag :name :type)
(with-json-values (json-entry tag (argument-name :name) type)
(assert (equal tag "parameter"))
(let* ((cffi-type (json-type-to-cffi-type type `(:function ,function-name ,argument-name)))
(canonicalized-type (cffi::canonicalize-foreign-type cffi-type)))
(when (and (consp canonicalized-type)
(member (first canonicalized-type) '(:struct :union)))
(setf uses-struct-by-value? t))
`(,(if argument-name
(json-name-to-cffi-name argument-name :argument)
(symbolicate '#:arg (princ-to-string index)))
,cffi-type)))))
(let ((cffi-args (loop
:for arg :in parameters
:for index :upfrom 1
:collect (process-arg arg index))))
(cond
((and uses-struct-by-value?
(not *assume-struct-by-value-support*))
(values))
(inline
;; TODO inline functions should go into a separate grovel file?
(output/string "~&;; Skipping inline function ~S" function-name)
(values))
(t `(cffi:defcfun (,function-name ,(json-name-to-cffi-name function-name :function))
,(json-type-to-cffi-type return-type `(:function ,function-name :return-type))
,@(append cffi-args
(when variadic
'(&rest))))))))))
(define-processor extern (name type)
(expected-json-keys -json-entry- :tag :name :type)
`(cffi:defcvar (,name ,(json-name-to-cffi-name name :variable))
,(json-type-to-cffi-type type `(:variable ,name))))
;; ((TAG . enum) (NS . 0) (NAME . ) (ID . 3) (LOCATION . /usr/include/bits/confname.h:24:1) (FIELDS ((TAG . field) (NAME . _PC_LINK_MAX) (VALUE . 0)) ((TAG . field) (NAME . _PC_MAX_CANON) (VALUE . 1)) ((TAG . field) (NAME . _PC_MAX_INPUT) (VALUE . 2)) ((TAG . field) (NAME . _PC_NAME_MAX) (VALUE . 3)) ((TAG . field) (NAME . _PC_PATH_MAX) (VALUE . 4)) ((TAG . field) (NAME . _PC_PIPE_BUF) (VALUE . 5)) ((TAG . field) (NAME . _PC_CHOWN_RESTRICTED) (VALUE . 6)) ((TAG . field) (NAME . _PC_NO_TRUNC) (VALUE . 7)) ((TAG . field) (NAME . _PC_VDISABLE) (VALUE . 8)) ((TAG . field) (NAME . _PC_SYNC_IO) (VALUE . 9)) ((TAG . field) (NAME . _PC_ASYNC_IO) (VALUE . 10)) ((TAG . field) (NAME . _PC_PRIO_IO) (VALUE . 11)) ((TAG . field) (NAME . _PC_SOCK_MAXBUF) (VALUE . 12)) ((TAG . field) (NAME . _PC_FILESIZEBITS) (VALUE . 13)) ((TAG . field) (NAME . _PC_REC_INCR_XFER_SIZE) (VALUE . 14)) ((TAG . field) (NAME . _PC_REC_MAX_XFER_SIZE) (VALUE . 15)) ((TAG . field) (NAME . _PC_REC_MIN_XFER_SIZE) (VALUE . 16)) ((TAG . field) (NAME . _PC_REC_XFER_ALIGN) (VALUE . 17)) ((TAG . field) (NAME . _PC_ALLOC_SIZE_MIN) (VALUE . 18)) ((TAG . field) (NAME . _PC_SYMLINK_MAX) (VALUE . 19)) ((TAG . field) (NAME . _PC_2_SYMLINKS) (VALUE . 20))))
(define-processor enum (name fields id)
(let ((bitmasks 0)
(non-bitmasks 0))
(labels
((for-bitmask-statistics (name value)
(declare (ignore name))
(if (cffi::single-bit-p value)
(incf bitmasks)
(incf non-bitmasks)))
(for-enum-body (name value)
`(,(json-name-to-cffi-name name :member)
,value))
(process-fields (visitor)
(loop
:for json-entry :in fields
:do (expected-json-keys json-entry :tag :name :value)
:collect
(with-json-values (json-entry tag name value)
(assert (equal tag "field"))
(check-type value integer)
(funcall visitor name value)))))
(process-fields #'for-bitmask-statistics)
`(,(if (> (/ bitmasks
(+ non-bitmasks bitmasks))
0.8)
'cffi:defbitfield
'cffi:defcenum)
,(json-name-to-cffi-name (or name
(register-anon-entity
id
(generate-anon-name '#:anon-enum-)))
:enum
(null name))
,@(process-fields #'for-enum-body)))))
(defun make-define-constant-form (name value)
(valid-name-or-die name)
(let ((test-fn (typecase value
(number)
(t 'equal))))
`(alexandria:define-constant ,(json-name-to-cffi-name name :constant)
,value ,@(when test-fn `(:test ',test-fn)))))
(define-processor const (name type (value :value :otherwise nil))
(expected-json-keys -json-entry- :tag :name :type :value :ns)
(let ((cffi-type (json-type-to-cffi-type type `(:contant ,name))))
(cond
((not value)
;; #define __FOO_H and friends... just ignore them.
(values))
((and (member cffi-type '(:int :unsigned-int
:long :unsigned-long
:long-long :unsigned-long-long))
(integerp value))
(make-define-constant-form name value))
((and (member cffi-type '(:float :double))
(floatp value))
(make-define-constant-form name value))
((member cffi-type '(:string (:pointer :char)) :test 'equal)
(make-define-constant-form name value))
(t
(warn "Don't know how to emit a constant of CFFI type ~S, with value ~S (json type is ~S)." cffi-type value type)
(values)))))
| 39,219 | Common Lisp | .lisp | 779 | 37.237484 | 1,222 | 0.550211 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | f2e59ea6a38f78d02314ca1d8f3519fa94600263f363532d16b1d7e49aa57333 | 42,992 | [
352917
] |
42,993 | asdf.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/src/c2ffi/asdf.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; asdf.lisp --- ASDF components for cffi/c2ffi.
;;;
;;; Copyright (C) 2015, Attila Lendvai <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi/c2ffi)
(defclass c2ffi-file (cl-source-file)
((package :initarg :package
:initform nil
:accessor c2ffi-file/package)
(c2ffi-executable :initarg :c2ffi-executable
:accessor c2ffi-file/c2ffi-executable)
(trace-c2ffi :initarg :trace-c2ffi
:accessor c2ffi-file/trace-c2ffi)
(prelude :initform nil
:initarg :prelude
:accessor c2ffi-file/prelude)
(sys-include-paths :initarg :sys-include-paths
:initform nil
:accessor c2ffi-file/sys-include-paths)
(exclude-archs :initarg :exclude-archs
:initform nil
:accessor c2ffi-file/exclude-archs)
;; The following slots correspond to an arg of the same name for
;; the generator function. No accessors are needed, they just hold
;; the data until it gets delegated to the generator function using
;; SLOT-VALUE and a LOOP.
(ffi-name-transformer :initarg :ffi-name-transformer
:initform 'default-ffi-name-transformer)
(ffi-name-export-predicate :initarg :ffi-name-export-predicate
:initform 'default-ffi-name-export-predicate)
(ffi-type-transformer :initarg :ffi-type-transformer
:initform 'default-ffi-type-transformer)
(callback-factory :initarg :callback-factory
:initform 'default-callback-factory)
(foreign-library-name :initarg :foreign-library-name
:initform nil)
(foreign-library-spec :initarg :foreign-library-spec
:initform nil)
(emit-generated-name-mappings :initarg :emit-generated-name-mappings
:initform :t)
(include-sources :initarg :include-sources
:initform :all)
(exclude-sources :initarg :exclude-sources
:initform nil)
(include-definitions :initarg :include-definitions
:initform :all)
(exclude-definitions :initarg :exclude-definitions
:initform nil))
(:default-initargs
:type nil)
(:documentation
"The input of this ASDF component is a C header file and the configuration for
the binding generation process. This header file will define the initial scope of
the generation process, which can be further filtered by other configuration
parameters.
A clang/llvm based external tool called 'c2ffi' is used to process this header
file and generate a json spec file for each supported architecture triplet. Normally
these .spec files are only (re)generated by the author of the lib and are checked into
the corresponding source repository. It needs to be done manually by invoking the
following command:
(cffi/c2ffi:generate-spec :your-system)
which is a shorthand for:
(asdf:operate 'cffi/c2ffi::generate-spec-op :your-system)
The generation of the underlying platform's json file must succeed, but the
generation for the other arch's is allowed to fail
\(see ENSURE-SPEC-FILE-IS-UP-TO-DATE for details).
During the normal build process the json file is used as the input to generate
a lisp file containing the CFFI definitions (see PROCESS-C2FFI-SPEC-FILE).
This file will be placed next to the .spec file, and will be compiled as any
other lisp file. This process requires loading the ASDF system called
\"cffi/c2ffi-generator\" that has more dependencies than CFFI itself. If you
want to avoid those extra dependencies in your project, then you can check in
these generated lisp files into your source repository, but keep in mind that
you'll need to manually force their regeneration if CFFI/C2FFI itself gets
updated (by e.g. deleting them from the filesystem) ."))
(defun input-file (operation component)
(let ((files (input-files operation component)))
(assert (length=n-p files 1))
(first files)))
(defclass generate-spec-op (selfward-operation)
((selfward-operation :initform 'prepare-op)))
(defun generate-spec (system &key force)
(asdf:operate 'generate-spec-op system :force force))
(defmethod input-files ((op generate-spec-op) (c c2ffi-file))
(list (component-pathname c)))
(defmethod output-files ((op generate-spec-op) (c c2ffi-file))
(let* ((input-file (input-file op c))
(spec-file (spec-path input-file)))
(values
(list spec-file)
;; Tell ASDF not to apply output translation.
t)))
(defmethod perform ((op generate-spec-op) (c asdf:component))
(values))
(defmethod perform ((op generate-spec-op) (c c2ffi-file))
(let ((input-file (input-file op c))
(*c2ffi-executable* (if (slot-boundp c 'c2ffi-executable)
(c2ffi-file/c2ffi-executable c)
*c2ffi-executable*))
(*trace-c2ffi* (if (slot-boundp c 'trace-c2ffi)
(c2ffi-file/trace-c2ffi c)
*trace-c2ffi*)))
;; NOTE: we don't call OUTPUT-FILE here, which may be a violation
;; of the ASDF contract, that promises that OUTPUT-FILE can be
;; customized by users.
(ensure-spec-file-is-up-to-date
input-file
:exclude-archs (c2ffi-file/exclude-archs c)
:sys-include-paths (c2ffi-file/sys-include-paths c))))
(defclass generate-lisp-op (selfward-operation)
((selfward-operation :initform '()))) ; we will specify it in our own COMPONENT-DEPENDS-ON
(defmethod component-depends-on ((op generate-lisp-op) (c c2ffi-file))
`((load-op ,(find-system "cffi/c2ffi-generator"))
;; Regenerating the spec file is a lot of headache, so we ignore
;; the file modification times, and only communicate the
;; dependency to ASDF if the spec file is missing.
,@(let ((spec-file (input-file op c))) ; TODO is it legal to call ASDF:INPUT-FILES here?
(when (or (not (probe-file spec-file))
(zerop (with-input-from-file (s spec-file)
(file-length s))))
`((generate-spec-op ,c))))
,@(call-next-method)))
(defmethod component-depends-on ((op compile-op) (c c2ffi-file))
`((generate-lisp-op ,c) ,@(call-next-method)))
(defmethod component-depends-on ((op load-source-op) (c c2ffi-file))
`((generate-lisp-op ,c) ,@(call-next-method)))
(defmethod input-files ((op generate-lisp-op) (c c2ffi-file))
(list (output-file 'generate-spec-op c)))
(defmethod input-files ((op compile-op) (c c2ffi-file))
(list (output-file 'generate-lisp-op c)))
(defmethod output-files ((op generate-lisp-op) (c c2ffi-file))
(let* ((spec-file (input-file op c))
(generated-lisp-file (make-pathname :type "lisp"
:defaults spec-file)))
(values
(list generated-lisp-file)
;; Tell ASDF not to apply output translation.
t)))
(defmethod perform ((op generate-lisp-op) (c c2ffi-file))
(let ((spec-file (input-file op c))
(generated-lisp-file (output-file op c)))
(with-staging-pathname (tmp-output generated-lisp-file)
(format *debug-io* "~&; CFFI/C2FFI is generating the file ~S~%" generated-lisp-file)
(apply 'process-c2ffi-spec-file
spec-file (c2ffi-file/package c)
:output tmp-output
:output-encoding (asdf:component-encoding c)
:prelude (let ((prelude (c2ffi-file/prelude c)))
(if (and (pathnamep prelude)
(not (absolute-pathname-p prelude)))
(merge-pathnames* prelude (component-pathname c))
prelude))
;; The following slots and keyword args have the same name in the ASDF
;; component and in PROCESS-C2FFI-SPEC-FILE, and this loop copies them.
(loop
:for arg :in '(ffi-name-transformer
ffi-name-export-predicate
ffi-type-transformer
callback-factory
foreign-library-name
foreign-library-spec
emit-generated-name-mappings
include-sources
exclude-sources
include-definitions
exclude-definitions)
:append (list (make-keyword arg)
(slot-value c arg)))))))
;; Allow for naked :cffi/c2ffi-file in asdf definitions.
(setf (find-class 'asdf::cffi/c2ffi-file) (find-class 'c2ffi-file))
| 9,833 | Common Lisp | .lisp | 192 | 42.364583 | 92 | 0.654362 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 013d93b188b999547e6211b7c5797dba397e36630846942914db3a57bae2198e | 42,993 | [
480077
] |
42,994 | fsbv.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/fsbv.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; fsbv.lisp --- Tests of foreign structure by value calls.
;;;
;;; Copyright (C) 2011, Liam M. Healy
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
;; Requires struct.lisp
(defcfun "sumpair" :int
(p (:struct struct-pair)))
(defcfun "makepair" (:struct struct-pair)
(condition :bool))
(defcfun "doublepair" (:struct struct-pair)
(p (:struct struct-pair)))
(defcfun "prodsumpair" :double
(p (:struct struct-pair+double)))
(defcfun "doublepairdouble" (:struct struct-pair+double)
(p (:struct struct-pair+double)))
;;; Call struct by value
(deftest fsbv.1
(sumpair '(1 . 2))
3)
;;; See lp#1528719
(deftest (fsbv.wfo :expected-to-fail t)
(with-foreign-object (arg '(:struct struct-pair))
(convert-into-foreign-memory '(40 . 2) '(:struct struct-pair) arg)
(sumpair arg))
42)
;;; Call and return struct by value
(deftest fsbv.2
(doublepair '(1 . 2))
(2 . 4))
;;; return struct by value
(deftest (fsbv.makepair.1 :expected-to-fail t)
(makepair nil)
(-127 . 43))
(deftest (fsbv.makepair.2 :expected-to-fail t)
(makepair t)
(-127 . 42))
;;; Call recursive structure by value
(deftest fsbv.3
(prodsumpair '(pr (a 4 b 5) dbl 2.5d0))
22.5d0)
;;; Call and return recursive structure by value
(deftest fsbv.4
(let ((ans (doublepairdouble '(pr (a 4 b 5) dbl 2.5d0))))
(values (getf (getf ans 'pr) 'a)
(getf (getf ans 'pr) 'b)
(getf ans 'dbl)))
8
10
5.0d0)
(defcstruct (struct-with-array :size 6)
(s1 (:array :char 6)))
(defcfun "zork" :void
(p (:struct struct-with-array)))
;;; Typedef fsbv test
(defcfun ("sumpair" sumpair2) :int
(p struct-pair-typedef1))
(deftest fsbv.5
(sumpair2 '(1 . 2))
3)
(defcfun "returnpairpointer" (:pointer (:struct struct-pair))
(ignored (:struct struct-pair)))
(deftest fsbv.return-a-pointer
(let ((ptr (returnpairpointer '(1 . 2))))
(+ (foreign-slot-value ptr '(:struct struct-pair) 'a)
(foreign-slot-value ptr '(:struct struct-pair) 'b)))
42)
;;; Test ulonglong on no-long-long implementations.
(defcfun "ullsum" :unsigned-long-long
(a :unsigned-long-long) (b :unsigned-long-long))
(deftest fsbv.6
(ullsum #x10DEADBEEF #x2300000000)
#x33DEADBEEF)
;;; Combine structures by value with a string argument
(defcfun "stringlenpair" (:struct struct-pair)
(s :string)
(p (:struct struct-pair)))
(deftest fsbv.7
(stringlenpair "abc" '(1 . 2))
(3 . 6))
;;; Combine structures by value with an enum argument
(defcfun "enumpair" (:int)
(e numeros)
(p (:struct struct-pair)))
(deftest fsbv.8
(enumpair :two '(1 . 2))
5)
;;; returning struct with bitfield member (bug #1474631)
(defbitfield (struct-bitfield :unsigned-int)
(:a 1)
(:b 2))
(defcstruct bitfield-struct
(b struct-bitfield))
(defcfun "structbitfield" (:struct bitfield-struct)
(x :unsigned-int))
(defctype struct-bitfield-typedef struct-bitfield)
(defcstruct bitfield-struct.2
(b struct-bitfield-typedef))
(defcfun ("structbitfield" structbitfield.2) (:struct bitfield-struct.2)
(x :unsigned-int))
;; these would get stuck in an infinite loop previously
(deftest fsbv.struct-bitfield.0
(structbitfield 0)
(b nil))
(deftest fsbv.struct-bitfield.1
(structbitfield 1)
(b (:a)))
(deftest fsbv.struct-bitfield.2
(structbitfield 2)
(b (:b)))
(deftest fsbv.struct-bitfield.3
(structbitfield.2 2)
(b (:b)))
;;; Test for a discrepancy between normal and fsbv return values
(cffi:define-foreign-type int-return-code (cffi::foreign-type-alias)
()
(:default-initargs :actual-type (cffi::parse-type :int))
(:simple-parser int-return-code))
(defmethod cffi:expand-from-foreign (value (type int-return-code))
;; NOTE: strictly speaking it should be
;; (cffi:convert-from-foreign ,value :int), but it's irrelevant in this case
`(let ((return-code ,value))
(check-type return-code integer)
return-code))
(defcfun (noargs-with-typedef "noargs") int-return-code)
(deftest fsbv.noargs-with-typedef ; for reference, not an FSBV call
(noargs-with-typedef)
42)
(defcfun (sumpair-with-typedef "sumpair") int-return-code
(p (:struct struct-pair)))
(deftest (fsbv.return-value-typedef)
(sumpair-with-typedef '(40 . 2))
42)
| 5,372 | Common Lisp | .lisp | 155 | 31.922581 | 78 | 0.7052 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 01bd1677b2ec8d9146ae28c87a0e8cadd4f56246f09a22fe3fae0990679ad02d | 42,994 | [
66733,
232254,
459991
] |
42,995 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/package.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; package.lisp --- CFFI-TESTS package definition.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cl-user)
(defpackage #:cffi-tests
(:use #:cl #:cffi #:cffi-sys #:regression-test)
(:export #:do-tests #:run-cffi-tests #:run-all-cffi-tests)
(:shadow #:deftest))
| 1,463 | Common Lisp | .lisp | 31 | 45.935484 | 70 | 0.735664 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | c5d12e1b243c0ef739c8228fbf43060adec55839ef857f4cac80d360cf961a6d | 42,995 | [
12637,
42889
] |
42,996 | defcfun.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/defcfun.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; defcfun.lisp --- Tests function definition and calling.
;;;
;;; Copyright (C) 2005-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(deftest defcfun.parse-name-and-options.1
(multiple-value-bind (lisp-name foreign-name)
(let ((*package* (find-package '#:cffi-tests)))
(cffi::parse-name-and-options "foo_bar"))
(list lisp-name foreign-name))
(foo-bar "foo_bar"))
(deftest defcfun.parse-name-and-options.2
(multiple-value-bind (lisp-name foreign-name)
(let ((*package* (find-package '#:cffi-tests)))
(cffi::parse-name-and-options "foo_bar" t))
(list lisp-name foreign-name))
(*foo-bar* "foo_bar"))
(deftest defcfun.parse-name-and-options.3
(multiple-value-bind (lisp-name foreign-name)
(cffi::parse-name-and-options 'foo-bar)
(list lisp-name foreign-name))
(foo-bar "foo_bar"))
(deftest defcfun.parse-name-and-options.4
(multiple-value-bind (lisp-name foreign-name)
(cffi::parse-name-and-options '*foo-bar* t)
(list lisp-name foreign-name))
(*foo-bar* "foo_bar"))
(deftest defcfun.parse-name-and-options.5
(multiple-value-bind (lisp-name foreign-name)
(cffi::parse-name-and-options '("foo_bar" foo-baz))
(list lisp-name foreign-name))
(foo-baz "foo_bar"))
(deftest defcfun.parse-name-and-options.6
(multiple-value-bind (lisp-name foreign-name)
(cffi::parse-name-and-options '("foo_bar" *foo-baz*) t)
(list lisp-name foreign-name))
(*foo-baz* "foo_bar"))
(deftest defcfun.parse-name-and-options.7
(multiple-value-bind (lisp-name foreign-name)
(cffi::parse-name-and-options '(foo-baz "foo_bar"))
(list lisp-name foreign-name))
(foo-baz "foo_bar"))
(deftest defcfun.parse-name-and-options.8
(multiple-value-bind (lisp-name foreign-name)
(cffi::parse-name-and-options '(*foo-baz* "foo_bar") t)
(list lisp-name foreign-name))
(*foo-baz* "foo_bar"))
;;;# Name translation
(deftest translate-underscore-separated-name.to-symbol
(let ((*package* (find-package '#:cffi-tests)))
(translate-underscore-separated-name "some_name_with_underscores"))
some-name-with-underscores)
(deftest translate-underscore-separated-name.to-string
(translate-underscore-separated-name 'some-name-with-underscores)
"some_name_with_underscores")
(deftest translate-camelcase-name.to-symbol
(let ((*package* (find-package '#:cffi-tests)))
(translate-camelcase-name "someXmlFunction"))
some-xml-function)
(deftest translate-camelcase-name.to-string
(translate-camelcase-name 'some-xml-function)
"someXmlFunction")
(deftest translate-camelcase-name.to-string-upper
(translate-camelcase-name 'some-xml-function :upper-initial-p t)
"SomeXmlFunction")
(deftest translate-camelcase-name.to-symbol-special
(let ((*package* (find-package '#:cffi-tests)))
(translate-camelcase-name "someXMLFunction" :special-words '("XML")))
some-xml-function)
(deftest translate-camelcase-name.to-string-special
(translate-camelcase-name 'some-xml-function :special-words '("XML"))
"someXMLFunction")
(deftest translate-name-from-foreign.function
(let ((*package* (find-package '#:cffi-tests)))
(translate-name-from-foreign "some_xml_name" *package*))
some-xml-name)
(deftest translate-name-from-foreign.var
(let ((*package* (find-package '#:cffi-tests)))
(translate-name-from-foreign "some_xml_name" *package* t))
*some-xml-name*)
(deftest translate-name-to-foreign.function
(translate-name-to-foreign 'some-xml-name *package*)
"some_xml_name")
(deftest translate-name-to-foreign.var
(translate-name-to-foreign '*some-xml-name* *package* t)
"some_xml_name")
;;;# Calling with built-in c types
;;;
;;; Tests calling standard C library functions both passing
;;; and returning each built-in type. (adapted from funcall.lisp)
(defcfun "toupper" :char
"toupper docstring"
(char :char))
(deftest defcfun.char
(toupper (char-code #\a))
#.(char-code #\A))
(deftest defcfun.docstring
(documentation 'toupper 'function)
"toupper docstring")
(defcfun ("abs" c-abs) :int
(n :int))
(deftest defcfun.int
(c-abs -100)
100)
(defcfun "labs" :long
(n :long))
(deftest defcfun.long
(labs -131072)
131072)
#-cffi-features:no-long-long
(progn
(defcfun "my_llabs" :long-long
(n :long-long))
(deftest defcfun.long-long
(my-llabs -9223372036854775807)
9223372036854775807)
(defcfun "ullong" :unsigned-long-long
(n :unsigned-long-long))
#+allegro ; lp#914500
(pushnew 'defcfun.unsigned-long-long rtest::*expected-failures*)
(deftest defcfun.unsigned-long-long
(let ((ullong-max (1- (expt 2 (* 8 (foreign-type-size :unsigned-long-long))))))
(eql ullong-max (ullong ullong-max)))
t))
(defcfun "my_sqrtf" :float
(n :float))
(deftest defcfun.float
(my-sqrtf 16.0)
4.0)
(defcfun ("sqrt" c-sqrt) :double
(n :double))
(deftest defcfun.double
(c-sqrt 36.0d0)
6.0d0)
#+(and scl long-float)
(defcfun ("sqrtl" c-sqrtl) :long-double
(n :long-double))
#+(and scl long-float)
(deftest defcfun.long-double
(c-sqrtl 36.0l0)
6.0l0)
(defcfun "strlen" :int
(n :string))
(deftest defcfun.string.1
(strlen "Hello")
5)
(defcfun "strcpy" (:pointer :char)
(dest (:pointer :char))
(src :string))
(defcfun "strcat" (:pointer :char)
(dest (:pointer :char))
(src :string))
(deftest defcfun.string.2
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(strcpy s "Hello")
(strcat s ", world!"))
"Hello, world!")
(defcfun "strerror" :string
(n :int))
(deftest defcfun.string.3
(typep (strerror 1) 'string)
t)
;;; Regression test. Allegro would warn on direct calls to
;;; functions with no arguments.
;;;
;;; Also, let's check if void functions will return NIL.
;;;
;;; Check if a docstring without arguments doesn't cause problems.
(defcfun "noargs" :int
"docstring")
(deftest defcfun.noargs
(noargs)
42)
(defcfun "noop" :void)
#+(or allegro openmcl ecl) (pushnew 'defcfun.noop rtest::*expected-failures*)
(deftest defcfun.noop
(noop)
#|no values|#)
;;;# Calling varargs functions
(defcfun "sum_double_arbitrary" :double (n :int) &rest)
(deftest defcfun.varargs.nostdlib
(sum-double-arbitrary
26
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0)
81.64d0)
(defcfun "sprintf" :int
"sprintf docstring"
(str (:pointer :char))
(control :string)
&rest)
;;; CLISP and ABCL discard macro docstrings.
#+(or clisp abcl)
(pushnew 'defcfun.varargs.docstrings rtest::*expected-failures*)
(deftest defcfun.varargs.docstrings
(documentation 'sprintf 'function)
"sprintf docstring")
(deftest defcfun.varargs.char
(with-foreign-pointer-as-string (s 100)
(sprintf s "%c" :char 65))
"A")
(deftest defcfun.varargs.short
(with-foreign-pointer-as-string (s 100)
(sprintf s "%d" :short 42))
"42")
(deftest defcfun.varargs.int
(with-foreign-pointer-as-string (s 100)
(sprintf s "%d" :int 1000))
"1000")
(deftest defcfun.varargs.long
(with-foreign-pointer-as-string (s 100)
(sprintf s "%ld" :long 131072))
"131072")
(deftest defcfun.varargs.float
(with-foreign-pointer-as-string (s 100)
(sprintf s "%.0f" :float (* pi 100)))
"314")
(deftest defcfun.varargs.double
(with-foreign-pointer-as-string (s 100)
(sprintf s "%.0f" :double (* pi 100d0)))
"314")
#+(and scl long-float)
(deftest defcfun.varargs.long-double
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(sprintf s "%.0Lf" :long-double (* pi 100)))
"314")
(deftest defcfun.varargs.string
(with-foreign-pointer-as-string (s 100)
(sprintf s "%s, %s!" :string "Hello" :string "world"))
"Hello, world!")
;;; (let ((rettype (find-type :long))
;;; (arg-types (n-random-types-no-ll 127)))
;;; (c-function rettype arg-types)
;;; (gen-function-test rettype arg-types))
#+(and (not ecl)
#.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:and) '(:or)))
(progn
(defcfun "sum_127_no_ll" :long
(a1 :long) (a2 :unsigned-long) (a3 :short) (a4 :unsigned-short) (a5 :float)
(a6 :double) (a7 :unsigned-long) (a8 :float) (a9 :unsigned-char)
(a10 :unsigned-short) (a11 :short) (a12 :unsigned-long) (a13 :double)
(a14 :long) (a15 :unsigned-int) (a16 :pointer) (a17 :unsigned-int)
(a18 :unsigned-short) (a19 :long) (a20 :float) (a21 :pointer) (a22 :float)
(a23 :int) (a24 :int) (a25 :unsigned-short) (a26 :long) (a27 :long)
(a28 :double) (a29 :unsigned-char) (a30 :unsigned-int) (a31 :unsigned-int)
(a32 :int) (a33 :unsigned-short) (a34 :unsigned-int) (a35 :pointer)
(a36 :double) (a37 :double) (a38 :long) (a39 :short) (a40 :unsigned-short)
(a41 :long) (a42 :char) (a43 :long) (a44 :unsigned-short) (a45 :pointer)
(a46 :int) (a47 :unsigned-int) (a48 :double) (a49 :unsigned-char)
(a50 :unsigned-char) (a51 :float) (a52 :int) (a53 :unsigned-short)
(a54 :double) (a55 :short) (a56 :unsigned-char) (a57 :unsigned-long)
(a58 :float) (a59 :float) (a60 :float) (a61 :pointer) (a62 :pointer)
(a63 :unsigned-int) (a64 :unsigned-long) (a65 :char) (a66 :short)
(a67 :unsigned-short) (a68 :unsigned-long) (a69 :pointer) (a70 :float)
(a71 :double) (a72 :long) (a73 :unsigned-long) (a74 :short)
(a75 :unsigned-int) (a76 :unsigned-short) (a77 :int) (a78 :unsigned-short)
(a79 :char) (a80 :double) (a81 :short) (a82 :unsigned-char) (a83 :float)
(a84 :char) (a85 :int) (a86 :double) (a87 :unsigned-char) (a88 :int)
(a89 :unsigned-long) (a90 :double) (a91 :short) (a92 :short)
(a93 :unsigned-int) (a94 :unsigned-char) (a95 :float) (a96 :long)
(a97 :float) (a98 :long) (a99 :long) (a100 :int) (a101 :int)
(a102 :unsigned-int) (a103 :char) (a104 :char) (a105 :unsigned-short)
(a106 :unsigned-int) (a107 :unsigned-short) (a108 :unsigned-short)
(a109 :int) (a110 :long) (a111 :char) (a112 :double) (a113 :unsigned-int)
(a114 :char) (a115 :short) (a116 :unsigned-long) (a117 :unsigned-int)
(a118 :short) (a119 :unsigned-char) (a120 :float) (a121 :pointer)
(a122 :double) (a123 :int) (a124 :long) (a125 :char) (a126 :unsigned-short)
(a127 :float))
(deftest defcfun.bff.1
(sum-127-no-ll
1442906394 520035521 -4715 50335 -13557.0 -30892.0d0 24061483 -23737.0
22 2348 4986 104895680 8073.0d0 -571698147 102484400
(make-pointer 507907275) 12733353 7824 -1275845284 13602.0
(make-pointer 286958390) -8042.0 -773681663 -1289932452 31199 -154985357
-170994216 16845.0d0 177 218969221 2794350893 6068863 26327 127699339
(make-pointer 184352771) 18512.0d0 -12345.0d0 -179853040 -19981 37268
-792845398 116 -1084653028 50494 (make-pointer 2105239646) -1710519651
1557813312 2839.0d0 90 180 30580.0 -532698978 8623 9537.0d0 -10882 54
184357206 14929.0 -8190.0 -25615.0 (make-pointer 235310526)
(make-pointer 220476977) 7476055 1576685 -117 -11781 31479 23282640
(make-pointer 8627281) -17834.0 10391.0d0 -1904504370 114393659 -17062
637873619 16078 -891210259 8107 0 760.0d0 -21268 104 14133.0 10
588598141 310.0d0 20 1351785456 16159552 -10121.0d0 -25866 24821
68232851 60 -24132.0 -1660411658 13387.0 -786516668 -499825680
-1128144619 111849719 2746091587 -2 95 14488 326328135 64781 18204
150716680 -703859275 103 16809.0d0 852235610 -43 21088 242356110
324325428 -22380 23 24814.0 (make-pointer 40362014) -14322.0d0
-1864262539 523684371 -21 49995 -29175.0)
796447501))
;;; (let ((rettype (find-type :long-long))
;;; (arg-types (n-random-types 127)))
;;; (c-function rettype arg-types)
;;; (gen-function-test rettype arg-types))
#-(or ecl cffi-sys::no-long-long
#.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:or) '(:and)))
(progn
(defcfun "sum_127" :long-long
(a1 :pointer) (a2 :pointer) (a3 :float) (a4 :unsigned-long) (a5 :pointer)
(a6 :long-long) (a7 :double) (a8 :double) (a9 :unsigned-short) (a10 :int)
(a11 :long-long) (a12 :long) (a13 :short) (a14 :unsigned-int) (a15 :long)
(a16 :unsigned-char) (a17 :int) (a18 :double) (a19 :short) (a20 :short)
(a21 :long-long) (a22 :unsigned-int) (a23 :unsigned-short) (a24 :short)
(a25 :pointer) (a26 :short) (a27 :unsigned-short) (a28 :unsigned-short)
(a29 :int) (a30 :long-long) (a31 :pointer) (a32 :int) (a33 :unsigned-long)
(a34 :unsigned-long) (a35 :pointer) (a36 :unsigned-long-long) (a37 :float)
(a38 :int) (a39 :short) (a40 :pointer) (a41 :unsigned-long-long)
(a42 :long-long) (a43 :unsigned-long) (a44 :unsigned-long)
(a45 :unsigned-long-long) (a46 :unsigned-long) (a47 :char) (a48 :double)
(a49 :long) (a50 :unsigned-int) (a51 :int) (a52 :short) (a53 :pointer)
(a54 :long) (a55 :unsigned-long-long) (a56 :int) (a57 :unsigned-short)
(a58 :unsigned-long-long) (a59 :float) (a60 :pointer) (a61 :float)
(a62 :unsigned-short) (a63 :unsigned-long) (a64 :float) (a65 :unsigned-int)
(a66 :unsigned-long-long) (a67 :pointer) (a68 :double)
(a69 :unsigned-long-long) (a70 :double) (a71 :double) (a72 :long-long)
(a73 :pointer) (a74 :unsigned-short) (a75 :long) (a76 :pointer) (a77 :short)
(a78 :double) (a79 :long) (a80 :unsigned-char) (a81 :pointer)
(a82 :unsigned-char) (a83 :long) (a84 :double) (a85 :pointer) (a86 :int)
(a87 :double) (a88 :unsigned-char) (a89 :double) (a90 :short) (a91 :long)
(a92 :int) (a93 :long) (a94 :double) (a95 :unsigned-short)
(a96 :unsigned-int) (a97 :int) (a98 :char) (a99 :long-long) (a100 :double)
(a101 :float) (a102 :unsigned-long) (a103 :short) (a104 :pointer)
(a105 :float) (a106 :long-long) (a107 :int) (a108 :long-long)
(a109 :long-long) (a110 :double) (a111 :unsigned-long-long) (a112 :double)
(a113 :unsigned-long) (a114 :char) (a115 :char) (a116 :unsigned-long)
(a117 :short) (a118 :unsigned-char) (a119 :unsigned-char) (a120 :int)
(a121 :int) (a122 :float) (a123 :unsigned-char) (a124 :unsigned-char)
(a125 :double) (a126 :unsigned-long-long) (a127 :char))
#+(and sbcl x86) (push 'defcfun.bff.2 rtest::*expected-failures*)
(deftest defcfun.bff.2
(sum-127
(make-pointer 2746181372) (make-pointer 177623060) -32334.0 3158055028
(make-pointer 242315091) 4288001754991016425 -21047.0d0 287.0d0 18722
243379286 -8677366518541007140 581399424 -13872 4240394881 1353358999
226 969197676 -26207.0d0 6484 11150 1241680089902988480 106068320 61865
2253 (make-pointer 866809333) -31613 35616 11715 1393601698
8940888681199591845 (make-pointer 1524606024) 805638893 3315410736
3432596795 (make-pointer 1490355706) 696175657106383698 -25438.0
1294381547 26724 (make-pointer 3196569545) 2506913373410783697
-4405955718732597856 4075932032 3224670123 2183829215657835866
1318320964 -22 -3786.0d0 -2017024146 1579225515 -626617701 -1456
(make-pointer 3561444187) 395687791 1968033632506257320 -1847773261
48853 142937735275669133 -17974.0 (make-pointer 2791749948) -14140.0
2707 3691328585 3306.0 1132012981 303633191773289330
(make-pointer 981183954) 9114.0d0 8664374572369470 -19013.0d0
-10288.0d0 -3679345119891954339 (make-pointer 3538786709) 23761
-154264605 (make-pointer 2694396308) 7023 997.0d0 1009561368 241
(make-pointer 2612292671) 48 1431872408 -32675.0d0
(make-pointer 1587599336) 958916472 -9857.0d0 111 -14370.0d0 -7308
-967514912 488790941 2146978095 -24111.0d0 13711 86681861 717987770
111 1013402998690933877 17234.0d0 -8772.0 3959216275 -8711
(make-pointer 3142780851) 9480.0 -3820453146461186120 1616574376
-3336232268263990050 -1906114671562979758 -27925.0d0 9695970875869913114
27033.0d0 1096518219 -12 104 3392025403 -27911 60 89 509297051
-533066551 29158.0 110 54 -9802.0d0 593950442165910888 -79)
7758614658402721936))
;;; regression test: defining an undefined foreign function should only
;;; throw some sort of warning, not signal an error.
#+(or cmucl (and sbcl win32))
(pushnew 'defcfun.undefined rtest::*expected-failures*)
(deftest defcfun.undefined
(progn
(eval '(defcfun ("undefined_foreign_function" undefined-foreign-function) :void))
(compile 'undefined-foreign-function)
t)
t)
;;; Test whether all doubles are passed correctly. On some platforms, eg.
;;; darwin/ppc, some are passed on registers others on the stack.
(defcfun "sum_double26" :double
(a1 :double) (a2 :double) (a3 :double) (a4 :double) (a5 :double)
(a6 :double) (a7 :double) (a8 :double) (a9 :double) (a10 :double)
(a11 :double) (a12 :double) (a13 :double) (a14 :double) (a15 :double)
(a16 :double) (a17 :double) (a18 :double) (a19 :double) (a20 :double)
(a21 :double) (a22 :double) (a23 :double) (a24 :double) (a25 :double)
(a26 :double))
(deftest defcfun.double26
(sum-double26 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0
3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0
3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0
3.14d0 3.14d0 3.14d0 3.14d0 3.14d0)
81.64d0)
;;; Same as above for floats.
(defcfun "sum_float26" :float
(a1 :float) (a2 :float) (a3 :float) (a4 :float) (a5 :float)
(a6 :float) (a7 :float) (a8 :float) (a9 :float) (a10 :float)
(a11 :float) (a12 :float) (a13 :float) (a14 :float) (a15 :float)
(a16 :float) (a17 :float) (a18 :float) (a19 :float) (a20 :float)
(a21 :float) (a22 :float) (a23 :float) (a24 :float) (a25 :float)
(a26 :float))
(deftest defcfun.float26
(sum-float26 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0
5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0)
130.0)
;;;# Namespaces
#-cffi-sys::flat-namespace
(progn
(defcfun ("ns_function" ns-fun1 :library libtest) :boolean)
(defcfun ("ns_function" ns-fun2 :library libtest2) :boolean)
(deftest defcfun.namespace.1
(values (ns-fun1) (ns-fun2))
t nil))
;;;# stdcall
#+(and x86 windows (not cffi-sys::no-stdcall))
(progn
(defcfun ("stdcall_fun@12" stdcall-fun :convention :stdcall) :int
(a :int)
(b :int)
(c :int))
(deftest defcfun.stdcall.1
(loop repeat 100 do (stdcall-fun 1 2 3)
finally (return (stdcall-fun 1 2 3)))
6))
| 19,913 | Common Lisp | .lisp | 440 | 40.934091 | 87 | 0.683852 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 45a701e7db018987182934ce886677f2e12038ba207364abcf8ba87d02217044 | 42,996 | [
383194
] |
42,997 | callbacks.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/callbacks.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; callbacks.lisp --- Tests on callbacks.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(defcfun "expect_char_sum" :int (f :pointer))
(defcfun "expect_unsigned_char_sum" :int (f :pointer))
(defcfun "expect_short_sum" :int (f :pointer))
(defcfun "expect_unsigned_short_sum" :int (f :pointer))
(defcfun "expect_int_sum" :int (f :pointer))
(defcfun "expect_unsigned_int_sum" :int (f :pointer))
(defcfun "expect_long_sum" :int (f :pointer))
(defcfun "expect_unsigned_long_sum" :int (f :pointer))
(defcfun "expect_float_sum" :int (f :pointer))
(defcfun "expect_double_sum" :int (f :pointer))
(defcfun "expect_pointer_sum" :int (f :pointer))
(defcfun "expect_strcat" :int (f :pointer))
#-cffi-sys::no-long-long
(progn
(defcfun "expect_long_long_sum" :int (f :pointer))
(defcfun "expect_unsigned_long_long_sum" :int (f :pointer)))
#+(and scl long-float)
(defcfun "expect_long_double_sum" :int (f :pointer))
(defcallback sum-char :char ((a :char) (b :char))
"Test if the named block is present and the docstring too."
;(format t "~%}}} a: ~A, b: ~A {{{~%" a b)
(return-from sum-char (+ a b)))
(defcallback sum-unsigned-char :unsigned-char
((a :unsigned-char) (b :unsigned-char))
;(format t "~%}}} a: ~A, b: ~A {{{~%" a b)
(+ a b))
(defcallback sum-short :short ((a :short) (b :short))
;(format t "~%}}} a: ~A, b: ~A {{{~%" a b)
(+ a b))
(defcallback sum-unsigned-short :unsigned-short
((a :unsigned-short) (b :unsigned-short))
;(format t "~%}}} a: ~A, b: ~A {{{~%" a b)
(+ a b))
(defcallback sum-int :int ((a :int) (b :int))
(+ a b))
(defcallback sum-unsigned-int :unsigned-int
((a :unsigned-int) (b :unsigned-int))
(+ a b))
(defcallback sum-long :long ((a :long) (b :long))
(+ a b))
(defcallback sum-unsigned-long :unsigned-long
((a :unsigned-long) (b :unsigned-long))
(+ a b))
#-cffi-sys::no-long-long
(progn
(defcallback sum-long-long :long-long
((a :long-long) (b :long-long))
(+ a b))
(defcallback sum-unsigned-long-long :unsigned-long-long
((a :unsigned-long-long) (b :unsigned-long-long))
(+ a b)))
(defcallback sum-float :float ((a :float) (b :float))
;(format t "~%}}} a: ~A, b: ~A {{{~%" a b)
(+ a b))
(defcallback sum-double :double ((a :double) (b :double))
;(format t "~%}}} a: ~A, b: ~A {{{~%" a b)
(+ a b))
#+(and scl long-float)
(defcallback sum-long-double :long-double ((a :long-double) (b :long-double))
;(format t "~%}}} a: ~A, b: ~A {{{~%" a b)
(+ a b))
(defcallback sum-pointer :pointer ((ptr :pointer) (offset :int))
(inc-pointer ptr offset))
(defcallback lisp-strcat :string ((a :string) (b :string))
(concatenate 'string a b))
(deftest callbacks.char
(expect-char-sum (get-callback 'sum-char))
1)
(deftest callbacks.unsigned-char
(expect-unsigned-char-sum (get-callback 'sum-unsigned-char))
1)
(deftest callbacks.short
(expect-short-sum (callback sum-short))
1)
(deftest callbacks.unsigned-short
(expect-unsigned-short-sum (callback sum-unsigned-short))
1)
(deftest callbacks.int
(expect-int-sum (callback sum-int))
1)
(deftest callbacks.unsigned-int
(expect-unsigned-int-sum (callback sum-unsigned-int))
1)
(deftest callbacks.long
(expect-long-sum (callback sum-long))
1)
(deftest callbacks.unsigned-long
(expect-unsigned-long-sum (callback sum-unsigned-long))
1)
#-cffi-sys::no-long-long
(progn
(deftest (callbacks.long-long :expected-to-fail (alexandria:featurep :openmcl))
(expect-long-long-sum (callback sum-long-long))
1)
(deftest callbacks.unsigned-long-long
(expect-unsigned-long-long-sum (callback sum-unsigned-long-long))
1))
(deftest callbacks.float
(expect-float-sum (callback sum-float))
1)
(deftest callbacks.double
(expect-double-sum (callback sum-double))
1)
#+(and scl long-float)
(deftest callbacks.long-double
(expect-long-double-sum (callback sum-long-double))
1)
(deftest callbacks.pointer
(expect-pointer-sum (callback sum-pointer))
1)
(deftest callbacks.string
(expect-strcat (callback lisp-strcat))
1)
#-cffi-sys::no-foreign-funcall
(defcallback return-a-string-not-nil :string ()
"abc")
#-cffi-sys::no-foreign-funcall
(deftest callbacks.string-not-docstring
(foreign-funcall-pointer (callback return-a-string-not-nil) () :string)
"abc")
(defcallback check-for-nil :boolean ((pointer :pointer))
(null pointer))
#-cffi-sys::no-foreign-funcall
(deftest callbacks.nil-for-null
(foreign-funcall-pointer (callback check-for-nil) nil
:pointer (null-pointer) :boolean)
nil)
;;; This one tests mem-aref too.
(defcfun "qsort" :void
(base :pointer)
(nmemb :int)
(size :int)
(fun-compar :pointer))
(defcallback < :int ((a :pointer) (b :pointer))
(let ((x (mem-ref a :int))
(y (mem-ref b :int)))
(cond ((> x y) 1)
((< x y) -1)
(t 0))))
(deftest callbacks.qsort
(with-foreign-object (array :int 10)
;; Initialize array.
(loop for i from 0 and n in '(7 2 10 4 3 5 1 6 9 8)
do (setf (mem-aref array :int i) n))
;; Sort it.
(qsort array 10 (foreign-type-size :int) (callback <))
;; Return it as a list.
(loop for i from 0 below 10
collect (mem-aref array :int i)))
(1 2 3 4 5 6 7 8 9 10))
;;; void callback
(defparameter *int* -1)
(defcfun "pass_int_ref" :void (f :pointer))
;;; CMUCL chokes on this one for some reason.
#-(and darwin cmucl)
(defcallback read-int-from-pointer :void ((a :pointer))
(setq *int* (mem-ref a :int)))
#+(and darwin cmucl)
(pushnew 'callbacks.void rtest::*expected-failures*)
(deftest callbacks.void
(progn
(pass-int-ref (callback read-int-from-pointer))
*int*)
1984)
;;; test funcalling of a callback and also declarations inside
;;; callbacks.
#-cffi-sys::no-foreign-funcall
(progn
(defcallback sum-2 :int ((a :int) (b :int) (c :int))
(declare (ignore c))
(+ a b))
(deftest callbacks.funcall.1
(foreign-funcall-pointer (callback sum-2) () :int 2 :int 3 :int 1 :int)
5)
(defctype foo-float :float)
(defcallback sum-2f foo-float
((a foo-float) (b foo-float) (c foo-float) (d foo-float) (e foo-float))
"This one ignores the middle 3 arguments."
(declare (ignore b c))
(declare (ignore d))
(+ a e))
(deftest callbacks.funcall.2
(foreign-funcall-pointer (callback sum-2f) () foo-float 1.0 foo-float 2.0
foo-float 3.0 foo-float 4.0 foo-float 5.0
foo-float)
6.0))
;;; (cb-test :no-long-long t)
(defcfun "call_sum_127_no_ll" :long (cb :pointer))
;;; CMUCL and CCL choke on this one.
#-(or cmucl clozure
#.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:or) '(:and)))
(defcallback sum-127-no-ll :long
((a1 :unsigned-long) (a2 :pointer) (a3 :long) (a4 :double)
(a5 :unsigned-long) (a6 :float) (a7 :float) (a8 :int) (a9 :unsigned-int)
(a10 :double) (a11 :double) (a12 :double) (a13 :pointer)
(a14 :unsigned-short) (a15 :unsigned-short) (a16 :pointer) (a17 :long)
(a18 :long) (a19 :int) (a20 :short) (a21 :unsigned-short)
(a22 :unsigned-short) (a23 :char) (a24 :long) (a25 :pointer) (a26 :pointer)
(a27 :char) (a28 :unsigned-char) (a29 :unsigned-long) (a30 :short)
(a31 :int) (a32 :int) (a33 :unsigned-char) (a34 :short) (a35 :long)
(a36 :long) (a37 :pointer) (a38 :unsigned-short) (a39 :char) (a40 :double)
(a41 :unsigned-short) (a42 :pointer) (a43 :short) (a44 :unsigned-long)
(a45 :unsigned-short) (a46 :float) (a47 :unsigned-char) (a48 :short)
(a49 :float) (a50 :short) (a51 :char) (a52 :unsigned-long)
(a53 :unsigned-long) (a54 :char) (a55 :float) (a56 :long) (a57 :pointer)
(a58 :short) (a59 :float) (a60 :unsigned-int) (a61 :float)
(a62 :unsigned-int) (a63 :double) (a64 :unsigned-int) (a65 :unsigned-char)
(a66 :int) (a67 :long) (a68 :char) (a69 :short) (a70 :double) (a71 :int)
(a72 :pointer) (a73 :char) (a74 :unsigned-short) (a75 :pointer)
(a76 :unsigned-short) (a77 :pointer) (a78 :unsigned-long) (a79 :double)
(a80 :pointer) (a81 :long) (a82 :float) (a83 :unsigned-short)
(a84 :unsigned-short) (a85 :pointer) (a86 :float) (a87 :int)
(a88 :unsigned-int) (a89 :double) (a90 :float) (a91 :long) (a92 :pointer)
(a93 :unsigned-short) (a94 :float) (a95 :unsigned-char) (a96 :unsigned-char)
(a97 :float) (a98 :unsigned-int) (a99 :float) (a100 :unsigned-short)
(a101 :double) (a102 :unsigned-short) (a103 :unsigned-long)
(a104 :unsigned-int) (a105 :unsigned-long) (a106 :pointer)
(a107 :unsigned-char) (a108 :char) (a109 :char) (a110 :unsigned-short)
(a111 :unsigned-long) (a112 :float) (a113 :short) (a114 :pointer)
(a115 :long) (a116 :unsigned-short) (a117 :short) (a118 :double)
(a119 :short) (a120 :int) (a121 :char) (a122 :unsigned-long) (a123 :long)
(a124 :int) (a125 :pointer) (a126 :double) (a127 :unsigned-char))
(let ((args (list a1 (pointer-address a2) a3 (floor a4) a5 (floor a6)
(floor a7) a8 a9 (floor a10) (floor a11) (floor a12)
(pointer-address a13) a14 a15 (pointer-address a16) a17 a18
a19 a20 a21 a22 a23 a24 (pointer-address a25)
(pointer-address a26) a27 a28 a29 a30 a31 a32 a33 a34 a35
a36 (pointer-address a37) a38 a39 (floor a40) a41
(pointer-address a42) a43 a44 a45 (floor a46) a47 a48
(floor a49) a50 a51 a52 a53 a54 (floor a55) a56
(pointer-address a57) a58 (floor a59) a60 (floor a61) a62
(floor a63) a64 a65 a66 a67 a68 a69 (floor a70) a71
(pointer-address a72) a73 a74 (pointer-address a75) a76
(pointer-address a77) a78 (floor a79) (pointer-address a80)
a81 (floor a82) a83 a84 (pointer-address a85) (floor a86)
a87 a88 (floor a89) (floor a90) a91 (pointer-address a92)
a93 (floor a94) a95 a96 (floor a97) a98 (floor a99) a100
(floor a101) a102 a103 a104 a105 (pointer-address a106) a107
a108 a109 a110 a111 (floor a112) a113 (pointer-address a114)
a115 a116 a117 (floor a118) a119 a120 a121 a122 a123 a124
(pointer-address a125) (floor a126) a127)))
#-(and)
(loop for i from 1 and arg in args do
(format t "a~A: ~A~%" i arg))
(reduce #'+ args)))
#+(or openmcl cmucl (and darwin (or allegro lispworks)))
(push 'callbacks.bff.1 regression-test::*expected-failures*)
#+#.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:and) '(:or))
(deftest callbacks.bff.1
(call-sum-127-no-ll (callback sum-127-no-ll))
2008547941)
;;; (cb-test)
#-(or cffi-sys::no-long-long
#.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(or) '(and)))
(progn
(defcfun "call_sum_127" :long-long (cb :pointer))
;;; CMUCL and CCL choke on this one.
#-(or cmucl clozure)
(defcallback sum-127 :long-long
((a1 :short) (a2 :char) (a3 :pointer) (a4 :float) (a5 :long) (a6 :double)
(a7 :unsigned-long-long) (a8 :unsigned-short) (a9 :unsigned-char)
(a10 :char) (a11 :char) (a12 :unsigned-short) (a13 :unsigned-long-long)
(a14 :unsigned-short) (a15 :long-long) (a16 :unsigned-short)
(a17 :unsigned-long-long) (a18 :unsigned-char) (a19 :unsigned-char)
(a20 :unsigned-long-long) (a21 :long-long) (a22 :char) (a23 :float)
(a24 :unsigned-int) (a25 :float) (a26 :float) (a27 :unsigned-int)
(a28 :float) (a29 :char) (a30 :unsigned-char) (a31 :long) (a32 :long-long)
(a33 :unsigned-char) (a34 :double) (a35 :long) (a36 :double)
(a37 :unsigned-int) (a38 :unsigned-short) (a39 :long-long)
(a40 :unsigned-int) (a41 :int) (a42 :unsigned-long-long) (a43 :long)
(a44 :short) (a45 :unsigned-int) (a46 :unsigned-int)
(a47 :unsigned-long-long) (a48 :unsigned-int) (a49 :long) (a50 :pointer)
(a51 :unsigned-char) (a52 :char) (a53 :long-long) (a54 :unsigned-short)
(a55 :unsigned-int) (a56 :float) (a57 :unsigned-char) (a58 :unsigned-long)
(a59 :long-long) (a60 :float) (a61 :long) (a62 :float) (a63 :int)
(a64 :float) (a65 :unsigned-short) (a66 :unsigned-long-long) (a67 :short)
(a68 :unsigned-long) (a69 :long) (a70 :char) (a71 :unsigned-short)
(a72 :long-long) (a73 :short) (a74 :double) (a75 :pointer)
(a76 :unsigned-int) (a77 :char) (a78 :unsigned-int) (a79 :pointer)
(a80 :pointer) (a81 :unsigned-char) (a82 :pointer) (a83 :unsigned-short)
(a84 :unsigned-char) (a85 :long) (a86 :pointer) (a87 :char) (a88 :long)
(a89 :unsigned-short) (a90 :unsigned-char) (a91 :double)
(a92 :unsigned-long-long) (a93 :unsigned-short) (a94 :unsigned-short)
(a95 :unsigned-int) (a96 :long) (a97 :char) (a98 :long) (a99 :char)
(a100 :short) (a101 :unsigned-short) (a102 :unsigned-long)
(a103 :unsigned-long) (a104 :short) (a105 :long-long) (a106 :long-long)
(a107 :long-long) (a108 :double) (a109 :unsigned-short)
(a110 :unsigned-char) (a111 :short) (a112 :unsigned-char) (a113 :long)
(a114 :long-long) (a115 :unsigned-long-long) (a116 :unsigned-int)
(a117 :unsigned-long) (a118 :unsigned-char) (a119 :long-long)
(a120 :unsigned-char) (a121 :unsigned-long-long) (a122 :double)
(a123 :unsigned-char) (a124 :long-long) (a125 :unsigned-char)
(a126 :char) (a127 :long-long))
(+ a1 a2 (pointer-address a3) (values (floor a4)) a5 (values (floor a6))
a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 a21 a22
(values (floor a23)) a24 (values (floor a25)) (values (floor a26))
a27 (values (floor a28)) a29 a30 a31 a32 a33 (values (floor a34))
a35 (values (floor a36)) a37 a38 a39 a40 a41 a42 a43 a44 a45 a46 a47
a48 a49 (pointer-address a50) a51 a52 a53 a54 a55 (values (floor a56))
a57 a58 a59 (values (floor a60)) a61 (values (floor a62)) a63
(values (floor a64)) a65 a66 a67 a68 a69 a70 a71 a72 a73
(values (floor a74)) (pointer-address a75) a76 a77 a78
(pointer-address a79) (pointer-address a80) a81 (pointer-address a82)
a83 a84 a85 (pointer-address a86) a87 a88 a89 a90 (values (floor a91))
a92 a93 a94 a95 a96 a97 a98 a99 a100 a101 a102 a103 a104 a105 a106 a107
(values (floor a108)) a109 a110 a111 a112 a113 a114 a115 a116 a117 a118
a119 a120 a121 (values (floor a122)) a123 a124 a125 a126 a127))
#+(or openmcl cmucl)
(push 'callbacks.bff.2 rtest::*expected-failures*)
(deftest callbacks.bff.2
(call-sum-127 (callback sum-127))
8166570665645582011))
;;; regression test: (callback non-existant-callback) should throw an error
(deftest callbacks.non-existant
(not (null (nth-value 1 (ignore-errors (callback doesnt-exist)))))
t)
;;; Handling many arguments of type double. Many lisps (used to) fail
;;; this one on darwin/ppc. This test might be bogus due to floating
;;; point arithmetic rounding errors.
;;;
;;; CMUCL chokes on this one.
#-(and darwin cmucl)
(defcallback double26 :double
((a1 :double) (a2 :double) (a3 :double) (a4 :double) (a5 :double)
(a6 :double) (a7 :double) (a8 :double) (a9 :double) (a10 :double)
(a11 :double) (a12 :double) (a13 :double) (a14 :double) (a15 :double)
(a16 :double) (a17 :double) (a18 :double) (a19 :double) (a20 :double)
(a21 :double) (a22 :double) (a23 :double) (a24 :double) (a25 :double)
(a26 :double))
(let ((args (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15
a16 a17 a18 a19 a20 a21 a22 a23 a24 a25 a26)))
#-(and)
(loop for i from 1 and arg in args do
(format t "a~A: ~A~%" i arg))
(reduce #'+ args)))
(defcfun "call_double26" :double (f :pointer))
#+(and darwin (or allegro cmucl))
(pushnew 'callbacks.double26 rtest::*expected-failures*)
(deftest callbacks.double26
(call-double26 (callback double26))
81.64d0)
#+(and darwin cmucl)
(pushnew 'callbacks.double26.funcall rtest::*expected-failures*)
#-cffi-sys::no-foreign-funcall
(deftest callbacks.double26.funcall
(foreign-funcall-pointer
(callback double26) () :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double)
81.64d0)
;;; Same as above, for floats.
#-(and darwin cmucl)
(defcallback float26 :float
((a1 :float) (a2 :float) (a3 :float) (a4 :float) (a5 :float)
(a6 :float) (a7 :float) (a8 :float) (a9 :float) (a10 :float)
(a11 :float) (a12 :float) (a13 :float) (a14 :float) (a15 :float)
(a16 :float) (a17 :float) (a18 :float) (a19 :float) (a20 :float)
(a21 :float) (a22 :float) (a23 :float) (a24 :float) (a25 :float)
(a26 :float))
(let ((args (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15
a16 a17 a18 a19 a20 a21 a22 a23 a24 a25 a26)))
#-(and)
(loop for i from 1 and arg in args do
(format t "a~A: ~A~%" i arg))
(reduce #'+ args)))
(defcfun "call_float26" :float (f :pointer))
#+(and darwin (or lispworks openmcl cmucl))
(pushnew 'callbacks.float26 regression-test::*expected-failures*)
(deftest callbacks.float26
(call-float26 (callback float26))
130.0)
#+(and darwin (or lispworks openmcl cmucl))
(pushnew 'callbacks.float26.funcall regression-test::*expected-failures*)
#-cffi-sys::no-foreign-funcall
(deftest callbacks.float26.funcall
(foreign-funcall-pointer
(callback float26) () :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0
:float)
130.0)
;;; Defining a callback as a non-toplevel form. Not portable. Doesn't
;;; work for CMUCL or Allegro.
#-(and)
(let ((n 42))
(defcallback non-toplevel-cb :int ()
n))
#-(and)
(deftest callbacks.non-toplevel
(foreign-funcall (callback non-toplevel-cb) :int)
42)
;;;# Stdcall
#+(and x86 (not cffi-sys::no-stdcall))
(progn
(defcallback (stdcall-cb :convention :stdcall) :int
((a :int) (b :int) (c :int))
(+ a b c))
(defcfun "call_stdcall_fun" :int
(f :pointer))
(deftest callbacks.stdcall.1
(call-stdcall-fun (callback stdcall-cb))
42))
;;; RT: many of the %DEFCALLBACK implementations wouldn't handle
;;; uninterned symbols.
(deftest callbacks.uninterned
(values (defcallback #1=#:foo :void ())
(pointerp (callback #1#)))
#1# t)
| 20,291 | Common Lisp | .lisp | 444 | 40.673423 | 81 | 0.642348 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b2d6efedcfe428aa37c09e868d221bae14eb0e1dd474c9c94d31c2b92ad1a46a | 42,997 | [
401290
] |
42,998 | foreign-globals.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/foreign-globals.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; foreign-globals.lisp --- Tests on foreign globals.
;;;
;;; Copyright (C) 2005-2007, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(defcvar ("var_char" *char-var*) :char)
(defcvar "var_unsigned_char" :unsigned-char)
(defcvar "var_short" :short)
(defcvar "var_unsigned_short" :unsigned-short)
(defcvar "var_int" :int)
(defcvar "var_unsigned_int" :unsigned-int)
(defcvar "var_long" :long)
(defcvar "var_unsigned_long" :unsigned-long)
(defcvar "var_float" :float)
(defcvar "var_double" :double)
(defcvar "var_pointer" :pointer)
(defcvar "var_string" :string)
(defcvar "var_long_long" :long-long)
(defcvar "var_unsigned_long_long" :unsigned-long-long)
;;; The expected failures marked below result from this odd behaviour:
;;;
;;; (foreign-symbol-pointer "var_char") => NIL
;;;
;;; (foreign-symbol-pointer "var_char" :library 'libtest)
;;; => #<Pointer to type :VOID = #xF7F50740>
;;;
;;; Why is this happening? --luis
#+lispworks
(mapc (lambda (x) (pushnew x rtest::*expected-failures*))
'(foreign-globals.ref.char foreign-globals.get-var-pointer.1
foreign-globals.get-var-pointer.2 foreign-globals.symbol-name
foreign-globals.read-only.1 ))
(deftest foreign-globals.ref.char
*char-var*
-127)
(deftest foreign-globals.ref.unsigned-char
*var-unsigned-char*
255)
(deftest foreign-globals.ref.short
*var-short*
-32767)
(deftest foreign-globals.ref.unsigned-short
*var-unsigned-short*
65535)
(deftest foreign-globals.ref.int
*var-int*
-32767)
(deftest foreign-globals.ref.unsigned-int
*var-unsigned-int*
65535)
(deftest foreign-globals.ref.long
*var-long*
-2147483647)
(deftest foreign-globals.ref.unsigned-long
*var-unsigned-long*
4294967295)
(deftest foreign-globals.ref.float
*var-float*
42.0)
(deftest foreign-globals.ref.double
*var-double*
42.0d0)
(deftest foreign-globals.ref.pointer
(null-pointer-p *var-pointer*)
t)
(deftest foreign-globals.ref.string
*var-string*
"Hello, foreign world!")
#+openmcl (push 'foreign-globals.set.long-long rtest::*expected-failures*)
(deftest foreign-globals.ref.long-long
*var-long-long*
-9223372036854775807)
(deftest foreign-globals.ref.unsigned-long-long
*var-unsigned-long-long*
18446744073709551615)
;; The *.set.* tests restore the old values so that the *.ref.*
;; don't fail when re-run.
(defmacro with-old-value-restored ((place) &body body)
(let ((old (gensym)))
`(let ((,old ,place))
(prog1
(progn ,@body)
(setq ,place ,old)))))
(deftest foreign-globals.set.int
(with-old-value-restored (*var-int*)
(setq *var-int* 42)
*var-int*)
42)
(deftest foreign-globals.set.string
(with-old-value-restored (*var-string*)
(setq *var-string* "Ehxosxangxo")
(prog1
*var-string*
;; free the string we just allocated
(foreign-free (mem-ref (get-var-pointer '*var-string*) :pointer))))
"Ehxosxangxo")
(deftest foreign-globals.set.long-long
(with-old-value-restored (*var-long-long*)
(setq *var-long-long* -9223000000000005808)
*var-long-long*)
-9223000000000005808)
(deftest foreign-globals.get-var-pointer.1
(pointerp (get-var-pointer '*char-var*))
t)
(deftest foreign-globals.get-var-pointer.2
(mem-ref (get-var-pointer '*char-var*) :char)
-127)
;;; Symbol case.
(defcvar "UPPERCASEINT1" :int)
(defcvar "UPPER_CASE_INT1" :int)
(defcvar "MiXeDCaSeInT1" :int)
(defcvar "MiXeD_CaSe_InT1" :int)
(deftest foreign-globals.ref.uppercaseint1
*uppercaseint1*
12345)
(deftest foreign-globals.ref.upper-case-int1
*upper-case-int1*
23456)
(deftest foreign-globals.ref.mixedcaseint1
*mixedcaseint1*
34567)
(deftest foreign-globals.ref.mixed-case-int1
*mixed-case-int1*
45678)
(when (string= (symbol-name 'nil) "NIL")
(let ((*readtable* (copy-readtable)))
(setf (readtable-case *readtable*) :invert)
(eval (read-from-string "(defcvar \"UPPERCASEINT2\" :int)"))
(eval (read-from-string "(defcvar \"UPPER_CASE_INT2\" :int)"))
(eval (read-from-string "(defcvar \"MiXeDCaSeInT2\" :int)"))
(eval (read-from-string "(defcvar \"MiXeD_CaSe_InT2\" :int)"))
(setf (readtable-case *readtable*) :preserve)
(eval (read-from-string "(DEFCVAR \"UPPERCASEINT3\" :INT)"))
(eval (read-from-string "(DEFCVAR \"UPPER_CASE_INT3\" :INT)"))
(eval (read-from-string "(DEFCVAR \"MiXeDCaSeInT3\" :INT)"))
(eval (read-from-string "(DEFCVAR \"MiXeD_CaSe_InT3\" :INT)"))))
;;; EVAL gets rid of SBCL's unreachable code warnings.
(when (string= (symbol-name (eval nil)) "nil")
(let ((*readtable* (copy-readtable)))
(setf (readtable-case *readtable*) :invert)
(eval (read-from-string "(DEFCVAR \"UPPERCASEINT2\" :INT)"))
(eval (read-from-string "(DEFCVAR \"UPPER_CASE_INT2\" :INT)"))
(eval (read-from-string "(DEFCVAR \"MiXeDCaSeInT2\" :INT)"))
(eval (read-from-string "(DEFCVAR \"MiXeD_CaSe_InT2\" :INT)"))
(setf (readtable-case *readtable*) :downcase)
(eval (read-from-string "(defcvar \"UPPERCASEINT3\" :int)"))
(eval (read-from-string "(defcvar \"UPPER_CASE_INT3\" :int)"))
(eval (read-from-string "(defcvar \"MiXeDCaSeInT3\" :int)"))
(eval (read-from-string "(defcvar \"MiXeD_CaSe_InT3\" :int)"))))
(deftest foreign-globals.ref.uppercaseint2
*uppercaseint2*
12345)
(deftest foreign-globals.ref.upper-case-int2
*upper-case-int2*
23456)
(deftest foreign-globals.ref.mixedcaseint2
*mixedcaseint2*
34567)
(deftest foreign-globals.ref.mixed-case-int2
*mixed-case-int2*
45678)
(deftest foreign-globals.ref.uppercaseint3
*uppercaseint3*
12345)
(deftest foreign-globals.ref.upper-case-int3
*upper-case-int3*
23456)
(deftest foreign-globals.ref.mixedcaseint3
*mixedcaseint3*
34567)
(deftest foreign-globals.ref.mixed-case-int3
*mixed-case-int3*
45678)
;;; regression test:
;;; gracefully accept symbols in defcvar
(defcvar *var-char* :char)
(defcvar var-char :char)
(deftest foreign-globals.symbol-name
(values *var-char* var-char)
-127 -127)
;;;# Namespace
#-cffi-sys::flat-namespace
(progn
(deftest foreign-globals.namespace.1
(values
(mem-ref (foreign-symbol-pointer "var_char" :library 'libtest) :char)
(foreign-symbol-pointer "var_char" :library 'libtest2))
-127 nil)
(deftest foreign-globals.namespace.2
(values
(mem-ref (foreign-symbol-pointer "ns_var" :library 'libtest) :boolean)
(mem-ref (foreign-symbol-pointer "ns_var" :library 'libtest2) :boolean))
t nil)
;; For its "default" module, Lispworks seems to cache lookups from
;; the newest module tried. If a lookup happens to have failed
;; subsequent lookups will fail even the symbol exists in other
;; modules. So this test fails.
#+lispworks
(pushnew 'foreign-globals.namespace.3 regression-test::*expected-failures*)
(deftest foreign-globals.namespace.3
(values
(foreign-symbol-pointer "var_char" :library 'libtest2)
(mem-ref (foreign-symbol-pointer "var_char") :char))
nil -127)
(defcvar ("ns_var" *ns-var1* :library libtest) :boolean)
(defcvar ("ns_var" *ns-var2* :library libtest2) :boolean)
(deftest foreign-globals.namespace.4
(values *ns-var1* *ns-var2*)
t nil))
;;;# Read-only
(defcvar ("var_char" *var-char-ro* :read-only t) :char
"docstring")
(deftest foreign-globals.read-only.1
(values *var-char-ro*
(ignore-errors (setf *var-char-ro* 12)))
-127 nil)
(deftest defcvar.docstring
(documentation '*var-char-ro* 'variable)
"docstring")
;;;# Other tests
;;; RT: FOREIGN-SYMBOL-POINTER shouldn't signal an error when passed
;;; an undefined variable.
(deftest foreign-globals.undefined.1
(foreign-symbol-pointer "surely-undefined?")
nil)
(deftest foreign-globals.error.1
(handler-case (foreign-symbol-pointer 'not-a-string)
(type-error () t))
t)
| 9,274 | Common Lisp | .lisp | 251 | 33.553785 | 79 | 0.691021 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | e93925f45dd5c75b7e7de4be09e138352212aa1711ab3813b6c3aaa719820c96 | 42,998 | [
201275
] |
42,999 | memory.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/memory.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; memory.lisp --- Tests for memory referencing.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(deftest deref.char
(with-foreign-object (p :char)
(setf (mem-ref p :char) -127)
(mem-ref p :char))
-127)
(deftest deref.unsigned-char
(with-foreign-object (p :unsigned-char)
(setf (mem-ref p :unsigned-char) 255)
(mem-ref p :unsigned-char))
255)
(deftest deref.short
(with-foreign-object (p :short)
(setf (mem-ref p :short) -32767)
(mem-ref p :short))
-32767)
(deftest deref.unsigned-short
(with-foreign-object (p :unsigned-short)
(setf (mem-ref p :unsigned-short) 65535)
(mem-ref p :unsigned-short))
65535)
(deftest deref.int
(with-foreign-object (p :int)
(setf (mem-ref p :int) -131072)
(mem-ref p :int))
-131072)
(deftest deref.unsigned-int
(with-foreign-object (p :unsigned-int)
(setf (mem-ref p :unsigned-int) 262144)
(mem-ref p :unsigned-int))
262144)
(deftest deref.long
(with-foreign-object (p :long)
(setf (mem-ref p :long) -536870911)
(mem-ref p :long))
-536870911)
(deftest deref.unsigned-long
(with-foreign-object (p :unsigned-long)
(setf (mem-ref p :unsigned-long) 536870912)
(mem-ref p :unsigned-long))
536870912)
#+(and darwin openmcl)
(pushnew 'deref.long-long rtest::*expected-failures*)
(deftest deref.long-long
(with-foreign-object (p :long-long)
(setf (mem-ref p :long-long) -9223372036854775807)
(mem-ref p :long-long))
-9223372036854775807)
(deftest deref.unsigned-long-long
(with-foreign-object (p :unsigned-long-long)
(setf (mem-ref p :unsigned-long-long) 18446744073709551615)
(mem-ref p :unsigned-long-long))
18446744073709551615)
(deftest deref.float.1
(with-foreign-object (p :float)
(setf (mem-ref p :float) 0.0)
(mem-ref p :float))
0.0)
(deftest deref.float.2
(with-foreign-object (p :float)
(setf (mem-ref p :float) *float-max*)
(mem-ref p :float))
#.*float-max*)
(deftest deref.float.3
(with-foreign-object (p :float)
(setf (mem-ref p :float) *float-min*)
(mem-ref p :float))
#.*float-min*)
(deftest deref.double.1
(with-foreign-object (p :double)
(setf (mem-ref p :double) 0.0d0)
(mem-ref p :double))
0.0d0)
(deftest deref.double.2
(with-foreign-object (p :double)
(setf (mem-ref p :double) *double-max*)
(mem-ref p :double))
#.*double-max*)
(deftest deref.double.3
(with-foreign-object (p :double)
(setf (mem-ref p :double) *double-min*)
(mem-ref p :double))
#.*double-min*)
;;; TODO: use something like *DOUBLE-MIN/MAX* above once we actually
;;; have an available lisp that supports long double.
;#-cffi-sys::no-long-float
#+(and scl long-double)
(progn
(deftest deref.long-double.1
(with-foreign-object (p :long-double)
(setf (mem-ref p :long-double) 0.0l0)
(mem-ref p :long-double))
0.0l0)
(deftest deref.long-double.2
(with-foreign-object (p :long-double)
(setf (mem-ref p :long-double) most-positive-long-float)
(mem-ref p :long-double))
#.most-positive-long-float)
(deftest deref.long-double.3
(with-foreign-object (p :long-double)
(setf (mem-ref p :long-double) least-positive-long-float)
(mem-ref p :long-double))
#.least-positive-long-float))
;;; make sure the lisp doesn't convert NULL to NIL
(deftest deref.pointer.null
(with-foreign-object (p :pointer)
(setf (mem-ref p :pointer) (null-pointer))
(null-pointer-p (mem-ref p :pointer)))
t)
;;; regression test. lisp-string-to-foreign should handle empty strings
(deftest lisp-string-to-foreign.empty
(with-foreign-pointer (str 2)
(setf (mem-ref str :unsigned-char) 42)
(lisp-string-to-foreign "" str 1)
(mem-ref str :unsigned-char))
0)
;;; regression test. with-foreign-pointer shouldn't evaluate
;;; the size argument twice.
(deftest with-foreign-pointer.evalx2
(let ((count 0))
(with-foreign-pointer (x (incf count) size-var)
(values count size-var)))
1 1)
(defconstant +two+ 2)
;;; regression test. cffi-allegro's with-foreign-pointer wasn't
;;; handling constants properly.
(deftest with-foreign-pointer.constant-size
(with-foreign-pointer (p +two+ size)
size)
2)
(deftest mem-ref.left-to-right
(let ((i 0))
(with-foreign-object (p :char 3)
(setf (mem-ref p :char 0) 66 (mem-ref p :char 1) 92)
(setf (mem-ref p :char (incf i)) (incf i))
(values (mem-ref p :char 0) (mem-ref p :char 1) i)))
66 2 2)
;;; This needs to be in a real function for at least Allegro CL or the
;;; compiler macro on %MEM-REF is not expanded and the test doesn't
;;; actually test anything!
(defun %mem-ref-left-to-right ()
(let ((result nil))
(with-foreign-object (p :char)
(%mem-set 42 p :char)
(%mem-ref (progn (push 1 result) p) :char (progn (push 2 result) 0))
(nreverse result))))
;;; Test left-to-right evaluation of the arguments to %MEM-REF when
;;; optimized by the compiler macro.
(deftest %mem-ref.left-to-right
(%mem-ref-left-to-right)
(1 2))
;;; This needs to be in a top-level function for at least Allegro CL
;;; or the compiler macro on %MEM-SET is not expanded and the test
;;; doesn't actually test anything!
(defun %mem-set-left-to-right ()
(let ((result nil))
(with-foreign-object (p :char)
(%mem-set (progn (push 1 result) 0)
(progn (push 2 result) p)
:char
(progn (push 3 result) 0))
(nreverse result))))
;;; Test left-to-right evaluation of the arguments to %MEM-SET when
;;; optimized by the compiler macro.
(deftest %mem-set.left-to-right
(%mem-set-left-to-right)
(1 2 3))
;; regression test. mem-aref's setf expansion evaluated its type argument twice.
(deftest mem-aref.eval-type-x2
(let ((count 0))
(with-foreign-pointer (p 1)
(setf (mem-aref p (progn (incf count) :char) 0) 127))
count)
1)
(deftest mem-aref.left-to-right
(let ((count -1))
(with-foreign-pointer (p 2)
(values
(setf (mem-aref p (progn (incf count) :char) (incf count)) (incf count))
(setq count -1)
(mem-aref (progn (incf count) p) :char (incf count))
count)))
2 -1 2 1)
;; regression tests. nested mem-ref's and mem-aref's had bogus getters
(deftest mem-ref.nested
(with-foreign-object (p :pointer)
(with-foreign-object (i :int)
(setf (mem-ref p :pointer) i)
(setf (mem-ref i :int) 42)
(setf (mem-ref (mem-ref p :pointer) :int) 1984)
(mem-ref i :int)))
1984)
(deftest mem-aref.nested
(with-foreign-object (p :pointer)
(with-foreign-object (i :int 2)
(setf (mem-aref p :pointer 0) i)
(setf (mem-aref i :int 1) 42)
(setf (mem-aref (mem-ref p :pointer 0) :int 1) 1984)
(mem-aref i :int 1)))
1984)
(cffi:defcstruct mem-aref.bare-struct
(a :uint8))
;;; regression test: although mem-aref was dealing with bare struct
;;; types as though they were pointers, it wasn't calculating the
;;; proper offsets. The offsets for bare structs types should be
;;; calculated as aggregate types.
(deftest mem-aref.bare-struct
(with-foreign-object (a 'mem-aref.bare-struct 2)
(eql (- (pointer-address (cffi:mem-aref a 'mem-aref.bare-struct 1))
(pointer-address (cffi:mem-aref a 'mem-aref.bare-struct 0)))
(foreign-type-size '(:struct mem-aref.bare-struct))))
t)
;;; regression tests. dereferencing an aggregate type. dereferencing a
;;; struct should return a pointer to the struct itself, not return the
;;; first 4 bytes (or whatever the size of :pointer is) as a pointer.
;;;
;;; This important for accessing an array of structs, which is
;;; what the deref.array-of-aggregates test does.
(defcstruct some-struct (x :int))
(deftest deref.aggregate
(with-foreign-object (s 'some-struct)
(pointer-eq s (mem-ref s 'some-struct)))
t)
(deftest deref.array-of-aggregates
(with-foreign-object (arr 'some-struct 3)
(loop for i below 3
do (setf (foreign-slot-value (mem-aref arr 'some-struct i)
'some-struct 'x)
112))
(loop for i below 3
collect (foreign-slot-value (mem-aref arr 'some-struct i)
'some-struct 'x)))
(112 112 112))
;;; pointer operations
(deftest pointer.1
(pointer-address (make-pointer 42))
42)
;;; I suppose this test is not very good. --luis
(deftest pointer.2
(pointer-address (null-pointer))
0)
(deftest pointer.null
(nth-value 0 (ignore-errors (null-pointer-p nil)))
nil)
(deftest foreign-pointer-type.nil
(typep nil 'foreign-pointer)
nil)
;;; Ensure that a pointer to the highest possible address can be
;;; created using MAKE-POINTER. Regression test for CLISP/X86-64.
(deftest make-pointer.high
(let* ((pointer-length (foreign-type-size :pointer))
(high-address (1- (expt 2 (* pointer-length 8))))
(pointer (make-pointer high-address)))
(- high-address (pointer-address pointer)))
0)
;;; Ensure that incrementing a pointer by zero bytes returns an
;;; equivalent pointer.
(deftest inc-pointer.zero
(with-foreign-object (x :int)
(pointer-eq x (inc-pointer x 0)))
t)
;;; Test the INITIAL-ELEMENT keyword argument to FOREIGN-ALLOC.
(deftest foreign-alloc.1
(let ((ptr (foreign-alloc :int :initial-element 42)))
(unwind-protect
(mem-ref ptr :int)
(foreign-free ptr)))
42)
;;; Test the INITIAL-ELEMENT and COUNT arguments to FOREIGN-ALLOC.
(deftest foreign-alloc.2
(let ((ptr (foreign-alloc :int :count 4 :initial-element 100)))
(unwind-protect
(loop for i from 0 below 4
collect (mem-aref ptr :int i))
(foreign-free ptr)))
(100 100 100 100))
;;; Test the INITIAL-CONTENTS and COUNT arguments to FOREIGN-ALLOC,
;;; passing a list of initial values.
(deftest foreign-alloc.3
(let ((ptr (foreign-alloc :int :count 4 :initial-contents '(4 3 2 1))))
(unwind-protect
(loop for i from 0 below 4
collect (mem-aref ptr :int i))
(foreign-free ptr)))
(4 3 2 1))
;;; Test INITIAL-CONTENTS and COUNT with FOREIGN-ALLOC passing a
;;; vector of initial values.
(deftest foreign-alloc.4
(let ((ptr (foreign-alloc :int :count 4 :initial-contents #(10 20 30 40))))
(unwind-protect
(loop for i from 0 below 4
collect (mem-aref ptr :int i))
(foreign-free ptr)))
(10 20 30 40))
;;; Ensure calling FOREIGN-ALLOC with both INITIAL-ELEMENT and
;;; INITIAL-CONTENTS signals an error.
(deftest foreign-alloc.5
(values
(ignore-errors
(let ((ptr (foreign-alloc :int :initial-element 1
:initial-contents '(1))))
(foreign-free ptr))
t))
nil)
;;; Regression test: FOREIGN-ALLOC shouldn't actually perform translation
;;; on initial-element/initial-contents since MEM-AREF will do that already.
(define-foreign-type not-an-int ()
()
(:actual-type :int)
(:simple-parser not-an-int))
(defmethod translate-to-foreign (value (type not-an-int))
(assert (not (integerp value)))
0)
(deftest foreign-alloc.6
(let ((ptr (foreign-alloc 'not-an-int :initial-element 'foooo)))
(foreign-free ptr)
t)
t)
;;; Ensure calling FOREIGN-ALLOC with NULL-TERMINATED-P and a non-pointer
;;; type signals an error.
(deftest foreign-alloc.7
(values
(ignore-errors
(let ((ptr (foreign-alloc :int :null-terminated-p t)))
(foreign-free ptr))
t))
nil)
;;; The opposite of the above test.
(defctype pointer-alias :pointer)
(deftest foreign-alloc.8
(progn
(foreign-free (foreign-alloc 'pointer-alias :count 0 :null-terminated-p t))
t)
t)
;;; Ensure calling FOREIGN-ALLOC with NULL-TERMINATED-P actually places
;;; a null pointer at the end. Not a very reliable test apparently.
(deftest foreign-alloc.9
(let ((ptr (foreign-alloc :pointer :count 0 :null-terminated-p t)))
(unwind-protect
(null-pointer-p (mem-ref ptr :pointer))
(foreign-free ptr)))
t)
;;; RT: FOREIGN-ALLOC with :COUNT 0 on CLISP signalled an error.
(deftest foreign-alloc.10
(null (foreign-free (foreign-alloc :char :count 0)))
t)
;;; Tests for mem-ref with a non-constant type. This is a way to test
;;; the functional interface (without compiler macros).
(deftest deref.nonconst.char
(let ((type :char))
(with-foreign-object (p type)
(setf (mem-ref p type) -127)
(mem-ref p type)))
-127)
(deftest deref.nonconst.unsigned-char
(let ((type :unsigned-char))
(with-foreign-object (p type)
(setf (mem-ref p type) 255)
(mem-ref p type)))
255)
(deftest deref.nonconst.short
(let ((type :short))
(with-foreign-object (p type)
(setf (mem-ref p type) -32767)
(mem-ref p type)))
-32767)
(deftest deref.nonconst.unsigned-short
(let ((type :unsigned-short))
(with-foreign-object (p type)
(setf (mem-ref p type) 65535)
(mem-ref p type)))
65535)
(deftest deref.nonconst.int
(let ((type :int))
(with-foreign-object (p type)
(setf (mem-ref p type) -131072)
(mem-ref p type)))
-131072)
(deftest deref.nonconst.unsigned-int
(let ((type :unsigned-int))
(with-foreign-object (p type)
(setf (mem-ref p type) 262144)
(mem-ref p type)))
262144)
(deftest deref.nonconst.long
(let ((type :long))
(with-foreign-object (p type)
(setf (mem-ref p type) -536870911)
(mem-ref p type)))
-536870911)
(deftest deref.nonconst.unsigned-long
(let ((type :unsigned-long))
(with-foreign-object (p type)
(setf (mem-ref p type) 536870912)
(mem-ref p type)))
536870912)
#+(and darwin openmcl)
(pushnew 'deref.nonconst.long-long rtest::*expected-failures*)
(deftest deref.nonconst.long-long
(let ((type :long-long))
(with-foreign-object (p type)
(setf (mem-ref p type) -9223372036854775807)
(mem-ref p type)))
-9223372036854775807)
(deftest deref.nonconst.unsigned-long-long
(let ((type :unsigned-long-long))
(with-foreign-object (p type)
(setf (mem-ref p type) 18446744073709551615)
(mem-ref p type)))
18446744073709551615)
(deftest deref.nonconst.float.1
(let ((type :float))
(with-foreign-object (p type)
(setf (mem-ref p type) 0.0)
(mem-ref p type)))
0.0)
(deftest deref.nonconst.float.2
(let ((type :float))
(with-foreign-object (p type)
(setf (mem-ref p type) *float-max*)
(mem-ref p type)))
#.*float-max*)
(deftest deref.nonconst.float.3
(let ((type :float))
(with-foreign-object (p type)
(setf (mem-ref p type) *float-min*)
(mem-ref p type)))
#.*float-min*)
(deftest deref.nonconst.double.1
(let ((type :double))
(with-foreign-object (p type)
(setf (mem-ref p type) 0.0d0)
(mem-ref p type)))
0.0d0)
(deftest deref.nonconst.double.2
(let ((type :double))
(with-foreign-object (p type)
(setf (mem-ref p type) *double-max*)
(mem-ref p type)))
#.*double-max*)
(deftest deref.nonconst.double.3
(let ((type :double))
(with-foreign-object (p type)
(setf (mem-ref p type) *double-min*)
(mem-ref p type)))
#.*double-min*)
;;; regression tests: lispworks's %mem-ref and %mem-set compiler
;;; macros were misbehaving.
(defun mem-ref-rt-1 ()
(with-foreign-object (a :int 2)
(setf (mem-aref a :int 0) 123
(mem-aref a :int 1) 456)
(values (mem-aref a :int 0) (mem-aref a :int 1))))
(deftest mem-ref.rt.1
(mem-ref-rt-1)
123 456)
(defun mem-ref-rt-2 ()
(with-foreign-object (a :double 2)
(setf (mem-aref a :double 0) 123.0d0
(mem-aref a :double 1) 456.0d0)
(values (mem-aref a :double 0) (mem-aref a :double 1))))
(deftest mem-ref.rt.2
(mem-ref-rt-2)
123.0d0 456.0d0)
(deftest incf-pointer.1
(let ((ptr (null-pointer)))
(incf-pointer ptr)
(pointer-address ptr))
1)
(deftest incf-pointer.2
(let ((ptr (null-pointer)))
(incf-pointer ptr 42)
(pointer-address ptr))
42)
(deftest pointerp.1
(values
(pointerp (null-pointer))
(null-pointer-p (null-pointer))
(typep (null-pointer) 'foreign-pointer))
t t t)
(deftest pointerp.2
(let ((p (make-pointer #xFEFF)))
(values
(pointerp p)
(typep p 'foreign-pointer)))
t t)
(deftest pointerp.3
(pointerp 'not-a-pointer)
nil)
(deftest pointerp.4
(pointerp 42)
nil)
(deftest pointerp.5
(pointerp 0)
nil)
(deftest pointerp.6
(pointerp nil)
nil)
(deftest mem-ref.setf.1
(with-foreign-object (p :char)
(setf (mem-ref p :char) 42))
42)
(define-foreign-type int+1 ()
()
(:actual-type :int)
(:simple-parser int+1))
(defmethod translate-to-foreign (value (type int+1))
(1+ value))
(defmethod translate-from-foreign (value (type int+1))
(1+ value))
(deftest mem-ref.setf.2
(with-foreign-object (p 'int+1)
(values (setf (mem-ref p 'int+1) 42)
(mem-ref p 'int+1)))
42 ; should this be 43?
44)
(deftest pointer-eq.non-pointers.1
(expecting-error (pointer-eq 1 2))
:error)
(deftest pointer-eq.non-pointers.2
(expecting-error (pointer-eq 'a 'b))
:error)
(deftest null-pointer-p.non-pointer.1
(expecting-error (null-pointer-p 'not-a-pointer))
:error)
(deftest null-pointer-p.non-pointer.2
(expecting-error (null-pointer-p 0))
:error)
(deftest null-pointer-p.non-pointer.3
(expecting-error (null-pointer-p nil))
:error)
| 19,026 | Common Lisp | .lisp | 557 | 29.271095 | 81 | 0.65322 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 3ce374f0f6f262d7dbe767e9612b72fd11a6311daebdf0fbcb3d87722570b7be | 42,999 | [
230432
] |
43,000 | enum.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/enum.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; enum.lisp --- Tests on C enums.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(defctype numeros-base-type :int)
(defcenum (numeros numeros-base-type)
(:one 1)
:two
:three
:four
(:forty-one 41)
:forty-two)
(defcfun "check_enums" :int
(%one numeros)
(%two numeros)
(%three numeros)
(%four numeros)
(%forty-one numeros)
(%forty-two numeros))
(deftest enum.1
(check-enums :one :two :three 4 :forty-one :forty-two)
1)
(defcenum another-boolean :false :true)
(defcfun "return_enum" another-boolean (x :uint))
(deftest enum.2
(and (eq :false (return-enum 0))
(eq :true (return-enum 1)))
t)
(defctype yet-another-boolean another-boolean)
(defcfun ("return_enum" return-enum2) yet-another-boolean
(x yet-another-boolean))
(deftest enum.3
(and (eq :false (return-enum2 :false))
(eq :true (return-enum2 :true)))
t)
(defctype numeros-typedef numeros)
(deftest enum.typedef.1
(eq (foreign-enum-keyword 'numeros-typedef 1)
(foreign-enum-keyword 'numeros 1))
t)
(deftest enum.typedef.2
(eql (foreign-enum-value 'numeros-typedef :four)
(foreign-enum-value 'numeros :four))
t)
(defcenum enum-size.int
(:one 1)
(enum-size-int #.(1- (expt 2 (1- (* (foreign-type-size :unsigned-int) 8)))))
(enum-size-negative-int #.(- (1- (expt 2 (1- (* (foreign-type-size :unsigned-int) 8))))))
(:two 2))
(defcenum enum-size.uint
(:one 1)
(enum-size-uint #.(1- (expt 2 (* (foreign-type-size :unsigned-int) 8))))
(:two 2))
(deftest enum.size
(mapcar (alexandria:compose 'cffi::unparse-type
'cffi::actual-type
'cffi::parse-type)
(list 'enum-size.int
'enum-size.uint))
;; The C standard only has weak constraints on the size of integer types, so
;; we cannot really test more than one type in a platform independent way due
;; to the possible overlaps.
(:int
:unsigned-int))
(deftest enum.size.members
(mapcar (alexandria:conjoin 'boundp 'constantp)
'(enum-size-int enum-size-negative-int enum-size-uint))
(t t t))
(deftest enum.size.error-when-too-large
(expecting-error
(eval '(defcenum enum-size-too-large
(:too-long #.(expt 2 129)))))
:error)
;; There are some projects that use non-integer base type. It's not in
;; adherence with the C standard, but we also don't lose much by
;; allowing it.
(defcenum (enum.double :double)
(:one 1)
(:two 2d0)
(:three 3.42)
:four)
(deftest enum.double
(values-list
(mapcar (alexandria:curry 'foreign-enum-value 'enum.double)
'(:one :two :three :four)))
1
2.0d0
3.42
4.42)
;; Test undeclared values
(defcenum (enum.undeclared :int :allow-undeclared-values T)
(:one 1)
(:two 2))
(deftest enum.undeclared
(with-foreign-object (enum 'enum.undeclared 3)
(setf (mem-aref enum 'enum.undeclared 0) 1)
(setf (mem-aref enum 'enum.undeclared 1) 2)
(setf (mem-aref enum 'enum.undeclared 2) 3)
(values (mem-aref enum 'enum.undeclared 0)
(mem-aref enum 'enum.undeclared 1)
(mem-aref enum 'enum.undeclared 2)))
:one
:two
3)
;;;# Bitfield tests
;;; Regression test: defbitfield was misbehaving when the first value
;;; was provided.
(deftest bitfield.1
(eval '(defbitfield (bf1 :long)
(:foo 0)))
bf1)
(defbitfield bf2
one
two
four
eight
sixteen
(bf2.outlier 42)
thirty-two
sixty-four)
(deftest bitfield.2
(mapcar (lambda (symbol)
(foreign-bitfield-value 'bf2 (list symbol)))
'(one two four eight sixteen thirty-two sixty-four))
(1 2 4 8 16 32 64))
(deftest bitfield.2.outlier
(mapcar (lambda (symbol)
(foreign-bitfield-value 'bf2 (list symbol)))
'(one two four eight sixteen thirty-two sixty-four))
(1 2 4 8 16 32 64))
(defbitfield (bf3 :int)
(three 3)
one
(seven 7)
two
(eight 8)
sixteen)
;;; Non-single-bit numbers must not influence the progression of
;;; implicit values. Single bits larger than any before *must*
;;; influence said progression.
(deftest bitfield.3
(mapcar (lambda (symbol)
(foreign-bitfield-value 'bf3 (list symbol)))
'(one two sixteen))
(1 2 16))
(defbitfield bf4
;; zero will be a simple enum member because it's not a valid mask
(zero 0)
one
two
four
(three 3)
(sixteen 16))
;;; Yet another edge case with the 0...
(deftest bitfield.4
;; These should macroexpand to the literals in Slime
;; due to the compiler macros. Same below.
(values (foreign-bitfield-value 'bf4 ())
(foreign-bitfield-value 'bf4 'one)
(foreign-bitfield-value 'bf4 '(one two))
(foreign-bitfield-value 'bf4 '(three)) ; or should it signal an error?
(foreign-bitfield-value 'bf4 '(sixteen)))
0
1
3
3
16)
(deftest bitfield.4b
(values (foreign-bitfield-symbols 'bf4 0)
(foreign-bitfield-symbols 'bf4 1)
(foreign-bitfield-symbols 'bf4 3)
(foreign-bitfield-symbols 'bf4 8)
(foreign-bitfield-symbols 'bf4 16))
nil
(one)
(one two)
nil
(sixteen))
(deftest bitfield.translators
(with-foreign-object (bf 'bf4 2)
(setf (mem-aref bf 'bf4 0) 1)
(setf (mem-aref bf 'bf4 1) 3)
(values (mem-aref bf 'bf4 0)
(mem-aref bf 'bf4 1)))
(one)
(one two))
#+nil
(deftest bitfield.base-type-error
(expecting-error
(eval '(defbitfield (bf1 :float)
(:foo 0))))
:error)
| 6,793 | Common Lisp | .lisp | 215 | 27.106977 | 91 | 0.661115 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 1b9c3ba8f1b79acf6fc9262079f6dae188ddd68be0c2bd923be4e7d6b0ff1864 | 43,000 | [
369146
] |
43,002 | run-tests.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/run-tests.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; run-tests.lisp --- Simple script to run the unit tests.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cl-user)
(setf *load-verbose* nil *compile-verbose* nil *compile-print* nil)
#+cmucl (setf ext:*gc-verbose* nil)
(require "asdf")
(format t "~&;;; -------- Running tests in ~A --------~%"
(uiop:implementation-identifier))
(asdf:load-system "cffi-tests" :verbose nil)
(asdf:test-system "cffi-tests")
(terpri)
(force-output)
(uiop:quit)
| 1,651 | Common Lisp | .lisp | 37 | 43.216216 | 70 | 0.728065 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | e4ae1d1355c3c076c7b0642adf923ef1041008aa2d4b2beaa91fb56088209122 | 43,002 | [
230701,
343602
] |
43,003 | misc-types.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/misc-types.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; misc-types.lisp --- Various tests on the type system.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(defcfun ("my_strdup" strdup) :string+ptr (str :string))
(defcfun ("my_strfree" strfree) :void (str :pointer))
(deftest misc-types.string+ptr
(destructuring-bind (string pointer)
(strdup "foo")
(strfree pointer)
string)
"foo")
#-(and)
(deftest misc-types.string+ptr.ub8
(destructuring-bind (string pointer)
(strdup (make-array 3 :element-type '(unsigned-byte 8)
:initial-contents (map 'list #'char-code "foo")))
(strfree pointer)
string)
"foo")
#-(and)
(deftest misc-types.string.ub8.1
(let ((array (make-array 7 :element-type '(unsigned-byte 8)
:initial-contents '(84 117 114 97 110 103 97))))
(with-foreign-string (foreign-string array)
(foreign-string-to-lisp foreign-string)))
"Turanga")
#-(and)
(deftest misc-types.string.ub8.2
(let ((str (foreign-string-alloc
(make-array 7 :element-type '(unsigned-byte 8)
:initial-contents '(84 117 114 97 110 103 97)))))
(prog1 (foreign-string-to-lisp str)
(foreign-string-free str)))
"Turanga")
(defcfun "equalequal" :boolean
(a (:boolean :int))
(b (:boolean :unsigned-int)))
(defcfun "bool_and" (:boolean :char)
(a (:boolean :unsigned-char))
(b (:boolean :char)))
(defcfun "bool_xor" (:boolean :unsigned-long)
(a (:boolean :long))
(b (:boolean :unsigned-long)))
(deftest misc-types.boolean.1
(list (equalequal nil nil)
(equalequal t t)
(equalequal t 23)
(bool-and 'a 'b)
(bool-and "foo" nil)
(bool-xor t nil)
(bool-xor nil nil))
(t t t t nil t nil))
(defcfun "sizeof_bool" :unsigned-int)
(deftest misc-types.sizeof.bool
(eql (sizeof-bool) (foreign-type-size :bool))
t)
(defcfun "bool_to_unsigned" :unsigned-int
(b :bool))
(defcfun "unsigned_to_bool" :bool
(u :unsigned-int))
(deftest misc-types.bool.convert-to-foreign.mem
(loop for v in '(nil t)
collect
(with-foreign-object (b :bool)
(setf (mem-ref b :bool) v)
(mem-ref b #.(cffi::canonicalize-foreign-type :bool))))
(0 1))
(deftest misc-types.bool.convert-to-foreign.call
(mapcar #'bool-to-unsigned '(nil t))
(0 1))
(deftest misc-types.bool.convert-from-foreign.mem
(loop for v in '(0 1 42)
collect
(with-foreign-object (b :bool)
(setf (mem-ref b #.(cffi::canonicalize-foreign-type :bool)) v)
(mem-ref b :bool)))
(nil t t))
(deftest misc-types.bool.convert-from-foreign.call
(mapcar #'unsigned-to-bool '(0 1 42))
(nil t t))
;;; Regression test: boolean type only worked with canonicalized
;;; built-in integer types. Should work for any type that canonicalizes
;;; to a built-in integer type.
(defctype int-for-bool :int)
(defcfun ("equalequal" equalequal2) :boolean
(a (:boolean int-for-bool))
(b (:boolean :uint)))
(deftest misc-types.boolean.2
(equalequal2 nil t)
nil)
(defctype my-string :string+ptr)
(defun funkify (str)
(concatenate 'string "MORE " (string-upcase str)))
(defun 3rd-person (value)
(list (concatenate 'string "Strdup says: " (first value))
(second value)))
;; (defctype funky-string
;; (:wrapper my-string
;; :to-c #'funkify
;; :from-c (lambda (value)
;; (list
;; (concatenate 'string "Strdup says: "
;; (first value))
;; (second value))))
;; "A useful type.")
(defctype funky-string (:wrapper my-string :to-c funkify :from-c 3rd-person))
(defcfun ("my_strdup" funky-strdup) funky-string
(str funky-string))
(deftest misc-types.wrapper
(destructuring-bind (string ptr)
(funky-strdup "code")
(strfree ptr)
string)
"Strdup says: MORE CODE")
(deftest misc-types.sized-ints
(mapcar #'foreign-type-size
'(:int8 :uint8 :int16 :uint16 :int32 :uint32 :int64 :uint64))
(1 1 2 2 4 4 8 8))
(define-foreign-type error-error ()
()
(:actual-type :int)
(:simple-parser error-error))
(defmethod translate-to-foreign (value (type error-error))
(declare (ignore value))
(error "translate-to-foreign invoked."))
(defmethod translate-from-foreign (value (type error-error))
(declare (ignore value))
(error "translate-from-foreign invoked."))
(eval-when (:load-toplevel :compile-toplevel :execute)
(defmethod expand-to-foreign (value (type error-error))
value)
(defmethod expand-from-foreign (value (type error-error))
value))
(defcfun ("abs" expand-abs) error-error
(n error-error))
(defcvar ("var_int" *expand-var-int*) error-error)
(defcfun ("expect_int_sum" expand-expect-int-sum) :boolean
(cb :pointer))
(defcallback expand-int-sum error-error ((x error-error) (y error-error))
(+ x y))
;;; Ensure that macroexpansion-time translators are called where this
;;; is guaranteed (defcfun, defcvar, foreign-funcall and defcallback)
(deftest misc-types.expand.1
(expand-abs -1)
1)
#-cffi-sys::no-foreign-funcall
(deftest misc-types.expand.2
(foreign-funcall "abs" error-error -1 error-error)
1)
(deftest misc-types.expand.3
(let ((old (mem-ref (get-var-pointer '*expand-var-int*) :int)))
(unwind-protect
(progn
(setf *expand-var-int* 42)
*expand-var-int*)
(setf (mem-ref (get-var-pointer '*expand-var-int*) :int) old)))
42)
(deftest misc-types.expand.4
(expand-expect-int-sum (callback expand-int-sum))
t)
(define-foreign-type translate-tracker ()
()
(:actual-type :int)
(:simple-parser translate-tracker))
(declaim (special .fto-called.))
(defmethod free-translated-object (value (type translate-tracker) param)
(declare (ignore value param))
(setf .fto-called. t))
(define-foreign-type expand-tracker ()
()
(:actual-type :int)
(:simple-parser expand-tracker))
(defmethod free-translated-object (value (type expand-tracker) param)
(declare (ignore value param))
(setf .fto-called. t))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod expand-to-foreign (value (type expand-tracker))
(declare (ignore value))
(call-next-method)))
(defcfun ("abs" ttracker-abs) :int
(n translate-tracker))
(defcfun ("abs" etracker-abs) :int
(n expand-tracker))
;; free-translated-object must be called when there is no etf
(deftest misc-types.expand.5
(let ((.fto-called. nil))
(ttracker-abs -1)
.fto-called.)
t)
;; free-translated-object must be called when there is an etf, but
;; they answer *runtime-translator-form*
(deftest misc-types.expand.6
(let ((.fto-called. nil))
(etracker-abs -1)
.fto-called.)
t)
(define-foreign-type misc-type.expand.7 ()
()
(:actual-type :int)
(:simple-parser misc-type.expand.7))
(defmethod translate-to-foreign (value (type misc-type.expand.7))
(values value 'second-value))
;; Auxiliary function to test CONVERT-TO-FOREIGN's compiler macro.
(defun misc-type.expand.7-aux ()
(convert-to-foreign "foo" 'misc-type.expand.7))
;; Checking that expand-to-foreign doesn't ignore the second value of
;; translate-to-foreign.
(deftest misc-type.expand.7
(misc-type.expand.7-aux)
"foo" second-value)
;; Like MISC-TYPE.EXPAND.7 but doesn't depend on compiler macros
;; kicking in.
(deftest misc-type.expand.8
(eval (expand-to-foreign "foo" (cffi::parse-type 'misc-type.expand.7)))
"foo" second-value)
;; stdint.h
(defcfun "sizeof_ptrdiff" :unsigned-int)
(defcfun "sizeof_size" :unsigned-int)
(defcfun "sizeof_offset" :unsigned-int)
(defcfun "sizeof_uintptr" :unsigned-int)
(defcfun "sizeof_intptr" :unsigned-int)
(deftest misc-types.sizeof.ptrdiff
(eql (sizeof-ptrdiff) (foreign-type-size :ptrdiff))
t)
(deftest misc-types.sizeof.size
(eql (sizeof-size) (foreign-type-size :size))
t)
(deftest misc-types.sizeof.offset
(eql (sizeof-offset) (foreign-type-size :offset))
t)
(deftest misc-types.sizeof.uintptr
(eql (sizeof-uintptr) (foreign-type-size :uintptr))
t)
(deftest misc-types.sizeof.intptr
(eql (sizeof-intptr) (foreign-type-size :intptr))
t)
| 9,485 | Common Lisp | .lisp | 260 | 32.584615 | 77 | 0.674634 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | eb85a8d11905867d497aea6d1ff6ab8e3448e1ee5f766d347f274b1de6ba2e33 | 43,003 | [
271853
] |
43,004 | grovel.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/grovel.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; grovel.lisp --- CFFI-Grovel tests.
;;;
;;; Copyright (C) 2014, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(deftest %invoke
(cffi-grovel::invoke "echo" "test")
nil nil 0)
(defun grovel-forms (forms &key (quiet t))
(uiop:with-temporary-file (:stream grovel-stream :pathname grovel-file)
(with-standard-io-syntax
(with-open-stream (*standard-output* grovel-stream)
(let ((*package* (find-package :keyword)))
(mapc #'write forms))))
(let ((lisp-file (let ((*debug-io* (if quiet (make-broadcast-stream) *debug-io*)))
(cffi-grovel:process-grovel-file grovel-file))))
(unwind-protect
(load lisp-file)
(uiop:delete-file-if-exists lisp-file)))))
(defun bug-1395242-helper (enum-type base-type constant-name)
(check-type enum-type (member constantenum cenum))
(check-type base-type string)
(check-type constant-name string)
(let ((enum-name (intern (symbol-name (gensym))))
(base-type-name (intern (symbol-name (gensym)))))
(grovel-forms `((ctype ,base-type-name ,base-type)
(,enum-type (,enum-name :base-type ,base-type-name)
((:value ,constant-name)))))
(cffi:foreign-enum-value enum-name :value)))
(deftest bug-1395242
(labels
((process-expression (expression)
(loop for enum-type in '(constantenum cenum)
always (destructuring-bind (base-type &rest evaluations) expression
(loop for (name expected-value) in evaluations
for actual-value = (bug-1395242-helper enum-type base-type name)
always (or (= expected-value actual-value)
(progn
(format *error-output*
"Test failed for case: ~A, ~A, ~A (expected ~A, actual ~A)~%"
enum-type base-type name expected-value actual-value)
nil)))))))
(every #'process-expression
'(("uint8_t" ("UINT8_MAX" 255) ("INT8_MAX" 127) ("INT8_MIN" 128))
("int8_t" ("INT8_MIN" -128) ("INT8_MAX" 127) ("UINT8_MAX" -1))
("uint16_t" ("UINT16_MAX" 65535) ("INT8_MIN" 65408))
("int16_t" ("INT16_MIN" -32768) ("INT16_MAX" 32767) ("UINT16_MAX" -1))
("uint32_t" ("UINT32_MAX" 4294967295) ("INT8_MIN" 4294967168))
("int32_t" ("INT32_MIN" -2147483648) ("INT32_MAX" 2147483647)))))
t)
(defvar *grovelled-features*)
(deftest grovel-feature
(let ((*grovelled-features* nil))
(grovel-forms `((in-package :cffi-tests)
(include "limits.h")
(feature grovel-test-feature "CHAR_BIT")
(feature :char-bit "CHAR_BIT"
:feature-list *grovelled-features*)
(feature :inexistent-grovel-feature
"INEXISTENT_CFFI_GROVEL_FEATURE"
:feature-list *grovelled-features*)))
(unwind-protect
(values (and (member 'grovel-test-feature *features*) t)
(and (member :char-bit *grovelled-features*) t)
(member :inexistent-grovel-feature *grovelled-features*))
(alexandria:removef *features* 'grovel-test-feature)))
t t nil)
(deftest grovel-types
(let* ((this #.(or *compile-file-truename* *load-truename*))
(include-dir (uiop:native-namestring (make-pathname :directory (pathname-directory this)))))
(grovel-forms `((in-package :cffi-tests)
(cc-flags ,(concatenate 'string "-I" include-dir))
(include "grovel-test.h")
(constant (tagged-array-max-length "TAGGED_ARRAY_MAX_LENGTH")
:documentation "Maximum length of tagged_array.arr (should be 64)")
(cstruct tagged-array "struct tagged_array"
(tagged-array-arr "arr" :type (:array :pointer 64))
(tagged-array-len "len" :type :unsigned-int))))
(let ((arr-type (cffi:foreign-slot-type '(:struct tagged-array) 'tagged-array-arr))
(len-type (cffi:foreign-slot-type '(:struct tagged-array) 'tagged-array-len)))
(values (eql tagged-array-max-length 64)
(and (eql (car arr-type) :array)
(eql (cadr arr-type) :pointer)
(eql (caddr arr-type) tagged-array-max-length))
(and (eql len-type :unsigned-int)))))
t t t)
| 5,888 | Common Lisp | .lisp | 108 | 42.657407 | 114 | 0.586972 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 151e9f3a32f124306115cf59b05e2e453ea8000bf9b1860a6f3b08f2afde54bb | 43,004 | [
369521,
374694
] |
43,005 | test-asdf.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/test-asdf.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; asdf.lisp --- CFFI-Grovel asdf support tests.
;;;
;;; Copyright (C) 2015, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
;; See lp#1953686.
#-sbcl
(when (cffi-toolchain::static-ops-enabled-p)
(deftest test-static-program
(progn
(asdf:operate :static-program-op :cffi-tests/example)
(let ((program (asdf:output-file :static-program-op :cffi-tests/example)))
(uiop:run-program `(,(native-namestring program) "1" "2 3") :output :lines)))
("Arguments: 1 \"2 3\"" "hello, world!") nil 0))
(deftest test-asdf-load
(progn
(asdf:load-system :cffi-tests/example)
(uiop:symbol-call :cffi-example :check-groveller))
nil)
| 1,852 | Common Lisp | .lisp | 41 | 42.731707 | 87 | 0.719027 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b630d0aaa25031f67f72318114b745144fb8f8195cf589a3e4fc9aca2edd3659 | 43,005 | [
441616
] |
43,006 | arrays.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/arrays.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; arrays.lisp --- Tests for foreign arrays.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2005-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
;;;#Foreign Array Conversion Tests
;;;
(in-package #:cffi-tests)
(deftest array.foreign-to-lisp.basic
(with-foreign-array (ptr #(1 2 3 4 5) '(:array :int32 5))
(foreign-array-to-lisp ptr '(:array :int32 5)))
#(1 2 3 4 5))
(deftest array.foreign-to-lisp.adjustable
(with-foreign-array (ptr #(1 2 3 4 5) '(:array :int32 5))
(let ((array (foreign-array-to-lisp ptr '(:array :int32 5)
:adjustable t)))
(adjustable-array-p array)))
t)
(deftest array.foreign-to-lisp.displaced
(let ((array (make-array 10 :initial-contents '(1 2 3 4 5 6 7 8 9 0))))
(with-foreign-array (ptr #(10 20 30 40 50) '(:array :int32 5))
(let ((displaced (foreign-array-to-lisp ptr '(:array :int32 5)
:displaced-to array
:displaced-index-offset 5)))
array)))
#(1 2 3 4 5 10 20 30 40 50))
;;; Implementation detail: 15.1.2.2 of the CL standard states that the only
;;; truly portable array specializations are for bits (bit-vectors) and
;;; characters (strings). Since char-codes are implementation-dependent, it
;;; would be tricky to write a portable test for them without generating
;;; characters at runtime. So, for a truly portable test, we are only left with
;;; bits, which are luckily numeric, and equal to (UNSIGNED-BYTE 1).
;;; This is why the below test is so terribly wasteful, spending a whole byte
;;; for a single bit - CFFI has no capabilities for dealing with single bits,
;;; and this test is only meant to check correctness of the :ELEMENT-TYPE
;;; argument to MAKE-ARRAY. In actual use cases of specialized
;;; FOREIGN-ARRAY-TO-LISP, capable implementations will be able to make
;;; specialized arrays of types that are commonly optimized for and/or
;;; representable in hardware, such as (UNSIGNED-BYTE 8) on x86 architectures.
(deftest array.foreign-to-lisp.specialized
(with-foreign-array (ptr #(1 0 1 0 1 1 1 0) '(:array :int8 8))
(foreign-array-to-lisp ptr '(:array :int8 8) :element-type 'bit))
#*10101110)
| 3,464 | Common Lisp | .lisp | 65 | 48.938462 | 79 | 0.691424 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | df3d2a50d298254f86504afde6240443dd95b4bc08e1e74ec96fed234a339dc6 | 43,006 | [
96814
] |
43,007 | funcall.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/funcall.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; funcall.lisp --- Tests function calling.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2005-2007, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
;;;# Calling with Built-In C Types
;;;
;;; Tests calling standard C library functions both passing and
;;; returning each built-in type.
;;; Don't run these tests if the implementation does not support
;;; foreign-funcall.
#-cffi-sys::no-foreign-funcall
(progn
(deftest funcall.char
(foreign-funcall "toupper" :char (char-code #\a) :char)
#.(char-code #\A))
(deftest funcall.int.1
(foreign-funcall "abs" :int -100 :int)
100)
(defun funcall-abs (n)
(foreign-funcall "abs" :int n :int))
;;; regression test: lispworks's %foreign-funcall based on creating
;;; and caching foreign-funcallables at macro-expansion time.
(deftest funcall.int.2
(funcall-abs -42)
42)
(deftest funcall.long
(foreign-funcall "labs" :long -131072 :long)
131072)
#-cffi-sys::no-long-long
(deftest funcall.long-long
(foreign-funcall "my_llabs" :long-long -9223372036854775807 :long-long)
9223372036854775807)
#-cffi-sys::no-long-long
(deftest funcall.unsigned-long-long
(let ((ullong-max (1- (expt 2 (* 8 (foreign-type-size :unsigned-long-long))))))
(eql ullong-max
(foreign-funcall "ullong" :unsigned-long-long ullong-max
:unsigned-long-long)))
t)
(deftest funcall.float
(foreign-funcall "my_sqrtf" :float 16.0 :float)
4.0)
(deftest funcall.double
(foreign-funcall "sqrt" :double 36.0d0 :double)
6.0d0)
#+(and scl long-float)
(deftest funcall.long-double
(foreign-funcall "sqrtl" :long-double 36.0l0 :long-double)
6.0l0)
(deftest funcall.string.1
(foreign-funcall "strlen" :string "Hello" :int)
5)
(deftest funcall.string.2
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(foreign-funcall "strcpy" :pointer s :string "Hello" :pointer)
(foreign-funcall "strcat" :pointer s :string ", world!" :pointer))
"Hello, world!")
(deftest funcall.string.3
(with-foreign-pointer (ptr 100)
(lisp-string-to-foreign "Hello, " ptr 8)
(foreign-funcall "strcat" :pointer ptr :string "world!" :string))
"Hello, world!")
;;;# Calling Varargs Functions
(deftest funcall.varargs.nostdlib
(foreign-funcall-varargs
"sum_double_arbitrary" (:int 26)
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0
:double)
81.64d0)
;; The CHAR argument must be passed as :INT because chars are promoted
;; to ints when passed as variable arguments.
(deftest funcall.varargs.char
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(foreign-funcall-varargs
"sprintf" (:pointer s :string "%c") :int 65 :int))
"A")
(deftest funcall.varargs.int
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(foreign-funcall-varargs
"sprintf" (:pointer s :string "%d") :int 1000 :int))
"1000")
(deftest funcall.varargs.long
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(foreign-funcall-varargs
"sprintf" (:pointer s :string "%ld")
:long 131072 :int))
"131072")
;;; There is no FUNCALL.VARARGS.FLOAT as floats are promoted to double
;;; when passed as variable arguments. Currently this fails in SBCL
;;; and CMU CL on Darwin/ppc.
(deftest funcall.varargs.double
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(foreign-funcall-varargs
"sprintf" (:pointer s :string "%.0f") :double (* pi 100d0) :int))
"314")
#+(and scl long-float)
(deftest funcall.varargs.long-double
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(foreign-funcall-varargs
"sprintf" :pointer s :string "%.0Lf" :long-double (* pi 100) :int))
"314")
(deftest funcall.varargs.string
(with-foreign-pointer-as-string (s 100)
(setf (mem-ref s :char) 0)
(foreign-funcall-varargs
"sprintf" (:pointer s :string "%s, %s!") :string "Hello" :string "world" :int))
"Hello, world!")
;;; See DEFCFUN.DOUBLE26.
(deftest funcall.double26
(foreign-funcall "sum_double26"
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double 3.14d0
:double 3.14d0 :double 3.14d0 :double)
81.64d0)
;;; See DEFCFUN.FLOAT26.
(deftest funcall.float26
(foreign-funcall "sum_float26"
:float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0
:float 5.0 :float)
130.0)
;;; Funcalling a pointer.
(deftest funcall.f-s-p.1
(foreign-funcall-pointer (foreign-symbol-pointer "abs") nil :int -42 :int)
42)
;;;# Namespaces
#-cffi-sys::flat-namespace
(deftest funcall.namespace.1
(values (foreign-funcall ("ns_function" :library libtest) :boolean)
(foreign-funcall ("ns_function" :library libtest2) :boolean))
t nil)
;;;# stdcall
#+(and x86 windows (not cffi-sys::no-stdcall))
(deftest funcall.stdcall.1
(flet ((fun ()
(foreign-funcall ("stdcall_fun@12" :convention :stdcall)
:int 1 :int 2 :int 3 :int)))
(loop repeat 100 do (fun)
finally (return (fun))))
6)
;;; RT: NIL arguments are skipped
(defvar *nil-skipped*)
(define-foreign-type check-nil-skip-type ()
()
(:actual-type :pointer)
(:simple-parser check-nil-skip-type))
(defmethod expand-to-foreign (val (type check-nil-skip-type))
(declare (ignore val))
(setf *nil-skipped* nil)
(null-pointer))
(deftest funcall.nil-skip
(let ((*nil-skipped* t))
(compile nil '(lambda ()
(foreign-funcall "abs" check-nil-skip-type nil)))
*nil-skipped*)
nil)
;;; RT: CLISP returns NIL instead of a null-pointer
(deftest funcall.pointer-not-nil
(not (null (foreign-funcall "strchr" :string "" :int 1 :pointer)))
t)
) ;; #-cffi-sys::no-foreign-funcall
| 8,238 | Common Lisp | .lisp | 206 | 34.718447 | 86 | 0.660703 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 2e629fbf0564304bedba7ac47410a6c0a988483dd320f69e8bc3810f7c4f01aa | 43,007 | [
249456
] |
43,008 | misc.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/misc.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; misc.lisp --- Miscellaneous tests.
;;;
;;; Copyright (C) 2006, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
;;;# foreign-symbol-pointer tests
;;; This might be useful for some libraries that compare function
;;; pointers. http://thread.gmane.org/gmane.lisp.cffi.devel/694
(defcfun "compare_against_abs" :boolean (p :pointer))
(deftest foreign-symbol-pointer.1
(compare-against-abs (foreign-symbol-pointer "abs"))
t)
(defcfun "compare_against_xpto_fun" :boolean (p :pointer))
(deftest foreign-symbol-pointer.2
(compare-against-xpto-fun (foreign-symbol-pointer "xpto_fun"))
t)
;;;# Library tests
;;;
;;; Need to figure out a way to test this. CLISP, for instance, will
;;; automatically reopen the foreign-library when we call a foreign
;;; function so we can't test CLOSE-FOREIGN-LIBRARY this way.
;;;
;;; IIRC, GCC has some extensions to have code run when a library is
;;; loaded and stuff like that. That could work.
#||
#-(and ecl (not dffi))
(deftest library.close.2
(unwind-protect
(progn
(close-foreign-library 'libtest)
(ignore-errors (my-sqrtf 16.0)))
(load-test-libraries))
nil)
#-(or (and ecl (not dffi))
cffi-sys::flat-namespace
cffi-sys::no-foreign-funcall)
(deftest library.close.2
(unwind-protect
(values
(foreign-funcall ("ns_function" :library libtest) :boolean)
(close-foreign-library 'libtest)
(foreign-funcall "ns_function" :boolean)
(close-foreign-library 'libtest2)
(close-foreign-library 'libtest2)
(ignore-errors (foreign-funcall "ns_function" :boolean)))
(load-test-libraries))
t t nil t nil nil)
||#
(deftest library.error.1
(handler-case (load-foreign-library "libdoesnotexistimsure")
(load-foreign-library-error () 'error))
error)
(define-foreign-library pseudo-library
(t pseudo-library-spec))
;;; RT: T clause was being handled as :T by FEATUREP.
;;;
;;; We might want to export (and clean up) the API used in this test
;;; when the need arises.
(deftest library.t-clause
(eq (cffi::foreign-library-spec
(cffi::get-foreign-library 'pseudo-library))
'pseudo-library-spec)
t)
(define-foreign-library library-with-pathname
(t #p"libdoesnotexistimsure"))
;;; RT: we were mishandling pathnames within libraries. (lp#1720626)
(deftest library.error.2
(handler-case (load-foreign-library 'library-with-pathname)
(load-foreign-library-error () 'error))
error)
(deftest library.error.3
(handler-case (load-foreign-library #p"libdoesnotexistimsure")
(load-foreign-library-error () 'error))
error)
;;;# Shareable Byte Vector Tests
#+ecl
(mapc (lambda (x) (pushnew x rtest::*expected-failures*))
'(shareable-vector.1 shareable-vector.2))
(deftest shareable-vector.1
(let ((vector (cffi-sys::make-shareable-byte-vector 5)))
(cffi::with-pointer-to-vector-data (pointer vector)
(strcpy pointer "xpto"))
vector)
#(120 112 116 111 0))
(deftest shareable-vector.2
(block nil
(let ((vector (cffi-sys::make-shareable-byte-vector 5)))
(cffi::with-pointer-to-vector-data (pointer vector)
(strcpy pointer "xpto")
(return vector))))
#(120 112 116 111 0))
| 4,449 | Common Lisp | .lisp | 113 | 35.699115 | 70 | 0.706509 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 7deb1f9b605f8274e48deb12e07faeae8c3c14846b4e80bdce66a3083fa96073 | 43,008 | [
246162
] |
43,010 | struct.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/tests/struct.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; struct.lisp --- Foreign structure type tests.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2005-2011, Luis Oliveira <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi-tests)
(defcstruct timeval
(tv-secs :long)
(tv-usecs :long))
(defparameter *timeval-size* (* 2 (max (foreign-type-size :long)
(foreign-type-alignment :long))))
;;;# Basic Structure Tests
(deftest struct.1
(- (foreign-type-size 'timeval) *timeval-size*)
0)
(deftest struct.2
(with-foreign-object (tv 'timeval)
(setf (foreign-slot-value tv 'timeval 'tv-secs) 0)
(setf (foreign-slot-value tv 'timeval 'tv-usecs) 1)
(values (foreign-slot-value tv 'timeval 'tv-secs)
(foreign-slot-value tv 'timeval 'tv-usecs)))
0 1)
(deftest struct.3
(with-foreign-object (tv 'timeval)
(with-foreign-slots ((tv-secs tv-usecs) tv timeval)
(setf tv-secs 100 tv-usecs 200)
(values tv-secs tv-usecs)))
100 200)
;; regression test: accessing a struct through a typedef
(defctype xpto (:struct timeval))
(deftest struct.4
(with-foreign-object (tv 'xpto)
(setf (foreign-slot-value tv 'xpto 'tv-usecs) 1)
(values (foreign-slot-value tv 'xpto 'tv-usecs)
(foreign-slot-value tv 'timeval 'tv-usecs)))
1 1)
(deftest struct.names
(sort (foreign-slot-names 'xpto) #'<
:key (lambda (x) (foreign-slot-offset 'xpto x)))
(tv-secs tv-usecs))
;; regression test: compiler macro not quoting the type in the
;; resulting mem-ref form. The compiler macro on foreign-slot-value
;; is not guaranteed to be expanded though.
(defctype my-int :int)
(defcstruct s5 (a my-int))
(deftest struct.5
(with-foreign-object (s 's5)
(setf (foreign-slot-value s 's5 'a) 42)
(foreign-slot-value s 's5 'a))
42)
;;;# Structs with type translators
(defcstruct struct-string
(s :string))
(deftest struct.string.1
(with-foreign-object (ptr 'struct-string)
(with-foreign-slots ((s) ptr struct-string)
(setf s "So long and thanks for all the fish!")
s))
"So long and thanks for all the fish!")
(deftest struct.string.2
(with-foreign-object (ptr 'struct-string)
(setf (foreign-slot-value ptr 'struct-string 's) "Cha")
(foreign-slot-value ptr 'struct-string 's))
"Cha")
;;;# Structure Alignment Tests
;;;
;;; See libtest.c and types.lisp for some comments about alignments.
(defcstruct s-ch
(a-char :char))
(defctype s-ch (:struct s-ch))
(defcstruct s-s-ch
(another-char :char)
(a-s-ch s-ch))
(defctype s-s-ch (:struct s-s-ch))
(defcvar "the_s_s_ch" s-s-ch)
(deftest struct.alignment.1
(list 'a-char (foreign-slot-value
(foreign-slot-pointer *the-s-s-ch* 's-s-ch 'a-s-ch)
's-ch 'a-char)
'another-char (foreign-slot-value *the-s-s-ch* 's-s-ch 'another-char))
(a-char 1 another-char 2))
(defcstruct s-short
(a-char :char)
(another-char :char)
(a-short :short))
(defctype s-short (:struct s-short))
(defcstruct s-s-short
(yet-another-char :char)
(a-s-short s-short))
(defctype s-s-short (:struct s-s-short))
(defcvar "the_s_s_short" s-s-short)
(deftest struct.alignment.2
(with-foreign-slots ((yet-another-char a-s-short) *the-s-s-short* s-s-short)
(with-foreign-slots ((a-char another-char a-short) a-s-short s-short)
(list 'a-char a-char
'another-char another-char
'a-short a-short
'yet-another-char yet-another-char)))
(a-char 1 another-char 2 a-short 3 yet-another-char 4))
(defcstruct s-double
(a-char :char)
(a-double :double)
(another-char :char))
(defctype s-double (:struct s-double))
(defcstruct s-s-double
(yet-another-char :char)
(a-s-double s-double)
(a-short :short))
(defctype s-s-double (:struct s-s-double))
(defcvar "the_s_s_double" s-s-double)
(deftest struct.alignment.3
(with-foreign-slots
((yet-another-char a-s-double a-short) *the-s-s-double* s-s-double)
(with-foreign-slots ((a-char a-double another-char) a-s-double s-double)
(list 'a-char a-char
'a-double a-double
'another-char another-char
'yet-another-char yet-another-char
'a-short a-short)))
(a-char 1 a-double 2.0d0 another-char 3 yet-another-char 4 a-short 5))
(defcstruct s-s-s-double
(another-short :short)
(a-s-s-double s-s-double)
(last-char :char))
(defctype s-s-s-double (:struct s-s-s-double))
(defcvar "the_s_s_s_double" s-s-s-double)
(deftest struct.alignment.4
(with-foreign-slots
((another-short a-s-s-double last-char) *the-s-s-s-double* s-s-s-double)
(with-foreign-slots
((yet-another-char a-s-double a-short) a-s-s-double s-s-double)
(with-foreign-slots ((a-char a-double another-char) a-s-double s-double)
(list 'a-char a-char
'a-double a-double
'another-char another-char
'yet-another-char yet-another-char
'a-short a-short
'another-short another-short
'last-char last-char))))
(a-char 1 a-double 2.0d0 another-char 3 yet-another-char 4 a-short 5
another-short 6 last-char 7))
(defcstruct s-double2
(a-double :double)
(a-short :short))
(defctype s-double2 (:struct s-double2))
(defcstruct s-s-double2
(a-char :char)
(a-s-double2 s-double2)
(another-short :short))
(defctype s-s-double2 (:struct s-s-double2))
(defcvar "the_s_s_double2" s-s-double2)
(deftest struct.alignment.5
(with-foreign-slots
((a-char a-s-double2 another-short) *the-s-s-double2* s-s-double2)
(with-foreign-slots ((a-double a-short) a-s-double2 s-double2)
(list 'a-double a-double
'a-short a-short
'a-char a-char
'another-short another-short)))
(a-double 1.0d0 a-short 2 a-char 3 another-short 4))
(defcstruct s-long-long
(a-long-long :long-long)
(a-short :short))
(defctype s-long-long (:struct s-long-long))
(defcstruct s-s-long-long
(a-char :char)
(a-s-long-long s-long-long)
(another-short :short))
(defctype s-s-long-long (:struct s-s-long-long))
(defcvar "the_s_s_long_long" s-s-long-long)
(deftest struct.alignment.6
(with-foreign-slots
((a-char a-s-long-long another-short) *the-s-s-long-long* s-s-long-long)
(with-foreign-slots ((a-long-long a-short) a-s-long-long s-long-long)
(list 'a-long-long a-long-long
'a-short a-short
'a-char a-char
'another-short another-short)))
(a-long-long 1 a-short 2 a-char 3 another-short 4))
(defcstruct s-s-double3
(a-s-double2 s-double2)
(another-short :short))
(defctype s-s-double3 (:struct s-s-double3))
(defcstruct s-s-s-double3
(a-s-s-double3 s-s-double3)
(a-char :char))
(defctype s-s-s-double3 (:struct s-s-s-double3))
(defcvar "the_s_s_s_double3" s-s-s-double3)
(deftest struct.alignment.7
(with-foreign-slots ((a-s-s-double3 a-char) *the-s-s-s-double3* s-s-s-double3)
(with-foreign-slots ((a-s-double2 another-short) a-s-s-double3 s-s-double3)
(with-foreign-slots ((a-double a-short) a-s-double2 s-double2)
(list 'a-double a-double
'a-short a-short
'another-short another-short
'a-char a-char))))
(a-double 1.0d0 a-short 2 another-short 3 a-char 4))
(defcstruct empty-struct)
(defctype empty-struct (:struct empty-struct))
(defcstruct with-empty-struct
(foo empty-struct)
(an-int :int))
;; commented out this test because an empty struct is not valid/standard C
;; left the struct declarations anyway because they should be handled
;; gracefuly anyway.
; (defcvar "the_with_empty_struct" with-empty-struct)
;
; (deftest struct.alignment.5
; (with-foreign-slots ((foo an-int) *the-with-empty-struct* with-empty-struct)
; an-int)
; 42)
;; regression test, setf-ing nested foreign-slot-value forms
;; the setf expander used to return a bogus getter
(defcstruct s1
(an-int :int))
(defctype s1 (:struct s1))
(defcstruct s2
(an-s1 s1))
(defctype s2 (:struct s2))
(deftest struct.nested-setf
(with-foreign-object (an-s2 's2)
(setf (foreign-slot-value (foreign-slot-value an-s2 's2 'an-s1)
's1 'an-int)
1984)
(foreign-slot-value (foreign-slot-value an-s2 's2 'an-s1)
's1 'an-int))
1984)
;; regression test, some Lisps were returning 4 instead of 8 for
;; (foreign-type-alignment :unsigned-long-long) on darwin/ppc32
(defcstruct s-unsigned-long-long
(an-unsigned-long-long :unsigned-long-long)
(a-short :short))
(defctype s-unsigned-long-long (:struct s-unsigned-long-long))
(defcstruct s-s-unsigned-long-long
(a-char :char)
(a-s-unsigned-long-long s-unsigned-long-long)
(another-short :short))
(defctype s-s-unsigned-long-long (:struct s-s-unsigned-long-long))
(defcvar "the_s_s_unsigned_long_long" s-s-unsigned-long-long)
(deftest struct.alignment.8
(with-foreign-slots
((a-char a-s-unsigned-long-long another-short)
*the-s-s-unsigned-long-long* s-s-unsigned-long-long)
(with-foreign-slots ((an-unsigned-long-long a-short)
a-s-unsigned-long-long s-unsigned-long-long)
(list 'an-unsigned-long-long an-unsigned-long-long
'a-short a-short
'a-char a-char
'another-short another-short)))
(an-unsigned-long-long 1 a-short 2 a-char 3 another-short 4))
;;;# C Struct Wrappers
(define-c-struct-wrapper timeval ())
(define-c-struct-wrapper (timeval2 (:struct timeval)) ()
(tv-secs))
(defmacro with-example-timeval (var &body body)
`(with-foreign-object (,var 'timeval)
(with-foreign-slots ((tv-secs tv-usecs) ,var timeval)
(setf tv-secs 42 tv-usecs 1984)
,@body)))
(deftest struct-wrapper.1
(with-example-timeval ptr
(let ((obj (make-instance 'timeval :pointer ptr)))
(values (timeval-tv-secs obj)
(timeval-tv-usecs obj))))
42 1984)
(deftest struct-wrapper.2
(with-example-timeval ptr
(let ((obj (make-instance 'timeval2 :pointer ptr)))
(timeval2-tv-secs obj)))
42)
;;;# Structures as Values
(defcstruct (struct-pair :class pair)
(a :int)
(b :int))
(defctype struct-pair-typedef1 (:struct struct-pair))
(defctype struct-pair-typedef2 (:pointer (:struct struct-pair)))
(deftest struct.unparse.1
(mapcar (alexandria:compose #'cffi::unparse-type #'cffi::parse-type)
'(struct-pair
(:struct struct-pair)
struct-pair-typedef1
struct-pair-typedef2))
(struct-pair
(:struct struct-pair)
struct-pair-typedef1
struct-pair-typedef2))
(deftest struct.canonicalize.1
(mapcar #'cffi::canonicalize-foreign-type
'(struct-pair
(:struct struct-pair)
struct-pair-typedef1
struct-pair-typedef2))
(:pointer
(:struct struct-pair)
(:struct struct-pair)
:pointer))
(deftest struct.canonicalize.2
(mapcar #'cffi::canonicalize-foreign-type
'(struct-pair
(:struct struct-pair)
struct-pair-typedef1
struct-pair-typedef2))
(:pointer
(:struct struct-pair)
(:struct struct-pair)
:pointer))
(defmethod translate-from-foreign (pointer (type pair))
(with-foreign-slots ((a b) pointer (:struct struct-pair))
(cons a b)))
(defmethod translate-into-foreign-memory (object (type pair) pointer)
(with-foreign-slots ((a b) pointer (:struct struct-pair))
(setf a (car object)
b (cdr object))))
(defmethod translate-to-foreign (object (type pair))
(let ((p (foreign-alloc '(:struct struct-pair))))
(translate-into-foreign-memory object type p)
(values p t)))
(defmethod free-translated-object (pointer (type pair) freep)
(when freep
(foreign-free pointer)))
(deftest struct-values.translation.1
(multiple-value-bind (p freep)
(convert-to-foreign '(1 . 2) 'struct-pair)
(assert freep)
(unwind-protect
(convert-from-foreign p 'struct-pair)
(free-converted-object p 'struct-pair freep)))
(1 . 2))
(defcfun "pair_pointer_sum" :int
(p (:pointer (:struct struct-pair))))
#+#:pointer-translation-not-yet-implemented
(deftest struct-values.translation.2
(pair-pointer-sum '(1 . 2))
3)
;;; should the return type be something along the lines of
;;; (:pointer (:struct pair) :free t)?
;;; LMH: error on ":free t" option?
(defcfun "alloc_pair" (:pointer (:struct struct-pair))
(a :int)
(b :int))
;; bogus: doesn't free() pointer.
#+#:pointer-translation-not-yet-implemented
(deftest struct-values.translation.3
(alloc-pair 1 2)
(1 . 2))
(deftest struct-values.translation.mem-ref.1
(with-foreign-object (p '(:struct struct-pair))
(setf (mem-ref p '(:struct struct-pair)) '(1 . 2))
(with-foreign-slots ((a b) p (:struct struct-pair))
(values (mem-ref p '(:struct struct-pair))
a
b)))
(1 . 2)
1
2)
(deftest struct-values.translation.mem-aref.1
(with-foreign-object (p '(:struct struct-pair) 2)
(setf (mem-aref p '(:struct struct-pair) 0) '(1 . 2)
(mem-aref p '(:struct struct-pair) 1) '(3 . 4))
(values (mem-aref p '(:struct struct-pair) 0)
(mem-aref p '(:struct struct-pair) 1)))
(1 . 2)
(3 . 4))
(defcstruct (struct-pair-default-translate)
(a :int)
(b :int))
(deftest struct-values-default.translation.mem-ref.1
(with-foreign-object (p '(:struct struct-pair-default-translate))
(setf (mem-ref p '(:struct struct-pair-default-translate)) '(a 1 b 2))
(with-foreign-slots ((a b) p (:struct struct-pair-default-translate))
(let ((plist (mem-ref p '(:struct struct-pair-default-translate))))
(values (getf plist 'a)
(getf plist 'b)
a
b))))
1
2
1
2)
(defcstruct (struct-pair+double)
(pr (:struct struct-pair-default-translate))
(dbl :double))
(deftest struct-values-default.translation.mem-ref.2
(with-foreign-object (p '(:struct struct-pair+double))
(setf (mem-ref p '(:struct struct-pair+double)) '(pr (a 4 b 5) dbl 2.5d0))
(with-foreign-slots ((pr dbl) p (:struct struct-pair+double))
(let ((plist (mem-ref p '(:struct struct-pair+double))))
(values (getf (getf plist 'pr) 'a)
(getf (getf plist 'pr) 'b)
(getf plist 'dbl)))))
4
5
2.5d0)
(defcstruct (struct-pair+1 :class pair+1)
(p (:pointer (:struct struct-pair)))
(c :int))
(defctype struct-pair+1 (:struct struct-pair+1))
(defmethod translate-from-foreign (pointer (type pair+1))
(with-foreign-slots ((p c) pointer struct-pair+1)
(cons p c)))
(defmethod translate-into-foreign-memory (object (type pair+1) pointer)
(with-foreign-slots ((c) pointer struct-pair+1)
(convert-into-foreign-memory (car object)
'struct-pair
(foreign-slot-pointer pointer
'struct-pair+1
'p))
(setf c (cdr object))))
(defmethod translate-to-foreign (object (type pair+1))
(let ((p (foreign-alloc 'struct-pair+1)))
(translate-into-foreign-memory object type p)
(values p t)))
(defmethod free-translated-object (pointer (type pair+1) freep)
(when freep
(foreign-free pointer)))
#+#:pointer-translation-not-yet-implemented
(deftest struct-values.translation.ppo.1
(multiple-value-bind (p freep)
(convert-to-foreign '((1 . 2) . 3) 'struct-pair+1)
(assert freep)
(unwind-protect
(convert-from-foreign p 'struct-pair+1)
(free-converted-object p 'struct-pair+1 freep)))
((1 . 2) . 3))
#+#:unimplemented
(defcfun "pair_plus_one_sum" :int
(p (:struct pair+1)))
#+#:unused
(defcfun "pair_plus_one_pointer_sum" :int
(p (:pointer (:struct struct-pair+1))))
#+#:pointer-translation-not-yet-implemented
(deftest struct-values.translation.ppo.2
(pair-plus-one-pointer-sum '((1 . 2) . 3))
6)
(defcfun "make_pair_plus_one" (:struct struct-pair+1)
(a :int)
(b :int)
(c :int))
(defcfun "alloc_pair_plus_one" (:pointer (:struct struct-pair+1))
(a :int)
(b :int)
(c :int))
;; bogus: doesn't free() pointer.
#+#:pointer-translation-not-yet-implemented
(deftest struct-values.translation.ppo.3
(alloc-pair-plus-one 1 2 3)
((1 . 2) . 3))
(defcfun "pair_sum" :int
(p (:struct struct-pair)))
(defcfun "make_pair" (:struct struct-pair)
(a :int)
(b :int))
(deftest struct-values.fn.1
(pair-sum '(-1 . 2))
1)
(deftest struct-values.fn.2
(make-pair 13 17)
(13 . 17))
(defcstruct single-byte-struct
(a :uint8))
(deftest bare-struct-types.1
(eql (foreign-type-size 'single-byte-struct)
(foreign-type-size '(:struct single-byte-struct)))
t)
(defctype single-byte-struct-alias (:struct single-byte-struct))
(deftest bare-struct-types.2
(eql (foreign-type-size 'single-byte-struct-alias)
(foreign-type-size '(:struct single-byte-struct)))
t)
;;; Old-style access to inner structure fields.
(defcstruct inner-struct (x :int))
(defcstruct old-style-outer (inner inner-struct))
(defcstruct new-style-outer (inner (:struct inner-struct)))
(deftest old-style-struct-access
(with-foreign-object (s '(:struct old-style-outer))
(let ((inner-ptr (foreign-slot-pointer s 'old-style-outer 'inner)))
(setf (foreign-slot-value inner-ptr 'inner-struct 'x) 42))
(assert (pointerp (foreign-slot-value s 'old-style-outer 'inner)))
(foreign-slot-value (foreign-slot-value s 'old-style-outer 'inner)
'inner-struct 'x))
42)
(deftest new-style-struct-access
(with-foreign-object (s '(:struct new-style-outer))
(let ((inner-ptr (foreign-slot-pointer s 'new-style-outer 'inner)))
(setf (foreign-slot-value inner-ptr 'inner-struct 'x) 42))
(foreign-slot-value s 'new-style-outer 'inner))
(x 42))
;;; regression test: setting the value of aggregate slots.
(defcstruct aggregate-struct
(x :int)
(pair (:struct struct-pair))
(y :int))
(deftest set-aggregate-struct-slot
(with-foreign-objects ((pair-struct '(:struct struct-pair))
(aggregate-struct '(:struct aggregate-struct)))
(with-foreign-slots ((a b) pair-struct (:struct struct-pair))
(setf a 1 b 2)
(with-foreign-slots ((x pair y) aggregate-struct (:struct aggregate-struct))
(setf x 42 y 42)
(setf pair pair-struct)
(values x pair y))))
42
(1 . 2)
42)
;; TODO this needs to go through compile-file to exhibit the error
;; ("don't know how to dump #<CFFI::AGGREGATE-STRUCT-SLOT>"), but
;; there's no support for that, so let's leave it at toplevel here.
(defcstruct (aggregate-struct.acc :conc-name acc-)
(x :int)
(pair (:struct struct-pair))
(y :int))
(deftest set-aggregate-struct-slot.acc
(with-foreign-objects ((pair-struct '(:struct struct-pair))
(aggregate-struct '(:struct aggregate-struct)))
(with-foreign-slots ((a b) pair-struct (:struct struct-pair))
(setf a 1 b 2)
(setf (acc-x aggregate-struct) 42)
(setf (acc-y aggregate-struct) 42)
(setf (acc-pair aggregate-struct) pair-struct)
(values (acc-x aggregate-struct)
(acc-pair aggregate-struct)
(acc-y aggregate-struct))))
42
(1 . 2)
42)
;; Test with-foreign-slots :pointer access and new binding syntax
(defcstruct struct.wfs
(tv-secs :long)
(tv-usecs :long))
(deftest struct.with-foreign-slots.1
(with-foreign-object (tv 'struct.wfs)
(with-foreign-slots (((secs tv-secs) (usecs tv-usecs)) tv timeval)
(setf secs 100 usecs 200)
(values secs usecs)))
100 200)
(deftest struct.with-foreign-slots.2
(with-foreign-object (tv 'struct.wfs)
(with-foreign-slots (((:pointer tv-secs) (:pointer tv-usecs)
(secs tv-secs) (usecs tv-usecs))
tv timeval)
(setf secs 100 usecs 200)
(values (mem-ref tv-secs :long) (mem-ref tv-usecs :long))))
100 200)
(deftest struct.with-foreign-slots.3
(with-foreign-object (tv 'struct.wfs)
(with-foreign-slots (((psecs :pointer tv-secs) (pusecs :pointer tv-usecs) (secs tv-secs) (usecs tv-usecs)) tv timeval)
(setf secs 100 usecs 200)
(values (mem-ref psecs :long) (mem-ref pusecs :long))))
100 200)
| 22,107 | Common Lisp | .lisp | 571 | 33.042032 | 124 | 0.642156 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b654dde63b601dbf4fe2a5a6d0dd4f90f3a82abb443de1ca998d3f7bbf5c4950 | 43,010 | [
236401
] |
43,011 | libffi-types.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/libffi/libffi-types.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; libffi-types.lisp -- CFFI-Grovel definitions for libffi
;;;
;;; Copyright (C) 2009, 2010, 2011, 2017 Liam M. Healy <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
#+linux
(define "_GNU_SOURCE")
;; When installed through Mac Ports, libffi include files
;; will be found in /opt/local/include.
#+darwin
(cc-flags "-I/opt/local/include/")
#+openbsd
(cc-flags "-I/usr/local/include")
#+freebsd
(cc-flags "-I/usr/local/include")
(pkg-config-cflags "libffi" :optional t)
#+darwin
(include "ffi/ffi.h")
#-darwin
(include "ffi.h")
(cenum status
((:ok "FFI_OK"))
((:bad-typedef "FFI_BAD_TYPEDEF"))
((:bad-abi "FFI_BAD_ABI")))
#+freebsd
(cenum abi
((:default-abi "FFI_DEFAULT_ABI")))
#+(and windows x86-64)
(cenum abi
((:default-abi "FFI_DEFAULT_ABI"))
((:win64 "FFI_WIN64")))
#+(and windows (not x86-64))
(cenum abi
((:default-abi "FFI_DEFAULT_ABI"))
((:sysv "FFI_SYSV"))
((:stdcall "FFI_STDCALL")))
#-(or freebsd windows)
(cenum abi
((:default-abi "FFI_DEFAULT_ABI"))
#-x86-64
((:sysv "FFI_SYSV"))
#+x86-64
((:unix64 "FFI_UNIX64")))
(ctype ffi-abi "ffi_abi")
(ctype size-t "size_t")
(cstruct ffi-type "struct _ffi_type"
(size "size" :type size-t)
(alignment "alignment" :type :unsigned-short)
(type "type" :type :unsigned-short)
(elements "elements" :type :pointer))
(cstruct ffi-cif "ffi_cif"
(abi "abi" :type ffi-abi)
(argument-count "nargs" :type :unsigned-int)
(argument-types "arg_types" :type :pointer)
(return-type "rtype" :type :pointer)
(bytes "bytes" :type :unsigned-int)
(flags "flags" :type :unsigned-int))
(constant (+type-void+ "FFI_TYPE_VOID"))
(constant (+type-int+ "FFI_TYPE_INT"))
(constant (+type-float+ "FFI_TYPE_FLOAT"))
(constant (+type-double+ "FFI_TYPE_DOUBLE"))
(constant (+type-longdouble+ "FFI_TYPE_LONGDOUBLE"))
(constant (+type-uint8+ "FFI_TYPE_UINT8"))
(constant (+type-sint8+ "FFI_TYPE_SINT8"))
(constant (+type-uint16+ "FFI_TYPE_UINT16"))
(constant (+type-sint16+ "FFI_TYPE_SINT16"))
(constant (+type-uint32+ "FFI_TYPE_UINT32"))
(constant (+type-sint32+ "FFI_TYPE_SINT32"))
(constant (+type-uint64+ "FFI_TYPE_UINT64"))
(constant (+type-sint64+ "FFI_TYPE_SINT64"))
(constant (+type-struct+ "FFI_TYPE_STRUCT"))
(constant (+type-pointer+ "FFI_TYPE_POINTER"))
| 3,460 | Common Lisp | .lisp | 94 | 35.329787 | 80 | 0.694237 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | c1212611207d659b42b144d2c0f7a6d0c770360be1d013c45a7240a1cf5f5660 | 43,011 | [
7152
] |
43,012 | type-descriptors.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/libffi/type-descriptors.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; type-descriptors.lisp --- Build malloc'd libffi type descriptors
;;;
;;; Copyright (C) 2009, 2011 Liam M. Healy
;;;
;;; 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.
;;;
(in-package #:cffi)
(defmacro type-descriptor-ptr (type)
`(foreign-symbol-pointer ,(format nil "ffi_type_~(~A~)" type)))
(defmacro type-descriptor-ptr/integer (type)
`(foreign-symbol-pointer
,(format nil "ffi_type_~Aint~D"
(if (string-equal type "unsigned"
:end1 (min 8 (length (string type))))
"u" "s")
(* 8 (foreign-type-size type)))))
(defun %make-libffi-type-descriptor/struct (type)
(labels
((slot-multiplicity (slot)
(if (typep slot 'aggregate-struct-slot)
(slot-count slot)
1))
(number-of-items (structure-type)
"Total number of items in the foreign structure."
(loop for val being the hash-value of (structure-slots structure-type)
sum (slot-multiplicity val))))
(let* ((ptr (foreign-alloc '(:struct ffi-type)))
(nitems (number-of-items type))
(type-pointer-array
(foreign-alloc :pointer :count (1+ nitems))))
(loop for slot in (slots-in-order type)
for ltp = (make-libffi-type-descriptor
(parse-type (slot-type slot)))
with slot-counter = 0
do (if ltp
(loop
repeat (slot-multiplicity slot)
do (setf
(mem-aref
type-pointer-array :pointer slot-counter)
ltp)
(incf slot-counter))
(libffi-error nil
"Slot type ~A in foreign structure is unknown to libffi."
(unparse-type (slot-type slot)))))
(setf (mem-aref type-pointer-array :pointer nitems)
(null-pointer))
(macrolet ((store (slot value)
`(setf (foreign-slot-value ptr '(:struct ffi-type) ',slot) ,value)))
(store size 0)
(store alignment 0)
(store type +type-struct+)
(store elements type-pointer-array))
ptr)))
(defgeneric make-libffi-type-descriptor (object)
(:documentation "Build a libffi struct that describes the type for libffi. This will be used as a cached static read-only argument when the actual call happens.")
(:method ((object foreign-built-in-type))
(let ((type-keyword (type-keyword object)))
#.`(case type-keyword
,@(loop
:for type :in (append *built-in-float-types*
*other-builtin-types*)
:collect `(,type (type-descriptor-ptr ,type)))
,@(loop
:for type :in *built-in-integer-types*
:collect `(,type (type-descriptor-ptr/integer ,type)))
;; there's a generic error report in an :around method
)))
(:method ((type foreign-pointer-type))
;; simplify all pointer types into a void*
(type-descriptor-ptr :pointer))
(:method ((type foreign-struct-type))
(%make-libffi-type-descriptor/struct type))
(:method :around (object)
(let ((result (call-next-method)))
(assert result () "~S failed on ~S. That's bad."
'make-libffi-type-descriptor object)
result))
(:method ((type foreign-type-alias))
;; Set the type pointer on demand for alias types (e.g. typedef, enum, etc)
(make-libffi-type-descriptor (actual-type type))))
| 4,698 | Common Lisp | .lisp | 101 | 37.257426 | 164 | 0.609756 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 2296553b4a705911b6174c79388ac9df9f024e42cdc8d84ad78c6ccf0bb26651 | 43,012 | [
222259,
377070
] |
43,013 | libffi.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/libffi/libffi.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; libffi.lisp --- Load libffi
;;;
;;; Copyright (C) 2009, 2011 Liam M. Healy
;;;
;;; 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.
;;;
(in-package #:cffi)
(define-foreign-library (libffi)
(:darwin (:or "libffi.dylib" "libffi32.dylib" "/usr/lib/libffi.dylib"))
(:solaris (:or "/usr/lib/amd64/libffi.so" "/usr/lib/libffi.so"))
((:or :netbsd :freebsd :openbsd) "libffi.so")
(:unix (:or "libffi.so.8" "libffi32.so.8" "libffi.so.7" "libffi32.so.7" "libffi.so.6" "libffi32.so.6" "libffi.so.5" "libffi32.so.5" "libffi.so" "libffi32.so"))
(:windows (:or "libffi-8.dll" "libffi-7.dll" "libffi-6.dll" "libffi-5.dll" "libffi.dll"))
(t (:default "libffi")))
(load-foreign-library 'libffi)
| 1,793 | Common Lisp | .lisp | 35 | 49.8 | 161 | 0.717379 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 990c2eab8e4d04f2e3e313f08c19af71a940d3a66dcd54190455c49653604412 | 43,013 | [
101298
] |
43,014 | libffi-functions.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/libffi/libffi-functions.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; init.lisp --- Load libffi and define basics
;;;
;;; Copyright (C) 2009, 2010, 2011 Liam Healy <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
;;; See file:///usr/share/doc/libffi-dev/html/The-Basics.html#The-Basics
(defcfun ("ffi_prep_cif" libffi/prep-cif) status
(ffi-cif :pointer)
(ffi-abi abi)
(nargs :uint)
(rtype :pointer)
(argtypes :pointer))
(defcfun ("ffi_call" libffi/call) :void
(ffi-cif :pointer)
(function :pointer)
(rvalue :pointer)
(avalues :pointer))
| 1,647 | Common Lisp | .lisp | 39 | 40.666667 | 72 | 0.733791 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | a641270fcf8df26fe4e79827d5439e8a1eec7aaaa0f141eff5522ecf772e25a2 | 43,014 | [
12431,
316653
] |
43,015 | funcall.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/libffi/funcall.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; funcall.lisp -- FOREIGN-FUNCALL implementation using libffi
;;;
;;; Copyright (C) 2009, 2010, 2011 Liam M. Healy <[email protected]>
;;;
;;; 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.
;;;
(in-package #:cffi)
(define-condition libffi-error (cffi-error)
((function-name
:initarg :function-name :reader function-name)))
(define-condition simple-libffi-error (simple-error libffi-error)
())
(defun libffi-error (function-name format-control &rest format-arguments)
(error 'simple-libffi-error
:function-name function-name
:format-control format-control
:format-arguments format-arguments))
(defun make-libffi-cif (function-name return-type argument-types
&optional (abi :default-abi))
"Generate or retrieve the Call InterFace needed to call the function through libffi."
(let* ((argument-count (length argument-types))
(cif (foreign-alloc '(:struct ffi-cif)))
(ffi-argtypes (foreign-alloc :pointer :count argument-count)))
(loop
:for type :in argument-types
:for index :from 0
:do (setf (mem-aref ffi-argtypes :pointer index)
(make-libffi-type-descriptor (parse-type type))))
(unless (eql :ok (libffi/prep-cif cif abi argument-count
(make-libffi-type-descriptor (parse-type return-type))
ffi-argtypes))
(libffi-error function-name
"The 'ffi_prep_cif' libffi call failed for function ~S."
function-name))
cif))
(defun free-libffi-cif (ptr)
(foreign-free (foreign-slot-value ptr '(:struct ffi-cif) 'argument-types))
(foreign-free ptr))
(defun translate-objects-ret (symbols function-arguments types return-type call-form)
(translate-objects
symbols
function-arguments
types
return-type
(if (or (eql return-type :void)
(typep (parse-type return-type) 'translatable-foreign-type))
call-form
;; built-in types won't be translated by
;; expand-from-foreign, we have to do it here
`(mem-ref
,call-form
',(canonicalize-foreign-type return-type)))
t))
(defun foreign-funcall-form/fsbv-with-libffi (function function-arguments symbols types
return-type argument-types
&optional pointerp (abi :default-abi))
"A body of foreign-funcall calling the libffi function #'call (ffi_call)."
(let ((argument-count (length argument-types)))
`(with-foreign-objects ((argument-values :pointer ,argument-count)
,@(unless (eql return-type :void)
`((result ',return-type))))
,(translate-objects-ret
symbols function-arguments types return-type
;; NOTE: We must delay the cif creation until the first call
;; because it's FOREIGN-ALLOC'd, i.e. it gets corrupted by an
;; image save/restore cycle. This way a lib will remain usable
;; through a save/restore cycle if the save happens before any
;; FFI calls will have been made, i.e. nothing is malloc'd yet.
`(progn
(loop
:for arg :in (list ,@symbols)
:for count :from 0
:do (setf (mem-aref argument-values :pointer count) arg))
(let* ((libffi-cif-cache (load-time-value (cons 'libffi-cif-cache nil)))
(libffi-cif (or (cdr libffi-cif-cache)
;; TODO use compare-and-swap to set it and call
;; FREE-LIBFFI-CIF when someone else did already.
(setf (cdr libffi-cif-cache)
;; FIXME we should install a finalizer on the cons cell
;; that calls FREE-LIBFFI-CIF on the cif (when the function
;; gets redefined, and the cif becomes unreachable). but a
;; finite world is full of compromises... - attila
(make-libffi-cif ,function ',return-type
',argument-types ',abi)))))
(libffi/call libffi-cif
,(if pointerp
function
`(foreign-symbol-pointer ,function))
,(if (eql return-type :void) '(null-pointer) 'result)
argument-values)
,(if (eql return-type :void)
'(values)
'result)))))))
(setf *foreign-structures-by-value* 'foreign-funcall-form/fsbv-with-libffi)
;; DEPRECATED Its presence encourages the use of #+fsbv which may lead to the
;; situation where a fasl was produced by an image that has fsbv feature
;; and then ends up being loaded into an image later that has no fsbv support
;; loaded. Use explicit ASDF dependencies instead and assume the presence
;; of the feature accordingly.
(pushnew :fsbv *features*)
;; DEPRECATED This is here only for backwards compatibility until its fate is
;; decided. See the mailing list discussion for details.
(defctype :sizet size-t)
| 6,437 | Common Lisp | .lisp | 123 | 41.276423 | 100 | 0.617008 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 2c002c2eeebdf891f3e253968fd5ff5c7b5731d25f3789c9ab0aef84782b3b3d | 43,015 | [
408688
] |
43,016 | static-link.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/toolchain/static-link.lisp | ;; FIXME: arrange packages so that this can be moved in ASDF some time later?
(in-package #:cffi-toolchain)
(defun static-ops-enabled-p ()
(ensure-toolchain-parameters)
(and (or *linkkit-start* *linkkit-end*) t))
(defclass static-runtime-op (monolithic-bundle-op link-op selfward-operation) ()
(:documentation "Create a Lisp runtime linkable library for the system and its dependencies."))
(defmethod bundle-type ((o static-runtime-op)) :program)
(defmethod selfward-operation ((o static-runtime-op)) 'monolithic-lib-op)
(defmethod output-files ((o static-runtime-op) (s system))
#-(or ecl mkcl)
(list (subpathname (component-pathname s)
(strcat (coerce-name s) "-runtime")
:type (bundle-pathname-type :program))))
(defmethod perform ((o static-runtime-op) (s system))
(link-lisp-executable
(output-file o s)
(link-all-library (first (input-files o s)))))
(defclass static-image-op (image-op) ()
(:documentation "Create a statically linked standalone image for the system."))
#-(or ecl mkcl) (defmethod selfward-operation ((o static-image-op)) '(load-op static-runtime-op))
#+(or ecl mkcl) (defmethod gather-operation ((o static-image-op)) 'compile-op)
#+(or ecl mkcl) (defmethod gather-operation ((o static-image-op)) :object)
(defclass static-program-op (program-op static-image-op) ()
(:documentation "Create a statically linked standalone executable for the system."))
;; Problem? Its output may conflict with the program-op output :-/
#-(or ecl mkcl)
(defmethod perform ((o static-image-op) (s system))
#-(or clisp sbcl) (error "Not implemented yet")
#+(or clisp sbcl)
(let* ((name (coerce-name s))
(runtime (output-file 'static-runtime-op s))
(image
#+clisp (implementation-file "base/lispinit.mem")
#+sbcl (subpathname (lisp-implementation-directory) "sbcl.core"))
(output (output-file o s))
(child-op (if (typep o 'program-op) 'program-op 'image-op)))
(with-temporary-output (tmp output)
(apply 'invoke runtime
#+clisp "-M" #+sbcl "--core" image
`(#+clisp ,@'("--silent" "-ansi" "-norc" "-x")
#+sbcl ,@'("--noinform" "--non-interactive" "--no-sysinit" "--no-userinit" "--eval")
,(with-safe-io-syntax (:package :asdf)
(let ((*print-pretty* nil)
(*print-case* :downcase))
(format
;; This clever staging allows to put things in a single form,
;; as required for CLISP not to print output for the first form,
;; yet allow subsequent forms to rely on packages defined by former forms.
nil "'(~@{#.~S~^ ~})"
'(require "asdf")
'(in-package :asdf)
`(progn
(setf asdf:*central-registry* ',asdf:*central-registry*)
(initialize-source-registry ',asdf::*source-registry-parameter*)
(initialize-output-translations ',asdf::*output-translations-parameter*)
(upgrade-asdf)
,@(if-let (ql-home
(symbol-value (find-symbol* '*quicklisp-home* 'ql-setup nil)))
`((load ,(subpathname ql-home "setup.lisp"))))
(load-system "cffi-grovel")
;; We force the (final step of the) operation to take place
(defmethod operation-done-p
((operation ,child-op) (system (eql (find-system ,name))))
nil)
;; Some implementations (notably SBCL) die as part of dumping an image,
;; so redirect output-files to desired destination, for this processs might
;; never otherwise get a chance to move the file to destination.
(defmethod output-files
((operation ,child-op) (system (eql (find-system ,name))))
(values (list ,tmp) t))
(operate ',child-op ,name)
(quit))))))))))
#+(or ecl mkcl)
(defmethod perform ((o static-image-op) (s system))
(let (#+ecl
(c::*ld-flags*
(format nil "-Wl,--export-dynamic ~@[ ~A~]"
c::*ld-flags*)))
(call-next-method)))
;; Allow for :static-FOO-op in ASDF definitions.
(setf (find-class 'asdf::static-runtime-op) (find-class 'static-runtime-op)
(find-class 'asdf::static-image-op) (find-class 'static-image-op)
(find-class 'asdf::static-program-op) (find-class 'static-program-op))
| 4,750 | Common Lisp | .lisp | 84 | 43.964286 | 99 | 0.576369 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | 05778382af9ad9fb1e0285d4e2e073720ca886ed30be6b8a19e21273db38f207 | 43,016 | [
458917
] |
43,017 | package.lisp | NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cffi-20221106-git/toolchain/package.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; package.lisp --- Toolchain DEFPACKAGE.
;;;
;;; 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.
;;;
(uiop:define-package #:cffi-toolchain
(:mix #:asdf #:uiop #:common-lisp)
(:import-from #:asdf/bundle
#:link-op #:bundle-pathname-type #:bundle-type
#:gather-operation #:gather-type)
(:export
;; Variables
#:*cc* #:*cc-flags*
#:*ld* #:*ld-exe-flags* #:*ld-dll-flags*
#:*linkkit-start* #:*linkkit-end*
;; Functions from c-toolchain
#:make-c-file-name #:make-o-file-name
#:make-so-file-name #:make-exe-file-name
#:parse-command-flags #:parse-command-flags-list
#:invoke #:invoke-build #:cc-compile
#:link-static-library #:link-shared-library
#:link-executable #:link-lisp-executable
;; ASDF classes
#:c-file #:o-file
#:static-runtime-op #:static-image-op #:static-program-op
))
| 1,932 | Common Lisp | .lisp | 45 | 40.644444 | 70 | 0.716331 | NailykSturm/Info805-TP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:51:23 AM (Europe/Amsterdam) | b9603b840ef3f93e226b4ee5f8851b4c6e8712fb00ed8c88d6d63aafe4a2badd | 43,017 | [
374623
] |