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
30,172
grovel.lisp
ivankocienski_xpng/src/grovel.lisp
(flag "-I/opt/local/include") (include "png.h") (in-package #:xpng) (constant (+png-color-mask-palette+ "PNG_COLOR_MASK_PALETTE")) (constant (+png-color-mask-color+ "PNG_COLOR_MASK_COLOR")) (constant (+png-color-mask-alpha+ "PNG_COLOR_MASK_ALPHA")) (constant (+png-color-type-palette+ "PNG_COLOR_TYPE_PALETTE")) (constant (+png-color-type-gray+ "PNG_COLOR_TYPE_GRAY")) (constant (+png-color-type-gray-alpha+ "PNG_COLOR_TYPE_GRAY_ALPHA")) (constant (+png-color-type-rgb+ "PNG_COLOR_TYPE_RGB")) (constant (+png-color-type-rgba+ "PNG_COLOR_TYPE_RGB_ALPHA")) (constant (+png-transform-strip-16+ "PNG_TRANSFORM_STRIP_16")) (constant (+png-transform-strip-alpha+ "PNG_TRANSFORM_STRIP_ALPHA")) (constant (+png-transform-swap-endian+ "PNG_TRANSFORM_SWAP_ENDIAN")) (constant (+png-transform-identity+ "PNG_TRANSFORM_IDENTITY")) (constant (+png-compression-type-base+ "PNG_COMPRESSION_TYPE_BASE")) (constant (+png-compression-type-default+ "PNG_COMPRESSION_TYPE_DEFAULT")) (constant (+png-filter-type-base+ "PNG_FILTER_TYPE_BASE")) (constant (+png-filter-type-default+ "PNG_FILTER_TYPE_DEFAULT")) ;; misc (constant (+png-interlace-none+ "PNG_INTERLACE_NONE")) (constant (+png-info-trns+ "PNG_INFO_tRNS")) (ctype ssize "ssize_t") (ctype size "size_t") (ctype png-size "png_size_t")
1,318
Common Lisp
.lisp
25
51.36
74
0.711838
ivankocienski/xpng
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
7cbc5d2ac1da841ae4d08df0504569bc91876034d6657dec99cefe28e64f821d
30,172
[ -1 ]
30,173
ffi.lisp
ivankocienski_xpng/src/ffi.lisp
(in-package :xpng) (define-foreign-library libpng ;; (:unix (:or "libpng12.0.dylib" "libpng12.dylib" "libpng12.so.0")) (t (:default "libpng16"))) (use-foreign-library libpng) (defconstant +png-libpng-ver-string+ (symbol-name '|1.6.16|)) ;;; Foreign function definitions. (defcfun "png_access_version_number" :uint32) (defcfun "png_create_read_struct" :pointer (user-png-ver :string) (error-ptr :pointer) (error-fn :pointer) (warn-fn :pointer)) (defcfun "png_destroy_read_struct" :void (png-ptr-ptr :pointer) (info-ptr-ptr :pointer) (end-info-ptr-ptr :pointer)) (defcfun "png_create_write_struct" :pointer (user-png-ver :string) (error-ptr :pointer) (error-fn :pointer) (warn-fn :pointer)) (defcfun "png_destroy_write_struct" :void (png-ptr-ptr :pointer) (info-ptr-ptr :pointer)) (defcfun "png_create_info_struct" :pointer (png-ptr :pointer)) (defcfun "png_destroy_info_struct" :void (png-ptr :pointer) (info-ptr-ptr :pointer)) (defcfun "png_init_io" :void (png-ptr :pointer) (file :pointer)) (defcfun "png_set_read_fn" :void (png-ptr :pointer) (io-ptr :pointer) (read-data-fn :pointer)) (defcfun "png_set_write_fn" :void (png-ptr :pointer) (io-ptr :pointer) (write-data-fn :pointer) (output-flush-fn :pointer)) (defcfun "png_get_io_ptr" :pointer (png-ptr :pointer)) (defcfun "png_read_info" :void (png-ptr :pointer) (info-ptr :pointer)) (defcfun "png_read_png" :void (png-ptr :pointer) (info-ptr :pointer) (png-transforms :int) (params :pointer)) (defcfun "png_get_IHDR" :uint32 (png-ptr :pointer) (info-ptr :pointer) (width-uint32-ptr :pointer) (height-uint32-ptr :pointer) (bit-depth-int-ptr :pointer) (color-type-int-ptr :pointer) (interlace-type-int-ptr :pointer) (compression-type-int-ptr :pointer) (filter-type-int-ptr :pointer)) (defcfun "png_set_IHDR" :void (png-ptr :pointer) (info-ptr :pointer) (width :uint32) (height :uint32) (bit-depth :int) (color-type :int) (interlace-type :int) (compression-type :int) (filter-type :int)) (defcfun "png_get_PLTE" :int32 (png-ptr :pointer) (png-info :pointer) (palette :pointer) (num-colors :pointer)) (defcfun "png_set_palette_to_rgb" :void (png-ptr :pointer)) (defcfun "png_set_expand_gray_1_2_4_to_8" :void (png-ptr :pointer)) (defcfun "png_set_expand" :void (png-ptr :pointer)) (defcfun "png_get_valid" :uint32 (png-ptr :pointer) (info-ptr :pointer) (flag :uint32)) (defcfun "png_set_tRNS_to_alpha" :void (png-ptr :pointer)) (defcfun "png_set_strip_16" :void (png-ptr :pointer)) (defcfun "png_set_packing" :void (png-ptr :pointer)) (defcfun "png_set_strip_alpha" :void (png-ptr :pointer)) (defcfun "png_set_swap" :void (png-ptr :pointer)) (defcfun "png_get_rows" :pointer (png-ptr :pointer) (info-ptr :pointer)) (defcfun "png_set_rows" :void (png-ptr :pointer) (info-ptr :pointer) (row-pointers :pointer)) (defcfun "png_read_image" :void (png-ptr :pointer) (row-pointers :pointer)) (defcfun "png_read_end" :void (png-ptr :pointer) (info-ptr :pointer)) (defcfun "png_write_png" :void (png-ptr :pointer) (info-ptr :pointer) (transforms :int) (params :pointer)) (defcfun "memcpy" :pointer (dest :pointer) (source :pointer) (n :uint)) (defvar *stream*) (defvar *buffer*) (defun ensure-buffer-sufficient (needed) (when (< (length *buffer*) needed) (let ((new-length (length *buffer*))) (loop while (< new-length needed) do (setf new-length (* 2 new-length))) (setf *buffer* (make-shareable-byte-vector new-length))))) (defcallback user-read-data :void ((png-ptr :pointer) (data :pointer) (length png-size)) (declare (ignore png-ptr)) (ensure-buffer-sufficient length) (let ((bytes-read (read-sequence *buffer* *stream* :start 0 :end length))) (unless (= bytes-read length) (error "Expected to read ~D bytes, but only read ~D." length bytes-read))) (with-pointer-to-vector-data (buffer-ptr *buffer*) (memcpy data buffer-ptr length))) (defcallback user-flush-data :void ((png-ptr :pointer)) (declare (ignore png-ptr))) ;;; Error handling. (defcallback error-fn :void ((png-structp :pointer) (message :string)) (declare (ignore png-structp)) (error message)) (defcallback warn-fn :void ((png-structp :pointer) (message :string)) (declare (ignore png-structp)) (error message))
5,121
Common Lisp
.lisp
146
27.239726
93
0.592796
ivankocienski/xpng
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
d172e13f4fb35f6aa25b760d8a6876161e9d1aef09e26727c2c8e0fa82a7990f
30,173
[ -1 ]
30,174
common.lisp
ivankocienski_xpng/src/common.lisp
(in-package #:xpng) (defmacro with-png-struct ((var) &body body) "allocate space for PNG data structure" (let ((pointer (gensym "POINTER"))) `(let ((,var (png-create-read-struct +png-libpng-ver-string+ (null-pointer) (callback error-fn) (callback warn-fn))) (*buffer* (make-shareable-byte-vector 1024))) (when (null-pointer-p ,var) (error "Failed to allocate PNG write struct.")) (unwind-protect (progn ,@body) (with-foreign-pointer (,pointer (foreign-type-size :pointer)) (setf (mem-ref ,pointer :pointer) ,var) (png-destroy-read-struct ,pointer (null-pointer) (null-pointer))))))) (defmacro with-png-info-struct ((var png-struct) &body body) (let ((pointer (gensym "POINTER"))) `(let ((,var (png-create-info-struct ,png-struct))) (when (null-pointer-p ,var) (error "Failed to allocate PNG info struct.")) (unwind-protect (progn ,@body) (with-foreign-pointer (,pointer (foreign-type-size :pointer)) (setf (mem-ref ,pointer :pointer) ,var) (png-destroy-info-struct ,png-struct ,pointer)))))) (defmacro with-row-pointers ((rows-ptr image) &body body) (let ((row-pointers (gensym "ROW-POINTERS")) (raw-data (gensym "RAW-DATA")) (row-pos (gensym "I")) (buffer (gensym "BUFFER")) (ptr-inc (gensym "PTR-INC"))) `(let ((,row-pointers (make-shareable-byte-vector (* (image-height ,image) (foreign-type-size :pointer)))) (,buffer (image-pixels ,image)) (,ptr-inc (* (image-width ,image) (image-pixel-size ,image)))) (with-pointer-to-vector-data (,rows-ptr ,row-pointers) (with-pointer-to-vector-data (,raw-data ,buffer) (dotimes (,row-pos (image-height ,image)) (setf (mem-aref ,rows-ptr :pointer ,row-pos) (inc-pointer ,raw-data (* ,row-pos ,ptr-inc)))) ,@body)))))
1,993
Common Lisp
.lisp
44
37.363636
78
0.613419
ivankocienski/xpng
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
b2169347e5743ec690bd54fd48b93cf2c22b71319543fb9d4b556d71bf333cf9
30,174
[ -1 ]
30,175
compat.lisp
ivankocienski_xpng/src/compat.lisp
(in-package #:xpng) #-(or lispworks allegro) (defun make-shareable-byte-vector (size &optional (byte-size 8)) (make-array size :element-type (list 'unsigned-byte byte-size))) (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)) (nbytes (gensym))) `(let* ((,vector-var ,vector)) (with-foreign-pointer (,ptr-var (length ,vector-var) ,nbytes) ;; copy-in (loop for word from 0 and byte below ,nbytes do (cffi-sys:%mem-set (aref ,vector-var word) ,ptr-var :unsigned-char byte)) (unwind-protect (progn ,@body) ;; copy-out (loop for word from 0 and byte below ,nbytes do (setf (aref ,vector-var word) (cffi-sys:%mem-ref ,ptr-var :unsigned-char byte))))))))
905
Common Lisp
.lisp
22
33.727273
81
0.618881
ivankocienski/xpng
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
214961724c6f62b1c05930aaf55bfdc33e2b333c06968dd2cb975c4958712fa2
30,175
[ -1 ]
30,176
xpng-test.asd
ivankocienski_xpng/xpng-test.asd
;;;; -*- Mode: Lisp; -*- (asdf:defsystem :xpng-test :components ((:file "test/test")) :depends-on (#:xpng :lisp-unit))
125
Common Lisp
.asd
4
28.75
35
0.605042
ivankocienski/xpng
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
d38e98b71bed052bdaa9e407fcb6fa02f8f4e5ca33b795d2080597833d73bc9a
30,176
[ -1 ]
30,177
xpng.asd
ivankocienski_xpng/xpng.asd
;;;; -*- Mode: Lisp; -*- (in-package #:cl-user) (eval-when (:load-toplevel :execute) (asdf:operate 'asdf:load-op '#:cffi-grovel)) (asdf:defsystem #:xpng :description "Read PNG (Portable Network Graphics) files." :depends-on (#:cffi) :serial T :components ((:file "src/package") (cffi-grovel:grovel-file "src/grovel") (:file "src/ffi") (:file "src/compat") (:file "src/common") (:file "src/image") (:file "src/decode"))) (asdf:defsystem #:xpng-gl :description "Upload PNGs to GL textures" :depends-on (#:xpng #:cl-opengl) :serial t :components ((:file "src/gl"))) (asdf:defsystem #:xpng-gl-demo :description "Demo app for XPNG-GL" :depends-on (#:xpng-gl #:cl-glfw3) :serial t :components ((:file "demo/gl-demo")))
801
Common Lisp
.asd
25
27.52
60
0.623377
ivankocienski/xpng
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
9ee70f8b8b1fca2fb85bb48cc9b652882bea70f89426063029912f31ffb4ecdb
30,177
[ -1 ]
30,190
index.html
ivankocienski_xpng/doc/index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE>CL-PNG</TITLE> <style type="text/css"> body { } hr { color: #000; background-color: #000; height: 1px; } div.narrow { max-width: 80ex; } table.paste-area tr td { min-width: 80ex; } body { background: white; color: black; } .paste { background-color: #F4F4F4; color: black; } .paste:hover { background-color: #F4F4F4; color: black; } .symbol { color : #770055; background-color : transparent; border: 0px; margin: 0px;} a.symbol:link { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; } a.symbol:active { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; } a.symbol:visited { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; } a.symbol:hover { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; } .special { color : #FF5000; background-color : inherit; } .keyword { color : #770000; background-color : inherit; } .comment { color : #007777; background-color : inherit; } .string { color : #777777; background-color : inherit; } .atom { color : #314F4F; background-color : inherit; } .macro { color : #FF5000; background-color : inherit; } .variable { color : #36648B; background-color : inherit; } .function { color : #8B4789; background-color : inherit; } .attribute { color : #FF5000; background-color : inherit; } .character { color : #0055AA; background-color : inherit; } .syntaxerror { color : #FF0000; background-color : inherit; } span.paren1 { background-color : inherit; -webkit-transition: background-color 0.2s linear; } span.paren1:hover { color : inherit; background-color : #BAFFFF; } span.paren2 { background-color : inherit; -webkit-transition: background-color 0.2s linear; } span.paren2:hover { color : inherit; background-color : #FFCACA; } span.paren3 { background-color : inherit; -webkit-transition: background-color 0.2s linear; } span.paren3:hover { color : inherit; background-color : #FFFFBA; } span.paren4 { background-color : inherit; -webkit-transition: background-color 0.2s linear; } span.paren4:hover { color : inherit; background-color : #CACAFF; } span.paren5 { background-color : inherit; -webkit-transition: background-color 0.2s linear; } span.paren5:hover { color : inherit; background-color : #CAFFCA; } span.paren6 { background-color : inherit; -webkit-transition: background-color 0.2s linear; } span.paren6:hover { color : inherit; background-color : #FFBAFF; } </style> </HEAD> <BODY> <div class="narrow"> <P><a href="http://www.ljosa.com/~ljosa/">Vebjorn Ljosa</a> » <a href="http://www.ljosa.com/~ljosa/software/">Software</a> » CL-PNG <h1>CL-PNG</h1> <p>CL-PNG is a Common Lisp library for reading and writing PNG (Portable Network Graphics) files. It is currently maintained by <a href="http://www.ljosa.com/~ljosa/contact">Vebjorn Ljosa</a>, and new versions can be found at the CL-PNG homepage, <A href="http://www.ljosa.com/~ljosa/software/cl-png/">http://www.ljosa.com/~ljosa/software/cl-png/</a>. <p>Copyright © 2001–2009 by the authors (see the file <A href="http://svn.ljosa.com/cl-png/trunk/AUTHORS">AUTHORS</A>). Licensed under the GNU Lesser General Public License; see the file <A href="http://svn.ljosa.com/cl-png/trunk/COPYING">COPYING</A> for details. This manual is in the public domain. <p>Table of contents: <ol> <li><a href="#Status">Status</a> <li><a href="#Download">Download</a> <li><a href="#Installation">Installation</a> <li><a href="#Example">Example</a> <li><a href="#API">API reference</a> <li><a href="#Index">Symbol index</a> </ol> <h2><a name="Status">Status</a></h2> <p>Since version 0.5, CL-PNG uses a foreign function interface to call <a href="http://www.libpng.org/pub/png/libpng.html">libpng</a>, the official PNG reference library. As a result, it benefits from all the effort that has been put into that library: CL-PNG is much faster than before, and better able to handle corner cases. <p>The interface is likely to change in future versions. Please <a href="http://www.ljosa.com/~ljosa/contact">report</a> on your experience with the current interface. <p>The current version has the following limitation: <ul> <li>Alpha channels and metadata (such as timestamps and comments) cannot be included when writing an image. They are silently ignored when reading an image. </ul> <p>CL-PNG 0.6 has been verified to work on the following platforms. <ul> <li>SBCL on Linux (x86_64) and Mac OS X (i386) <li>Clozure CL on Mac OS X (ppc and x86_64) <li>CLISP on Linux (x86_64) <li>Allegro CL on Mac OS X (i386 and ppc) <li>LispWorks on Mac OS X (i386) </ul> <p>Please <a href="http://www.ljosa.com/~ljosa/contact">report</a> success/failure on other platforms. <h2><a name="Download">Download</a></h2> <ul> <li>Version 0.6: <A href="http://www.ljosa.com/~ljosa/software/cl-png/download/cl-png-0.6.tar.gz">http://www.ljosa.com/~ljosa/software/cl-png/download/cl-png-0.6.tar.gz</A> <li><a href="http://svn.ljosa.com/cl-png/tags/REL_0_6">Individual source code files</a> (in case you would like to take a look at the code before downloading) <li>Older versions: <A href="http://www.ljosa.com/~ljosa/software/cl-png/download/">http://www.ljosa.com/~ljosa/software/cl-png/download/</A> <li>SVN repository: <a href="http://svn.ljosa.com/cl-png/">http://svn.ljosa.com/cl-png/</a> </ul> <h2><a name="Installation">Installation</a></h2> <p>CL-PNG depends on <a href="http://www.libpng.org/pub/png/libpng.html">libpng</a> (your operating system distribution may have a separate package, called <tt>libpng-dev</tt> or something similar, that contains the required <tt>png.h</tt> header file) and <a href="http://common-lisp.net/project/cffi/">CFFI</a>. CFFI in turn depends on <a href="http://common-lisp.net/project/alexandria/">Alexandria</a>, <a href="http://common-lisp.net/project/babel/">Babel</a>, and <a href="http://www.cliki.net/trivial-features">trivial-features</a>. <p>If you have <a href="http://common-lisp.net/project/asdf-install/">ASDF-INSTALL</a>, installation is easy: the following takes care of CL-PNG and all dependencies: <pre> (asdf-install:install '#:png) </pre> <p>Otherwise, install the dependencies, then symlink <tt>png.asd</tt> (and, if you'd like to run the unit tests, <tt>png-test.asd</tt>) to one of the directories in <a href="http://constantly.at/lisp/asdf/Using-asdf-to-load-systems.html#Using%20asdf%20to%20load%20systems"><b>asdf:*central-registry*</b></a>. Then, evaluate <code>(asdf:oos 'asdf:load-op '#:png)</code> in order to compile and load CL-PNG.</p> <p>On Mac OS X 10.4, you may discover that the C compiler does not accept the <code>-m32</code> option that <a href="http://common-lisp.net/project/cffi/manual/html_node/The-Groveller.html">CFFI-Grovel</a> attempts to pass to it. You will need to work around this, for instance by settings <b>cffi-grovel::*cpu-word-size-flags*</b> to the empty string. <p>If you would like to run the unit tests, evaluate <code>(asdf:oos 'adsf:load-op '#:png-test)</code> followed by <code>(lisp-unit:run-all-tests #:png-test)</code>. <h2><a name="Example">Example</a></h2> </div> <table class="paste-area"><tr><td bgcolor="#F4F4F4" colspan="2" width="100%"><tt><span class="paste"><span class="paren1">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/m_defun.htm" class="symbol"><i><span class="symbol">defun</span></i></a> rotate <span class="paren2">(<span class="paste">input-pathname output-pathname</span>)</span><br>&nbsp;&nbsp;<span class="string">"Read a PNG image, rotate it 90 degrees, and write it to a new file."</span><br>&nbsp;&nbsp;<span class="paren2">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/s_let_l.htm" class="symbol"><i><span class="symbol">let*</span></i></a> <span class="paren3">(<span class="paste"><span class="paren4">(<span class="paste">old <span class="paren5">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/m_w_open.htm" class="symbol"><i><span class="symbol">with-open-file</span></i></a> <span class="paren6">(<span class="paste">input input-pathname <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">:element-type</span> '<span class="paren1">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/t_unsgn_.htm" class="symbol">unsigned-byte</a> 8</span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="paren6">(<span class="paste"><a href="#decode" class="symbol">png:decode</a> input</span>)</span></span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="paren4">(<span class="paste">new <span class="paren5">(<span class="paste"><a href="#make-image" class="symbol">png:make-image</a> <span class="paren6">(<span class="paste"><a href="#image-width" class="symbol">png:image-width</a> old</span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="paren6">(<span class="paste"><a href="#image-height" class="symbol">png:image-height</a> old</span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="paren6">(<span class="paste"><a href="#image-channels" class="symbol">png:image-channels</a> old</span>)</span></span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="paren4">(<span class="paste">m <span class="paren5">(<span class="paste"><a href="#image-width" class="symbol">png:image-width</a> old</span>)</span></span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="paren3">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/m_dotime.htm" class="symbol">dotimes</a> <span class="paren4">(<span class="paste">i <span class="paren5">(<span class="paste"><a href="#image-height" class="symbol">png:image-height</a> new</span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="paren4">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/m_dotime.htm" class="symbol">dotimes</a> <span class="paren5">(<span class="paste">j <span class="paren6">(<span class="paste"><a href="#image-width" class="symbol">png:image-width</a> new</span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;<span class="paren5">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/m_dotime.htm" class="symbol">dotimes</a> <span class="paren6">(<span class="paste">k <span class="paren1">(<span class="paste"><a href="#image-channels" class="symbol">png:image-channels</a> new</span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<span class="paren6">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/a_setf.htm" class="symbol">setf</a> <span class="paren1">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/f_aref.htm" class="symbol">aref</a> new i j k</span>)</span> <span class="paren1">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/f_aref.htm" class="symbol">aref</a> old j <span class="paren2">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/a__.htm" class="symbol">-</a> m i 1</span>)</span> k</span>)</span></span>)</span></span>)</span></span>)</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="paren3">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/m_w_open.htm" class="symbol"><i><span class="symbol">with-open-file</span></i></a> <span class="paren4">(<span class="paste">output output-pathname <span class="keyword">:element-type</span> '<span class="paren5">(<span class="paste"><a href="http://www.lispworks.com/reference/HyperSpec/Body/t_unsgn_.htm" class="symbol">unsigned-byte</a> 8</span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">:direction</span> <span class="keyword">:output</span> <span class="keyword">:if-exists</span> <span class="keyword">:supersede</span></span>)</span><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="paren4">(<span class="paste"><a href="#encode" class="symbol">png:encode</a> new output</span>)</span></span>)</span></span>)</span></span>)</span></span></tt></td></tr></table> <div class="narrow"> <h2><a name="API">API reference</a></h2> <p><a name="image"><i>Type</i> <b>IMAGE</b></a> <p><b>Supertypes:</b><p><a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_array.htm"><b>array</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_t.htm"><b>t</b></a> <p><b>Description:</b> <p>An image is a three-dimensional array of <tt>(unsigned-byte 8)</tt> or <tt>(unsigned-byte 16)</tt>. The three dimensions represent row, column, and <a href="http://en.wikipedia.org/wiki/Channel_(digital_image)">channel</a>. In other words, <tt>(aref image i j k)</tt> is the intensity in the <tt>k</tt>-th channel of the pixel in the <tt>i</tt>-th row and <tt>j</tt>-th column of <tt>image</tt>.</p> <p>In the current version, an image is displaced to a one-dimensional <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_smp_ar.htm"><b>simple-array</b></a> with the same total number of elements, but applications should not rely on this implementation detail, as it is likely to change in future versions. The functions <a href="#make-image"><b>make-image</b></a>, <a href="#decode"><b>decode</b></a>, <a href="#copy-image"><b>copy-image</b></a>, <a href="#f_8-bit-image"><b>8-bit-image</b></a>, and <a href="#f_16-bit-image"><b>16-bit-image</b></a> return images.</p> <p><b>Compound Type Specifier Kind:</b> <p>Specializing. <p><b>Compound Type Specifier Syntax:</b> <p><b>image</b> <i>[{ height | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { width | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { channels | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> }]</i> <p><b>Compound Type Specifier Arguments:</b> <p><i>height, width, channels</i>---<a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimensions</a> <hr> <p><a name="8-bit-image"><i>Type</i> <b>8-BIT-IMAGE</b></a> <p><b>Supertypes:</b><p><a href="#image"><b>image</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_array.htm"><b>array</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_t.htm"><b>t</b></a> <p><b>Description:</b> <p>An <a href="#image"><b>image</b></a> with <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_a.htm#array_element_type">element type</a> <code>(unsigned-byte 8)</code>.</p> <p><b>Compound Type Specifier Kind:</b> <p>Specializing. <p><b>Compound Type Specifier Syntax:</b> <p><b>8-bit-image</b> <i>[{ height | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { width | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { channels | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> }]</i> <p><b>Compound Type Specifier Arguments:</b> <p><i>height, width, channels</i>---<a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimensions</a> <hr> <p><a name="16-bit-image"><i>Type</i> <b>16-BIT-IMAGE</b></a> <p><b>Supertypes:</b><p><a href="#image"><b>image</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_array.htm"><b>array</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_t.htm"><b>t</b></a> <p><b>Description:</b> <p>An <a href="#image"><b>image</b></a> with <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_a.htm#array_element_type">element type</a> <code>(unsigned-byte 16)</code>.</p> <p><b>Compound Type Specifier Kind:</b> <p>Specializing. <p><b>Compound Type Specifier Syntax:</b> <p><b>8-bit-image</b> <i>[{ height | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { width | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { channels | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> }]</i> <p><b>Compound Type Specifier Arguments:</b> <p><i>height, width, channels</i>---<a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimensions</a> <hr> <p><a name="grayscale-image"><i>Type</i> <b>GRAYSCALE-IMAGE</b></a> <p><b>Supertypes:</b><p><a href="#image"><b>image</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_array.htm"><b>array</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_t.htm"><b>t</b></a> <p><b>Description:</b> <p>An <a href="#image"><b>image</b></a> with one <a href="http://en.wikipedia.org/wiki/Channel_(digital_image)">channel</a>.</p> <p><b>Compound Type Specifier Kind:</b> <p>Specializing. <p><b>Compound Type Specifier Syntax:</b> <p><b>grayscale-image</b> <i>[{ height | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { width | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> }]</i> <p><b>Compound Type Specifier Arguments:</b> <p><i>height, width</i>---<a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimensions</a> <p><b>Notes:</b> <p><tt>(grayscale-image n m) == (image n m 1)</tt> <hr> <p><a name="rgb-image"><i>Type</i> <b>RGB-IMAGE</b></a> <p><b>Supertypes:</b><p><a href="#image"><b>image</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_array.htm"><b>array</b></a>, <a href="http://www.lispworks.com/documentation/HyperSpec/Body/t_t.htm"><b>t</b></a> <p><b>Description:</b> <p>An <a href="#image"><b>image</b></a> with three <a href="http://en.wikipedia.org/wiki/Channel_(digital_image)">channels</a>.</p> <p><b>Compound Type Specifier Kind:</b> <p>Specializing. <p><b>Compound Type Specifier Syntax:</b> <p><b>rgb-image</b> <i>[{ height | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> } { width | <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_st.htm#ST">*</a> }]</i> <p><b>Compound Type Specifier Arguments:</b> <p><i>height, width</i>---<a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimensions</a> <p><b>Notes:</b> <p><tt>(rgb-image n m) == (image n m 3)</tt> <hr> <p><a name="make-image"><i>Function</i> <b>MAKE-IMAGE</b></a> <p><b>Syntax:</b> <p><b>make-image</b> <i>height width channels <tt>&amp;optional</tt> bit-depth</i> => <i>image</i> <p><b>Arguments and Values:</b> <p><i>height, width, channels</i>---<a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimensions</a> <p><i>bit-depth</i>---either 8, or 16, or <b>nil</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><b>Description:</b> <p>Makes a new <a href="#image"><b>image</b></a> with the specified height, width, and number of <a href="http://en.wikipedia.org/wiki/Channel_(digital_image)">channels</a>. The image will be an <a href="#8-bit-image"><b>8-bit-image</b></a> if <i>bit-depth</i> is 8 or <b>nil</b>, and a <a href="#16-bit-image"><b>16-bit-image</b></a> if <i>bit-depth</i> is 16. The contents of the image are undefined. <hr> <p><a name="image-height"><i>Function</i> <b>IMAGE-HEIGHT</b></a> <p><b>Syntax:</b> <p><b>image-height</b> <i>image</i> => <i>height</i> <p><b>Arguments and Values:</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><i>height</i>---a <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimension</a> <p><b>Description:</b> <p>Returns the height of <i>image</i>, i.e., the number of rows.</p> <hr> <p><a name="image-width"><i>Function</i> <b>IMAGE-WIDTH</b></a> <p><b>Syntax:</b> <p><b>image-width</b> <i>image</i> => <i>width</i> <p><b>Arguments and Values:</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><i>width</i>---a <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimension</a> <p><b>Description:</b> <p>Returns the width of <i>image</i>, i.e., the number of columns.</p> <hr> <p><a name="image-channels"><i>Function</i> <b>IMAGE-CHANNELS</b></a> <p><b>Syntax:</b> <p><b>image-channels</b> <i>image</i> => <i>channels</i> <p><b>Arguments and Values:</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><i>channels</i>---a <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_v.htm#valid_array_dimension">valid array dimension</a> <p><b>Description:</b> <p>Returns the number of <a href="http://en.wikipedia.org/wiki/Channel_(digital_image)">channels</a> in <i>image</i>. Grayscale images have one channel, whereas RGB images have three.</p> <hr> <p><a name="image-bit-depth"><i>Function</i> <b>IMAGE-BIT-DEPTH</b></a> <p><b>Syntax:</b> <p><b>image-bit-depth</b> <i>image</i> => <i>bit-depth</i> <p><b>Arguments and Values:</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><i>bit-depth</i>---either 8 or 16 <p><b>Description:</b> <p>Returns the bit-depth of the image, i.e., the number of bits in the byte representing each sample. The bit depth of an <a href="#8-bit-image"><b>8-bit-image</b></a> is 8, and the bit-depth of a <a href="#16-bit-image"><b>16-bit-image</b></a> is 16.</p> <hr> <p><a name="copy-image"><i>Function</i> <b>COPY-IMAGE</b></a> <p><b>Syntax:</b> <p><b>copy-image</b> <i>image</i> => <i>copied-image</i> <p><b>Arguments and Values:</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><i>copied-image</i>---an <a href="#image"><b>image</b></a> <p><b>Description:</b> <p>Creates a copy of <i>image</i>. The elements of the new image are the <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_s.htm#same">same</a> as the corresponding elements of <i>image</i>, and <i>copied-image</i> has the same</a> height, width, number of channels, and bit depth as <i>image</i>.</p> <hr> <p><a name="f_8-bit-image"><i>Function</i> <b>8-BIT-IMAGE</b></a> <p><b>Syntax:</b> <p><b>8-bit-image</b> <i>image</i> => <i>result-image</i> <p><b>Arguments and Values:</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><i>result-image</i>---an <a href="#image"><b>image</b></a> <p><b>Description:</b> <p>If <i>image</i> is an <a href="#8-bit-image"><b>8-bit-image</b></a>, return it or a copy of it. If <i>image</i> is a <a href="#16-bit-image"><b>16-bit-image</b></a>, return an <a href="#8-bit-image"><b>8-bit-image</b></a> that has the same width, height, and number of channels as <i>image</i>, but where each element is the corresponding element in <i>image</i> divided by 257 and rounded to the nearest integer. The effect of this division is to compress the dynamic range of the image so as to fit within the smaller bit depth.</p> <hr> <p><a name="f_16-bit-image"><i>Function</i> <b>16-BIT-IMAGE</b></a> <p><b>Syntax:</b> <p><b>16-bit-image</b> <i>image</i> => <i>result-image</i> <p><b>Arguments and Values:</b> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><i>result-image</i>---an <a href="#image"><b>image</b></a> <p><b>Description:</b> <p>If <i>image</i> is a <a href="#16-bit-image"><b>16-bit-image</b></a>, return it or a copy of it. If <i>image</i> is an <a href="#8-bit-image"><b>8-bit-image</b></a>, return a <a href="#16-bit-image"><b>16-bit-image</b></a> that has the same width, height, and number of channels as <i>image</i>, but where each element is the corresponding element in <i>image</i> multiplied by 257. The effect of this multiplication is to stretch the dynamic range of the image to utilize the increased bit depth.</p> <hr> <p><a name="decode"><i>Function</i> <b>DECODE</b></a> <p><b>Syntax:</b> <p><b>decode</b> <i>input</i> => <i>image</i> <p><b>Arguments and Values:</b> <p><i>input</i>---an fd <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_i.htm#input">input</a> <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_s.htm#stream">stream</a></p> <p><i>image</i>---an <a href="#image"><b>image</b></a> <p><b>Description:</b> <p>Reads an image in PNG format from <i>input</i> and returns an array of type <a href="#image"><b>image</b></a>. If the bit depth of the PNG file is less than or equal to 8, an <a href="#8-bit-image"><b>8-bit-image</b></a> will be returned; otherwise, a <a href="#16-bit-image"><b>16-bit-image</b></a> will be returned. <p>Applications that would like to receive images of consistent bit depth (rather than 8 or 16 depending on the PNG file) can apply the function <a href="#f_8-bit-image"><b>8-bit-image</b></a> or the function <a href="#f_16-bit-image"><b>16-bit-image</b></a> to the result of <b>decode</b>. <p>An image with bit depths below 8 will be converted to 8 bits when read, and an image with bit depths between 8 and 16 bits will be converted to 16 bits. As an example, a 2-bit PNG file contains only the pixel values 0, 1, 2, and 3. These will be converted to 0, 85, 170, and 255, respectively, in order to fill the dynamic range of the 8-bit image that is returned. <p><b>Exceptional Situations:</b> <p>Signals an <a href="http://www.lispworks.com/documentation/HyperSpec/Body/e_error.htm#error"><b>error</b></a> if reading the image fails.</p> <hr> <p><a name="encode"><i>Function</i> <b>ENCODE</b></a> <p><b>Syntax:</b> <p><b>encode</b> <i>image</i> <i>output</i> => <a href="http://www.lispworks.com/documentation/HyperSpec/Body/a_t.htm"><b><i>t</i></b></a> <p><b>Arguments and Values:</b> <p><i>image</i>---a <a href="#grayscale-image"><i>grayscale-image</i></a> or <a href="#rgb-image"><i>rgb-image</i></a> <p><i>output</i>---an fd <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_o.htm#output">output</a> <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_s.htm#stream">stream</a></p> <p><b>Description:</b> <p>Writes <i>image</i> in PNG format to <i>output</i>. The current version always writes an 8-bit PNG file if <i>image</i> is an <a href="#8-bit-image"><b>8-bit-image</b></a> and a 16-bit PNG file if <i>image</i> is an <a href="#16-bit-image"><b>16-bit-image</b></a>. Future versions may write PNG files of lower bit depths than <i>image</i> when the least significant bits may be trimmed without loss of precision. <p><b>Exceptional Situations:</b> <p>Signals an <a href="http://www.lispworks.com/documentation/HyperSpec/Body/e_error.htm#error"><b>error</b></a> if writing the image fails. </p> <hr> <h2><a name="Index">SYMBOL INDEX:</a></h2> <ul> <li><a href="#8-bit-image"><b>8-bit-image</b></a> (type) <li><a href="#f_8-bit-image"><b>8-bit-image</b></a> (function) <li><a href="#16-bit-image"><b>16-bit-image</b></a> (type) <li><a href="#f_16-bit-image"><b>16-bit-image</b></a> (function) <li><a href="#copy-image"><b>copy-image</b></a> <li><a href="#decode"><b>decode</b></a> <li><a href="#encode"><b>encode</b></a> <li><a href="#grayscale-image"><b>grayscale-image</b></a> <li><a href="#image"><b>image</b></a> <li><a href="#image-bit-depth"><b>image-bit-depth</b></a> <li><a href="#image-channels"><b>image-channels</b></a> <li><a href="#image-height"><b>image-height</b></a> <li><a href="#image-width"><b>image-width</b></a> <li><a href="#make-image"><b>make-image</b></a> <li><a href="#rgb-image"><b>rgb-image</b></a> </ul> <hr> <p>Last updated: 2009-02-08</p> </div> </BODY> </HTML>
28,833
Common Lisp
.l
445
63.029213
5,828
0.684918
ivankocienski/xpng
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
74ab71d2ee611d730016fdcaa3331b37a27da2c63aa9837e370ce33502e368ad
30,190
[ -1 ]
30,205
flexichain-package.lisp
hpan-open_flexichain-mirror/flexichain-package.lisp
;;; Flexichain ;;; Package definition ;;; ;;; Copyright (C) 2003-2004 Robert Strandh ([email protected]) ;;; Copyright (C) 2003-2004 Matthieu Villeneuve ([email protected]) ;;; ;;; THIS LIBRARY IS FREE software; you can redistribute it and/or ;;; modify it under the terms of the GNU Lesser General Public ;;; License as published by the Free Software Foundation; either ;;; version 2.1 of the License, or (at your option) any later version. ;;; ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Lesser General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this library; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (defpackage :flexichain (:use :common-lisp) (:export #:flexichain #:standard-flexichain #:flexi-error #:flexi-initialization-error #:flexi-position-error #:flexi-incompatible-type-error #:nb-elements #:flexi-empty-p #:insert* #:insert-vector* #:element* #:delete* #:delete-elements* #:push-start #:pop-start #:push-end #:pop-end #:rotate #:cursorchain #:standard-cursorchain #:flexicursor #:standard-flexicursor #:left-sticky-flexicursor #:right-sticky-flexicursor #:chain #:clone-cursor #:cursor-pos #:at-beginning-error #:at-end-error #:at-beginning-p #:at-end-p #:move> #:move< #:insert #:insert-sequence #:element< #:element> #:delete< #:delete> #:flexirank-mixin #:element-rank-mixin #:rank #:flexi-first-p #:flexi-last-p #:flexi-next #:flexi-prev))
1,896
Common Lisp
.lisp
40
41.25
78
0.666487
hpan-open/flexichain-mirror
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
77d4083b6cd91ef9f170337fcd4a2c78d7f7350bfa67b73ae62047b71e2e3876
30,205
[ 274747 ]
30,206
flexichain.lisp
hpan-open_flexichain-mirror/flexichain.lisp
;;; Flexichain ;;; Flexichain data structure definition ;;; ;;; Copyright (C) 2003-2004 Robert Strandh ([email protected]) ;;; Copyright (C) 2003-2004 Matthieu Villeneuve ([email protected]) ;;; ;;; This library is free software; you can redistribute it and/or ;;; modify it under the terms of the GNU Lesser General Public ;;; License as published by the Free Software Foundation; either ;;; version 2.1 of the License, or (at your option) any later version. ;;; ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Lesser General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this library; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (in-package :flexichain) (defclass flexichain () ((element-type :initarg :element-type :initform t) (fill-element :initarg :fill-element) (expand-factor :initarg :expand-factor :initform 1.5) (min-size :initarg :min-size :initform 5)) (:documentation "The protocol class for flexichains.")) (defmethod initialize-instance :after ((chain flexichain) &rest initargs &key initial-contents) (declare (ignore initargs initial-contents)) (with-slots (expand-factor min-size) chain (assert (> expand-factor 1) () 'flexichain-initialization-error :cause "EXPAND-FACTOR should be greater than 1.") (assert (> min-size 0) () 'flexichain-initialization-error :cause "MIN-SIZE should be greater than 0.")) (if (slot-boundp chain 'fill-element) (with-slots (element-type fill-element) chain (assert (typep fill-element element-type) () 'flexichain-initialization-error :cause (format nil "FILL-ELEMENT ~A not of type ~S." fill-element element-type))) (multiple-value-bind (element foundp) (find-if-2 (lambda (x) (typep x (slot-value chain 'element-type))) '(nil 0 #\a)) (if foundp (setf (slot-value chain 'fill-element) element) (error 'flexichain-initialization-error :cause "FILL-ELEMENT not provided, no default applicable."))))) (define-condition flexi-error (simple-error) ()) (define-condition flexi-initialization-error (flexi-error) ((cause :reader flexi-initialization-error-cause :initarg :cause :initform "")) (:report (lambda (condition stream) (format stream "Error initializing FLEXICHAIN (~S)" (flexi-initialization-error-cause condition))))) (define-condition flexi-position-error (flexi-error) ((chain :reader flexi-position-error-chain :initarg :chain :initform nil) (position :reader flexi-position-error-position :initarg :position :initform nil)) (:report (lambda (condition stream) (format stream "Position ~D out of bounds in ~A" (flexi-position-error-position condition) (flexi-position-error-chain condition))))) (define-condition flexi-incompatible-type-error (flexi-error) ((chain :reader flexi-incompatible-type-error-chain :initarg :chain :initform nil) (element :reader flexi-incompatible-type-error-element :initarg :element :initform nil)) (:report (lambda (condition stream) (let ((element (flexi-incompatible-type-error-element condition))) (format stream "Element ~A of type ~A cannot be inserted in ~A" element (type-of element) (flexi-incompatible-type-error-chain condition)))))) (defgeneric nb-elements (chain) (:documentation "Returns the number of elements in the flexichain.")) (defgeneric flexi-empty-p (chain) (:documentation "Checks whether CHAIN is empty or not.")) (defgeneric insert* (chain position object) (:documentation "Inserts an object before the element at POSITION in the chain. If POSITION is out of range (less than 0 or greater than the length of CHAIN, the FLEXI-POSITION-ERROR condition will be signaled.")) (defgeneric insert-vector* (chain position vector) (:documentation "Inserts the elements of VECTOR before the element at POSITION in the chain. If POSITION is out of range (less than 0 or greater than the length of CHAIN, the FLEXI-POSITION-ERROR condition will be signaled.")) (defgeneric delete* (chain position) (:documentation "Deletes an element at POSITION of the chain. If POSITION is out of range (less than 0 or greater than or equal to the length of CHAIN, the FLEXI-POSITION-ERROR condition will be signaled.")) (defgeneric delete-elements* (chain position n) (:documentation "Delete N elements at POSITION of the chain. If POSITION+N is out of range (less than 0 or greater than or equal to the length of CHAIN, the FLEXI-POSITION-ERROR condition will be signaled. N can be negative, in which case elements will be deleted before POSITION.")) (defgeneric element* (chain position) (:documentation "Returns the element at POSITION of the chain. If POSITION is out of range (less than 0 or greater than or equal to the length of CHAIN, the FLEXI-POSITION-ERROR condition will be signaled.")) (defgeneric (setf element*) (object chain position) (:documentation "Replaces the element at POSITION of CHAIN by OBJECT. If POSITION if out of range (less than 0 or greater than or equal to the length of CHAIN, the FLEXI-POSITION-ERROR condition will be signaled.")) (defgeneric push-start (chain object) (:documentation "Inserts an object at the beginning of CHAIN.")) (defgeneric push-end (chain object) (:documentation "Inserts an object at the end of CHAIN.")) (defgeneric pop-start (chain) (:documentation "Pops and returns the element at the beginning of CHAIN.")) (defgeneric pop-end (chain) (:documentation "Pops and returns the element at the end of CHAIN.")) (defgeneric rotate (chain &optional n) (:documentation "Rotates the elements of CHAIN so that the element that used to be at position N is now at position 0. With a negative value of N, rotates the elements so that the element that used to be at position 0 is now at position N.")) (defclass standard-flexichain (flexichain) ((buffer) (gap-start) (gap-end) (data-start)) (:documentation "The standard instantiable subclass of FLEXICHAIN.")) (defun required-space (chain nb-elements) (with-slots (min-size expand-factor) chain (+ 2 (max (ceiling (* nb-elements expand-factor)) min-size)))) (defmethod initialize-instance :after ((chain standard-flexichain) &rest initargs &key initial-contents (initial-nb-elements 0) (initial-element nil)) (declare (ignore initargs)) ;; Check initial-contents if provided (unless (null initial-contents) (with-slots (element-type) chain (multiple-value-bind (offending-element foundp) (find-if-2 (lambda (x) (not (typep x element-type))) initial-contents) (assert (not foundp) () 'flexi-initialization-error :cause (format nil "Initial element ~A not of type ~S." offending-element element-type))))) ;; Initialize slots (with-slots (element-type fill-element buffer) chain (let* ((data-length (if (> (length initial-contents) initial-nb-elements) (length initial-contents) initial-nb-elements)) (size (required-space chain data-length)) (fill-size (- size data-length 2)) (sentinel-list (make-list 2 :initial-element fill-element)) (fill-list (make-list fill-size :initial-element fill-element))) (setf buffer (if initial-contents (make-array size :element-type element-type :initial-contents (concatenate 'list sentinel-list initial-contents fill-list)) (let ((arr (make-array size :element-type element-type :initial-element initial-element))) (fill arr fill-element :end (length sentinel-list)) (fill arr fill-element :start (+ (length sentinel-list) initial-nb-elements) :end size)))) (with-slots (gap-start gap-end data-start) chain (setf gap-start (+ 2 data-length) gap-end 0 data-start 1))))) (defmacro with-virtual-gap ((bl ds gs ge) chain &body body) (let ((c (gensym))) `(let* ((,c ,chain) (,bl (length (slot-value ,c 'buffer))) (,ds (slot-value ,c 'data-start)) (,gs (slot-value ,c 'gap-start)) (,ge (slot-value ,c 'gap-end))) (declare (ignorable ,bl ,ds ,gs ,ge)) (when (< ,gs ,ds) (incf ,gs ,bl)) (when (< ,ge ,ds) (incf ,ge ,bl)) ,@body))) (defmethod nb-elements ((chain standard-flexichain)) (with-virtual-gap (bl ds gs ge) chain (- bl (- ge gs) 2))) (defmethod flexi-empty-p ((chain standard-flexichain)) (zerop (nb-elements chain))) (defun position-index (chain position) "Returns the (0 indexed) index of the POSITION-th element of the CHAIN in the buffer." (with-virtual-gap (bl ds gs ge) chain (let ((index (+ ds position 1))) (when (>= index gs) (incf index (- ge gs))) (when (>= index bl) (decf index bl)) index))) (defun index-position (chain index) "Returns the position corresponding to the INDEX in the CHAIN. Note: the result is undefined if INDEX is not the index of a valid element of the CHAIN." (with-virtual-gap (bl ds gs ge) chain (when (< index ds) (incf index bl)) (when (>= index ge) (decf index (- ge gs))) (- index ds 1))) (defun ensure-gap-position (chain position) (move-gap chain (position-index chain position))) (defun ensure-room (chain nb-elements) (with-slots (buffer) chain (when (> nb-elements (- (length buffer) 2)) (increase-buffer-size chain nb-elements)))) (defmethod insert* ((chain standard-flexichain) position object) (with-slots (element-type buffer gap-start) chain (assert (<= 0 position (nb-elements chain)) () 'flexi-position-error :chain chain :position position) (assert (typep object element-type) () 'flexi-incompatible-type-error :element object :chain chain) (ensure-gap-position chain position) (ensure-room chain (1+ (nb-elements chain))) (setf (aref buffer gap-start) object) (incf gap-start) (when (= gap-start (length buffer)) (setf gap-start 0)))) (defmethod insert-vector* ((chain standard-flexichain) position vector) (with-slots (element-type buffer gap-start) chain (assert (<= 0 position (nb-elements chain)) () 'flexi-position-error :chain chain :position position) (assert (subtypep (array-element-type vector) element-type) () 'flexi-incompatible-type-error :element vector :chain chain) (ensure-gap-position chain position) (ensure-room chain (+ (nb-elements chain) (length vector))) (loop for elem across vector do (setf (aref buffer gap-start) elem) (incf gap-start) (when (= gap-start (length buffer)) (setf gap-start 0))))) (defmethod delete* ((chain standard-flexichain) position) (with-slots (buffer expand-factor min-size fill-element gap-end) chain (assert (< -1 position (nb-elements chain)) () 'flexi-position-error :chain chain :position position) (ensure-gap-position chain position) (setf (aref buffer gap-end) fill-element) (incf gap-end) (when (= gap-end (length buffer)) (setf gap-end 0)) (when (and (> (length buffer) (+ min-size 2)) (< (+ (nb-elements chain) 2) (/ (length buffer) (square expand-factor)))) (decrease-buffer-size chain)))) (defmethod delete-elements* ((chain standard-flexichain) position n) (unless (zerop n) (with-slots (buffer expand-factor min-size gap-end data-start) chain (when (minusp n) (incf position n) (setf n (* -1 n))) (assert (<= 0 (+ position n) (nb-elements chain)) () 'flexi-position-error :chain chain :position position) (ensure-gap-position chain position) ;; Two cases to consider - one where position+n is wholly on ;; this side of the gap in buffer, and one where part of it is ;; "wrapped around" to the beginning of buffer. (cond ((>= (length buffer) (+ gap-end n)) (fill-gap chain gap-end (+ gap-end n)) (incf gap-end n)) (t (let ((surplus-elements (- n (- (length buffer) gap-end)))) (fill-gap chain gap-end (length buffer)) (fill-gap chain 0 surplus-elements) (setf gap-end surplus-elements)))) (when (= gap-end (length buffer)) (setf gap-end 0)) (when (and (> (length buffer) (+ min-size 2)) (< (+ (nb-elements chain) 2) (/ (length buffer) (square expand-factor)))) (decrease-buffer-size chain))))) (defmethod element* ((chain standard-flexichain) position) (with-slots (buffer) chain (assert (< -1 position (nb-elements chain)) () 'flexi-position-error :chain chain :position position) (aref buffer (position-index chain position)))) (defmethod (setf element*) (object (chain standard-flexichain) position) (with-slots (buffer element-type) chain (assert (< -1 position (nb-elements chain)) () 'flexi-position-error :chain chain :position position) (assert (typep object element-type) () 'flexi-incompatible-type-error :chain chain :element object) (setf (aref buffer (position-index chain position)) object))) (defmethod push-start ((chain standard-flexichain) object) (insert* chain 0 object)) (defmethod push-end ((chain standard-flexichain) object) (insert* chain (nb-elements chain) object)) (defmethod pop-start ((chain standard-flexichain)) (prog1 (element* chain 0) (delete* chain 0))) (defmethod pop-end ((chain standard-flexichain)) (let ((position (1- (nb-elements chain)))) (prog1 (element* chain position) (delete* chain position)))) (defmethod rotate ((chain standard-flexichain) &optional (n 1)) (when (> (nb-elements chain) 1) (cond ((plusp n) (loop repeat n do (push-start chain (pop-end chain)))) ((minusp n) (loop repeat (- n) do (push-end chain (pop-start chain)))) (t nil)))) (defun move-gap (chain hot-spot) "Moves the elements and gap inside the buffer so that the element currently at HOT-SPOT becomes the first element following the gap, or does nothing if there are no elements." (with-slots (gap-start gap-end) chain (unless (= hot-spot gap-end) (case (gap-location chain) (:gap-empty (move-empty-gap chain hot-spot)) (:gap-left (move-left-gap chain hot-spot)) (:gap-right (move-right-gap chain hot-spot)) (:gap-middle (move-middle-gap chain hot-spot)) (:gap-non-contiguous (move-non-contiguous-gap chain hot-spot)))) (values gap-start gap-end))) (defun move-empty-gap (chain hot-spot) "Moves the gap. Handles the case where the gap is empty." (with-slots (gap-start gap-end) chain (setf gap-start hot-spot gap-end hot-spot))) (defun move-left-gap (chain hot-spot) "Moves the gap. Handles the case where the gap is on the left of the buffer." (with-slots (buffer gap-start gap-end data-start) chain (let ((buffer-size (length buffer))) (cond ((< (- hot-spot gap-end) (- buffer-size hot-spot)) (push-elements-left chain (- hot-spot gap-end))) ((<= (- buffer-size hot-spot) gap-end) (hop-elements-left chain (- buffer-size hot-spot))) (t (hop-elements-left chain (- gap-end gap-start)) (push-elements-right chain (- gap-start hot-spot))))))) (defun move-right-gap (chain hot-spot) "Moves the gap. Handles the case where the gap is on the right of the buffer." (with-slots (buffer gap-start gap-end) chain (let ((buffer-size (length buffer))) (cond ((< (- gap-start hot-spot) hot-spot) (push-elements-right chain (- gap-start hot-spot))) ((<= hot-spot (- buffer-size gap-start)) (hop-elements-right chain hot-spot)) (t (hop-elements-right chain (- buffer-size gap-start)) (push-elements-left chain (- hot-spot gap-end))))))) (defun move-middle-gap (chain hot-spot) "Moves the gap. Handles the case where the gap is in the middle of the buffer." (with-slots (buffer gap-start gap-end) chain (let ((buffer-size (length buffer))) (cond ((< hot-spot gap-start) (cond ((<= (- gap-start hot-spot) (+ (- buffer-size gap-end) hot-spot)) (push-elements-right chain (- gap-start hot-spot))) (t (push-elements-left chain (- buffer-size gap-end)) (move-right-gap chain hot-spot)))) (t (cond ((< (- hot-spot gap-end) (+ (- buffer-size hot-spot) gap-start)) (push-elements-left chain (- hot-spot gap-end))) (t (push-elements-right chain gap-start) (move-left-gap chain hot-spot)))))))) (defun move-non-contiguous-gap (chain hot-spot) "Moves the gap. Handles the case where the gap is in 2 parts, on both ends of the buffer." (with-slots (buffer gap-start gap-end) chain (let ((buffer-size (length buffer))) (cond ((< (- hot-spot gap-end) (- gap-start hot-spot)) (hop-elements-right chain (min (- buffer-size gap-start) (- hot-spot gap-end))) (let ((nb-left (- hot-spot gap-end))) (unless (zerop nb-left) (push-elements-left chain nb-left)))) (t (hop-elements-left chain (min gap-end (- gap-start hot-spot))) (let ((nb-right (- gap-start hot-spot))) (unless (zerop nb-right) (push-elements-right chain nb-right)))))))) (defgeneric move-elements (standard-flexichain to from start1 start2 end2) (:documentation "move elements of a flexichain and adjust data-start")) (defmethod move-elements ((fc standard-flexichain) to from start1 start2 end2) (replace to from :start1 start1 :start2 start2 :end2 end2) (with-slots (data-start) fc (when (and (<= start2 data-start) (< data-start end2)) (incf data-start (- start1 start2))))) (defgeneric fill-gap (standard-flexichain start end) (:documentation "fill part of gap with the fill element")) (defmethod fill-gap ((fc standard-flexichain) start end) (with-slots (buffer fill-element) fc (fill buffer fill-element :start start :end end))) (defun push-elements-left (chain count) "Pushes the COUNT elements of CHAIN at the right of the gap, to the beginning of the gap. The gap must be continuous. Example: PUSH-ELEMENTS-LEFT abcd-----efghijklm 2 => abcdef-----ghijklm" (with-slots (buffer gap-start gap-end) chain (move-elements chain buffer buffer gap-start gap-end (+ gap-end count)) (fill-gap chain (max gap-end (+ gap-start count)) (+ gap-end count)) (incf gap-start count) (incf gap-end count) (normalize-indices chain))) (defun push-elements-right (chain count) "Pushes the COUNT elements of CHAIN at the left of the gap, to the end of the gap. The gap must be continuous. Example: PUSH-ELEMENTS-RIGHT abcd-----efghijklm 2 => ab-----cdefghijklm" (with-slots (buffer gap-start gap-end) chain (let* ((buffer-size (length buffer)) (rotated-gap-end (if (zerop gap-end) buffer-size gap-end))) (move-elements chain buffer buffer (- rotated-gap-end count) (- gap-start count) gap-start) (fill-gap chain (- gap-start count) (min gap-start (- rotated-gap-end count))) (decf gap-start count) (setf gap-end (- rotated-gap-end count)) (normalize-indices chain)))) (defun hop-elements-left (chain count) "Moves the COUNT rightmost elements to the end of the gap, on the left of the data. Example: HOP-ELEMENTS-LEFT ---abcdefghijklm--- 2 => -lmabcdefghijk-----" (with-slots (buffer gap-start gap-end) chain (let* ((buffer-size (length buffer)) (rotated-gap-start (if (zerop gap-start) buffer-size gap-start))) (move-elements chain buffer buffer (- gap-end count) (- rotated-gap-start count) rotated-gap-start) (fill-gap chain (- rotated-gap-start count) rotated-gap-start) (setf gap-start (- rotated-gap-start count)) (decf gap-end count) (normalize-indices chain)))) (defun hop-elements-right (chain count) "Moves the COUNT leftmost elements to the beginning of the gap, on the right of the data. Example: HOP-ELEMENTS-RIGHT ---abcdefghijklm--- 2 => -----cdefghijklmab-" (with-slots (buffer gap-start gap-end) chain (move-elements chain buffer buffer gap-start gap-end (+ gap-end count)) (fill-gap chain gap-end (+ gap-end count)) (incf gap-start count) (incf gap-end count) (normalize-indices chain))) (defun increase-buffer-size (chain nb-elements) (resize-buffer chain (required-space chain nb-elements))) (defun decrease-buffer-size (chain) (resize-buffer chain (required-space chain (nb-elements chain)))) (defgeneric resize-buffer (standard-flexichain new-buffer-size) (:documentation "allocate a new buffer with the size indicated")) (defmethod resize-buffer ((fc standard-flexichain) new-buffer-size) (with-slots (buffer gap-start gap-end fill-element element-type expand-factor) fc (let ((buffer-size (length buffer)) (buffer-after (make-array new-buffer-size :element-type element-type :initial-element fill-element))) (case (gap-location fc) ((:gap-empty :gap-middle) (move-elements fc buffer-after buffer 0 0 gap-start) (let ((gap-end-after (- new-buffer-size (- buffer-size gap-end)))) (move-elements fc buffer-after buffer gap-end-after gap-end buffer-size) (setf gap-end gap-end-after))) (:gap-right (move-elements fc buffer-after buffer 0 0 gap-start)) (:gap-left (let ((gap-end-after (- new-buffer-size (+ 2 (nb-elements fc))))) (move-elements fc buffer-after buffer gap-end-after gap-end buffer-size) (setf gap-end gap-end-after))) (:gap-non-contiguous (move-elements fc buffer-after buffer 0 gap-end gap-start) (decf gap-start gap-end) (setf gap-end 0))) (setf buffer buffer-after))) (normalize-indices fc)) (defun normalize-indices (chain) "Sets gap limits to 0 if they are at the end of the buffer." (with-slots (buffer gap-start gap-end data-start) chain (let ((buffer-size (length buffer))) (when (>= data-start buffer-size) (setf data-start 0)) (when (>= gap-start buffer-size) (setf gap-start 0)) (when (>= gap-end buffer-size) (setf gap-end 0))))) (defun gap-location (chain) "Returns a keyword indicating the general location of the gap." (with-slots (buffer gap-start gap-end) chain (cond ((= gap-start gap-end) :gap-empty) ((and (zerop gap-start) (>= gap-end 0)) :gap-left) ((and (zerop gap-end) (> gap-start 0)) :gap-right) ((> gap-end gap-start) :gap-middle) (t :gap-non-contiguous))))
24,554
Common Lisp
.lisp
500
40.666
90
0.635553
hpan-open/flexichain-mirror
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
90ee65cf0230505ba1d862bcce607c78c975a996f27d847231fa58ef8d35f622
30,206
[ 269124 ]
30,209
flexicursor.lisp
hpan-open_flexichain-mirror/flexicursor.lisp
;;; Flexichain ;;; Flexicursor data structure definition ;;; ;;; Copyright (C) 2003-2004 Robert Strandh ([email protected]) ;;; Copyright (C) 2003-2004 Matthieu Villeneuve ([email protected]) ;;; ;;; This library is free software; you can redistribute it and/or ;;; modify it under the terms of the GNU Lesser General Public ;;; License as published by the Free Software Foundation; either ;;; version 2.1 of the License, or (at your option) any later version. ;;; ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Lesser General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this library; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (in-package :flexichain) (defclass cursorchain (flexichain) () (:documentation "The protocol class for cursor chains.")) (defclass flexicursor () () (:documentation "The protocol class for flexicursors.")) (define-condition at-beginning-error (flexi-error) ((cursor :reader at-beginning-error-cursor :initarg :cursor :initform nil)) (:report (lambda (condition stream) (let ((cursor (at-beginning-error-cursor condition))) (format stream "Cursor ~A already at the beginning of ~A" cursor (chain cursor)))))) (define-condition at-end-error (flexi-error) ((cursor :reader at-end-error-cursor :initarg :cursor :initform nil)) (:report (lambda (condition stream) (let ((cursor (at-end-error-cursor condition))) (format stream "Cursor ~A already at the end of ~A" cursor (chain cursor)))))) (defgeneric clone-cursor (cursor) (:documentation "Creates a cursor that is initially at the same location as the one given as argument.")) (defgeneric cursor-pos (cursor) (:documentation "Returns the position of the cursor.")) (defgeneric (setf cursor-pos) (posistion cursor) (:documentation "Set the position of the cursor.")) (defgeneric at-beginning-p (cursor) (:documentation "Returns true if the cursor is at the beginning of the chain.")) (defgeneric at-end-p (cursor) (:documentation "Returns true if the cursor is at the beginning of the chain.")) (defgeneric move> (cursor &optional n) (:documentation "Moves the cursor forward N positions.")) (defgeneric move< (cursor &optional n) (:documentation "Moves the cursor backward N positions.")) (defgeneric insert (cursor object) (:documentation "Inserts an object at the cursor.")) (defgeneric insert-sequence (cursor sequence) (:documentation "The effect is the same as if each element of the sequence was inserted using INSERT.")) (defgeneric delete< (cursor &optional n) (:documentation "Deletes N objects before the cursor.")) (defgeneric delete> (cursor &optional n) (:documentation "Deletes N objects after the cursor.")) (defgeneric element< (cursor) (:documentation "Returns the element immediately before the cursor.")) (defgeneric (setf element<) (object cursor) (:documentation "Replaces the element immediately before the cursor.")) (defgeneric element> (cursor) (:documentation "Returns the element immediately after the cursor.")) (defgeneric (setf element>) (object cursor) (:documentation "Replaces the element immediately after the cursor.")) (defclass standard-cursorchain (cursorchain standard-flexichain) ((cursors :initform '())) (:documentation "The standard instantiable subclass of CURSORCHAIN")) (defclass standard-flexicursor (flexicursor) ((chain :reader chain :initarg :chain) (index :accessor flexicursor-index)) (:documentation "The standard instantiable subclass of FLEXICURSOR")) (defclass left-sticky-flexicursor (standard-flexicursor) ()) (defclass right-sticky-flexicursor (standard-flexicursor) ()) (defmethod initialize-instance :after ((cursor left-sticky-flexicursor) &rest initargs &key (position 0)) (declare (ignore initargs)) (with-slots (index chain) cursor (setf index (position-index chain (1- position))) (with-slots (cursors) chain (push (make-weak-pointer cursor) cursors)))) (defmethod initialize-instance :after ((cursor right-sticky-flexicursor) &rest initargs &key (position 0)) (declare (ignore initargs)) (with-slots (index chain) cursor (setf index (position-index chain position)) (with-slots (cursors) chain (push (make-weak-pointer cursor) cursors)))) (defun adjust-cursors (cursors start end increment) (let ((acc '())) (loop for cursor = (and cursors (weak-pointer-value (car cursors))) while cursors do (cond ((null cursor) (pop cursors)) ((<= start (flexicursor-index cursor) end) (incf (flexicursor-index cursor) increment) (let ((rest (cdr cursors))) (setf (cdr cursors) acc acc cursors cursors rest))) (t (let ((rest (cdr cursors))) (setf (cdr cursors) acc acc cursors cursors rest))))) acc)) (defmethod move-elements :after ((cc standard-cursorchain) to from start1 start2 end2) (declare (ignore to from)) (with-slots (cursors) cc (setf cursors (adjust-cursors cursors start2 (1- end2) (- start1 start2))))) (defmethod clone-cursor ((cursor standard-flexicursor)) (make-instance (class-of cursor) :chain (chain cursor) :position (cursor-pos cursor))) (defmethod cursor-pos ((cursor left-sticky-flexicursor)) (1+ (index-position (chain cursor) (slot-value cursor 'index)))) (defmethod (setf cursor-pos) (position (cursor left-sticky-flexicursor)) (assert (<= 0 position (nb-elements (chain cursor))) () 'flexi-position-error :chain (chain cursor) :position position) (with-slots (chain) cursor (setf (flexicursor-index cursor) (position-index chain (1- position))))) (defmethod cursor-pos ((cursor right-sticky-flexicursor)) (index-position (chain cursor) (slot-value cursor 'index))) (defmethod (setf cursor-pos) (position (cursor right-sticky-flexicursor)) (assert (<= 0 position (nb-elements (chain cursor))) () 'flexi-position-error :chain (chain cursor) :position position) (with-slots (chain) cursor (setf (flexicursor-index cursor) (position-index chain position)))) (defmethod at-beginning-p ((cursor standard-flexicursor)) (zerop (cursor-pos cursor))) (defmethod at-end-p ((cursor standard-flexicursor)) (= (cursor-pos cursor) (nb-elements (chain cursor)))) (defmethod insert ((cursor standard-flexicursor) object) (insert* (chain cursor) (cursor-pos cursor) object)) (defmethod insert-sequence ((cursor standard-flexicursor) sequence) (map nil (lambda (object) (insert cursor object)) sequence)) (defmethod delete* :before ((chain standard-cursorchain) position) (with-slots (cursors) chain (let* ((old-index (position-index chain position))) (loop for cursor-wp in cursors as cursor = (weak-pointer-value cursor-wp) when (and cursor (= old-index (flexicursor-index cursor))) do (typecase cursor (right-sticky-flexicursor (incf (cursor-pos cursor))) (left-sticky-flexicursor (decf (cursor-pos cursor)))))))) (defmethod delete-elements* :before ((chain standard-cursorchain) position n) (with-slots (cursors) chain (when (minusp n) (incf position n) (setf n (* -1 n))) (unless (zerop n) (loop for cursor-wp in cursors as cursor = (weak-pointer-value cursor-wp) when (and cursor (<= position (cursor-pos cursor) (+ position n))) do (typecase cursor (right-sticky-flexicursor (setf (cursor-pos cursor) (+ position n))) (left-sticky-flexicursor (setf (cursor-pos cursor) position))))))) (defmethod delete> ((cursor standard-flexicursor) &optional (n 1)) (let ((chain (chain cursor)) (position (cursor-pos cursor))) (assert (plusp n) () 'flexi-position-error :chain chain :position n) (loop repeat n do (delete* chain position)))) (defmethod delete< ((cursor standard-flexicursor) &optional (n 1)) (let ((chain (chain cursor)) (position (cursor-pos cursor))) (assert (plusp n) () 'flexi-position-error :chain chain :position n) (loop repeat n do (delete* chain (- position n))))) (defmethod element> ((cursor standard-flexicursor)) (assert (not (at-end-p cursor)) () 'at-end-error :cursor cursor) (element* (chain cursor) (cursor-pos cursor))) (defmethod (setf element>) (object (cursor standard-flexicursor)) (assert (not (at-end-p cursor)) () 'at-end-error :cursor cursor) (setf (element* (chain cursor) (cursor-pos cursor)) object)) (defmethod element< ((cursor standard-flexicursor)) (assert (not (at-beginning-p cursor)) () 'at-beginning-error :cursor cursor) (element* (chain cursor) (1- (cursor-pos cursor)))) (defmethod (setf element<) (object (cursor standard-flexicursor)) (assert (not (at-beginning-p cursor)) () 'at-beginning-error :cursor cursor) (setf (element* (chain cursor) (1- (cursor-pos cursor))) object))
9,817
Common Lisp
.lisp
207
40.521739
86
0.668409
hpan-open/flexichain-mirror
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
399445eb22891f7ada07c8fe83b7d17c5e428c94deb9ce28bf93b1a37df7c609
30,209
[ 413774 ]
30,210
flexichain-doc.asd
hpan-open_flexichain-mirror/flexichain-doc.asd
;;; flexichain-doc ;;; ASDF system definition ;;; ;;; Copyright (C) 2003-2004 Robert Strandh ([email protected]) ;;; Copyright (C) 2003-2004 Matthieu Villeneuve ([email protected]) ;;; Copyright (C) 2008 Cyrus Harmon ([email protected]) ;;; ;;; This library is free software; you can redistribute it and/or ;;; modify it under the terms of the GNU Lesser General Public ;;; License as published by the Free Software Foundation; either ;;; version 2.1 of the License, or (at your option) any later version. ;;; ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Lesser General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this library; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (asdf:defsystem :flexichain-doc :name "flexichain-doc" :version #.(with-open-file (vers (merge-pathnames "version.lisp-expr" *load-truename*)) (read vers)) :components ((:module "Doc" :components ((:static-file "Makefile") (:static-file flexichain-tex :pathname #p"flexichain.tex") (:static-file spec-macros-tex :pathname #p"spec-macros.tex") (:static-file circular-fig :pathname #p"circular.fig") (:static-file gap1-fig :pathname #p"gap1.fig") (:static-file gap2-fig :pathname #p"gap2.fig") (:static-file gap3-fig :pathname #p"gap3.fig") (:static-file "tex-dependencies") (:static-file "strip-dependence")))))
1,791
Common Lisp
.asd
37
42.783784
78
0.673516
hpan-open/flexichain-mirror
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
f24fe6bfb37c7576583f3f45ed50ad227225d2f7d62213cf6bfc8e41779aab13
30,210
[ 201840 ]
30,211
flexichain.asd
hpan-open_flexichain-mirror/flexichain.asd
;;; Flexichain ;;; ASDF system definition ;;; ;;; Copyright (C) 2003-2004 Robert Strandh ([email protected]) ;;; Copyright (C) 2003-2004 Matthieu Villeneuve ([email protected]) ;;; ;;; This library is free software; you can redistribute it and/or ;;; modify it under the terms of the GNU Lesser General Public ;;; License as published by the Free Software Foundation; either ;;; version 2.1 of the License, or (at your option) any later version. ;;; ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Lesser General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this library; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;; The tester is not included, for it depends on clim. The stupid ;; implementation has also been left out, since it seems mostly useful ;; for testing. (asdf:defsystem :flexichain :name "flexichain" :version #.(with-open-file (vers (merge-pathnames "version.lisp-expr" *load-truename*)) (read vers)) :components ((:static-file "version" :pathname #p"version.lisp-expr") (:file "flexichain-package") (:file "utilities" :depends-on ("flexichain-package")) (:file "flexichain" :depends-on ("utilities" "flexichain-package")) (:file "flexicursor" :depends-on ("flexichain")) (:file "flexirank" :depends-on ("flexichain"))))
1,676
Common Lisp
.asd
33
46.30303
82
0.695917
hpan-open/flexichain-mirror
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
4e88be2e1559020a63993aae712f6396e00af544aeb7a5c6d9051f826e757d46
30,211
[ 98005 ]
30,220
Makefile
hpan-open_flexichain-mirror/Doc/Makefile
NAME=flexichain TEXFILES=$(NAME).tex $(shell ./tex-dependencies $(NAME).tex) PSTEX_T=$(shell ./strip-dependence inputfig $(TEXFILES)) VERBATIM=$(shell ./strip-dependence verbatimtabinput $(TEXFILES)) PSTEX=$(subst .pstex_t,.pstex,$(PSTEX_T)) all : $(NAME).ps $(NAME).pdf %.pstex: %.fig fig2dev -Lpstex -m 0.75 $< $@ %.pstex_t: %.fig %.pstex fig2dev -Lpstex_t -m 0.75 -p $(basename $<).pstex $< $@ $(NAME).dvi: $(TEXFILES) $(PSTEX_T) $(VERBATIM) latex $< makeindex $(NAME) latex $< $(NAME).ps: $(NAME).dvi $(PSTEX) dvips $< -o $(NAME).pdf: $(NAME).dvi $(PSTEX) dvipdf $< $(NAME).pdf view: $(NAME).ps gv -antialias -scale 1 $< clean: rm -f *.aux *.log *~ spotless: make clean rm -f *.ps *.dvi *.pstex *.pstex_t *.toc *.idx *.ilg *.ind *.fig.bak
766
Common Lisp
.l
25
28.76
69
0.639726
hpan-open/flexichain-mirror
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
ace5898e66ec26e77db0acdf525f3095f6e4ca944c8ed04e51d19efc2278d8da
30,220
[ -1 ]
30,222
flexichain.tex
hpan-open_flexichain-mirror/Doc/flexichain.tex
\documentclass[11pt]{article} \usepackage[T1]{fontenc} \usepackage{alltt} \usepackage{moreverb} \usepackage{epsfig} \usepackage{makeidx} \usepackage{changebar} \setlength{\parskip}{0.3cm} \setlength{\parindent}{0cm} \def\inputfig#1{\input #1} \def\inputtex#1{\input #1} \input spec-macros.tex \makeindex \begin{document} \section{The \texttt{flexichain} protocol} In this section, we describe the \texttt{flexichain} protocol, allowing client code to dynamically add elements to, and delete elements from a sequence (or chain) of such elements. \subsection{The concept of a position} A flexichain uses the concept of a ``position'', which has two different meanings in different contexts. The first meaning is the position at which an element is located in the chain. In this context, the position must have a value between 0 and $l-1$, where $l$ is the length of the chain. This meaning is used when an element is to be deleted or when an element is accessed or replaced. The second meaning is the position \textit{between two elements} (or at one of the extreme ends of the chain). In this context, the position may have a value between 0 and the length of the chain inclusive. The position 0 means the beginning of the chain (before the first element, if any), and the position equal to the length means the end of the chain (after the last element if any). This meaning is used when an element is to be inserted. \subsection{Performance} Accessing and replacing an element are constant-time operations. We guarantee linear average complexity of a sequence of insert and delete operations provided that the position of two successive operations in the sequence is bounded. More specifically, the average complexity of an operation is proportional to the difference between the position of the operation and the position of the previous operation. Here we actually consider distance modulo the length of the chain so that the distance between the last position and the first is $1$. In particular, the longest possible distance between to operations is half of the number of elements in the chain. The implementation will allocate more space than is necessary. Whenever space runs out, we allocate a bigger chunk of memory to hold the elements. The new chunk size will be $lk$, were $l$ again is the length of the chain and $k$ is a \textit{constant factor}. We multiply rather than add, because we want to guarantee the linear average complexity of a sequence of insert and delete operations. Typically, $k$ is somewhere between $1.5$ and $2$. The default value is $k=1.5$. We shrink the space whenever the length of the chain (the number of elements) is significantly smaller than the available space. By default, the definition of ``significantly'' is that the ratio of length to size must be less than $1/k^2$ in order for the space to be shrunk. Again, the new chunk size will be $lk$. Using the default value of $k$, this means that the amount of wasted space can be as large as the length of the chain in the worst case, but for a sequence of insert operations, the average wasted space is only 25\%. Applications that store a number of elements that does not vary much, can choose a small value for the $k$ to waste less space. Such applications will have to resize the space relatively rarely so performance will not be affected by small values of $k$. The space will not shrink below a minimum size (default $5$ elements). The reason for this is to avoid to many resize operations for small chains. It is probably not reasonable to use a value below around $5$, since the bookkeeping information takes up at least this much space. This value is also used for the initial size of the chain. Applications that will typically store a large number of elements can choose a greater value for the minimum size. Doing so also improves performance since fewer resize operations will have to be executed. \subsection{Protocol classes and functions} Many names of operations in this section have a terminatin ``\texttt{*}'' which is meant to suggest a \emph{spread} version of the operation. Later (in the \texttt{flexicursor} section) we give \emph{nospread} versions of the operations. \Defprotoclass {flexichain} The protocol class for flexichains. \definitarg {:initial-contents} \definitarg {:element-type} \definitarg {:fill-element} \definitarg {:expand-factor} \Definitarg {:min-size} All instantiable subclasses of \cl{flexichain} accept these initargs. The \cl{:initial-contents} initarg is a sequence (list, vector, string) of objects to be stored in the \cl{flexichain} from the start. The \cl{:element-type} initarg determines the type of the elements of the \cl{flexichain} (default is \cl{t}). The \cl{:fill-element} initarg should be an object that is compatible with the \cl{:element-type} initarg and will be used to fill unoccupied space in the chain (to help the garbage collector). The default value for this initarg will be supplied by the implementation according to the element-type given. The implementation will test \cl{nil}, \cl{0}, and \cl{\#$\backslash$a}. If none of these values will work, the client must supply a value that is compatible with \cl{:element-type}. The \cl{:expand-factor} initarg is used to determine the factor by which the available space will be multiplied whenever the space for the chain is full. Default value is $1.5$. The \cl{:min-size} initarg determines the smallest space allocated to hold elements of the chain. Default value is $5$. It is not reasonable to supply values smaller than $5$. The instance created by make-instance will have a length which is that of the sequence given by \cl{:initial-contents} or $0$ if no \cl{:initial-contents} was given. \Defclass {standard-flexichain} The standard instantiable subclass of \cl{flexichain}. \Defgeneric {nb-elements} {chain} Return the number of elements in the flexichain \arg{chain}. \Deferror {flexi-error} The base condition for all conditions that may be signaled by the operations on flexichains. \Deferror {flexi-position} This condition will be signaled by operations that require a position argument whenever that argument is out of range. \defgeneric {insert*} {chain position object} Insert an object at \arg{position} of the flexichain. If \arg{position} is out of range (less than $0$ or greater than the length of \arg{chain}), the \cl{flexi-position} condition will be signaled. \Defgeneric {delete*} {chain position} Delete an element at \arg{position} of the flexichain. If \arg{position} is out of range (less than $0$ or greater than or equal to the length of \arg{chain}), the \cl{flexi-position} condition will be signaled. \Defgeneric {delete-elements*} {chain position n} Delete N elements at \arg{position} of the flexichain. If $\arg{position}+\arg{N}$ is out of range (less than $0$ or greater than or equal to the length of \arg{chain}, the \cl{flexi-position-error} condition will be signaled, and nothing will be deleted. \arg{n} can be negative, in which case elements will be deleted before \arg{position}. \Defgeneric {element*} {chain position} Return the element at \arg{position} of the \arg{chain}. If \arg{position} is out of range (less than $0$ or greater than or equal to the length of \arg{chain}), the \cl{flexi-position} condition will be signaled. \Defgeneric {(setf element*)} {object chain position} Replace the element at \arg{position} of \arg{chain} by \arg{object}. If \arg{position} is out of range (less than $0$ or greater than or equal to the length of \arg{chain}), the \cl{flexi-position} condition will be signaled. \subsection{Stack and queue operations} A \texttt{flexichain} can be used as a stack or as a queue with very good performance. In this section, we suggest a set of operations to facilitate such use. \Defgeneric {push-start} {chain object} Insert an object at the beginning of the chain. \Defgeneric {push-end} {chain object} Insert an object at the end of the chain. \Defgeneric {pop-start} {chain} Pop and return the element at the beginning of the \texttt{chain} \Defgeneric {pop-end} {chain} Pop and return the element at the end of the \texttt{chain} \Defgeneric {rotate} {chain \optional (n 1)} Rotate the elements of the \texttt{chain} so that the element that used to be at position $n$ now is at position $0$. With a negative value of $n$ rotate the elements so that the element that used to be at position $0$ now is at position $n$. When the magnitude of $n$ is greater than the length of the \texttt{chain}, the operation wraps around so that it becomes equivalent to the same operation with a value of $n$ modulo the length. When the length of the \texttt{chain} is less than $2$, this function does nothing. \section{Implementation of the \texttt{flexichain} protocol} \subsection{Representation} We keep elements in a vector treated as a circular gap buffer with two sentinel elements, one before the first element of the chain (with a position of $-1$), and one after the last element of the chain (with a position equal to the length of the chain). We use the word \textit{position} to refer to the abstract position of an element in a flexichain, and the word \textit{index} when we talk about indexes of the gap buffer used in the implementation. We say that an index $i$ is \emph{valid} if $0 \le i < l$ where $l$ is the size of the vector (the vector is never of size $0$, so it is always the case that $l > 0$). We use the term \emph{extended element} to mean a user element or a sentinel. We say that the vector is \textit{full} when it contains as many extended elements as its length (i.e., the gap has a size of $0$), and \textit{empty} when it contains no user elements (and thus only the sentinels) (i.e., the gap is the size as the vector minus 2). There are three different possible configurations of the gap with respect to the data. Figure \ref{fig-both-contiguous} shows the case where both the gap and the data are contiguous. Figure \ref{fig-data-not-contiguous} shows the case where the data is not contiguous. Finally, figure \ref{fig-gap-not-contiguous} shows the case where the gap is not contiguous. \begin{figure} \begin{center} \inputfig{gap1.pstex_t} \end{center} \caption{\label{fig-both-contiguous} Gap and data are both contiguous} \end{figure} \begin{figure} \begin{center} \inputfig{gap2.pstex_t} \end{center} \caption{\label{fig-data-not-contiguous} Data is not contiguous} \end{figure} \begin{figure} \begin{center} \inputfig{gap3.pstex_t} \end{center} \caption{\label{fig-gap-not-contiguous} Gap is not contiguous} \end{figure} The implementation of a flexichain allows for the first element (i.e., the first sentinel with a position of $-1$) to be located at any valid index of the vector. For that reason, we need an index (called \texttt{data-start}) which always indicates the index of the first sentinel i.e.. \texttt{data-start} is always a valid index A \textit{positional index} is an index in the vector that corresponds to a position in the flexichain, and so is an index either of a user object or the index of the last sentinel. We introduce two different indexes (always valid as well), \texttt{gap-start} and \texttt{gap-end}. The \texttt{gap-start} index is the first index of the gap. When the vector is not full, the \texttt{gap-start} is always an index containing no extended element, such that the previous index does contain an extended element. The \texttt{gap-end} index is the first index beyond the gap and is always the index of an extended element. When the vector is not full, the previous index does not contain an extended element. Notice that for certain configurations \texttt{gap-start} is smaller than \texttt{gap-end} and for certain other configurations, the reverse is true. When the vector is full, \texttt{gap-start} and \texttt{gap-end} are always equal. \subsection{Computing and index from a position} Step one in inserting or deleting an element is to determine an index corresponding to the position. Here is how it is done: we compute a value $s$ which is equal to \texttt{gap-start} if \texttt{gap-start} is greater than \texttt{data-start}. Otherwise $s$ is equal to \texttt{gap-start} plus the size of the vector. The position is added to \texttt{data-start}, giving the value $i$. If $i$ is greater than or equal to $s$, the size of the gap is added to $i$. Finally, if $i$ is greater than or equal to the length of the vector, the length of the vector is subtracted from $i$ (prove that the result is always a positional index). Call this final value of $i$ the \textit{hot spot}. \subsection{Moving the gap to the right place} After determining the index from a position, we need to determine whether the gap is in the right place. This is the case if and only if the hot spot is equal to \texttt{gap-end}. If that is not the case, we need to move the gap. There is a case when it is particularly simple to move the gap, namely when the vector is full. In that case, we can just assign both \texttt{gap-start} and \texttt{gap-end} to the value of the hot spot. There are two ways of getting \texttt{gap-end} to be equal to the hot spot either move everything to the left of the hot spot even further left, or everything to the right of the hot spot (including the hot spot itself) even further right. We always do the one that requires the fewest elements to be moved. One solution will require fewer than half the elements to be moved and the other one at least half. Moving to the right will require that a number of elements equal to the difference between \texttt{gap-start} and the hot spot to be moved, provided that \texttt{gap-start} is greater than the hot spot. If \texttt{gap-start} is smaller than the hot spot, it is that difference plus the size of the vector. We check whether that value is smaller than half of \texttt{nb-elements}. Moving the elements requires one, two, or three calls to \cl{replace}. \subsubsection{Moving elements to the left} Let us first consider the case of moving elements to the left. Case 1: If the entire contiguous gap is to the left of the hot spot (as in the upper half of figure \ref{fig-both-contiguous} or as in figure \ref{fig-data-not-contiguous} with the hot spot to the right of the gap), a single call is required. Case 2:A single call is also required if the highest valid index is inside the gap (as in the lower part of figure \ref{fig-both-contiguous} and in figure \ref{fig-gap-not-contiguous}) provided that the number of elements to be moved is no greater than the part of the gap that is flush right in the vector. Case 3: Two calls are needed if the highest valid index is inside the gap (as in the lower part of figure \ref{fig-both-contiguous} and in figure \ref{fig-gap-not-contiguous}), but the number of elements to be moved is greater than the part of the gap that is flush right in the vector. The first call will fill the part of the gap that is flush right in the vector, giving the situation of the upper half of figure \ref{fig-both-contiguous}. The second call will be as in case 1 above. Case 4: Two calls are also needed if the data is not contiguous (as in figure \ref{fig-data-not-contiguous}) and the entire contiguous gap is to the right of the hot spot, but the number of elements to the left of the hot spot (i.e., the index of the hot spot before the move) is no greater than the size of the gap. The first call will move everything to the right of the gap so that the gap will be flush right as in case 2 above. The second call will move the remaining elements. Case 5: Three calls are needed if the data is not contiguous (as in figure \ref{fig-data-not-contiguous}) and the entire contiguous gap is to the right of the hot spot, but the number of elements to the left of the hot spot (i.e., the index of the hot spot before the move) is greater than the size of the gap. The first call will move the gap flush right, creating the situation of case 3 above (which then requires another two calls). \subsubsection{Moving elements to the right} Let us now consider moving elements to the right. Case 1: If the entire contiguous gap is to the right of the hot spot (as in the lower half of figure \ref{fig-both-contiguous} or as in figure \ref{fig-data-not-contiguous} with the hot spot to the left of the gap), a single call is required. Case 2:A single call is also required if the index 0 is inside the gap (as in the higher part of figure \ref{fig-both-contiguous} and in figure \ref{fig-gap-not-contiguous}) provided that the number of elements to be moved is no greater than the part of the gap that is flush left in the vector. Case 3: Two calls are needed if index 0 is inside the gap (as in the lower part of figure \ref{fig-both-contiguous} and in figure \ref{fig-gap-not-contiguous}), but the number of elements to be moved is greater than the part of the gap that is flush left in the vector. The first call will fill the part of the gap that is flush left in the vector, giving the situation of the lower half of figure \ref{fig-both-contiguous}. The second call will be as in case 1 above. Case 4: Two calls are also needed if the data is not contiguous (as in figure \ref{fig-data-not-contiguous}) and the entire contiguous gap is to the left of the hot spot, but the number of elements to the right of the hot spot (i.e., the index of the hot spot before the move) is no greater than the size of the gap. The first call will move everything to the left of the gap so that the gap will be flush left as in case 2 above. The second call will move the remaining elements. Case 5: Three calls are needed if the data is not contiguous (as in figure \ref{fig-data-not-contiguous}) and the entire contiguous gap is to the left of the hot spot, but the number of elements to the right of the hot spot is greater than the size of the gap. The first call will move the gap flush left, creating the situation of case 3 above (which then requires another two calls). \subsection{Increasing the size of the vector} We increase the size of the vector whenever it is full and another element needs to be added. When this call is made, \texttt{gap-start} and \texttt{gap-end} have the same value. We must preserve the position of the gap in the new vector. A new vector with the size of the number of required elements multiplied by \texttt{size-multiplier} is first allocated. Next, we copy (using a single call to \cl{replace}) all elements before the gap to the start of the new vector. Then we copy (using another single call to \cl{replace}) all elements after the gap to the end of the new vector. The value of \texttt{gap-end} is incremented by the difference in size of the two vectors, as is \texttt{data-start} if it was greater than or equal to \texttt{gap-end}. \subsection{Decreasing the size of the vector} Again, a new vector with the size of the number of required elements multiplied by \texttt{size-multiplier} is first allocated. Next, we copy (using a single call to \cl{replace}) all elements before the gap to the start of the new vector. Then we copy (using another single call to \cl{replace}) all elements after the gap to the end of the new vector. The value of \texttt{gap-end} is decremented by the difference in size of the two vectors, as is \texttt{data-start} if it was greater than or equal to \texttt{gap-end}. \subsection{Inserting an object} The insertion operation is given a position. The semantics of the insertion operation require that all elements having a position greater than or equal to the one given as argument to the insertion operation be ``moved to the right'' i.e., that they have their positions incremented by one. After moving the hot spot to the right place, the value of \texttt{gap-end} is the index corresponding to the position supplied by the call. It should be noted that the same index will result from a position of $0$ and from a position equal to the current length of the chain. But first, we need to make sure the vector is not full. If it is, we call the function to increase its size. We place the object to be inserted at the index of \texttt{gap-start} and then increment \texttt{gap-start}. If this operation gives a \texttt{gap-start} equal to the size of the vector, then it is set to $0$. \subsection{Deleting an element} After moving the hot spot to the right place, we need to delete the element at \texttt{gap-end}. We do this by replacing it by the \texttt{fill-element} so as to avoid holding on to it in case it is no longer referenced. Then we increment \texttt{gap-end}. Finally, we check whether the size of the vector should be decreased. \subsection{Stack and queue operations} The stack and queue operations are implemented very efficiently. The \texttt{push} and \texttt{pop} operations simply call the corresponding \texttt{insert} and \texttt{delete} operations. The \texttt{rotate} operation deletes from one end of the chain and inserts on the other. \section{The \texttt{flexicursor} protocol} A \textit{cursorchain} is like a flexichain, but it also keeps around a bunch of ``flexicursors''. \subsection{The concept of a flexicursor} A flexicursor is an object that corresponds to a position between two elements of the chain. There are two types of flexicursors, \emph{left-sticky} and \emph{right-sticky}. The difference between the two is the way they behave when an object is inserted at corresponding position. When an object is inserted at the position corresponding to a left-sticky flexicursor, this cursor will be positioned \emph{before} the newly inserted object, i.e., the cursor ``sticks'' to the element on its left. When an object is inserted at the position corresponding to a right-sticky flexicursor, this cursor will be positioned \emph{after} the newly inserted object, i.e., the cursor ``sticks'' to the element on its right. Whenever an object is inserted before the position of a cursor, the position of the cursor will be incremented. Conversely, whenever an element is deleted from a position below that of a cursor, the position of the cursor is decremented. \subsection{Mixing \texttt{flexicursor} and \texttt{flexichain} operations} The user can freely mix editing operations from the \texttt{flexicursor} and the \texttt{flexichain} protocol. When an editing operation from the \texttt{flexichain} protocol is used on an \texttt{cursorchain} object, the cursors of the \texttt{cursorchain} object are updated accordingly. \subsection{Performance} There can be a very large number of cursors in a chain without any negative impact on performance. In particular, a sequence of insert operations is not affected by the number of cursors of the chain. For insert operations, we maintain the complexity proportional to the distance between two consecutive positions. A delete operation takes time proportional to the number of left-sticky cursors to the right of the element to delete plus the number of right-sticky cursors to the left of it. The only bad case is thus a delete operation of an element with an unbounded number of cursors sticking to it. \subsection{Protocol classes and functions} \Defprotoclass {cursorchain} This is a subclass of \cl{flexichain}. \Defclass {standard-cursorchain} The standard instantiable subclass of \cl{cursorchain}. \Defprotoclass {flexicursor} The protocol class for all flexicursors. \Definitarg {chain} This initarg determines the cursorchain with which the cursor is associated. \Defclass {standard-flexicursor} The standard instantiable subclass of \cl{flexicursor}. \Defclass {left-sticky-flexicursor} The standard instantiable class for left-sticky flexicursors. It is a subclass of standard-flexicursor. \Defclass {right-sticky-flexicursor} The standard instantiable class for right-sticky flexicursors. It is a subclass of standard-flexicursor. \Defgeneric {chain} {cursor} Return the underlying cursorchain of the flexicursor given as argument. \Defgeneric {clone-cursor} {cursor} Create a cursor that is initially at the same location as the one given as argument. \Deferror {flexi-position-error} This condition is signaled whenever an attempt is made to use position outside of the range of valid positions. \Defgeneric {cursor-pos} {cursor} Return the position of the cursor. \Defgeneric {(setf cursor-pos)} {position cursor} Set the position of the cursor. If the new position of the cursor is before the first position or after the last position of the chain, the condition \cl{flexi-position-error} is signaled. \Defgeneric {at-beginning-p} {cursor} Return true if the cursor is at the beginning of the chain (i.e., if it has a position of 0). This operation is guaranteed to be executed in O(1) time. \Deferror {at-beginning} This condition is signaled whenever an attempt is made to move a cursor beyond the beginning of the chain. \Defgeneric {at-end-p} {cursor} Return true if the cursor is at the end of the chain (i.e., if it has a position equal to the length of the chain). This operation is guaranteed to be executed in O(1) time. \Deferror {at-end} This condition is signaled whenever an attempt is made to move a cursor beyond the end of the chain. \Deferror {incompatible-object-type} This condition is signaled whenever an attempt is made to insert an object of an incompatible type into an chain. \Defgeneric {insert} {cursor object} Insert an object at the position corresponding to that of the cursor. All cursors located at positions greater than the one corresponding to the cursor given as argument, as well as left-sticky cursors (possibly including the one given as argument) located at the same position as the one given as argument will have their positions incremented by one. Other cursors are unaffected. If the type of the object does not match the type accepted by the underlying chain, the \cl{incompatible-object-type} condition is signaled. \Defgeneric {insert-sequence} {cursor sequence} The effect is the same as if each object of the sequence were inserted using the \texttt{insert} generic function. \Defgeneric {delete<} {cursor \optional (n 1)} Delete n elements before the cursor. \Defgeneric {delete>} {cursor \optional (n 1)} Delete n elements after the cursor. ... A sequence of insert and delete operations is guaranteed to be efficient if the positions of successive operations are not too far apart as measured by the shortest distance of the chain viewed as a circular list. Thus, the beginning and the end of the chain are considered close. \Defmacro {with-editing-operations} {cursor \body body} This macro can be used to group a bunch of editing operations (insert, delete) into a body. The sequence remains locked for the duration of invocation. Other cursors of the underlying chain are updated only after the last operation has been completed, thus making it more efficient to use this macro than to use individual editing operations. \Defgeneric {element<} {cursor} Return the element immediately before the cursor. If the cursor is at the beginning, an at-beginning condition will be signaled. \Defgeneric {(setf element<)} {object cursor} Replace the element immediately before the cursor by the object given as argument. If the cursor is at the beginning, an at-beginning condition will be signaled. \Defgeneric {element>} {cursor} Return the element immediately after the cursor. If the cursor is at the end, an at-end condition will be signaled. \Defgeneric {(setf element>)} {object cursor} Replace the element immediately after the cursor by the object given as argument. If the cursor is at the end, an at-end condition will be signaled. \section{Implementation of the \texttt{flexicursor} protocol} Cursors are stored as lists of weak references so that they can be recycled when no longer referenced by client code. A vector that parallels the one holding elements of the flexichain holds per-element lists of cursors that stick to that element. A cursor contains its \textit{index in the vector} as opposed to its \textit{position in the sequence}. This method avoids most updates of cursors at each insert and delete operation. Most cursors need only be updated whenever the gap moves. For left-sticky cursors, we store the index of $p-1$, where $p$ is the position of the cursor. For right-sticky cursors, we store $p$ itself. After a delete operation, cursors with indexes equal to the old value of \texttt{gap-end} need to be updated. Right-sticky cursors will be attached to the index corresponding to the new value of \texttt{gap-end}, whereas left-sticky cursors get attached to the position immediately preceding \texttt{gap-start}. Insert operations do not affect cursors at all. Mixing of \texttt{flexicursor} and \texttt{flexichain} editing operations is possible thanks to an internal protocol for moving the gap. The \texttt{flexicursor} code uses :before, :after, and :around methods on the \texttt{flexichain} editing operations as well as on the code for moving the gap to update the cursors accordingly. This way, a \texttt{flexicursor} editing operation translates directly to a \texttt{flexichain} editing operation with no extra code. \end{document}
29,428
Common Lisp
.l
537
53.333333
77
0.790607
hpan-open/flexichain-mirror
0
0
0
LGPL-2.1
9/19/2024, 11:38:46 AM (Europe/Amsterdam)
910e725cdca18db4eb76f8a479e5ecbfa438ed75e366f774b5a9fd57a5e89f36
30,222
[ -1 ]
30,237
spider.lisp
hutenajey_shareLisp/spider.lisp
(ql:quickload :drakma) (ql:quickload :cl-ppcre) (ql:quickload :closure-html) (ql:quickload :cxml-stp) (defun sliver (page) (handler-case (drakma:http-request page :connection-timeout 5) (condition nil))) (defun picklinks (content) (let ((result (list "result"))) (when (not (null content)) (stp:do-recursively (a (chtml:parse content (cxml-stp:make-builder))) (when (and (typep a 'stp:element) (equal (stp:local-name a) "a")) (nconc result (cons (stp:attribute-value a "href") nil))))) (cdr result))) (defun cleartags(content) (cl-ppcre:regex-replace-all "&.{1,5};|&#.{1,5};" (cl-ppcre:regex-replace-all "<[\\d\\D]*?>" (cl-ppcre:regex-replace-all "<script[\\d\\D]*?>[\\d\\D]*?<\/script>" (cl-ppcre:regex-replace-all "<style[\\d\\D]*?>[\\d\\D]*?<\/style>" content "") "") "") "")) (defun content-split-trim (content ltrim) (mapcar #'(lambda (line) (string-trim ltrim line)) (cl-ppcre:split "\\n+" content))) (defun addprevN (num list) (mapcon #'(lambda (cur) (if (< (length cur) num) (loop for x across (subseq cur 0 num) summing x))) list)) (defun pickMainContent (content block-line-num) (let* ((lines (content-split-trim content '(#\Space #\Tab #\Newline))) (blocklengths (addprevN block-line-num (mapcar #'length lines)))) ) (defun create-breed-spider (url) (let ((index ()) (graph ()) (nest ()) (remainpage ())) (lambda () (labels ((breed-spider (curpage) (if (null curpage) (values index graph nest) (progn (when (not (find curpage nest :test #'string=)) (nconc nest curpage) (setq remainpage (union (picklinks (sliver curpage)) remainpage)) (print remainpage)) (setq curpage (pop remainpage)) (breed-spider curpage))))) (breed-spider url)))))
1,868
Common Lisp
.lisp
58
27.431034
75
0.618009
hutenajey/shareLisp
0
0
0
GPL-2.0
9/19/2024, 11:38:54 AM (Europe/Amsterdam)
f799f98e4098ab5e6097689f997bf9abfcaddc7bd9096c9af2bb510a61aa71e6
30,237
[ -1 ]
30,254
projeto.lisp
Drowze_lisp-phonelist/projeto.lisp
(defun incluir (agenda lista) (cond ((equal agenda 'nil) (reverse (cons lista agenda)) );caso agenda esteja vazia ((equal (car(car agenda)) (car lista)) (cond ((comp_num (cdr(car agenda)) (cdr lista)) agenda );caso comparar numero retornar true retorna a agenda ('t (cons (concatenate 'cons (car agenda) (cdr lista)) (cdr agenda))) );caso contrario retorna a concatenização ) ('t (incluirauxiliar (cdr agenda) agenda lista)) );caso contrario vai para função com fim da agenda e uma agenda sem alteração ) (defun incluirauxiliar (agenda agendacompleta lista) (cond ((equal agenda 'nil) (reverse (cons lista agendacompleta)) );caso agenda esteja vazia ((equal (car(car agenda)) (car lista)) (cond ((comp_num (cdr(car agenda)) (cdr lista));envia o numero agendacompleta );caso comparar numero retornar true retorna a agendacompleta ('t (append (concatenatudo agenda agendacompleta) (cons (concatenate 'cons (car agenda) (cdr lista)) (cdr agenda)))) ) ) ('t (incluirauxiliar (cdr agenda) agendacompleta lista)) ) ) (defun comp_num (agenda numero);verifica se tem o numero na agenda (cond ((equal agenda 'nil) 'nil );caso agenda esteja vazia ((equal (car agenda) (car numero)) 't );caso encontre o numero ('t (comp_num (cdr agenda) numero)) ) ) (defun concatenatudo (agenda agendacompleta) (cond ((equal (caar (last agendacompleta)) (caar agenda)) (butlast agendacompleta) ) ('t (concatenatudo agenda (butlast agendacompleta))) );pega tudo menos o ultimo ) ;----------------------------------------------------------------------------------------- (defun Telefones(agenda nome) (cond ((equal agenda 'nil) 'INEXISTENTE );caso agenda esteja vazia ((equal (caar agenda) nome) (car agenda) );verifica se ja existe o nome informado ('t (Telefones (cdr agenda) nome));recursao ) ) ;----------------------------------------------------------------------------------------- (defun excluir (agenda lista) (cond ((equal agenda 'nil) 'INEXISTENTE );caso agenda esteja vazia avisa q nao existe ((equal (car(car agenda)) (car lista)) (cond ((comp_num_exc (cdr(car agenda)) agenda (cdr lista)));caso comparar numero retornar true retorna a agenda ('t 'INEXISTENTE) );caso contrario retorna a concatenização ) ('t 'INEXISTENTE) );caso contrario vai para função com fim da agenda e uma agenda sem alteração ) (defun comp_num_exc (agenda agendacompleta lista);verifica se tem o numero na agenda e exclui (cond ((equal agenda 'nil) 'nil );caso agenda esteja vazia ((equal (car agenda) (car lista)) );caso encontre o numero exclui ('t (comp_num (cdr agenda) lista)) ) )
2,744
Common Lisp
.lisp
88
27.931818
120
0.657078
Drowze/lisp-phonelist
0
0
0
GPL-2.0
9/19/2024, 11:39:03 AM (Europe/Amsterdam)
b13668924053e6be1f1d98217d5d8d015055c3fed623bf2acbdd801fc72ccc4b
30,254
[ -1 ]
30,271
package.lisp
humbhenri_pb/package.lisp
;;;; package.lisp (defpackage #:pb (:use #:cl) (:export :progress-bar :pb-inc :pb-finish))
97
Common Lisp
.lisp
4
21.75
45
0.637363
humbhenri/pb
0
0
0
GPL-2.0
9/19/2024, 11:39:03 AM (Europe/Amsterdam)
1e19172358fae04e0640218cf79356e867d43c1bc5cd0ae77a905ed58bd0ab0a
30,271
[ -1 ]
30,272
pb.lisp
humbhenri_pb/pb.lisp
;;;; pb.lisp (in-package #:pb) (defclass progress-bar () ((count :initarg :count :initform 1 :reader pb-count) (total :initarg :total :initform (error "Must inform a total value") :reader pb-total) (width :initarg :width :initform 10 :reader width))) (defmethod pb-inc ((pb progress-bar)) (format t "~D / ~D [" (pb-count pb) (pb-total pb)) (let* ((n (floor (/ (* (width pb) (pb-count pb)) (pb-total pb)))) (blanks (- (width pb) n))) (loop repeat n do (write-string "=")) (loop repeat blanks do (write-string " "))) (format t "]~C" #\return) (finish-output nil) (incf (slot-value pb 'count))) (defmethod pb-finish ((pb progress-bar)) (format t "Finished~%"))
753
Common Lisp
.lisp
28
22.5
67
0.590846
humbhenri/pb
0
0
0
GPL-2.0
9/19/2024, 11:39:03 AM (Europe/Amsterdam)
72f72d85766f72bf31582e486ba54bc4ec4cce57f075ccf6426201e1749fd282
30,272
[ -1 ]
30,273
pb.asd
humbhenri_pb/pb.asd
;;;; pb.asd (asdf:defsystem #:pb :description "Simple command line progress bar" :author "Humberto Henrique <[email protected]>" :license "GPL" :serial t :components ((:file "package") (:file "pb")))
234
Common Lisp
.asd
8
24.875
56
0.651786
humbhenri/pb
0
0
0
GPL-2.0
9/19/2024, 11:39:03 AM (Europe/Amsterdam)
480d8725bc44014848c729bde668d46e304d8a33f5945ea7cb3dc243f9d758d1
30,273
[ -1 ]
30,291
dns_with_openvpn.lisp
Michael-S_dns_for_openvpn/dns_with_openvpn.lisp
; Copyright 2015 Mike Swierczek ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. ; Simple script to update DNS entries in resolv.conf ; after an OpenVPN connection is established. ; ; This has been tested on Ubuntu and Fedora Linux ; with SBCL installed. ; You can use the included vpn.sh shell script ; as a starting point. ; ; Author's note - this is my first attempt to write ; anything in Lisp more complicated than "Hello World". ; There is almost certainly un-idiomatic Lisp code ; and bad practices here. ; ; This code has been tested with SBCL, it may ; be compatible with other Lisp distributions, I don't know. ; ; (write-line "OpenVPN DNS fixup started.") ; *posix-argv* is the command line arguments in ; SBCL ;(mapcar (function write-line) *posix-argv*) (if (> 2 (length *posix-argv*)) (progn (write-line "You have to put \"start\" or \"stop\" on the command line.") (exit))) (defparameter *option* (cadr *posix-argv*)) (write-line (concatenate 'string "Received option \"" *option* "\".")) (if (not (or (string= "stop" (string-downcase *option*)) (string= "start" (string-downcase *option*)))) (progn (write-line "Option not recognized, expected \"start\" or \"stop\".") (exit))) ; This function was taken from The Common Lisp Cookbook and is ; assumed to be freely usable. http://cl-cookbook.sourceforge.net/os.html ; If that is not the case, please contact me and I will remove it. (defun my-getenv (name &optional default) #+CMU (let ((x (assoc name ext:*environment-list* :test #'string=))) (if x (cdr x) default)) #-CMU (or #+Allegro (sys:getenv name) #+CLISP (ext:getenv name) #+ECL (si:getenv name) #+SBCL (sb-unix::posix-getenv name) #+LISPWORKS (lispworks:environment-variable name) default)) ; OpenVPN supplies DHCP options to the client that get ; fed to the script as environment variables, each named ; foreign_option_X where X is a number, starting at 1. ; The foreign_option_X values are in the format dhcp-option DNS ..... ; or dhcp-option DOMAIN ..... This program only manages DNS. (defun getdhcpdnsoptions () (loop for x from 1 to 30 for y = (my-getenv (concatenate 'string "foreign_option_" (write-to-string x))) if (and (and (not (null y)) (string= "dhcp-option DNS" (subseq y 0 15))) (< 22 (length y))) collect (concatenate 'string "nameserver " (subseq y 16)))) ; Simple file copy. I made it binary just because I could, it's modifying text ; files so that was not necessary. (defun copyfile (src dest) (with-open-file (stream src :if-does-not-exist :error :element-type '(unsigned-byte 8)) (with-open-file (outstream dest :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)) (loop for item = (read-byte stream nil) until (null item) do (write-byte item outstream)))) t) ; I wanted simpler error messages - a Lisp guru would want the whole stacktrace, ; but then a Lisp guru could write a better version in ten minutes. (defun niceerrorcopyfile (src dest) (handler-case (copyfile src dest) (t (someerror) (progn (write-line "There was an error copying the file - do you have the right permissions?") (write-line "Maybe you need to be root or use sudo?") nil)))) ; in contrast to the file copy, the write uses text handling. (defun writefile (filename contents) (with-open-file (outstream filename :direction :output :if-exists :supersede) (loop for item in contents do (write-line item outstream))) t) (defun niceerrorwritefile (filename contents) (handler-case (writefile filename contents) (t (someerror) (progn (write-line "There was an error writing the file - do you have the right permissions?") (write-line "Maybe you need to be root or use sudo?") (print someerror) nil)))) ; the meat of the program (if (string= "stop" *option*) (progn (write-line "Stop received, attempting to restore previous DNS.") (if (niceerrorcopyfile "/etc/resolv.conf.backup" "/etc/resolv.conf") (write-line "Finished"))) (progn (write-line "Start received. Attempting to get DNS entries from") (write-line "Environment variables.") (let ((dnslist (getdhcpdnsoptions))) (if (null dnslist) (progn (write-line "No DNS options were received from input.") (write-line "Expected environment variables in the form.") (write-line "foreign_option_1 = DNS 1.2.3.4 ") (write-line "foreign_option_2 = DNS 1.2.3.5 ")) (progn (write-line "Received: ") (mapcar (function write-line) dnslist) (write-line "Attempting to backup previous DNS.") (if (niceerrorcopyfile "/etc/resolv.conf" "/etc/resolv.conf.backup") (write-line "Backed up previous DNS.") ) (if (niceerrorwritefile "/etc/resolv.conf" (cons "#Generated by Simple DNS fixup for OpenVPN" dnslist)) (write-line "Finished")))))))
5,963
Common Lisp
.lisp
128
39.757813
116
0.652974
Michael-S/dns_for_openvpn
0
1
0
GPL-3.0
9/19/2024, 11:39:03 AM (Europe/Amsterdam)
6f7f2f6b1492c47eb1545ab4d5438ab01d1d5a74fa64b4aebb50fc1268656550
30,291
[ -1 ]
30,309
factorial.lsp
tusharwalzade216_lisp/factorial.lsp
(defun factorial (n) (if (= n 0) 1 (* n (factorial (- n 1))) ) ) (loop for i from 0 to 16 do (format t "~D! = ~D~%" i (factorial i)) ) ;;; ~D corresponds to printing an integer, and ~% is end-of-line.
221
Common Lisp
.l
7
27.714286
66
0.54717
tusharwalzade216/lisp
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
9eb0476d273660f11c11fe68ed3a45330e84857dc2ac7c26544124db8bdda0fb
30,309
[ -1 ]
30,310
sum.lsp
tusharwalzade216_lisp/sum.lsp
(loop for n from 1 to 1000 when (or (eq (mod n 5) 0) (eq (mod n 3) 0)) (sum n)))
105
Common Lisp
.l
5
15.2
32
0.45
tusharwalzade216/lisp
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
0553b9abb37b229695848a7113ff415237e3326badf7edd5df42db4b19fd73bd
30,310
[ -1 ]
30,311
multiplication_table.lsp
tusharwalzade216_lisp/multiplication_table.lsp
(defun mult_table(a) (dotimes (n 11) (print n) (prin1(* n a))))
66
Common Lisp
.l
3
20.333333
27
0.603175
tusharwalzade216/lisp
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
71ba2bacf10684dfb2be692aa65bf1ef970849927a2f1a50c7db245ba0ad85d1
30,311
[ -1 ]
30,312
is_prime.lsp
tusharwalzade216_lisp/is_prime.lsp
(defun is-prime (n &optional (d (- n 1))) (or (= d 1) (and (/= (rem n d) 0) (is-prime n (- d 1))))) #| (def is-prime (x) (if (is x 2) t (or (< x 2) (is (mod x 2) 0)) nil (check-prime x))) (def check-prime (x) (with (return t i 3 limit (sqrt x)) (while (<= i limit) (when (is (mod x i) 0) (= return nil) (= limit 0)) (zap [+ _ 2] i)) return)) |#
468
Common Lisp
.l
18
18.222222
62
0.395089
tusharwalzade216/lisp
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
436263eda915d84771d380b27118ecda8807b156ec625d9b2043fdb7da61110e
30,312
[ -1 ]
30,331
ch1.lisp
whitelilis_eopl-questions/ch1.lisp
;;; 1.7 The error message from nth-element is uninformative. Rewrite nth-element so that it produces a more informative error message, such as "a b c does not have 8 elements" (defun report-error (msg) (format t "~a" msg)) (defun nth-element (lst n) (defun nth-helper (_lst _n _lst_raw _n_raw) (if (null _lst) (report-error (format nil "~a does not have ~a elements" _lst_raw (+ _n_raw 1))) (progn (if (= 0 _n) (car _lst) (nth-helper (cdr _lst) (- _n 1) _lst_raw _n_raw))))) (nth-helper lst n lst n)) ;;; 1.8 In the definition of remove-first, if the last line were replaced by (remove-first s (cdr los)), what function would the resulting procedure compute? Give the contract, including the usage statement, for the revised procedure. ;; remove-until-first : Sym × Listof(Sym) → Listof(Sym) ;; (remove-until-first s los) removing from beginning until first occurrence of the symbol s, then remove s, return others with the same elements arranged in the same order as los. ;;; 1.9 Define remove, which is like remove-first, except that it removes all occurrences of a given symbol from a list of symbols, not just the first. ;; remove is defined in cl, so define remove-wizard (defun remove-wizard (s los) (if (null los) los (progn (if (eql s (car los)) (remove-wizard s (cdr los)) (cons (car los) (remove-wizard s (cdr los)))))))
1,454
Common Lisp
.lisp
24
54.541667
234
0.668076
whitelilis/eopl-questions
0
0
0
LGPL-3.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
030283a172f203150a8e8a680007643dc4e10e2c4a2a0593866b4734c08835c1
30,331
[ -1 ]
30,348
generic-data-structures.asdf
Lifelovinglight_generic-data-structures/generic-data-structures.asdf
(defsystem "generic-data-structures" :description "A library containing generic data structures." :version "0.1.0" :author "Victor Fors <[email protected]>" :licence "GPL3" :
186
Common Lisp
.asd
6
28.333333
62
0.738889
Lifelovinglight/generic-data-structures
0
0
0
GPL-3.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
3520c93acc64038fbd8c2ddbc22381ea9db461a9c91494a7f4d1c712c15a374e
30,348
[ -1 ]
30,349
quad-tree.cl
Lifelovinglight_generic-data-structures/quad-tree.cl
;;;; Copyright 2015 Victor Fors <[email protected]> ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program. If not, see <http://www.gnu.org/licenses/>. (defpackage :quad-tree (:use :common-lisp) (:export :quad-tree :make-quad-tree :quadtree-set :quadtree-get) (:documentation "A quad-tree implementation.")) (locally (declaim (optimize (compilation-speed 0) (debug 0) (safety 0) (space 2) (speed 3))) (defclass quad-tree () ((depth :initform 1 :initarg :depth :type fixnum :accessor quad-tree-depth :documentation "The depth of the quad-tree.") (contents :initform (cons nil (cons nil (cons nil nil))) :initarg :contents :type cons :accessor quad-tree-contents :documentation "The contents of the quad-tree.")) (:documentation "A quad-tree implementation.")) (declaim (type fixnum *most-positive-2pow*) (type (simple-array fixnum 1) *2pow*) (ftype (function (fixnum) quad-tree) make-quadtree) (ftype (function (fixnum fixnum quad-tree *) nil) quadtree-set) (ftype (function (fixnum fixnum quad-tree) *) quadtree-get)) (defparameter *most-positive-2pow* (loop for x from 1 for y = (expt 2 x) when (> y most-positive-fixnum) return (1- x))) (defparameter *2pow* (make-array (list *most-positive-2pow*) :element-type 'fixnum :initial-contents (cons 0 (loop for n from 0 to (- *most-positive-2pow* 2) collect (expt 2 n)))) "A lookup table of the powers of 2.") (defun make-quad-tree (depth) (check-type depth fixnum) (assert (and (> depth 0) (<= depth *most-positive-2pow*))) "A constructor for a quad-tree." (make-instance 'quad-tree :depth depth)) (defun quadtree-set (x y quadtree arg) "Set a position in a quad-tree to a value." (labels ((inner (x y depth pow2 tree arg) (declare (type (simple-array fixnum 1) pow2) (fixnum x y depth)) ; (print (list x y depth tree)) (if (>= x 0) (if (>= y 0) (if (= 1 depth) (progn (setf (cdddr tree) arg) (values)) (inner (- x (the fixnum (aref pow2 depth))) (- y (the fixnum (aref pow2 depth))) (1- depth) pow2 (if (null (cdddr tree)) (progn (setf (cdddr tree) (cons nil (cons nil (cons nil nil)))) (cdddr tree)) (cdddr tree)) arg)) (if (= 1 depth) (progn (setf (caddr tree) arg) (values)) (inner (- x (the fixnum (aref pow2 depth))) (+ y (the fixnum (aref pow2 depth))) (1- depth) pow2 (if (null (caddr tree)) (progn (setf (caddr tree) (cons nil (cons nil (cons nil nil)))) (caddr tree)) (caddr tree)) arg))) (if (>= y 0) (if (= 1 depth) (progn (setf (car tree) arg) (values)) (inner (+ x (the fixnum (aref pow2 depth))) (- y (the fixnum (aref pow2 depth))) (1- depth) pow2 (if (null (car tree)) (progn (setf (car tree) (cons nil (cons nil (cons nil nil)))) (car tree)) (car tree)) arg)) (if (= 1 depth) (progn (setf (cadr tree) arg) (values)) (inner (+ x (the fixnum (aref pow2 depth))) (+ y (the fixnum (aref pow2 depth))) (1- depth) pow2 (if (null (cadr tree)) (progn (setf (cadr tree) (cons nil (cons nil (cons nil nil)))) (cadr tree)) (cadr tree)) arg)))))) (inner x y (quad-tree-depth quadtree) *2pow* (quad-tree-contents quadtree) arg))) (defun quadtree-get (x y quadtree) "Get the value associated with a position in a quad-tree." (labels ((inner (x y depth pow2 tree) (declare (type (simple-array fixnum 1) pow2) (fixnum x y depth)) ; (print (list x y depth tree)) (if (null tree) nil (if (zerop depth) tree (if (>= x 0) (if (>= y 0) (inner (- x (the fixnum (aref pow2 depth))) (- y (the fixnum (aref pow2 depth))) (1- depth) pow2 (cdddr tree)) (inner (- x (the fixnum (aref pow2 depth))) (+ y (the fixnum (aref pow2 depth))) (1- depth) pow2 (caddr tree))) (if (>= y 0) (inner (+ x (the fixnum (aref pow2 depth))) (- y (the fixnum (aref pow2 depth))) (1- depth) pow2 (car tree)) (inner (+ x (the fixnum (aref pow2 depth))) (+ y (the fixnum (aref pow2 depth))) (1- depth) pow2 (cadr tree)))))))) (inner x y (quad-tree-depth quadtree) *2pow* (quad-tree-contents quadtree)))))
5,401
Common Lisp
.cl
163
25.944785
74
0.568721
Lifelovinglight/generic-data-structures
0
0
0
GPL-3.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
fd4fd6a8da23ee4acec777d8b42f6f958e842f5c58c4ba598a2d8f61e11cdb5e
30,349
[ -1 ]
30,350
fixnum-math.cl
Lifelovinglight_generic-data-structures/fixnum-math.cl
(defpackage :fixnum-math (:use :common-lisp) (:export :pow :sub :add :sum :mul :inc :dec) (:documentation "A collection of fixed-arity fixnum-only math functions for use in certain highly optimized data structures.")) (in-package :fixnum-math) (declaim (optimize (compilation-speed 0) (debug 0) (safety 0) (space 2) (speed 3))) (declaim (inline pow sub add sum mul dec inc) (ftype (function (fixnum) fixnum) dec inc) (ftype (function (fixnum fixnum) fixnum) pow sub add mul) (ftype (function (list) fixnum) sum)) (defun dec (x) "FIXNUM decrementation of X." (the fixnum (1- x))) (assert (= 1 (dec 2))) (defun inc (x) "FIXNUM incrementation of X." (the fixnum (1+ x))) (assert (= 2 (inc 1))) (defun pow (x y) "FIXNUM X to the power of Y." (labels ((inner (x n r) (declare (fixnum x n r)) (if (zerop n) r (inner x (1- n) (mul r x))))) (inner x y x))) (assert (= 256 (pow 2 7))) (defun sub (x y) "FIXNUM subtraction of X and Y." (the fixnum (- x y))) (assert (= 1 (sub 2 1))) (defun add (x y) "FIXNUM addition of X and Y." (the fixnum (+ x y))) (assert (= 4 (add 2 2))) (defun sum (ln) "FIXNUM summation of the LIST LN." (labels ((inner (ln r) (declare (list ln) (fixnum r)) (if (null ln) r (inner (cdr ln) (add r (car ln)))))) (inner ln 0))) (assert (= 8 (sum (list 2 2 4)))) (defun mul (x y) "FIXNUM product of X and Y." (the fixnum (* x y))) (assert (= 4 (mul 2 2)))
1,524
Common Lisp
.cl
65
20.030769
129
0.604716
Lifelovinglight/generic-data-structures
0
0
0
GPL-3.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
5697d46c5251c6dd440b18b0bf6b8509d1323f98a34a3828f6ce2fe0a0feb436
30,350
[ -1 ]
30,351
simple-xml.cl
Lifelovinglight_generic-data-structures/simple-xml.cl
(defpackage :simple-xml (:use :common-lisp) (:export :parse-xml :tokenize-xml)) (in-package :simple-xml) (locally (declaim (optimize (speed 3) (space 2) (safety 2) (debug 1) (compilation-speed 0))) (declaim (ftype (function (list list) list) parse-xml)) (defun whitespacep (char) (member char '(#\Space #\Tab #\Newline #\Return))) (defun letterp (char) (member char (coerce "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 'list))) (defun open-bracketp (char) (eq char #\<)) (defun question-markp (char) (eq char #\?)) (defun equalsp (char) (eq char #\=)) (defun double-quotep (char) (eq char #\")) (defun closing-bracketp (char) (eq char #\>)) (defun forward-slashp (char) (eq char #\/)) (defun produce-string (input &optional (stack (list 'empty-stack))) (if (symbolp (car input)) (cons (coerce (butlast stack) 'string) input) (produce-string (cdr input) (cons (car input) stack)))) (defun produce-symbol (input &optional (stack (list 'empty-stack))) (if (symbolp (car input)) (cons (intern (string-upcase (coerce (butlast stack) 'string))) input) (produce-symbol (cdr input) (cons (car input) stack)))) (defun tokenize-tag-data (input stack) (if (null input) (error "EOF in tag data string.") (if (open-bracketp (car input)) (values input (produce-string stack)) (tokenize-tag-data (cdr input) (cons (car input) stack))))) (defun tokenize-tag-value (input stack) (if (null input) (error "EOF in tag value string.") (if (double-quotep (car input)) (values (cdr input) (produce-string stack)) (tokenize-tag-value (cdr input) (cons (car input) stack))))) (defun tokenize-symbol (input stack) (if (null input) (error "EOF in symbol.") (if (letterp (car input)) (tokenize-symbol (cdr input) (cons (car input) stack)) (values input (produce-symbol stack))))) (defun tokenize-xml (input &optional (stack (list 'empty-stack))) (if (null input) (cdr (reverse stack)) (cond ((whitespacep (car input)) (tokenize-xml (cdr input) stack)) ((open-bracketp (car input)) (tokenize-xml (cdr input) (cons :xml-bracket-open stack))) ((question-markp (car input)) (if (eq :xml-bracket-open (car stack)) (tokenize-xml (cdr input) (cons :xml-metadata-begin (cdr stack))) (tokenize-xml (cdr input) (cons :xml-question-mark stack)))) ((double-quotep (car input)) (multiple-value-bind (input stack) (tokenize-tag-value (cdr input) stack) (tokenize-xml input stack))) ((equalsp (car input)) (tokenize-xml (cdr input) (cons :xml-equals stack))) ((forward-slashp (car input)) (if (eq :xml-bracket-open (car stack)) (tokenize-xml (cdr input) (cons :xml-closing-tag-open (cdr stack))) (tokenize-xml (cdr input) (cons :xml-forward-slash stack)))) ((closing-bracketp (car input)) (cond ((eq :xml-question-mark (car stack)) (tokenize-xml (cdr input) (cons :xml-metadata-end (cdr stack)))) ((eq :xml-forward-slash (car stack)) (tokenize-xml (cdr input) (cons :xml-self-close-tag (cdr stack)))) (t (tokenize-xml (cdr input) (cons :xml-bracket-close stack))))) ((member (car stack) '(:xml-metadata-end :xml-bracket-close :xml-self-close-tag)) (multiple-value-bind (input stack) (tokenize-tag-data input stack) (tokenize-xml input stack))) ((letterp (car input)) (multiple-value-bind (input stack) (tokenize-symbol input stack) (tokenize-xml input stack))) (t (error (format nil "Unknown character in XML data: ~a" (car input))))))) (defun parse-xml (input &optional (stack (list 'empty-stack))) (if (null input) (if (eq 2 (length stack)) (car stack) (error (format nil "Tag not closed in ~a" stack))) (case (car input) ((:xml-bracket-open) (parse-xml-tag (cdr input) (cons (car input) stack))) ((:xml-metadata-begin) (skip-xml-metadata (cdr input) stack)) ((:xml-closing-tag-open) (parse-xml-closing-tag (cdr input) stack)) (t (if (stringp (car input)) (parse-xml (cdr input) (cons (car input) stack)) (error (format nil "Wrong token: ~a" (car input)))))))) (defun parse-xml-tag (input stack) (if (null input) (error (format nil "EOF in tag after: ~a" (car stack))) (if (eq :xml-bracket-open (car stack)) (parse-xml-tag (cdr input) (cons (car input) stack)) (case (car input) ((:xml-bracket-close) (parse-xml (cdr input) stack)) ((:xml-self-close-tag) (parse-xml (cdr input) (produce-xml-tag stack))) ((:xml-metadata-begin) (skip-xml-metadata (cdr input) stack)) (t (if (symbolp (car input)) (parse-xml-value-pair (cdr input) (cons (car input) stack)) (error (format nil "Unexpected token: ~a" (car input))))))))) (defun parse-xml-value-pair (input stack) (if (null input) (error "Error in value pair.") (if (and (symbolp (car stack)) (eq :xml-equals (car input))) (parse-xml-value-pair (cdr input) (cons (car input) stack)) (if (and (eq :xml-equals (car stack)) (stringp (car input))) (parse-xml-tag (cdr input) (cons (car input) (cdr stack))) (error (format nil "Expected :XML-EQUALS instead of ~a" (car input))))))) (defun skip-xml-metadata (input stack) (if (null input) (error "EOF in xml metadata tag") (if (eq (car input) :xml-metadata-end) (parse-xml (cdr input) stack)))) (defun produce-xml-tag (input &optional (stack (list 'empty-stack))) (if (eq :xml-bracket-open (car input)) (cons (butlast stack) (cdr input)) (produce-xml-tag (cdr input) (cons (car input) stack)))) (defun parse-xml-closing-tag (input stack) (if (symbolp (car input)) (parse-xml-tag (cdr input) (close-xml-tag stack (car input))) (error (format nil "Expected symbol, not ~a" (car input))))) (defun close-xml-tag (input tag &optional (stack (list 'empty-stack))) (if (null input) (error (format nil "Could not close tag: ~a" tag)) (if (eq tag (car input)) (cons (butlast (cons (car input) stack)) (cddr input)) (close-xml-tag (cdr input) tag (push (car input) stack))))))
6,250
Common Lisp
.cl
160
34.15625
88
0.641513
Lifelovinglight/generic-data-structures
0
0
0
GPL-3.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
2c6f3716ff1672bae30bbd843194b3c374e1baa2f98df8f27fa3acb5c5716988
30,351
[ -1 ]
30,352
circular-buffer.cl
Lifelovinglight_generic-data-structures/circular-buffer.cl
(defpackage :circular-buffer (:use :common-lisp) (:export :circular-buffer :make-circular-buffer :circular-buffer-push :circular-buffer-pop :circular-buffer-resize) (:documentation "A module implementing a circular buffer.")) (in-package :circular-buffer) (defclass circular-buffer () ((circular-buffer-contents :initform nil :initarg :contents :accessor circular-buffer-contents :type list :documentation "The contents of the circular buffer.") (circular-buffer-max-items :initform 1 :initarg max-items :accessor circular-buffer-max-items :type (integer 1 *) :documentation "The max number of items in the circular buffer.")) (:documentation "A circular buffer")) (defgeneric circular-buffer-push (circular-buffer arg)) (defgeneric circular-buffer-pop (circular-buffer)) (defgeneric circular-buffer-resize (circular-buffer new-size)) (declaim (ftype (function (list) list) circular-list) (ftype (function (list integer) circular-buffer) make-circular-buffer)) (defun circular-list (arg) "Create a circular list." (setf (cdr (last arg)) arg)) (assert (= 1 (nth 3 (circular-list (list 1 2 3))))) (defun make-circular-buffer (initial-data max-items) (let ((data-length (length initial-data))) (assert (>= max-items data-length)) (let ((empty-space (loop repeat (- max-items data-length) collect nil))) (make-instance 'circular-buffer :contents (circular-list (append empty-space initial-data)))))) (assert (let ((test-circular-buffer (make-circular-buffer (list 1 2 3) 3))) (and (equal (circular-list (list 1 2 3)) (circular-buffer-contents test-circular-buffer)) (= 3 (circular-buffer-max-items test-circular-buffer))))) (defmethod circular-buffer-push ((circular-buffer circular-buffer) arg) (let ((contents (circular-buffer-contents circular-buffer))) (setf (cdr contents) (cons arg (cddr contents))))) (assert (let ((test-circular-buffer (make-circular-buffer (list 1 2 3) 4))) (and (progn (circular-buffer-push test-circular-buffer 4) (equal (circular-list (list 4 1 2 3)) (circular-buffer-contents test-circular-buffer))) (progn (circular-buffer-push test-circular-buffer 5) (equal (circular-list (list 5 4 1 2)) (circular-buffer-contents test-circular-buffer)))))) (defmethod circular-buffer-pop ((circular-buffer circular-buffer)) (let ((retval (copy-list (list (car (circular-buffer-contents circular-buffer)))))) (setf (circular-buffer-contents circular-buffer) (
2,560
Common Lisp
.cl
57
40.614035
85
0.715261
Lifelovinglight/generic-data-structures
0
0
0
GPL-3.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
dd3fc7aa8b7b8ae6c6148172b946b82bf1c41e7975fb620938d4266502d9e6aa
30,352
[ -1 ]
30,353
queue.cl
Lifelovinglight_generic-data-structures/queue.cl
(defpackage :queue (:use :common-lisp) (:export :queue :queue-data :queue-rear :enqueue :dequeue) (:documentation "A queue implementation.")) (in-package :queue) (defclass queue () ((queue-data :initform nil :initarg :data :accessor queue-data :type list :documentation "The contents of the queue.") (queue-rear :initform nil :initarg :rear :accessor queue-rear :documentation "The rear of the queue.")) (:documentation "A queue implementation.")) (defgeneric enqueue (queue arg)) (defgeneric dequeue (queue)) (defmethod initialize-instance :after ((this-queue queue) &key) (setf (queue-rear this-queue) (last (queue-data this-queue)))) (defmethod enqueue ((queue queue) arg) "Add an item to the rear of a queue." (setf (cdr (queue-rear queue)) (cons arg nil)) (setf (queue-rear queue) (cdr (queue-rear queue)))) (defmethod dequeue ((queue queue)) "Remove an item from the front of a queue." (pop (queue-data queue)))
1,004
Common Lisp
.cl
33
26.818182
66
0.692946
Lifelovinglight/generic-data-structures
0
0
0
GPL-3.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
78ab0570c41ac0ba5013e993e41b3a061fac1f3080815e753791ec24416e75a1
30,353
[ -1 ]
30,374
package.lisp
leongithub_work-utils/package.lisp
;;;; package.lisp (defpackage #:work-utils (:use #:cl #:com.gigamonkeys.pathnames) (:shadow :walk-directory) (:export :compute-all :compute-sub-max-min :add-comment-for-strxml :remove-comment-for-strxml :find-out-lack-strings :copy-string-from-res1-to-res2 :delete-unuse-resource :find-out-new-strings))
340
Common Lisp
.lisp
12
24.333333
41
0.699387
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
7e8dbb7adb11cdd5fa6556f56996d311539599139e4f9dff6e561b04b2421749
30,374
[ -1 ]
30,375
find-out-lack-strings.lisp
leongithub_work-utils/find-out-lack-strings.lisp
;;;; 由于说高通原生对小语种支持缺失,如:values/strings.xml 有 <string name="a">a</string>,而values-fi/strings.xml 没有此字段。 ;;;; 此代码寻找出缺失的字符串 (in-package #:work-utils) (defparameter *base-strings* "values") (defparameter *compare-strings-list* (list "values-ca" "values-ca-rES" "values-cs" "values-cs-rCZ" "values-da" "values-da-rDK" "values-de" "values-de-rAT" "values-de-rch" "values-de-rDE" "values-el" "values-el-rGR" "values-en-rGB" "values-es" "values-es-rES" "values-fi" "values-fi-rFI" "values-fr" "values-fr-rBE" "values-fr-rCH" "values-fr-rFR" "values-hu" "values-hu-rHU" "values-it" "values-it-rIT" "values-nb" "values-nb-rNO" "values-nl-rBE" "values-nl-rNL" "values-pl" "values-pl-rPL" "values-pt" "values-pt-rBR" "values-pt-rPT" "values-ro" "values-ro-rRO" "values-ru" "values-ru-rRU" "values-sv" "values-sv-rSE" "values-tr" "values-tr-rTR" "values-zh-rCN" "values-zh-rHK" "values-zh-rTW")) (defparameter *source-table* (make-hash-table)) (defparameter *compare-table* (make-hash-table :test 'equal)) (defstruct tag content line-number) (defun find-out-lack-strings (dir-res) (base-xml-to-hash-table dir-res) (with-open-file (out "~/compare-strings-result.txt" :direction :output :if-exists :supersede :external-format :utf8) (dolist (dir-value *compare-strings-list*) (format out "~%~%~A~%" dir-value) (if (compare-xml-to-hash-table dir-res dir-value) (compare-strings out) (format out "file ~A is not exist~%" dir-value)))) (clrhash *source-table*) (clrhash *compare-table*)) (defun base-xml-to-hash-table (dir-res) (with-open-file (in (rtn-strings-xml dir-res *base-strings*) :direction :input :if-does-not-exist nil :external-format :utf8) (let ((multi-line-p) (name) (multi-line-buffer)) (do ((line (read-line in nil 'eof) (read-line in nil 'eof)) (line-number 1 (1+ line-number))) ((eql line 'eof)) (let ((name-position (search "name=" line))) (cond (name-position (setf name (subseq line (+ name-position 6) (search "\"" line :start2 (+ name-position 6)))) (setf multi-line-p (not (search "</string>" line :from-end t))) (if multi-line-p (setf multi-line-buffer line) (set-source-hash name line line-number))) (multi-line-p (setf multi-line-buffer (concatenate 'string multi-line-buffer line)) (setf multi-line-p (not (search "</string>" line :from-end t))) (unless multi-line-p (set-source-hash name multi-line-buffer line-number))))))))) (defun set-source-hash (name content line-number) (setf (gethash name *source-table*) (make-tag :content content :line-number line-number))) (defun compare-xml-to-hash-table (dir-res dir-value) (clrhash *compare-table*) (with-open-file (in (rtn-strings-xml dir-res dir-value) :direction :input :if-does-not-exist nil :external-format :utf-8) (when in (do ((line (read-line in nil 'eof) (read-line in nil 'eof))) ((eql line 'eof) t) (let ((name-position (search "name=" line))) (if name-position (let ((name (subseq line (+ name-position 6) (search "\"" line :start2 (+ name-position 6))))) (setf (gethash name *compare-table*) t)))))))) (defun compare-strings (out) (maphash #'(lambda (k v) (unless (gethash k *compare-table*) (format out "~A:~A~%" (tag-line-number v) (tag-content v)))) *source-table*)) (defun rtn-strings-xml (dir-res dir-values) (merge-pathnames (make-pathname :directory `(:relative ,dir-values) :name "strings" :type "xml") dir-res))
3,680
Common Lisp
.lisp
79
40.696203
661
0.654131
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
8ff8602ef2dc79070ad742869bd8c0a75a8409fde9c4119e2a71c56e2af72c4c
30,375
[ -1 ]
30,376
delete-unuse-resource.lisp
leongithub_work-utils/delete-unuse-resource.lisp
;;;; 最近对项目中的无用资源(主要图片和xml文件)进行清理 ;;;; 用法: ;;;; (delete-unuse-resource "path-to-project") ;;;; (delete-unuse-resource "path-to-project" '(other-path-to-search)) (in-package #:work-utils) (defun delete-unuse-resource (project-pathname &optional search-project-lst) "删除 Android 项目中的无用资源" (pushnew project-pathname search-project-lst :test 'equal) (dolist (pathname search-project-lst) (unless (file-exists-p pathname) (error "~a is not exists" pathname))) (let ((result (find-out-unuse-resource project-pathname search-project-lst))) (print (mapcar #'(lambda (p) (namestring p)) result)) (when (y-or-n-p "是否删除以上资源") (dolist (p result 'done) (delete-file p))))) (defun find-out-unuse-resource (project-pathname search-project-lst) (labels ((find-out-unuse-resource-1 (name) (let ((regex (concatenate 'string name "[^a-z_]"))) (dolist (project search-project-lst) (walk-directory project #'(lambda (p) (with-open-file (stream p :external-format :utf8) (when (cl-ppcre:scan regex (%read-body stream)) ;; 当找到后就退出此函数 (return-from find-out-unuse-resource-1)))) :test #'(lambda (p) (let ((type (pathname-type p))) (or (string= type "java") (string= type "xml")))) :list-directory-test #'(lambda (p) (let ((last-dir (car (last (pathname-directory p))))) ;; 这里排除 build 目录,查找 build 目录会花很多时间 (not (string= "build" last-dir)))))) name))) (let (lst (res-dir (make-pathname :directory (append (pathname-directory (pathname-as-directory project-pathname)) (list "res"))))) (dolist (x (list-directory res-dir)) (let ((last-dir (car (last (pathname-directory x))))) ;; 只找 drawable** 和 layout** 目录下的文件 (when (or (search "drawable" last-dir) (search "layout" last-dir)) (dolist (resource (list-directory x)) ;; 因为有 xxx.9.png 这样的,所以用两次 pathname-name 函数 (when (find-out-unuse-resource-1 (pathname-name (pathname-name resource))) (push resource lst)))))) (nreverse lst))))
2,565
Common Lisp
.lisp
53
33.867925
88
0.559673
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
25d4478f5922640d6c36caa5e9219f3ac46d0d629ca470885c870b3da0eb424f
30,376
[ -1 ]
30,377
work-utils.lisp
leongithub_work-utils/work-utils.lisp
;;;; work-utils.lisp (in-package #:work-utils) ;;; "work-utils" goes here. Hacks and glory await! (defconstant +buffer-size+ 8192) (defun read-file (filespec) "Helper function to read from file into a buffer of character, which is returned." (with-open-file (in filespec :direction :input :if-does-not-exist nil :external-format :utf8) (%read-body in))) ;; drakma's %read-body (defun %read-body (stream) "Helper function to read from stream into a buffer of character, which is returned." (let ((buffer (make-array +buffer-size+ :element-type 'character)) (result (make-array 0 :element-type 'character :adjustable t))) (loop for index = 0 then (+ index pos) for pos = (read-sequence buffer stream) do (adjust-array result (+ index pos)) (replace result buffer :start1 index :end2 pos) while (= pos +buffer-size+)) result)) ;; 对 com.gigamonkeys.pathnames 中的 walk-directory 添加了一个 list-directory-test 参数 (defun walk-directory (dirname fn &key directories (test (constantly t)) (list-directory-test (constantly t))) "Walk a directory invoking `fn' on each pathname found. If `test' is supplied fn is invoked only on pathnames for which `test' returns true. If `directories' is t invokes `test' and `fn' on directory pathnames as well." (labels ((walk (name) (cond ((directory-pathname-p name) (when (and directories (funcall test name)) (funcall fn name)) (when (funcall list-directory-test name) (dolist (x (list-directory name)) (walk x)))) ((funcall test name) (funcall fn name))))) (walk (pathname-as-directory dirname)))) (defmacro aif (test then &optional else) "if 的指代宏,在 then 和 else 的 form 中,可以用 it 来指代 test 的结果" `(let ((it ,test)) (if it ,then ,else))) (declaim (inline mklist)) (defun mklist (obj) (if (listp obj) obj (list obj)))
1,988
Common Lisp
.lisp
46
36.782609
86
0.670043
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
7c2cf05631664621c0b017e4f7720fc9d816c1d224ffb455f9fd67b901be6076
30,377
[ -1 ]
30,378
copy-string-from-res1-to-res2.lisp
leongithub_work-utils/copy-string-from-res1-to-res2.lisp
;; 由于其他应用中有字段:<string name="test">test</string> ;; 我想移到我的应用,但是res目录下的values*目录好多,所以此程式诞生 ;; (copy-string-from-res1-to-res2 "path/res/" "path/res/" "name") (in-package #:work-utils) (defun copy-string-from-res1-to-res2 (dir-res1 dir-res2 names &optional deletep) (let ((name-regex (create-scanner names))) (walk-directory dir-res1 #'(lambda (p) (aif (find-out-strings p name-regex deletep) (let ((out-path (merge-pathnames (enough-namestring p dir-res1) dir-res2))) (add-content-to-file out-path it)))) :test #'(lambda (p) (and (string= (pathname-type p) "xml") (string= (pathname-name p) "strings")))))) (defun find-out-strings (filespec name-regex &optional deletep) (let ((file-string (read-file filespec)) (lst (cl-ppcre:all-matches-as-strings name-regex file-string :sharedp t))) (if (and lst deletep) (with-open-file (out filespec :direction :output :if-exists :supersede :external-format :utf8) (write-sequence (cl-ppcre:regex-replace-all name-regex file-string "") out))) lst)) (defun create-scanner (names) (let ((names (mklist names))) (cl-ppcre:create-scanner (concatenate 'string "(?:^[ \\t]*<!--(?:(?!-->).)*-->\\s?\\n)?^[ \\t]*<string(-array)? name=\"" (if (= (length names) 1) (car names) (concatenate 'string "(" (let ((lst)) (dolist (name names) (push name lst) (push "|" lst)) (apply #'concatenate 'string (cdr lst))) ")")) "\"(?: [a-zA-Z]+=\"\\w*\")*>.*?</string(?(1)\\1)>") :single-line-mode t :multi-line-mode t))) (defun add-content-to-file (filepath content) (with-open-file (in filepath :direction :input :if-does-not-exist nil :external-format :utf8) (when in (with-open-file (out filepath :direction :output :if-exists :overwrite :external-format :utf8) (do ((line (read-line in nil 'eof) (read-line in nil 'eof))) ((eql line 'eof)) (when (search "</resources>" line) (dolist (str content) (write-line str out))) (format out "~A~%" line))))))
2,266
Common Lisp
.lisp
67
26.880597
80
0.593292
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
71510f617034bc6da2abfd9841e9c4d258d1e06e63098137a146fc988d11d121
30,378
[ -1 ]
30,379
find-out-new-strings.lisp
leongithub_work-utils/find-out-new-strings.lisp
;;;; 要求找出现在的工程与原生工程之间,新增加的字符串 ;;; 把原生文件中的字符串加载到 hash-table 中,然后循环目前工程中的文件, ;;; 找出新增的(目前只比较 name 是否相同) (in-package #:work-utils) (defun find-out-new-strings (old-res new-res values-lst out-dir) "old-res,旧的工程 res 目录。new-res,新的工程 res 目录。values-lst,values-* 目录列表。out-dir,结果输出目录" (dolist (dir-values values-lst 'done) (with-open-file (out (make-pathname :name dir-values :type "txt" :defaults (pathname-as-directory out-dir)) :direction :output :if-exists :supersede :external-format :utf8) (let ((old-file (generate-strings-file-pathname old-res dir-values)) (new-file (generate-strings-file-pathname new-res dir-values))) (unless (file-exists-p old-file) (format out "~a is not exists~%" (namestring old-file))) (unless (file-exists-p new-file) (format out "~a is not exists~%" (namestring new-file))) (when (and (file-exists-p old-file) (file-exists-p new-file)) (loop for (nil . str) in (find-out-new-string-for-file old-file new-file) do (format out "~a~%" str))))))) (defun generate-strings-file-pathname (dir-res dir-values) (make-pathname :directory (append (pathname-directory (pathname-as-directory dir-res)) (list dir-values)) :name "strings" :type "xml")) (defun find-out-new-string-for-file (old-file new-file) "传递旧文件和新文件,返回新增字符串的列表" (labels ((find-out-new-string-for-file1 (hash-table) (with-open-file (in new-file :if-does-not-exist nil :external-format :utf8) (let ((target-string (%read-body in)) (lst)) (do-string target-string #'(lambda (name str) (unless (gethash name hash-table) (push (cons name str) lst)))) (nreverse lst))))) (let ((hash-table (old-file-to-hash-table old-file))) (and hash-table (find-out-new-string-for-file1 hash-table))))) (defun old-file-to-hash-table (old-file) "旧文件转换成 hash-table" (with-open-file (in old-file :if-does-not-exist nil :external-format :utf8) (when in (let ((target-string (%read-body in)) (hash-table (make-hash-table :test 'equal))) (do-string target-string #'(lambda (name str) (setf (gethash name hash-table) str))) hash-table)))) (defun do-string (target-string fn) "Helper function to loop target-string apply fn" (cl-ppcre:do-matches-as-strings (str "<string .*</string>" target-string) (funcall fn (svref (nth-value 1 (cl-ppcre:scan-to-strings "name=\"([^\"]+)\"" str)) 0) str)))
2,791
Common Lisp
.lisp
73
29.739726
83
0.649372
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
2fde2b4a6611c9b7234dd1fd7fcb5bf064d18194e41dc018ab29348268422311
30,379
[ -1 ]
30,380
add-comment-to-duplicate-strings.lisp
leongithub_work-utils/add-comment-to-duplicate-strings.lisp
;;;; 用来批量替换文件中的字符串 ;; 应用场景:在看Android源码的时候,发现values-*/strings.xml有很多 ;; <string name="account_phone" product="tablet">Tablet-only, unsynced</string> ;; <string name="account_phone" product="default">Phone-only, unsynced</string> ;; ;; <string name="fail_reason_too_many_vcard" product="nosdcard">Too many vCard files are in the storage.</string> ;; <string name="fail_reason_too_many_vcard" product="default">Too many vCard files are on the SD card.</string> ;; 会使我用Android studio引入源码自己build报错,所以要留下default ,注释掉其他的 ;; ;; 程序设计:由于这些strings.xml文件分布在res/values*/strings.xml,res目录大部分是vaules*目录,所以就把 ;; res目录下的所有目录加载进来,然后再与strings.xml合并为一个完整的文件路径。进入文件,查看每一行,是否包 ;; 含"product="字符串,如果有再查看product的值是否不为“default”,如果符合替换条件,在输出原本行的同时加上 ;; 注释前后缀。 ;; (add-comment-for-strxml "/home/.../res/") (in-package #:work-utils) (defparameter *multi-line* nil) (defparameter *pre-str* "<!--") (defparameter *post-str* "-->") (defun add-comment-for-strxml (dir-res) (loop-strxml dir-res #'add-comment-for-line)) (defun remove-comment-for-strxml (dir-res) (loop-strxml dir-res #'remove-comment-for-line)) ;; 去除strings.xml注释 (defun remove-comment-for-line (filepath) (labels ((need-modify-p (line) (or ; 符合修改条件 (let ((pos 0)) (and (setq pos (search "product=" line)) (not (search "default" line :start2 (+ pos 9) :end2 (+ pos 16))) (search *pre-str* line :end2 10))) ; 多行的<string></string>,并且为</string> (and *multi-line* (search "</string>" line :from-end t) (search *post-str* line :from-end t)))) (modify-line (line) (if (search "</string>" line :from-end t) (subseq line (if *multi-line* (progn (setf *multi-line* nil) 0) (length *pre-str*)) (search *post-str* line)) (progn (setf *multi-line* t) (subseq line (length *pre-str*))))) (handle-line (line) (if (need-modify-p line) (modify-line line) line))) (replace-line filepath #'handle-line))) ;; 给strings.xml加入注释 (defun add-comment-for-line (filepath) (labels ((need-modify-p (line) (or ; 符合修改条件 (let ((pos 0)) (and (setq pos (search "product=" line)) (not (search "default" line :start2 (+ pos 9) :end2 (+ pos 16))) (not (search *pre-str* line :end2 10)))) ; 多行的<string></string>,并且为</string> (and *multi-line* (search "</string>" line :from-end t) (not (search *post-str* line :from-end t))))) (modify-line (line) (if (search "</string>" line :from-end t) (concatenate 'string (if *multi-line* (setf *multi-line* nil) *pre-str*) line *post-str*) (progn (setf *multi-line* t) (concatenate 'string *pre-str* line)))) (handle-line (line) (if (need-modify-p line) (modify-line line) line))) (replace-line filepath #'handle-line))) ;; 之前输出流用:if-exists :overwrite, ;; 如果是去掉注释就会出现输出比输入少,导致文件尾部会有多余字符 ;; 现在采用输出新文件,再删除原有文件,最后重命名新文件为旧文件 (defun replace-line (filepath handle-line) (with-open-file (in filepath :direction :input :if-does-not-exist nil :external-format :utf8) (when in (let ((temp-filename (make-pathname :name "temp-strings" :defaults filepath))) (with-open-file (out temp-filename :direction :output :if-exists :supersede :external-format :utf8) (do ((line (read-line in nil 'eof) (read-line in nil 'eof))) ((eql line 'eof)) (write-line (funcall handle-line line) out))) (delete-file in) (rename-file temp-filename filepath))))) ;; 找出在res目录下的所有strings.xml文件,并循环应用到fn函数上 (defun loop-strxml (dir-res fn) (dolist (filepath (find-strxml-files dir-res)) (funcall fn filepath))) ;; 从所给的res目录下找出所有strings.xml文件 (defun find-strxml-files (dir-parent) (let ((dir-object (make-pathname :name :wild :type :wild :defaults dir-parent))) (mapcar #'(lambda (dir) (merge-pathnames dir (make-pathname :name "strings" :type "xml"))) (directory dir-object))))
4,690
Common Lisp
.lisp
123
28.065041
113
0.641006
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
05474a1846f1b4562cde7898fbb12b92cc1b2907981e65ad34e3aa7e7d979761
30,380
[ -1 ]
30,381
compute-number.lisp
leongithub_work-utils/compute-number.lisp
;;;; 需求: ;;;; 由于公司网页表格里有很多这样的数据:1+2+3+2+4 ;;;; 最后要求去掉最大最小,然后算平均值,最后两个平均值按照a*8+b*2计算得除结果。 ;;;; 应该有的计算器会支持,但还是练习下cl吧:) ;;;; 解决大概步骤: ;;;; 1.先把1+2+3去掉+("123"),然后转换成list(#\1 #\2 #\3),再转换成数字列表(1 2 3) ;;;; 2.套用a*8+b*2计算 (in-package #:work-utils) ;; 现在出现打分数据较少,就不减去最高最低的值了 (defun compute-all () (read-data-for-compute t)) (defun compute-sub-max-min () (read-data-for-compute)) ;; 循环读取用户输入的数据 (defun read-data-for-compute (&OPTIONAL allp) (labels ((prompt (x) (format t "~&please input ~A : " x) (string-trim '(#\Space #\Tab) (read-line)))) (let ((x (prompt "需求评分")) (y (prompt "风险评分"))) (print (compute x y allp)) (read-data-for-compute)))) (defun compute (x y &OPTIONAL allp) (let ((ppx (preproccess x)) (ppy (preproccess y))) (+ (* 8 (number-seq-average ppx allp)) (* 2 (number-seq-average ppy allp))))) (defun number-seq-average (seq allp) (print (if allp (all-number-seq-average seq) (n-sub-max-min-to-average seq)))) (defun n-sub-max-min-to-average (seq) (/ (- (reduce #'+ seq) (reduce #'max seq) (reduce #'min seq)) (- (length seq) 2.0))) (defun all-number-seq-average (seq) (float (/ (reduce #'+ seq) (length seq)))) (defun preproccess (x) (char-list->number-list (concatenate 'list (remove #\+ (string x))))) (defun char-list->number-list (char-lst) (mapcar #'(lambda (c) (parse-integer (string c))) char-lst))
1,732
Common Lisp
.lisp
52
24.211538
63
0.614938
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
87196c289c9ee0bf91c01030886a011703f922b3732945a75a03771397bf75c8
30,381
[ -1 ]
30,382
work-utils.asd
leongithub_work-utils/work-utils.asd
;;;; work-utils.asd (asdf:defsystem #:work-utils :description "Describe work-utils here" :author "Your Name <[email protected]>" :license "Specify license here" :depends-on (#:cl-ppcre #:com.gigamonkeys.pathnames) :serial t :components ((:file "package") (:file "work-utils") (:file "compute-number") (:file "add-comment-to-duplicate-strings") (:file "find-out-lack-strings") (:file "copy-string-from-res1-to-res2" :depends-on ("work-utils")) (:file "delete-unuse-resource" :depends-on ("work-utils")) (:file "find-out-new-strings" :depends-on ("work-utils"))))
618
Common Lisp
.asd
17
32.294118
69
0.66778
leongithub/work-utils
0
0
0
GPL-2.0
9/19/2024, 11:39:15 AM (Europe/Amsterdam)
2ba91b16ddcc39d3f83dd22d286fcde8510725d4e903123b482508e7c319f7b6
30,382
[ -1 ]
30,407
parse-uri.lisp
firaja_lisp-uri-parser/parse-uri.lisp
;;;; Bertoldi David 735213 ;;;; Garasi Gabriele Francesco 735964 ;;;; ----- LISP URI PARSER ----- ;;; A Common Lisp Library that builds structures ;;; that rappresents URI from strings ;;; The library accepts 6 types of URI ;;; if any part of the syntax results wrong ;;; it will be generated an error message ;; structure definition ;; :scheme :userinfo :host :port :path :query :fragment (defstruct uri scheme userinfo host port path query fragment) ;; The main function ;; parse-uri: string --> list (defun parse-uri (stringa) (let ((lista (coerce stringa 'list))) (if (null lista) (error "Empty is not a URI") (check-scheme lista)))) ;; An helper function: it makes results more comprehensible (defun magitrasforma (lista) (if (null lista) nil (coerce lista 'string))) ;;; The code below defines the atoms of an URI ;;; <identifier, host-identifier, digit, query, fragment> (defun is-query (lista) (if (null lista) nil (eval (cons 'and (mapcar (lambda (char) (if (eq char #\#) nil t)) lista))))) (defun is-fragment (lista) (if (null lista) nil (eval (cons 'and (mapcar 'characterp lista))))) (defun is-char-id (char) (if (null char) nil (if (or (eq char #\/) (eq char #\?) (eq char #\#) (eq char #\@) (eq char #\:)) nil t))) (defun is-char-host (char) (if (or (eq char #\.) (eq char #\/) (eq char #\?) (eq char #\#) (eq char #\@) (eq char #\:)) nil t)) (defun is-identificatore (lista) (eval (cons 'and (mapcar (lambda (char) (if (or (eq char #\/) (eq char #\?) (eq char #\#) (eq char #\@) (eq char #\:)) nil t)) lista)))) (defun is-identificatore-host (lista) (eval (cons 'and (mapcar (lambda (char) (if (or (eq char #\.) (eq char #\/) (eq char #\?) (eq char #\#) (eq char #\@) (eq char #\:)) nil t)) lista)))) (defun is-digit (lista) (eval (cons 'and (mapcar (lambda (num) (if (null (to-number num)) nil t)) lista)))) ;; this function (with its helper) checks the propriety of an IP address ;; basically it's useless ;; {IP} c {HOST} (defun is-ip (ip) (if (is-ip-h (ipip (coerce (ipify ip) 'string))) (if (and (integerp (to-number (car ip))) (integerp (to-number (car (last ip))))) t nil) nil)) (defun ipify (ip) (if (integerp (to-number (car ip))) (cons (car ip) (ipify (cdr ip))) (if (eq (car ip) #\.) (if (eq (car (cdr ip)) #\.) nil (cons #\Space (ipify (cdr ip)))) nil))) (defun ipip (ip) (with-input-from-string (s ip) (cons (read s nil 'eof) (cons (read s nil 'eof) (cons (read s nil 'eof) (cons (read s nil 'eof) (cons (read s nil 'eof) nil))))))) (defun is-ip-h (ip) (if (and (integerp (in-position ip 1)) (<= (in-position ip 1) 255) (integerp (in-position ip 2)) (<= (in-position ip 2) 255) (integerp (in-position ip 3)) (<= (in-position ip 3) 255) (integerp (in-position ip 4)) (<= (in-position ip 4) 255) (eq (in-position ip 5) 'eof)) t nil)) ;; A little function that transforms #\numbers in numbers (defun to-number (n) (cond ((eq n #\0) 0) ((eq n #\1) 1) ((eq n #\2) 2) ((eq n #\3) 3) ((eq n #\4) 4) ((eq n #\5) 5) ((eq n #\6) 6) ((eq n #\7) 7) ((eq n #\8) 8) ((eq n #\9) 9) (t nil))) ;;; Below the syntactic definition of scheme, userinfo, path, host (defun is-scheme (lista) (and (is-identificatore lista) (not (null lista)))) (defun is-userinfo (lista) (if (null lista) nil (and (is-identificatore lista) (not (null lista))))) (defun is-path (lista) (if (null lista) nil (if (is-char-id (car lista)) (is-path2 lista) nil))) (defun is-path2 (lista) (if (null lista) t (if (is-char-id (car lista)) (is-path2 (cdr lista)) (if (eq (car lista) #\/) (cond ((is-char-id (car (cdr lista))) (is-path2 (cdr lista))) ((null (cdr lista)) t) (t nil)) nil)))) (defun is-host (lista) (if (null lista) nil (cond ((is-ip lista) t) ((is-char-host (car lista)) (is-host2 lista)) (t nil)))) (defun is-host2 (lista) (if (null lista) t (if (is-char-host (car lista)) (is-host2 (cdr lista)) (if (eq (car lista) #\.) (if (is-char-host (car (cdr lista))) (is-host2 (cdr lista)) nil) nil)))) (defun is-path-after-auth (lista) (if (eq (car lista) #\/) t (if (eq (car lista) #\/) (if (is-path (cdr lista)) t nil) nil))) (defun is-port (lista) (if (null lista) nil (is-digit lista))) ;;; The core: definition of the automata that ;;; recognizes the syntax of a URI (defun in-position (lista n) (if (= n 1) (car lista) (in-position (cdr lista) (- n 1)))) ;; list-to-sym and sym-to-list "read" the string (defun list-to-sym (lista sym) (if (eval (cons 'or (mapcar (lambda (x) (eq x sym)) lista))) (if (null lista) nil (if (eq (car lista) sym) nil (append (list (car lista)) (list-to-sym (cdr lista) sym)))) nil)) (defun sym-to-list (lista sym) (if (null lista) nil (if (eq (car lista) sym) (cdr lista) (sym-to-list (cdr lista) sym)))) ;; check-scheme begin the parsing and ;; recognize the type of URIs (defun check-scheme (lista) (let ((l (list-to-sym lista #\:)) (s (sym-to-list lista #\:))) (if (is-scheme l) (cond ((equal l '(#\m #\a #\i #\l #\t #\o)) (mailto-ss s (list l))) ((equal l '(#\n #\e #\w #\s)) (news-ss s (list l))) ((or (equal l '(#\t #\e #\l)) (equal l '(#\f #\a #\x))) (telfax-ss s (list l))) (t (if (and (eq (car s) #\/) (eq (car (cdr s)) #\/)) (first-uri-type s (list l)) (second-uri-type s (list l))))) (error "Not valid SCHEME: SCHEME IS OBLIGATORY definition of SCHEME: scheme := <identifier> identifier := chars without {/ ? # @ :}")))) ;; the 1) type of URI (defun first-uri-type (lista cumulo) (userinfo-opt (cdr (cdr lista)) cumulo)) ;; the 2) type of URI (defun second-uri-type (lista cumulo) (if (eq (car lista) #\/) (path-opt (cdr lista) (append cumulo '(nil) '(nil) '(nil))) (path-opt lista (append cumulo '(nil) '(nil) '(nil))))) ;; the 3) type of URI (defun mailto-ss (lista cumulo) (if (is-userinfo lista) (the-end (append cumulo (list lista))) (if (is-userinfo (list-to-sym lista #\@)) (host-opt (sym-to-list lista #\@) (append cumulo (list (list-to-sym lista #\@)))) (error "NOT VALID USERINFO: USERINFO IS OBLIGATORY definition of USERINFO: userinfo := <identifier> identifier := chars without {/ ? # @ :}")))) ;; the 4) type of URI (defun news-ss (lista cumulo) (if (is-host lista) (the-end (append cumulo (list nil lista))) (error "NOT VALID HOST: HOST IS OBLIGATORY definition of HOST: host := <host-identifier> [ . <host-identifier>]* host-identifier := chars without {. / ? # @ :}"))) ;;the 5) and the 6) type of URI (defun telfax-ss (lista cumulo) (if (is-userinfo lista) (the-end (append cumulo (list lista))) (error "NOT VALID USERINFO: USERINFO IS OBLIGATORY definition of USERINFO: userinfo := <identifier> identifier := chars without {/ ? # @ :}"))) ;; optional presence of ['@' userinfo] (defun userinfo-opt (lista cumulo) (let ((l (list-to-sym lista #\@)) (s (sym-to-list lista #\@))) (if (is-userinfo l) (host-obb s (append cumulo (list l))) (if (and (null l) (not (eq (car lista) #\@))) (if (null s) (host-obb lista (append cumulo '(nil))) (host-obb s (append cumulo '(nil) (list l)))) (error "NOT VALID USERINFO definition of USERINFO: userinfo := <identifier> identifier := chars without {/ ? # @ :}"))))) ;; obligatory presence of host (defun host-obb (lista cumulo) (if (is-host lista) (the-end (append cumulo (list lista))) (cond ((is-host (list-to-sym lista #\:)) (port-opt (sym-to-list lista #\:) (append cumulo (list (list-to-sym lista #\:))))) ((is-host (list-to-sym lista #\/)) (path-opt (sym-to-list lista #\/) (append cumulo (list (list-to-sym lista #\/)) '(nil)))) ((is-host (list-to-sym lista #\?)) (query-opt (sym-to-list lista #\?) (append cumulo (list (list-to-sym lista #\?)) '(nil) '(nil)))) ((is-host (list-to-sym lista #\#)) (fragment-opt (sym-to-list lista #\#) (append cumulo (list (list-to-sym lista #\#)) '(nil) '(nil) '(nil)))) (t (error "NOT VALID HOST: HOST IS OBLIGATORY definition of HOST: host := <host-identifier> [ . <host-identifier>]* host-identifier := chars without {. / ? # @ :}"))))) ;; optional presence of [':' port] (defun port-opt (lista cumulo) (if (is-port lista) (the-end (append cumulo (list lista))) (cond ((is-port (list-to-sym lista #\/)) (path-opt (sym-to-list lista #\/) (append cumulo (list (list-to-sym lista #\/))))) ((is-port (list-to-sym lista #\?)) (query-opt (sym-to-list lista #\?) (append cumulo (list (list-to-sym lista #\?)) '(nil)))) ((is-port (list-to-sym lista #\#)) (fragment-opt (sym-to-list lista #\#) (append cumulo (list (list-to-sym lista #\#)) '(nil) '(nil)))) (t (error "NOT VALID PORT definition of PORT: port := <digit> digit := chars form 0 to 9"))))) ;; optional presence of [path] (defun path-opt (lista cumulo) (cond ((is-path lista) (the-end (append cumulo (list lista)))) ((eq (car lista) #\?) (query-opt (cdr lista) (append cumulo '(nil)))) ((eq (car lista) #\#) (fragment-opt (cdr lista) (append cumulo '(nil) '(nil)))) ((null lista) (the-end cumulo)) ((is-path (list-to-sym lista #\?)) (query-opt (sym-to-list lista #\?) (append cumulo (list (list-to-sym lista #\?))))) ((is-path (list-to-sym lista #\#)) (fragment-opt (sym-to-list lista #\#) (append cumulo (list (sym-to-list lista #\#)) '(nil)))) (t (error "NOT VALID PATH definition of PATH: path := <identifier> [ / <identifier>]* '/' identifier := chars without {/ ? # @ :}")))) ;; optional presence of ['?' query] (defun query-opt (lista cumulo) (cond ((is-query lista) (the-end (append cumulo (list lista)))) ((is-query (list-to-sym lista #\#)) (fragment-opt (sym-to-list lista #\#) (append cumulo (list (list-to-sym lista #\#))))) (t (error "NOT VALID QUERY definition of QUERY: query := chars without {#}")))) ;; optional presence of ['#' fragment] (defun fragment-opt (lista cumulo) (cond ((is-fragment lista) (the-end (append cumulo (list lista)))) (t (error "NOT VALID FRAGMENT definition of FRAGMENT: fragment := chars")))) ;; optional presence of ['@' host] (defun host-opt (lista cumulo) (if (is-host lista) (the-end (append cumulo (list lista))) (error "NOT VALID HOST definition of HOST: host := <host-identifier> [ . <host-identifier>]* host-identifier := chars without {. / ? # @ :}"))) ;; The final function (TFF) (defun the-end (cumulo) (make-uri :scheme (magitrasforma (in-position cumulo 1)) :userinfo (magitrasforma (in-position cumulo 2)) :host (magitrasforma (in-position cumulo 3)) :port (magitrasforma (in-position cumulo 4)) :path (magitrasforma (in-position cumulo 5)) :query (magitrasforma (in-position cumulo 6)) :fragment (magitrasforma (in-position cumulo 7))))
14,178
Common Lisp
.lisp
330
30.145455
77
0.474549
firaja/lisp-uri-parser
0
0
0
GPL-2.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
dac10090a3c0e550007e3215c5716ac2790d8f207e621e6f7e667081073dbf85
30,407
[ -1 ]
30,424
model.lisp
johncorn271828_X_Orrery/model.lisp
#| This is the top-level file for the state logic, ie non-IO code. |# ;;;Physics and astronomy code ;;All these two lines do is suppress meaningless compiler warnings. (defgeneric objects (m)) ;Geodesic following code wants to be able to see a list of massive objects. (defgeneric player (s)) (defgeneric v (p)) ;To account for moving reference frames in physics code. (load "mathphysics.lisp") (load "astrometry.lisp") ;;;Define some classes for maintaining the global program state. ;;The main objects of the application world, attributes tbd: (defclass celestial-body (rigid-body) ()) (defclass sun (celestial-body) ()) (defclass planet (celestial-body) ()) (defclass moon (celestial-body) ()) (defclass laboratory (rigid-body) ()) (defclass vessel (rigid-body) ((v :accessor v :initarg :v :initform 0))) (defclass player (vessel) ((phi :accessor phi :initarg :phi :initform 0) ;angle from roll to pitch axis (theta :accessor theta :initarg :theta :initform (/ pi 2)))) ;angle off yaw axis ;;Global state wrapper object. Obviously from all the hardcoding, I am still ;; missing a lot of astrometry data. (defclass X_Orrery-state () ((elapsed-time :reader elapsed-time :initarg :elapsed-time :initform 0) (last-internal-real-time :reader last-internal-real-time :initarg :last-internal-real-time :initform (get-internal-real-time)) (objects :reader objects :initarg :objects :initform (list ;;starfield (needs to be first...?) (make-instance 'celestial-body :name "Starfield" :size 100000000) ;;sun (make-instance 'sun :name "Sun" :mass sun-mass :x (vector 0 0 (- earth-orbital-radius) 0) :size sun-radius) ;;mercury (make-instance 'planet :name "Mercury" :mass mercury-mass :x (vector 0 (- mercury-orbital-radius) (- earth-orbital-radius) 0) :xdot (vector 0 0 mercury-orbital-speed 0) :omega mercury-angular-velocity :size mercury-radius) ;;venus (make-instance 'planet :name "Venus" :mass venus-mass :x (vector 0 (* venus-orbital-radius 0.707) (- (* venus-orbital-radius 0.707) earth-orbital-radius) 0) :xdot (vector 0 (* venus-orbital-speed -0.717) (* venus-orbital-speed 0.717) 0) :omega venus-angular-velocity :size venus-radius) ;;earth (make-instance 'planet :name "Earth" :mass earth-mass :x (vector 0 1.3 0 0) :xdot (vector 0 earth-orbit-speed 0 0) :roll (vector 0 -1 0 0) :pitch (vector 0 0 1 0) :yaw (vector 0 0 0 -1) :omega (- earth-angular-velocity) :size earth-radius) ;;mars (make-instance 'planet :name "Mars" :mass mars-mass :x (vector 0 0 (- mars-orbital-radius earth-orbital-radius) 0) :xdot (vector 0 (- mars-orbital-speed) 0 0) :omega mars-angular-velocity :size mars-radius) ;;jupiter (make-instance 'planet :name "Jupiter" :mass jupiter-mass :x (vector 0 (* -1 (sqrt 0.5) jupiter-orbital-radius) (- (* (sqrt 0.5) jupiter-orbital-radius) earth-orbital-radius) 0) :xdot (vector 0 (* (sqrt 0.5) jupiter-orbital-speed) (* -1 (sqrt 0.5) jupiter-orbital-speed) 0) :omega jupiter-angular-velocity :size jupiter-radius) ;;saturn (make-instance 'planet :name "Saturn" :mass saturn-mass :x (vector 0 (* -1 (sqrt 0.5) saturn-orbital-radius) (- (+ earth-orbital-radius (* (sqrt 0.5) saturn-orbital-radius))) 0) :xdot (vector 0 (* -1 (sqrt 0.5) saturn-orbital-speed) (* (sqrt 0.5) saturn-orbital-speed) 0) :roll (vector 0 0 (sqrt 0.5) (sqrt 0.5)) :pitch (vector 0 1 0 0) :yaw (vector 0 0 (sqrt 0.5) (- (sqrt 0.5))) :omega saturn-angular-velocity :size saturn-radius) ;;uranus (make-instance 'planet :name "Uranus" :mass uranus-mass :x (vector 0 (* (sqrt 0.5) uranus-orbital-radius) (- (* (sqrt 0.5) uranus-orbital-radius) earth-orbital-radius) 0) :xdot (vector 0 (* -1 (sqrt 0.5) uranus-orbital-speed) (* (sqrt 0.5) uranus-orbital-speed) 0) :omega uranus-angular-velocity :size uranus-radius) ;;neptune (make-instance 'planet :name "Neptune" :mass neptune-mass :x (vector 0 (* (sqrt 0.5) neptune-orbital-radius) (- (- (sqrt 0.5) neptune-orbital-radius) earth-orbital-radius) 0) :xdot (vector 0 (* (sqrt 0.5) neptune-orbital-speed) (* -1 (sqrt 0.5) neptune-orbital-speed) 0) :omega neptune-angular-velocity :size neptune-radius) ;;moon (make-instance 'moon :name "Moon" :mass moon-mass :x (vector 0 (- 1.3 moon-orbital-radius) 0.007 0) :xdot (vector 0 earth-orbit-speed (- moon-orbit-speed) 0 0) :omega earth-angular-velocity :size moon-radius ) ;;international space station (make-instance 'laboratory :name "Low Earth Orbiter" :mass 0 :x (vector 0 1.3 (- low-earth-orbital-radius) 0) :xdot (vector 0 earth-orbit-speed 0 low-earth-orbit-speed) :omega earth-angular-velocity :size (* 1000000 meter) ;not sure why this has to be so big? ) ) ) (player :accessor player :initarg :player :initform (make-instance 'player :mass 0 :name "Player")))) ;;;This updates global state given new controller state and the old state. ;;It's a pure function for thread safety and overall robustitude. (defun get-new-state (old-state controller time) ;;(debugvar "called new state with mouse-keys" (mouse-keys controller)) (make-instance 'X_Orrery-state :elapsed-time (+ (elapsed-time old-state) (- time (last-internal-real-time old-state))) :last-internal-real-time time :objects (mapcar (compose (lambda (p) (follow-geodesic p (/ (- time (last-internal-real-time old-state)) 1000.0) old-state)) (lambda (p) (rotate p #(0 1 0 0) ;always the player's roll axis (roll-rate controller))) (lambda (p) (rotate p #(0 0 1 0) ;always the player's pitch axis (* (pitch-rate controller) (max (expt 2 (- (v (player old-state)))) 0.001)))) (lambda (p) (rotate p #(0 0 0 1) (* (yaw-rate controller) (max (expt 2 (- (v (player old-state)))) 0.001))))) (objects old-state)) :player (copy-instance (player old-state) ;;update phi and theta, shifting them back to their usual domains if needed :phi (let* ((old-phi (phi (player old-state))) (dphi 0.007) ;mouse sensitivity (delta-phi (* -1 (mouse-deltax controller) dphi))) (cond ((> (+ old-phi delta-phi) (* 2 pi) ) (- (+ old-phi delta-phi) (* 2 pi))) ((< (+ old-phi delta-phi) 0) (+ old-phi delta-phi (* 2 pi))) (t (+ old-phi delta-phi)))) :theta (let* ((old-theta (theta (player old-state))) (dtheta 0.007) ;mouse sensitivity (delta-theta (* (mouse-deltay controller) dtheta))) (cond ((> (+ old-theta delta-theta) pi) pi) ((< (+ old-theta delta-theta) 0) 0) (t (+ old-theta delta-theta)))) :v (cond ((assoc #\b (key-down-time-table controller)) 250) ((member 'control-wheel-up (mouse-events controller)) (+ (v (player old-state)) (* 0.00001 (- c (v (player old-state)))))) ((member 'wheel-up (mouse-events controller)) (+ (v (player old-state)) (* 0.001 (- c (v (player old-state)))))) ((member 'shift-wheel-up (mouse-events controller)) (+ (v (player old-state)) (* 0.05 (- c (v (player old-state)))))) ((member 'control-wheel-down (mouse-events controller)) (* (v (player old-state)) 0.9)) ((member 'wheel-down (mouse-events controller)) (* (v (player old-state)) 0.6)) ((member 'shift-wheel-down (mouse-events controller)) 0) (t (v (player old-state)))))))
8,667
Common Lisp
.lisp
224
29.910714
113
0.571683
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
5bdc76998a2c7a03e66ece06e64b53b83ab9aa924a3e616ae25f303605694415
30,424
[ -1 ]
30,425
audio.lisp
johncorn271828_X_Orrery/audio.lisp
#| This file contains code to spawn threads for audio events, including music. Not tested on windows. |# ;;See the cl-openal github for info about how this works. (defun wav-thread (file-name &optional (x 0.0) (y 0.0) (z 0.0)) (let ((data nil) (format nil) (stereop nil) (bytes-per-sample) (size nil) (frequency nil) (duration nil) (data-info-list)) (alut:with-init ;;load the song data (setf data-info-list (multiple-value-bind (d fo s fr) (alut:load-memory-from-file file-name) (list d fo s fr))) (setf data (first data-info-list)) (setf format (second data-info-list)) (setf stereop (if (or (equal format :stereo8) (equal format :stereo16)) t nil)) (setf bytes-per-sample (if (or (equal format :stereo8) (equal format :mono8)) 1 2)) (setf size (third data-info-list)) (setf frequency (round (fourth data-info-list))) ;;(debugvar "data-info-list" data-info-list) (setf duration (/ size frequency (if stereop 2 1) bytes-per-sample))) (alc:with-device (device) (alc:with-context (context device) (alc:make-context-current context) (al:with-buffer (buffer) (al:with-source (source) (al:buffer-data buffer format data size frequency) (al:source source :buffer buffer) (al:source source :position (vector x y z)) (al:source source :velocity #(0 0 0)) (al:listener :position #(0 0 0)) (al:listener :orientation #(1 0 0 0 0 1)) ;; Let the music play... (al:source source :looping :false) (al:source-play source) (sleep duration) (al:source-stop source))))))) (defun run-music-daemon () (sleep 10) (loop while t do (loop for song in (list "audio/venus.wav" "audio/jupiter.wav" "audio/mercury.wav" "audio/saturn.wav") do (debugvar "playing :" song) (wav-thread song)))) (defun play-wav (filename &optional (x 0.0) (y 0.0) (z 0.0)) ;coordinates only work for mono files (bordeaux-threads:make-thread (lambda () (wav-thread filename x y z))))
2,194
Common Lisp
.lisp
61
29.229508
117
0.613787
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
e0b0566b0227298bb3b83d90b539dc97ddc6fd4e89b7cfd9fb44fa07815b57a8
30,425
[ -1 ]
30,426
displaylistpopulator.lisp
johncorn271828_X_Orrery/displaylistpopulator.lisp
#| Using GL's display lists allows better performance. |# (defgeneric populate-display-lists (w)) (defmethod populate-display-lists ((w X_Orrery-gui)) (let ((sphere-ring-count 100)) ;;generate display lists. ;;currently starfield sun, 8 planets, 2 satellites, player (setf (draw-list w) (gl:gen-lists 30)) ;;starfield 0 (gl:color 0 0 0) (gl:with-new-list ((+ 0 (draw-list w)) :compile) ;;bottom (let ((starfield-size 100000)) (gl:with-primitives :quads (gl:tex-coord 0 0) (gl:vertex (- starfield-size) (- starfield-size) (- starfield-size)) (gl:tex-coord 0 1) (gl:vertex (- starfield-size) starfield-size (- starfield-size)) (gl:tex-coord 1 1) (gl:vertex starfield-size starfield-size (- starfield-size)) (gl:tex-coord 1 0) (gl:vertex starfield-size (- starfield-size) (- starfield-size))) ;;top (gl:with-primitives :quads (gl:tex-coord 0 0) (gl:vertex (- starfield-size) (- starfield-size) starfield-size) (gl:tex-coord 0 1) (gl:vertex (- starfield-size) starfield-size starfield-size) (gl:tex-coord 1 1) (gl:vertex starfield-size starfield-size starfield-size) (gl:tex-coord 1 0) (gl:vertex starfield-size (- starfield-size) starfield-size)) ;;left (gl:with-primitives :quads (gl:tex-coord 0 0) (gl:vertex (- starfield-size) starfield-size (- starfield-size)) (gl:tex-coord 0 1) (gl:vertex (- starfield-size) starfield-size starfield-size) (gl:tex-coord 1 1) (gl:vertex starfield-size starfield-size starfield-size) (gl:tex-coord 1 0) (gl:vertex starfield-size starfield-size (- starfield-size))) ;;right (gl:with-primitives :quads (gl:tex-coord 0 0) (gl:vertex (- starfield-size) (- starfield-size) (- starfield-size)) (gl:tex-coord 0 1) (gl:vertex (- starfield-size) (- starfield-size) starfield-size) (gl:tex-coord 1 1) (gl:vertex starfield-size (- starfield-size) starfield-size) (gl:tex-coord 1 0) (gl:vertex starfield-size (- starfield-size) (- starfield-size))) ;;front (gl:with-primitives :quads (gl:tex-coord 0 0) (gl:vertex starfield-size (- starfield-size) (- starfield-size)) (gl:tex-coord 0 1) (gl:vertex starfield-size (- starfield-size) starfield-size) (gl:tex-coord 1 1) (gl:vertex starfield-size starfield-size starfield-size) (gl:tex-coord 1 0) (gl:vertex starfield-size starfield-size (- starfield-size))) ;;back (gl:with-primitives :quads (gl:tex-coord 0 0) (gl:vertex (- starfield-size) (- starfield-size) (- starfield-size)) (gl:tex-coord 0 1) (gl:vertex (- starfield-size) (- starfield-size) starfield-size) (gl:tex-coord 1 1) (gl:vertex (- starfield-size) starfield-size starfield-size) (gl:tex-coord 1 0) (gl:vertex (- starfield-size) starfield-size (- starfield-size))))) ;;Sun 1 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 1 (draw-list w)) :compile) (glu:sphere qo sun-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;Mercury 2 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 2 (draw-list w)) :compile) (glu:sphere qo mercury-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;Venus 3 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 3 (draw-list w)) :compile) (glu:sphere qo venus-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;Earth 4 (let ((earth-quadric-obj)) (setf earth-quadric-obj (glu:new-quadric)) (glu:quadric-draw-style earth-quadric-obj :fill) (glu:quadric-texture earth-quadric-obj 1) (glu:quadric-normals earth-quadric-obj :smooth) (gl:with-new-list ((+ 4 (draw-list w)) :compile) (glu:sphere earth-quadric-obj earth-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric earth-quadric-obj)) ;;Mars 5 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 5 (draw-list w)) :compile) (glu:sphere qo mars-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;Jupiter 6 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 6 (draw-list w)) :compile) (glu:sphere qo jupiter-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;Saturn 7 and 13 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 7 (draw-list w)) :compile) (glu:sphere qo saturn-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;now the rings (gl:with-new-list ((+ 13 (draw-list w)) :compile) (loop for i from 0 to 40 do (gl:with-primitives :quads (gl:tex-coord 0 0) (gl:vertex (* saturn-inner-ring-radius (cos (* i (/ (* 2 pi) 40)))) (* saturn-inner-ring-radius (sin (* i (/ (* 2 pi) 40)))) 0) (gl:tex-coord 0 1) (gl:vertex (* saturn-outer-ring-radius (cos (* i (/ (* 2 pi) 40)))) (* saturn-outer-ring-radius (sin (* i (/ (* 2 pi) 40)))) 0) (gl:tex-coord 1 1) (gl:vertex (* saturn-outer-ring-radius (cos (* (+ i 1) (/ (* 2 pi) 40)))) (* saturn-outer-ring-radius (sin (* (+ i 1) (/ (* 2 pi) 40)))) 0) (gl:tex-coord 1 0) (gl:vertex (* saturn-inner-ring-radius (cos (* (+ i 1) (/ (* 2 pi) 40)))) (* saturn-inner-ring-radius (sin (* (+ i 1) (/ (* 2 pi) 40)))) 0)))) ;;Uranus 8 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 8 (draw-list w)) :compile) (glu:sphere qo uranus-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;Neptune 9 (let ((qo (glu:new-quadric))) (glu:quadric-draw-style qo :fill) (glu:quadric-texture qo 1) (glu:quadric-normals qo :smooth) (gl:with-new-list ((+ 9 (draw-list w)) :compile) (glu:sphere qo neptune-radius sphere-ring-count sphere-ring-count)) (glu:delete-quadric qo)) ;;moon 10 (let ((moon-quadric-obj)) (setf moon-quadric-obj (glu:new-quadric)) (glu:quadric-draw-style moon-quadric-obj :fill) (glu:quadric-texture moon-quadric-obj 1) (glu:quadric-normals moon-quadric-obj :smooth) (gl:with-new-list ((+ 10 (draw-list w)) :compile) (glu:sphere moon-quadric-obj moon-radius sphere-ring-count sphere-ring-count) ) (glu:delete-quadric moon-quadric-obj) ) ;;player 11 (gl:with-new-list ((+ 11 (draw-list w)) :compile) (let ((iss-mesh (read-mesh-from-obj-file "meshes/player.obj" 1)) (normal-index)) (loop for face in (faces iss-mesh) do (gl:with-primitives :line-loop (setf normal-index (- (aref (normal-indices face) 0) 1)) ;;(debugvar "normal index" normal-index) (gl:normal (aref (aref (normals iss-mesh) normal-index) 0) (aref (aref (normals iss-mesh) normal-index) 1) (aref (aref (normals iss-mesh) normal-index) 2)) (loop for i across (vertex-indices face) do (gl:vertex (aref (aref (vertices iss-mesh) (- i 1)) 0) (aref (aref (vertices iss-mesh) (- i 1)) 1) (aref (aref (vertices iss-mesh) (- i 1)) 2))))))) ;;laboratory 12 (gl:with-new-list ((+ 12 (draw-list w)) :compile) (let ((iss-mesh (read-mesh-from-obj-file "meshes/antenna.obj" (* 10000 meter))) (normal-index)) (loop for face in (faces iss-mesh) do (if (= (length (vertex-indices face)) 4) (gl:with-primitives :quads (setf normal-index (- (aref (normal-indices face) 0) 1)) ;;(debugvar "normal index" normal-index) (gl:normal (aref (aref (normals iss-mesh) normal-index) 0) (aref (aref (normals iss-mesh) normal-index) 1) (aref (aref (normals iss-mesh) normal-index) 2)) (gl:tex-coord 0 0) (gl:vertex (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 0) 1)) 0) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 0) 1)) 1) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 0) 1)) 2)) (gl:tex-coord 0 1) (gl:vertex (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 1) 1)) 0) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 1) 1)) 1) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 1) 1)) 2)) (gl:tex-coord 1 1) (gl:vertex (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 2) 1)) 0) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 2) 1)) 1) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 2) 1)) 2)) (gl:tex-coord 1 0) (gl:vertex (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 3) 1)) 0) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 3) 1)) 1) (aref (aref (vertices iss-mesh) (- (aref (vertex-indices face) 3) 1)) 2))))))) ;;Saturn's rings are #13. see above ) ;;end let ) ;end defmethod
9,624
Common Lisp
.lisp
223
37.426009
88
0.63412
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
c5f067d7bf57d200cecb8a440036922fbfe1f1e9344616400135d6874e51e666
30,426
[ -1 ]
30,427
mathphysics.lisp
johncorn271828_X_Orrery/mathphysics.lisp
#| This has some useful math and physics code I wrote for simulating the solar system and changing reference frames. |# ;;;Vector math ;;Rotate the space components of the 4-vector 4vect around the axis specified by the 4-vector n by angle theta. ;;See http://inside.mines.edu/fs_home/gmurray/ArbitraryAxisRotation/ (defun rotate-4-vector (4vect n theta) (if (= 0 theta) 4vect (let* ((length-n (sqrt (+ (expt (aref n 1) 2) (expt (aref n 2) 2) (expt (aref n 3) 2)))) (u (/ (aref n 1) length-n)) (v (/ (aref n 2) length-n)) (w (/ (aref n 3) length-n)) (x (aref 4vect 1)) (y (aref 4vect 2)) (z (aref 4vect 3)) (result)) ;;(princln "doing some vector rotating") (setf result (vector (aref 4vect 0) (+ (* u (+ (* u x) (* v y) (* w z) ) (- 1 (cos theta))) (* x (cos theta)) (* (- (* v z) (* w y)) (sin theta))) (+ (* v (+ (* u x) (* v y) (* w z) ) (- 1 (cos theta))) (* y (cos theta)) (* (- (* w x) (* u z)) (sin theta))) (+ (* w (+ (* u x) (* v y) (* w z)) (- 1 (cos theta))) (* z (cos theta)) (* (- (* u y) (* v x)) (sin theta))))) ;;(debugvar "rotated vector" result) result))) ;;;Physics stuff. ;;Physical constants in kilogram light-second second units. (defconstant meter 3.33564e-9) (defconstant G 2.477e-36) (defconstant c 1) ;;This class handles degrees of freedom of a rigid body, with a generic "size" variable and some ;; other redundancies for coding convenience. (defclass rigid-body () ((name :accessor name :initarg :name :initform "") (mass :accessor mass :initarg :mass :initform 0) (x :accessor x :initarg :x :initform (vector 0d0 0d0 0d0 0d0)) ;position 4-vector (xdot :accessor xdot :initarg :xdot :initform (vector 0d0 0d0 0d0 0d0)) ;and its derivatives wrt player time (xdotdot :accessor xdotdot :initarg :xdotdot :initform (vector 0 0 0 0)) (roll :reader roll :initarg :roll :initform (vector 0 1 0 0)) (pitch :reader pitch :initarg :pitch :initform (vector 0 0 1 0)) (yaw :reader yaw :initarg :yaw :initform (vector 0 0 0 1)) ;Don't technically need this. (omega :reader omega :initarg :omega :initform 0) (size :reader size :initarg :size :initform 0))) ;;This method rotates a rigid body object's vectors around a vector n by an angle theta. (defgeneric rotate (x n theta)) (defmethod rotate ((rb rigid-body) n theta) (copy-instance rb :x (rotate-4-vector (x rb) n theta) :xdot (rotate-4-vector (xdot rb) n theta) :xdotdot (rotate-4-vector (xdotdot rb) n theta) :roll (rotate-4-vector (roll rb) n theta) ;rotation axis :pitch (rotate-4-vector (pitch rb) n theta) :yaw (rotate-4-vector (yaw rb) n theta))) ;;Use Newtonian gravity (for now) to simulate planetary motion. (defgeneric follow-geodesic (p deltat old-state)) ;deltat is small change in player's rf time (defmethod follow-geodesic ((p rigid-body) deltat old-state) (copy-instance p :x (vector (+ (aref (x p) 0) (* deltat (aref (xdot p) 0))) (+ (aref (x p) 1) (* deltat (aref (xdot p) 1)) (* -1 deltat (v (player old-state))) ) (+ (aref (x p) 2) (* deltat (aref (xdot p) 2))) (+ (aref (x p) 3) (* deltat (aref (xdot p) 3)))) :xdot (vector (expt (- 1 ( / (+ (expt (aref (xdot p) 1) 2) (expt (aref (xdot p) 2) 2) (expt (aref (xdot p) 3) 2)) (expt c 2))) -0.5) ;aka gamma (+ (aref (xdot p) 1) (* deltat (aref (xdotdot p) 1))) (+ (aref (xdot p) 2) (* deltat (aref (xdotdot p) 2))) (+ (aref (xdot p) 3) (* deltat (aref (xdotdot p) 3)))) ;;for now, Newtonian gravity :xdotdot (vector 0 (loop for object in (objects old-state) sum (if (not (equal (name object) (name p))) (* G (mass object) (- (aref (x object) 1) (aref (x p) 1)) (expt (+ (expt (- (aref (x object) 1) (aref (x p) 1)) 2) (expt (- (aref (x object) 2) (aref (x p) 2)) 2) (expt (- (aref (x object) 3) (aref (x p) 3)) 2) ) -1.5)) 0.0)) (loop for object in (objects old-state) sum (if (not (equal (name object) (name p))) (* G (mass object) (- (aref (x object) 2) (aref (x p) 2)) (expt (+ (expt (- (aref (x object) 1) (aref (x p) 1)) 2) (expt (- (aref (x object) 2) (aref (x p) 2)) 2) (expt (- (aref (x object) 3) (aref (x p) 3)) 2) ) -1.5)) 0.0)) (loop for object in (objects old-state) sum (if (not (equal (name object) (name p))) (* G (mass object) (- (aref (x object) 3) (aref (x p) 3)) (expt (+ (expt (- (aref (x object) 1) (aref (x p) 1)) 2) (expt (- (aref (x object) 2) (aref (x p) 2)) 2) (expt (- (aref (x object) 3) (aref (x p) 3)) 2) ) -1.5)) 0.0))) ;;:pitch (rotate-4-vector (pitch p) (roll p) (* deltat (omega p))) ;;:yaw (rotate-4-vector (yaw p) (roll p) (* deltat (omega p))))) :pitch (rotate-4-vector (pitch p) (yaw p) (* deltat (omega p))) :roll (rotate-4-vector (roll p) (yaw p) (* deltat (omega p)))))
5,192
Common Lisp
.lisp
116
38.586207
112
0.559827
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
9a6119d94f490f7856002bbbba04f89af3148cb42c6196497675f735d20b7c96
30,427
[ -1 ]
30,428
hud.lisp
johncorn271828_X_Orrery/hud.lisp
#| For drawing a heads-up display. |# (defun princ-to-screen (thing x y) (gl:color 1 1 1) (let* ((str (princ-to-string thing))) (loop for i from 0 to (- (length str) 1) do (gl:window-pos (+ x (* i 9)) y 0) (glut:bitmap-character glut:+bitmap-9-by-15+ (char-code (aref str i)))))) (defgeneric draw-hud (w)) (defmethod draw-hud ((w X_Orrery-gui)) ;;v=0 with shift+rolldown = picture mode (if (not (eq 0 (v (player *model*)))) (progn ;;speedometer relative to sun (princ-to-screen "v = " 10 10) (princ-to-screen (v (player *model*)) 50 10) ;;put labels on objects (loop for object in (objects *model*) do (let* ((screen-coords (multiple-value-list (glu:project (aref (x object) 1) (aref (x object) 2) (aref (x object) 3)))) (distance (sqrt (+ (expt (aref (x object) 1) 2) (expt (aref (x object) 2) 2) (expt (aref (x object) 3) 2)))) (screenx (round (first screen-coords))) (screeny (round (second screen-coords))) ;;(screenz (third screen-coords)) (behind (> (third screen-coords) 1)) (drawx (if behind nil (cond ((< screenx 0) 1) ((> screenx (- (glut:game-mode-get :game-mode-width) (* (length (name object)) 9))) (- (glut:game-mode-get :game-mode-width) (* (length (name object)) 9))) (t screenx)))) (drawy (if behind nil (cond ((< screeny 0) 0) ((> screeny (- (glut:game-mode-get :game-mode-height) 9)) (- (glut:game-mode-get :game-mode-height) 9)) (t screeny))))) ;;;label planets, the sun, and other close stuff, plus ETAs (if (and drawx drawy (not (equal (name object) "Starfield")) (or (typep object 'sun) (typep object 'planet) (and (typep object 'moon) (< distance 10)) (< distance 1))) (progn (princ-to-screen (name object) drawx drawy) (if (and (> drawx 100) (< drawx (- (glut:game-mode-get :game-mode-width) 100)) (> drawy 50) (< drawy (- (glut:game-mode-get :game-mode-height) 50))) (cond ((> distance 3600) (princ-to-screen (concatenate 'string (princ-to-string (floor (round (/ distance 60)) 60)) "h " (princ-to-string (mod (round (/ distance 60)) 60)) "m") (+ drawx 4) (- drawy 16))) ((> distance 60) (princ-to-screen (concatenate 'string (princ-to-string (round (/ distance 60))) "m") (+ drawx 9) (- drawy 16))) ((> distance 1) (princ-to-screen (concatenate 'string (princ-to-string (round distance)) "s") (+ drawx 9) (- drawy 16))) (t nil))))))))) ) ;end draw hud method
2,708
Common Lisp
.lisp
79
27.949367
93
0.5659
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
0c1fa9f673dc944f669c754deadf3ed36329dffca361ff829df5aaf34e52684f
30,428
[ -1 ]
30,429
renderer.lisp
johncorn271828_X_Orrery/renderer.lisp
#| This file contains the code that draws objects, mostly by calling GL display lists and textures as specified in displaylistpopulator.lisp and textureloader.lisp. Todo: Refactor huge cond black into a single statement with a display-attribute-wrapper object for each renderable (or something like that). |# ;;;Rendering functions (defgeneric render (p)) (defmethod render ((rb rigid-body)) (let* ((rollx (aref (roll rb) 1)) (rolly (aref (roll rb) 2)) (rollz (aref (roll rb) 3)) (pitchx (aref (pitch rb) 1)) (pitchy (aref (pitch rb) 2)) (pitchz (aref (pitch rb) 3)) (yawx (aref (yaw rb) 1)) (yawy (aref (yaw rb) 2)) (yawz (aref (yaw rb) 3)) (M (vector rollx rolly rollz 0 pitchx pitchy pitchz 0 yawx yawy yawz 0 0 0 0 1)) (Minv (vector rollx pitchx yawx 0 rolly pitchy yawy 0 rollz pitchz yawz 0 0 0 0 1))) (gl:with-pushed-matrix ;;translate (gl:translate (aref (x rb) 1) (aref (x rb) 2) (aref (x rb) 3)) ;;rotate (gl:mult-matrix M) ;;draw (cond ((and (typep rb 'celestial-body) (equal (name rb) "Starfield")) (progn (gl:material :front :emission #(1 1 1 1)) (gl:disable :cull-face) (gl:depth-mask 0) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 0 (textures *view*))) (gl:call-list (+ 0 (draw-list *view*))) (gl:bind-texture :texture-2d 0) (gl:depth-mask 1) (gl:enable :cull-face))) ((and (typep rb 'celestial-body) (equal (name rb) "Sun")) (progn (gl:material :front :emission #(1 1 0 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 1 (textures *view*))) (gl:call-list (+ 1 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Mercury")) (progn (gl:material :front :emission #(0.03 0.03 0.03 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 2 (textures *view*))) (gl:call-list (+ 2 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Venus")) (progn (gl:material :front :emission #(0.03 0.03 0.03 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 3 (textures *view*))) (gl:call-list (+ 3 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Earth")) (progn (gl:material :front :emission #(0.03 0.03 0.03 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 4 (textures *view*))) (gl:call-list (+ 4 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Mars")) (progn (gl:material :front :emission #(0.03 0.03 0.03 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 5 (textures *view*))) (gl:call-list (+ 5 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Jupiter")) (progn (gl:material :front :emission #(0.01 0.01 0.01 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 6 (textures *view*))) (gl:rotate 90 0 0 1) (gl:call-list (+ 6 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Saturn")) (progn (gl:material :front :emission #(0.01 0.01 0.01 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) ;;draw saturn (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 7 (textures *view*))) (gl:call-list (+ 7 (draw-list *view*))) (gl:bind-texture :texture-2d 0) ;;draw rings, top first (gl:material :front :emission #(0.7 0.7 0.7 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:material :back :emission #(0.01 0.01 0.01 1)) (gl:material :back :ambient #(1 1 1 1)) (gl:material :back :diffuse #(1 1 1 1)) (gl:material :back :shininess 128) (gl:tex-parameter :texture-2d :texture-wrap-s :clamp-to-edge) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 11 (textures *view*))) (gl:call-list (+ 13 (draw-list *view*))) ;;bottom of rings (gl:rotate 180 1 0 0) (gl:material :front :emission #(0.01 0.01 0.01 1)) ;;weird how this looks same? (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:material :back :emission #(0.01 0.01 0.01 1)) (gl:material :back :ambient #(1 1 1 1)) (gl:material :back :diffuse #(1 1 1 1)) (gl:material :back :shininess 128) (gl:tex-parameter :texture-2d :texture-wrap-s :clamp-to-edge) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 11 (textures *view*))) (gl:translate 0 0 0.001) (gl:call-list (+ 13 (draw-list *view*))) (gl:rotate 180 1 0 0) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Uranus")) (progn (gl:material :front :emission #(0.01 0.01 0.01 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 8 (textures *view*))) (gl:call-list (+ 8 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Neptune")) (progn (gl:material :front :emission #(0.01 0.01 0.01 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 9 (textures *view*))) (gl:call-list (+ 9 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((and (typep rb 'celestial-body) (equal (name rb) "Moon")) (progn (gl:material :front :emission #(0.03 0.03 0.03 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 10 (textures *view*))) (gl:call-list (+ 10 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ((typep rb 'laboratory) (progn (gl:material :front :emission #(0.03 0.03 0.03 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) (gl:enable :texture-2d) (gl:bind-texture :texture-2d (nth 12 (textures *view*))) (gl:call-list (+ 12 (draw-list *view*))) (gl:bind-texture :texture-2d 0))) ) ;;unrotate (gl:mult-matrix Minv) ;;untranslate (gl:translate (- (aref (x rb) 1)) (- (aref (x rb) 2)) (- (aref (x rb) 3)))))) (defmethod render ((p player)) ;;get rid of depth testing and just make the player vessel big enough to be outside znear (gl:disable :depth-test) (gl:with-pushed-matrix (gl:material :front-and-back :emission #(0.2 0.2 0.2 1)) ;;(gl:material :front-and-back :emission #(1 1 1 1)) (gl:material :front :ambient #(1 1 1 1)) (gl:material :front :diffuse #(1 1 1 1)) (gl:material :front :shininess 128) ;;a little crosshair to show direction (gl:with-primitives :lines (gl:vertex 1 -0.01 0) (gl:vertex 1 0.01 0)) (gl:with-primitives :lines (gl:vertex 1 0 -0.01) (gl:vertex 1 0 0.01)) ;;load a wireframe (if (not (eq 0 (v (player *model*)))) (progn (gl:translate 1.6 0 -5.2) ;-4.1) (gl:rotate 90 0 0 1) (gl:rotate 90 1 0 0) ;;(gl:call-list (+ 11 (draw-list *view*))) )) ) (gl:enable :depth-test) )
9,114
Common Lisp
.lisp
215
34.874419
95
0.579321
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
9ba4c362526dd91d2a3808dbc69652e79e609ba9e829be6e840f16be0eb5ee43
30,429
[ -1 ]
30,430
setup.lisp
johncorn271828_X_Orrery/setup.lisp
(defpackage #:ql-setup (:use #:cl) (:export #:*quicklisp-home* #:qmerge #:qenough)) (in-package #:ql-setup) (unless *load-truename* (error "This file must be LOADed to set up quicklisp.")) (defvar *quicklisp-home* (make-pathname :name nil :type nil :defaults *load-truename*)) (defun qmerge (pathname) "Return PATHNAME merged with the base Quicklisp directory." (merge-pathnames pathname *quicklisp-home*)) (defun qenough (pathname) (enough-namestring pathname *quicklisp-home*)) ;;; ASDF is a hard requirement of quicklisp. Make sure it's either ;;; already loaded or load it from quicklisp's bundled version. (defvar *required-asdf-version* "2.26") ;;; Put ASDF's fasls in a separate directory (defun implementation-signature () "Return a string suitable for discriminating different implementations, or similar implementations with possibly-incompatible FASLs." ;; XXX Will this have problems with stuff like threads vs ;; non-threads fasls? (let ((*print-pretty* nil)) (format nil "lisp-implementation-type: ~A~%~ lisp-implementation-version: ~A~%~ machine-type: ~A~%~ machine-version: ~A~%" (lisp-implementation-type) (lisp-implementation-version) (machine-type) (machine-version)))) (defun dumb-string-hash (string) "Produce a six-character hash of STRING." (let ((hash #xD13CCD13)) (loop for char across string for value = (char-code char) do (setf hash (logand #xFFFFFFFF (logxor (ash hash 5) (ash hash -27) value)))) (subseq (format nil "~(~36,6,'0R~)" (mod hash 88888901)) 0 6))) (defun asdf-fasl-pathname () "Return a pathname suitable for storing the ASDF FASL, separated from ASDF FASLs from incompatible implementations. Also, save a file in the directory with the implementation signature, if it doesn't already exist." (let* ((implementation-signature (implementation-signature)) (original-fasl (compile-file-pathname (qmerge "asdf.lisp"))) (fasl (qmerge (make-pathname :defaults original-fasl :directory (list :relative "cache" "asdf-fasls" (dumb-string-hash implementation-signature))))) (signature-file (merge-pathnames "signature.txt" fasl))) (ensure-directories-exist fasl) (unless (probe-file signature-file) (with-open-file (stream signature-file :direction :output) (write-string implementation-signature stream))) fasl)) (defun ensure-asdf-loaded () "Try several methods to make sure that a sufficiently-new ASDF is loaded: first try (require 'asdf), then loading the ASDF FASL, then compiling asdf.lisp to a FASL and then loading it." (let ((source (qmerge "asdf.lisp"))) (labels ((asdf-symbol (name) (let ((asdf-package (find-package '#:asdf))) (when asdf-package (find-symbol (string name) asdf-package)))) (version-satisfies (version) (let ((vs-fun (asdf-symbol '#:version-satisfies)) (vfun (asdf-symbol '#:asdf-version))) (when (and vs-fun vfun (fboundp vs-fun) (fboundp vfun)) (funcall vs-fun (funcall vfun) version))))) (block nil (macrolet ((try (&body asdf-loading-forms) `(progn (handler-bind ((warning #'muffle-warning)) (ignore-errors ,@asdf-loading-forms)) (when (version-satisfies *required-asdf-version*) (return t))))) (try) (try (require 'asdf)) (let ((fasl (asdf-fasl-pathname))) (try (load fasl :verbose nil)) (try (load (compile-file source :verbose nil :output-file fasl)))) (error "Could not load ASDF ~S or newer" *required-asdf-version*)))))) (ensure-asdf-loaded) ;;; ;;; Quicklisp sometimes must upgrade ASDF. Ugrading ASDF will blow ;;; away existing ASDF methods, so e.g. FASL recompilation :around ;;; methods would be lost. This config file will make it possible to ;;; ensure ASDF can be configured before loading Quicklisp itself via ;;; ASDF. Thanks to Nikodemus Siivola for pointing out this issue. ;;; (let ((asdf-init (probe-file (qmerge "asdf-config/init.lisp")))) (when asdf-init (with-simple-restart (skip "Skip loading ~S" asdf-init) (load asdf-init :verbose nil :print nil)))) (push (qmerge "quicklisp/") asdf:*central-registry*) (let ((*compile-print* nil) (*compile-verbose* nil) (*load-verbose* nil) (*load-print* nil)) (asdf:oos 'asdf:load-op "quicklisp" :verbose nil)) (quicklisp:setup)
5,054
Common Lisp
.lisp
117
33.675214
80
0.606424
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
e203985f574ac2c660686fdd6ab8a58ab19f01437782315e48fe93586411c283
30,430
[ 447781, 456618 ]
30,431
view.lisp
johncorn271828_X_Orrery/view.lisp
#| This is the top level output-handling file. Given the state of the opengl-cl documentation, it is difficult to better explain what some of this code does without lots more research (to be completed). |# ;;;Audio commented out until cross-platform testing. (load "audio.lisp") ;;;This is the gui class and the display method acts as the main "read-eval-print" loop (defclass X_Orrery-gui (glut:window) ((hud-text :accessor hud-text :initform "hello") (draw-list :accessor draw-list) (textures :accessor textures) (fov :accessor fov :initform 0.9);0.6109) ;;field of view angle in radians (music-daemon :accessor music-daemon)) (:default-initargs :game-mode 't :mode '(:double :rgba :depth ) :title "X_Orrery.lisp")) ;;You have to pass this to glut even for fullscreen apps. (defmethod glut:reshape ((w X_Orrery-gui) width height) (gl:viewport 0 0 width height) (gl:matrix-mode :projection) (gl:load-identity) (glu:perspective (* (fov w) (/ 180 pi)) ;vertical field of view angle in degrees (/ width height) ;aspect ratio ;;znear=1e-4 and zfar=1e4 seem to work for everything but closest stuff 1e-4 1e4) (gl:matrix-mode :modelview)) ;;;Load meshes from .obj files. (load "meshloader.lisp") ;;;Populate GL's display lists. (load "displaylistpopulator.lisp") ;;;Load textures into GL's texture list. (load "textureloader.lisp") ;;Called once when window is first displayed. (defmethod glut:display-window :before ((w X_Orrery-gui)) (if (not (glut:game-mode-get :game-mode-possible)) (progn (princln "Error: glut game mode not possible.") (exit))) ;;get the cursor started sanely (glut:set-cursor 101) ;101 is the value of GLUT_CURSOR_NONE. (glut:warp-pointer (/ (glut:game-mode-get :game-mode-width) 2) (/ (glut:game-mode-get :game-mode-height) 2)) ;;this is necessary on linux (glut:set-key-repeat :key-repeat-off) ;;need to look up these functions and insert decent comments (gl:cull-face :back) (gl:depth-func :lequal) (gl:disable :dither) (gl:shade-model :smooth) ;previously :flat (gl:light-model :light-model-ambient #(0.1 0.1 0.1 1)) ;;turns ambient light down low ;;(gl:light-model :light-model-two-side 1) (gl:depth-range 0 1) (gl:enable :light0 :lighting :cull-face :depth-test) ;;can only have 8 of these ;;set up gl with the display lists and textures (populate-display-lists w) (load-textures w) ;;initialize camera angle (glu:look-at 0 0 0 (cos (phi (player *model*))) (sin (phi (player *model*))) (cos (theta (player *model*))) 0 0 1)) ;;;Load rendering code that calls draw lists, specifies materials, etc. (load "renderer.lisp") ;;;Code for drawing a heads-up-display (load "hud.lisp") ;;;This is the main loop of the program!!! (defmethod glut:display ((w X_Orrery-gui)) (gl:clear :color-buffer :depth-buffer) ;;update state (setf *model* (get-new-state (copy-instance *model*) (copy-instance *controller*) (get-internal-real-time))) ;;update controller (update-controller) (gl:light :light0 :position (vector (aref (x (second (objects *model*))) 1) (aref (x (second (objects *model*))) 2) (aref (x (second (objects *model*))) 3) 1)) ;;position camera (gl:load-identity) (glu:look-at 0 0 0 (cos (phi (player *model*))) (sin (phi (player *model*))) (cos (theta (player *model*))) 0 0 1) ;;draw stuff (loop for object in (objects *model*) do ;eventually update to draw only relevant things (let ((render-cube-size (* 60000 (size object) (size object)))) (when (or (typep object 'sun) (and (< (abs (aref (x object) 1)) render-cube-size) (< (abs (aref (x object) 2)) render-cube-size) (< (abs (aref (x object) 3)) render-cube-size))) (render object))) (render (player *model*)) (draw-hud w)) (glut:swap-buffers)) ;;;I am not entirely clear on the importance of this, but it seemed like there were race conditions or something ;; whacked out going on with glut before I did this. (defmethod glut:idle ((w X_Orrery-gui)) (glut:post-redisplay))
4,110
Common Lisp
.lisp
96
39.28125
112
0.691401
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
b492887dd9c00a2d86577710f336279506a8db57a06444ba57410bd91eb2ba16
30,431
[ -1 ]
30,432
utilities.lisp
johncorn271828_X_Orrery/utilities.lisp
#| This file has a few general-use functions. |# ;;for purposes of immutability, this function produces a copy of an object with optional changed slots. ;;see http://stackoverflow.com/questions/11067899/is-there-a-generic-method-for-cloning-clos-objects (defgeneric copy-instance (object &rest initargs &key &allow-other-keys) (:method ((object standard-object) &rest initargs &key &allow-other-keys) (let* ((class (class-of object)) (copy (allocate-instance class))) (dolist (slot-name (mapcar #'sb-mop:slot-definition-name (sb-mop:class-slots class))) (when (slot-boundp object slot-name) (setf (slot-value copy slot-name) (slot-value object slot-name)))) (apply #'reinitialize-instance copy initargs)))) (defun princln (x) (princ x) (fresh-line)) (defun debugvar (label x) (princ label) (princ " = ") (princln x)) ;;Form Paul Graham's book page 110 (defun compose (&rest fns) (destructuring-bind (fn1 . rest) (reverse fns) #'(lambda (&rest args) (reduce #'(lambda (v f) (funcall f v)) rest :initial-value (apply fn1 args))))) (defun shuffle (sequence) (loop for i from (length sequence) downto 2 do (rotatef (elt sequence (random i)) (elt sequence (1- i)))) sequence)
1,258
Common Lisp
.lisp
33
34.484848
103
0.696473
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
7a553ee617d6aba77eabecf073ed3969735a9b8249c4d040b008ad50494c6516
30,432
[ -1 ]
30,433
textureloader.lisp
johncorn271828_X_Orrery/textureloader.lisp
#| Without calling image processing libraries, you can read .rgb files into OpenGL's texture memory. |# (defgeneric load-textures (w)) (defmethod load-textures ((w X_Orrery-gui)) ;;tell gl to start a list of N textures (setf (textures w) (gl:gen-textures 30)) (let ((texture-file-stream) (texture-file-data)) ;;starfield 0 (setf texture-file-stream (open "textures/starfield.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 0 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 4096 4096 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Sun 1 (setf texture-file-stream (open "textures/sun.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 1 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 1024 1024 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Mercury 2 (setf texture-file-stream (open "textures/mercury.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 2 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 2048 2048 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Venus 3 (setf texture-file-stream (open "textures/venus.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 3 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 1024 1024 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Earth 4 (setf texture-file-stream (open "textures/earth.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 4 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 2048 2048 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Mars 5 (setf texture-file-stream (open "textures/mars.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 5 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 2048 2048 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Jupiter 6 (setf texture-file-stream (open "textures/jupiter.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 6 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 2048 2048 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Saturn 7 (setf texture-file-stream (open "textures/saturn.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 7 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 1024 1024 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Uranus 8 (setf texture-file-stream (open "textures/uranus.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 8 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 1024 1024 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;Neptune 9 (setf texture-file-stream (open "textures/neptune.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 9 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 1024 1024 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;moon 10 (setf texture-file-stream (open "textures/moon.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 10 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 2048 2048 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;saturn's rings 11 (setf texture-file-stream (open "textures/saturn-ring.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 11 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 512 512 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ;;metal1 texture 12 (setf texture-file-stream (open "textures/metal1.rgb" :direction :input :element-type '(unsigned-byte 8))) (setf texture-file-data (make-array (file-length texture-file-stream) :element-type '(unsigned-byte 8))) (read-sequence texture-file-data texture-file-stream) (close texture-file-stream) (gl:bind-texture :texture-2d (nth 12 (textures w))) (glu:build-2d-mipmaps :texture-2d 3 1024 1024 :rgb :unsigned-byte texture-file-data) (gl:tex-env :texture-env :texture-env-mode :modulate) ) )
7,266
Common Lisp
.lisp
115
57.913043
116
0.71622
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
2d4c7b18f46f5abd225da95e81064f1cb6c321667608341e597e94493c2a819c
30,433
[ -1 ]
30,435
meshloader.lisp
johncorn271828_X_Orrery/meshloader.lisp
#| This file loads meshes from .obj files for populating the gl display lists. |# ;;this class keeps track of the vector, texture, normal indices of a polygon face as in a .obj file (defclass face-indexer () ((vertex-indices :accessor vertex-indices :initform (make-array 0 :fill-pointer 0 :adjustable t)) (texture-indices :accessor texture-indices :initform (make-array 0 :fill-pointer 0 :adjustable t)) (normal-indices :accessor normal-indices :initform (make-array 0 :fill-pointer 0 :adjustable t)))) ;;this class represents a polygon mesh (defclass mesh () ((vertices :accessor vertices :initform (make-array 0 :fill-pointer 0 :adjustable t)) (textures-vertices :accessor texture-vertices :initform (make-array 0 :fill-pointer 0 :adjustable t)) (normals :accessor normals :initform (make-array 0 :fill-pointer 0 :adjustable t)) (faces :accessor faces :initform nil))) (defun read-mesh-from-obj-file (filename scale) (let ((m (make-instance 'mesh)) ;mesh to be constructed (line-counter 0) (line-parts) (vert-parts) (a-face)) ;;open file specified by filename (with-open-file (stream filename) ;;iterate over lines (loop for line = (read-line stream nil :eof) until (eq line :eof) do ;;(debugvar "reading line number" line-counter) (setf line-counter (+ line-counter 1)) ;;split the line on spaces (setf line-parts (split-sequence:SPLIT-SEQUENCE #\Space line)) ;;handle v, vt, vn, and f lines separately (cond ((equal (first line-parts) "v") ;vertex line found (vector-push-extend (vector (* scale (parse-number:PARSE-REAL-NUMBER (second line-parts))) (* scale (parse-number:PARSE-REAL-NUMBER (third line-parts))) (* scale (parse-number:PARSE-REAL-NUMBER (fourth line-parts)))) (vertices m))) ((equal (first line-parts) "vt") ;texture line found (vector-push-extend (vector (parse-number:PARSE-REAL-NUMBER (second line-parts)) (parse-number:PARSE-REAL-NUMBER (third line-parts))) (texture-vertices m))) ((equal (first line-parts) "vn") ;normal vector found (vector-push-extend (vector (parse-number:PARSE-REAL-NUMBER (second line-parts)) (parse-number:PARSE-REAL-NUMBER (third line-parts)) (parse-number:PARSE-REAL-NUMBER (fourth line-parts))) (normals m))) ((equal (first line-parts) "f") ;face found (progn (setf a-face (make-instance 'face-indexer)) (loop for item in (rest line-parts) do (setf vert-parts (split-sequence:SPLIT-SEQUENCE #\/ item)) (vector-push-extend (parse-number:PARSE-NUMBER (first vert-parts)) (vertex-indices a-face)) (if (not (equal "" (second vert-parts))) (vector-push-extend (parse-number:PARSE-NUMBER (second vert-parts)) (texture-indices a-face))) (if (not (equal "" (third vert-parts))) (vector-push-extend (parse-number:PARSE-NUMBER (third vert-parts)) (normal-indices a-face)))) (push a-face (faces m)))) (t nil)))) m))
3,019
Common Lisp
.lisp
59
45.745763
104
0.684727
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
edc88339a06cf597f2d0ad2fa2fbd469ef9428a65b413024338304e7dd66d5f0
30,435
[ -1 ]
30,436
controller.lisp
johncorn271828_X_Orrery/controller.lisp
#| This file handles keyboard and mouse inputs using glut. To allow more nuanced controls, some state logic is passed from one instance of a controller object to the next. I'm not sure whether these variables should be part of the model object. |# ;;;Controller object for maintaining duration of key presses, mouse position, and mouse events. (defclass controller () ((wtf :initform (glut:init)) (key-down-time-table :accessor key-down-time-table :initform nil) (roll-rate :accessor roll-rate :initform 0) (pitch-rate :accessor pitch-rate :initform 0) (yaw-rate :accessor yaw-rate :initform 0) (mouse-events :accessor mouse-events :initform nil) (mouse-x :accessor mouse-x :initform (/ (glut:game-mode-get :game-mode-width) 2)) (mouse-y :accessor mouse-y :initform (/ (glut:game-mode-get :game-mode-height) 2)) (mouse-deltax :accessor mouse-deltax :initform 0) (mouse-deltay :accessor mouse-deltay :initform 0))) ;;;Declare some functions to pass to glut for input event handling. ;;Keyboard button events (defmethod glut:keyboard ((w glut:window) key x y) (declare (ignore x y)) (when (eq key #\Esc) (progn (princln "Exit requested...") ;;(bordeaux-threads:destroy-thread music-daemon) ;not sure if this is necessary (glut:destroy-current-window))) ;;(when (eq key #\f) (play-wav "fart.wav" 0 -1 0)) (when (eq key #\p) (sb-ext:run-program "/usr/bin/scrot" nil)) (unless (assoc key (key-down-time-table *controller*)) (push (cons key (get-internal-real-time)) (key-down-time-table *controller*)))) (defmethod glut:keyboard-up ((w glut:window) key x y) (declare (ignore x y)) (let ((entry (assoc key (key-down-time-table *controller*)))) (when entry (setf (key-down-time-table *controller*) (remove entry (key-down-time-table *controller*)))))) ;;Mouse motion events (defmethod glut:passive-motion ((w glut:window) x y) (let ((deltax (- x (mouse-x *controller*))) (deltay (- y (mouse-y *controller*)))) (if (and (< deltax 40) (< deltay 40)) ;set a limit on deltax to avoid the jumping (progn (setf (mouse-deltax *controller*) deltax) (setf (mouse-deltay *controller*) deltay)))) ;;always warping pointer back to center causes a glut bug to act up (if (or (< x 100) (> x (- (glut:game-mode-get :game-mode-width) 100)) (< y 100) (> y (- (glut:game-mode-get :game-mode-height) 100))) (progn (glut:warp-pointer (/ (glut:game-mode-get :game-mode-width) 2) (/ (glut:game-mode-get :game-mode-height) 2)) (setf (mouse-x *controller*) (/ (glut:game-mode-get :game-mode-width) 2)) (setf (mouse-y *controller*) (/ (glut:game-mode-get :game-mode-height) 2))) (progn (setf (mouse-x *controller*) x) (setf (mouse-y *controller*) y)))) ;;Mouse button events (defmethod glut:mouse ((w glut:window) button state x y) (cond ((and (eq state :down) (eq button :wheel-up) (member :active-shift (glut:get-modifiers))) (push 'shift-wheel-up (mouse-events *controller*))) ((and (eq state :down) (eq button :wheel-up) (member :active-ctrl (glut:get-modifiers))) (push 'control-wheel-up (mouse-events *controller*))) ((and (eq state :down) (eq button :wheel-up) (not (member :active-shift (glut:get-modifiers)))) (push 'wheel-up (mouse-events *controller*))) ((and (eq state :down) (eq button :wheel-down) (member :active-shift (glut:get-modifiers))) (push 'shift-wheel-down (mouse-events *controller*))) ((and (eq state :down) (eq button :wheel-down) (member :active-ctrl (glut:get-modifiers))) (push 'control-wheel-down (mouse-events *controller*))) ((and (eq state :down) (eq button :wheel-down) (not (member :active-shift (glut:get-modifiers)))) (push 'wheel-down (mouse-events *controller*))))) ;;;This function will get called after every state update to update the *controller* global state variable. (defun update-controller () ;;reset mouse (setf (mouse-deltax *controller*) 0) (setf (mouse-deltay *controller*) 0) (setf (mouse-events *controller*) nil) ;change this line to allow holding down mouse buttons ;;The following is intended to smooth out the rotation controls. A better solution is probably needed ;;in subsequent versions. (let ((roll-sensitivity (/ pi 30 1000)) (pitch-sensitivity (/ pi 200 1000)) (yaw-sensitivity (/ pi 200 1000))) (cond ((and (assoc #\a (key-down-time-table *controller*)) (assoc #\d (key-down-time-table *controller*))) nil) ((and (assoc #\a (key-down-time-table *controller*)) (not (assoc #\d (key-down-time-table *controller*)))) (setf (roll-rate *controller*) (* +1 roll-sensitivity (min 2000 (- (get-internal-real-time) (cdr (assoc #\a (key-down-time-table *controller*)))))))) ((and (assoc #\d (key-down-time-table *controller*)) (not (assoc #\a (key-down-time-table *controller*)))) (setf (roll-rate *controller*) (* -1 roll-sensitivity (min 2000 (- (get-internal-real-time) (cdr (assoc #\d (key-down-time-table *controller*)))))))) (t (setf (roll-rate *controller*) 0))) (cond ((and (assoc #\w (key-down-time-table *controller*)) (assoc #\s (key-down-time-table *controller*))) nil) ((and (assoc #\w (key-down-time-table *controller*)) (not (assoc #\s (key-down-time-table *controller*)))) (setf (pitch-rate *controller*) (* -1 pitch-sensitivity (min 1500 (- (get-internal-real-time) (cdr (assoc #\w (key-down-time-table *controller*)))))))) ((and (assoc #\s (key-down-time-table *controller*)) (not (assoc #\w (key-down-time-table *controller*)))) (setf (pitch-rate *controller*) (* +1 pitch-sensitivity (min 1500 (- (get-internal-real-time) (cdr (assoc #\s (key-down-time-table *controller*)))))))) (t (setf (pitch-rate *controller*) 0))) (cond ((and (assoc #\q (key-down-time-table *controller*)) (assoc #\e (key-down-time-table *controller*))) nil) ((and (assoc #\q (key-down-time-table *controller*)) (not (assoc #\e (key-down-time-table *controller*)))) (setf (yaw-rate *controller*) (* -1 yaw-sensitivity (min 2000 (- (get-internal-real-time) (cdr (assoc #\q (key-down-time-table *controller*)))))))) ((and (assoc #\e (key-down-time-table *controller*)) (not (assoc #\q (key-down-time-table *controller*)))) (setf (yaw-rate *controller*) (* +1 yaw-sensitivity (min 2000 (- (get-internal-real-time) (cdr (assoc #\e (key-down-time-table *controller*)))))))) (t (setf (yaw-rate *controller*) 0)))))
6,538
Common Lisp
.lisp
135
44.42963
107
0.664842
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
bf1cb0a1a909488b2537b6b923d7d6b8dfec144df22999665eafa3396c997817
30,436
[ -1 ]
30,437
astrometry.lisp
johncorn271828_X_Orrery/astrometry.lisp
#| Some useful solar system measurements. |# ;;;Approximate constants for solar system astrometry. Units are kilograms, light-seconds for lengths, seconds for time. (defconstant sun-mass 1.989e30) (defconstant sun-radius 2.321) (defconstant mercury-mass 3.285e23) (defconstant mercury-radius 0.008138) (defconstant mercury-orbital-radius 153.44) ;;could correct this to make orbit realistically eccentric (defconstant mercury-orbital-speed 0.00015798) (defconstant mercury-angular-velocity 6.29e-7) (defconstant venus-mass 4.868e24) (defconstant venus-radius 0.02018) (defconstant venus-orbital-radius 358) (defconstant venus-orbital-speed 0.0001168) (defconstant venus-angular-velocity 1.245e-7) (defconstant earth-mass 5.972e24) (defconstant earth-radius 0.02125) (defconstant earth-orbital-radius 499) (defconstant earth-orbit-speed 9.99e-5) (defconstant earth-angular-velocity 7.272e-5) (defconstant mars-mass 6.39e23) (defconstant mars-radius 0.01131) (defconstant mars-orbital-radius 760) (defconstant mars-orbital-speed 8.031e-5) (defconstant mars-angular-velocity 7.09e-5) (defconstant jupiter-mass 1.898e27) (defconstant jupiter-radius 0.2332) (defconstant jupiter-orbital-radius 2595) (defconstant jupiter-orbital-speed 4.36e-5) (defconstant jupiter-angular-velocity 0.00017) (defconstant saturn-mass 568.3e24) (defconstant saturn-radius 0.19424) (defconstant saturn-orbital-radius 4781) (defconstant saturn-orbital-speed 3.232e-5) (defconstant saturn-angular-velocity 0.000164) (defconstant saturn-inner-ring-radius 0.2245) (defconstant saturn-outer-ring-radius 0.468) (defconstant uranus-mass 8.681e25) (defconstant uranus-radius 0.0846) (defconstant uranus-orbital-radius 9575) (defconstant uranus-orbital-speed 2.27e-5) (defconstant uranus-angular-velocity 0.000101) (defconstant neptune-mass 1.0243e26) (defconstant neptune-radius 0.08213) (defconstant neptune-orbital-radius 15005) (defconstant neptune-orbital-speed 1.81e-5) (defconstant neptune-angular-velocity 0.00011) (defconstant moon-mass 7.3477e22) (defconstant moon-radius 0.005796) (defconstant moon-orbital-radius 1.284) (defconstant moon-orbit-speed 3.412e-6) (defconstant low-earth-orbital-radius 0.02188261) (defconstant low-earth-orbit-speed 2.6e-5)
2,233
Common Lisp
.lisp
54
40.333333
119
0.825069
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
e9e7e319f5e27907887447af51bdb4c71187f3cddf4506e6493692f239f9a755
30,437
[ -1 ]
30,438
X_Orrery.lisp
johncorn271828_X_Orrery/X_Orrery.lisp
#| This is the main file for the X_Orrery prototype, a solar system simulator and planetarium application. This is basically my playground from teaching myself OpenGL. I have attempted to design this with the most vanilla possible main loop, and being purely functional when the libraries let me. Also, not being too clever. It's a little bit cowboy code, but I'm happy to respond to inquiries about how I was thinking. To run this, you need sbcl, freeglut (freeglut3-dev in debian), and freealut (libalut-dev in debian). I use "sbcl --load". This will look for a quicklisp installation, and install quicklisp to the working directory otherwise. The next version is on the way and will have much better everything :) By John Corn This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# ;;;Load other people's code using quicklisp: https://www.quicklisp.org/beta/ (load "quicklisp.lisp") (unless (probe-file "~/quicklisp/setup.lisp") (quicklisp-quickstart:install)) (load "~/quicklisp/setup.lisp") ;;Common Common Lisp utilities (ql:quickload "split-sequence") (ql:quickload "parse-number") (ql:quickload "bordeaux-threads") ;;Graphics via OpenGL bindings. (ql:quickload "cl-opengl") (ql:quickload "cl-glu") (ql:quickload "cl-glut") ;;Audio via openal.. (ql:quickload "cl-openal") (ql:quickload "cl-alc") (ql:quickload "cl-alut") ;;globals for library-imposed use of observer pattern. Maybe this could be ;;rewired with FRP? (defparameter *model* nil) (defparameter *view* nil) (defparameter *controller* nil) ;;;Load my code (load "utilities.lisp") ;Generic stuff not specific to this program. (load "controller.lisp") (load "model.lisp") (load "view.lisp") ;;Persistence is to-do (defun saved-state-on-disk-p () nil) (defun get-state-from-disk () nil) ;;(defun save-to-disk (old-state) nil) (defun main () (princln "Welcome to X_Orrery. Loading...") ;;This is needed here to pass screen dimensions to routines called before showing the window (glut:init) (princ "Controls... ") (setf *controller* (make-instance 'controller)) (princln "done.") (princ "Initializing/recovering state... ") (setf *model* (if (saved-state-on-disk-p) (progn (princln "found saved state.") (get-state-from-disk)) (progn (princln "starting anew.") (make-instance 'X_Orrery-state)))) (princ "Starting graphics engine...") (setf *view* (make-instance 'X_Orrery-gui)) (princln "done.") ;;Music (princ "Starting music daemon... ") (setf (music-daemon *view*) (bordeaux-threads:make-thread (lambda () (run-music-daemon)))) (princln "done.") ;;Main loop is in the glut window methods. Ugly but fixed in upcoming Haskell version. (princln "Attempting to display window...") (glut:display-window *view*) ;;persist after exit ;;(princln "Saving state to disk...") ;;(save-to-disk *model*) (princln "exiting normally.")) ;;Run without saving an executable file. (main) (exit) ;;;This command instructs the sbcl compiler to write an executable. Problematic in windows. ;;(sb-ext:save-lisp-and-die "X_Orrery.bin" :executable t :toplevel 'main)
3,681
Common Lisp
.lisp
89
39.089888
94
0.748244
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
fe91d6282b2756747ea1bbc69e36cb2870065cf7fcef8ece030cdae20d27dc88
30,438
[ -1 ]
30,439
impl-util.lisp
johncorn271828_X_Orrery/quicklisp/impl-util.lisp
;;;; impl-util.lisp (in-package #:ql-impl-util) (definterface call-with-quiet-compilation (fun) (:documentation "Call FUN with warnings, style-warnings, and other verbose messages suppressed.") (:implementation t (let ((*load-verbose* nil) (*compile-verbose* nil) (*load-print* nil) (*compile-print* nil)) (handler-bind ((warning #'muffle-warning)) (funcall fun))))) (defimplementation (call-with-quiet-compilation :for sbcl :qualifier :around) (fun) (declare (ignore fun)) (handler-bind ((ql-sbcl:compiler-note #'muffle-warning)) (call-next-method))) (defimplementation (call-with-quiet-compilation :for cmucl :qualifier :around) (fun) (declare (ignore fun)) (let ((ql-cmucl:*gc-verbose* nil)) (call-next-method))) (definterface rename-directory (from to) (:implementation t (rename-file from to) (truename to)) (:implementation cmucl (rename-file from (string-right-trim "/" (namestring to))) (truename to)) (:implementation clisp (ql-clisp:rename-directory from to) (truename to))) (definterface probe-directory (pathname) (:documentation "Return the truename of PATHNAME, if it exists and is a directory, or NIL otherwise.") (:implementation t (let ((directory (probe-file pathname))) (when directory ;; probe-file is specified to return the truename of the path, ;; but Allegro does not return the truename; truenamize it. (truename directory)))) (:implementation clisp (let ((directory (ql-clisp:probe-pathname pathname))) (when (and directory (ql-clisp:probe-directory directory)) directory)))) (definterface init-file-name () (:documentation "Return the init file name for the current implementation.") (:implementation allegro ".clinit.cl") (:implementation abcl ".abclrc") (:implementation ccl #+windows "ccl-init.lisp" #-windows ".ccl-init.lisp") (:implementation clasp ".clasprc") (:implementation clisp ".clisprc.lisp") (:implementation ecl ".eclrc") (:implementation mkcl ".mkclrc") (:implementation lispworks ".lispworks") (:implementation sbcl ".sbclrc") (:implementation cmucl ".cmucl-init.lisp") (:implementation scl ".scl-init.lisp") ) (defun init-file-name-for (&optional implementation-designator) (let* ((class-name (find-symbol (string-upcase implementation-designator) 'ql-impl)) (class (find-class class-name nil))) (when class (let ((*implementation* (make-instance class))) (init-file-name))))) (defun quicklisp-init-file-form () "Return a form suitable for describing the location of the quicklisp init file. If the file is available relative to the home directory, returns a form that merges with the home directory instead of specifying an absolute file." (let* ((init-file (ql-setup:qmerge "setup.lisp")) (enough (enough-namestring init-file (user-homedir-pathname)))) (cond ((equal (pathname enough) (pathname init-file)) ;; The init-file is somewhere outside of the home directory (pathname enough)) (t `(merge-pathnames ,enough (user-homedir-pathname)))))) (defun write-init-forms (stream &key (indentation 0)) (format stream "~%~v@T;;; The following lines added by ql:add-to-init-file:~%" indentation) (format stream "~v@T#-quicklisp~%" indentation) (let ((*print-case* :downcase)) (format stream "~v@T(let ((quicklisp-init ~S))~%" indentation (quicklisp-init-file-form))) (format stream "~v@T (when (probe-file quicklisp-init)~%" indentation) (format stream "~v@T (load quicklisp-init)))~%~%" indentation)) (defun suitable-lisp-init-file (implementation) "Return the name of IMPLEMENTATION's init file. If IMPLEMENTAION is a string or pathname, return its merged pathname instead." (typecase implementation ((or string pathname) (merge-pathnames implementation)) ((or null (eql t)) (init-file-name)) (t (init-file-name-for implementation)))) (defun add-to-init-file (&optional implementation-or-file) "Add forms to the Lisp implementation's init file that will load quicklisp at CL startup." (let ((init-file (suitable-lisp-init-file implementation-or-file))) (unless init-file (error "Don't know how to add to init file for your implementation.")) (setf init-file (merge-pathnames init-file (user-homedir-pathname))) (format *query-io* "~&I will append the following lines to ~S:~%" init-file) (write-init-forms *query-io* :indentation 2) (when (ql-util:press-enter-to-continue) (with-open-file (stream init-file :direction :output :if-does-not-exist :create :if-exists :append) (write-init-forms stream))) init-file)) ;;; ;;; Native namestrings. ;;; (definterface native-namestring (pathname) (:documentation "In Clozure CL, #\\.s in pathname-names are escaped in namestrings with #\\> on Windows and #\\\\ elsewhere. This can cause a problem when using CL:NAMESTRING to store pathname data that might be used by other implementations. NATIVE-NAMESTRING is intended to provide a namestring that can be parsed as a same-enough object on multiple implementations.") (:implementation t (namestring pathname)) (:implementation ccl (ql-ccl:native-translated-namestring pathname)) (:implementation sbcl (ql-sbcl:native-namestring pathname))) ;;; ;;; Directory write date ;;; (definterface directory-write-date (pathname) (:documentation "Return the write-date of the directory designated by PATHNAME as a universal time, like file-write-date.") (:implementation t (file-write-date pathname)) (:implementation clisp (nth-value 2 (ql-clisp:probe-pathname pathname)))) ;;; ;;; Deleting a directory tree ;;; (defvar *wild-entry* (make-pathname :name :wild :type :wild :version :wild)) (defvar *wild-relative* (make-pathname :directory '(:relative :wild))) (definterface directoryp (entry) (:documentation "Return true if ENTRY refers to a directory.") (:implementation t (not (or (pathname-name entry) (pathname-type entry)))) (:implementation allegro (ql-allegro:file-directory-p entry)) (:implementation lispworks (ql-lispworks:file-directory-p entry))) (definterface directory-entries (directory) (:documentation "Return all directory entries of DIRECTORY as a list, or NIL if there are no directory entries. Excludes the \".\" and \"..\" entries.") (:implementation allegro (directory directory)) (:implementation abcl (directory (merge-pathnames *wild-entry* directory) #+abcl :resolve-symlinks #+abcl nil)) (:implementation ccl (directory (merge-pathnames *wild-entry* directory) #+ccl :directories #+ccl t)) (:implementation clasp (setf directory (truename directory)) (nconc (directory (merge-pathnames *wild-entry* directory) #+clasp :resolve-symlinks #+clasp nil) (directory (merge-pathnames *wild-relative* directory) #+clasp :resolve-symlinks #+clasp nil))) (:implementation clisp (mapcar 'first (nconc (directory (merge-pathnames *wild-entry* directory) #+clisp :full #+clisp t) (directory (merge-pathnames *wild-relative* directory) #+clisp :full #+clisp t)))) (:implementation cmucl (directory (merge-pathnames *wild-entry* directory) #+cmucl :truenamep #+cmucl nil)) (:implementation scl (directory (merge-pathnames *wild-entry* directory) #+scl :truenamep #+scl nil)) (:implementation lispworks (directory (merge-pathnames *wild-entry* directory) #+lispworks :directories #+lispworks t #+lispworks :link-transparency #+lispworks nil)) (:implementation ecl (setf directory (truename directory)) (nconc (directory (merge-pathnames *wild-entry* directory) #+ecl :resolve-symlinks #+ecl nil) (directory (merge-pathnames *wild-relative* directory) #+ecl :resolve-symlinks #+ecl nil))) (:implementation mkcl (setf directory (truename directory)) (nconc (directory (merge-pathnames *wild-entry* directory)) (directory (merge-pathnames *wild-relative* directory)))) (:implementation sbcl (directory (merge-pathnames *wild-entry* directory) #+sbcl :resolve-symlinks #+sbcl nil))) (defimplementation (directory-entries :qualifier :around) (directory) ;; Don't return any entries when called with a non-directory ;; argument (if (directoryp directory) (call-next-method) (warn "directory-entries - not a directory -- ~S" directory))) (definterface delete-directory (entry) (:documentation "Delete the directory ENTRY. Might signal an error if it is not an empty directory.") (:implementation t (delete-file entry)) (:implementation allegro (ql-allegro:delete-directory entry)) (:implementation ccl (ql-ccl:delete-directory entry)) (:implementation clasp (ql-clasp:rmdir entry)) (:implementation clisp (ql-clisp:delete-dir entry)) (:implementation cmucl (ql-cmucl:unix-rmdir (namestring entry))) (:implementation scl (ql-scl:unix-rmdir (ql-scl:unix-namestring entry))) (:implementation ecl (ql-ecl:rmdir entry)) (:implementation mkcl (ql-mkcl:rmdir entry)) (:implementation lispworks (ql-lispworks:delete-directory entry)) (:implementation sbcl (ql-sbcl:rmdir entry))) (defimplementation (delete-directory :qualifier :around) (directory) ;; Don't delete non-directories with delete-directory (if (directoryp directory) (call-next-method) (error "delete-directory - not a directory -- ~A" directory))) (definterface delete-directory-tree (pathname) (:documentation "Delete the directory tree rooted at PATHNAME.") (:implementation t (let ((directories-to-process (list (truename pathname))) (directories-to-delete '())) (loop (unless directories-to-process (return)) (let* ((current (pop directories-to-process)) (entries (directory-entries current))) (push current directories-to-delete) (dolist (entry entries) (if (directoryp entry) (push entry directories-to-process) (delete-file entry))))) (map nil 'delete-directory directories-to-delete))) (:implementation allegro (ql-allegro:delete-directory-and-files pathname)) (:implementation ccl (ql-ccl:delete-directory pathname))) (defimplementation (delete-directory-tree :qualifier :around) (pathname) (if (directoryp pathname) (call-next-method) (progn (warn "delete-directory-tree - not a directory, ~ deleting anyway -- ~s" pathname) (delete-file pathname))))
11,147
Common Lisp
.lisp
285
33.214035
80
0.677777
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
f5b5cd56a588431d6ad4568555e11866e0a17fe7fd007a33295fe9bbdf9c5f1f
30,439
[ -1 ]
30,440
package.lisp
johncorn271828_X_Orrery/quicklisp/package.lisp
;;;; package.lisp (defpackage #:ql-util (:documentation "Utility functions used in various places.") (:use #:cl) (:export #:write-line-to-file #:without-prompting #:press-enter-to-continue #:replace-file #:copy-file #:delete-file-if-exists #:ensure-file-exists #:split-spaces #:first-line #:file-size #:safely-read #:safely-read-file #:make-versions-url)) (defpackage #:ql-setup (:documentation "Functions and variables initialized early in the Quicklisp client configuration.") (:use #:cl) (:export #:qmerge #:qenough #:*quicklisp-home*)) (defpackage #:ql-config (:documentation "Getting and setting persistent configuration values.") (:use #:cl #:ql-util #:ql-setup) (:export #:config-value)) (defpackage #:ql-impl (:documentation "Configuration of implementation-specific packages and interfaces.") (:use #:cl) (:export #:*implementation*) (:export #:definterface #:defimplementation #:show-interfaces) (:export #:lisp #:abcl #:allegro #:ccl #:clasp #:clisp #:cmucl #:cormanlisp #:ecl #:gcl #:lispworks #:mkcl #:scl #:sbcl)) (defpackage #:ql-impl-util (:documentation "Utility functions that require implementation-specific functionality.") (:use #:cl #:ql-impl) (:export #:call-with-quiet-compilation #:add-to-init-file #:rename-directory #:delete-directory #:probe-directory #:directory-entries #:delete-directory-tree #:native-namestring #:directory-write-date)) (defpackage #:ql-network (:documentation "Simple, low-level network access.") (:use #:cl #:ql-impl) (:export #:open-connection #:write-octets #:read-octets #:close-connection #:with-connection)) (defpackage #:ql-progress (:documentation "Displaying a progress bar.") (:use #:cl) (:export #:make-progress-bar #:start-display #:update-progress #:finish-display)) (defpackage #:ql-http (:documentation "A simple HTTP client.") (:use #:cl #:ql-network #:ql-progress #:ql-config) (:export #:*proxy-url* #:fetch #:hostname #:port #:path #:url #:*maximum-redirects* #:*default-url-defaults*) (:export #:fetch-error #:unexpected-http-status #:unexpected-http-status-code #:unexpected-http-status-url #:too-many-redirects #:too-many-redirects-url #:too-many-redirects-count)) (defpackage #:ql-minitar (:documentation "A simple implementation of unpacking the 'tar' file format.") (:use #:cl) (:export #:unpack-tarball)) (defpackage #:ql-gunzipper (:documentation "An implementation of gunzip.") (:use #:cl) (:export #:gunzip)) (defpackage #:ql-cdb (:documentation "Read and write CDB files; code adapted from ZCDB.") (:use #:cl) (:export #:lookup #:map-cdb #:convert-index-file)) (defpackage #:ql-dist (:documentation "Generic functions, variables, and classes for interacting with the dist system. Documented, exported symbols are intended for public use.") (:use #:cl #:ql-util #:ql-http #:ql-setup #:ql-gunzipper #:ql-minitar) (:intern #:dist-version #:dist-url) (:import-from #:ql-impl-util #:delete-directory-tree #:directory-entries #:probe-directory) ;; Install/enable protocol (:export #:installedp #:install #:uninstall #:ensure-installed #:enabledp #:enable #:disable) ;; Preference protocol (:export #:preference #:preference-file #:preference-parent #:forget-preference) ;; Generic (:export #:all-dists #:enabled-dists #:find-dist #:find-dist-or-lose #:find-system #:find-release #:dist #:system #:release #:base-directory #:relative-to #:metadata-name #:install-metadata-file #:short-description #:provided-releases #:provided-systems #:installed-releases #:installed-systems #:name) ;; Dists (:export #:dist #:dist-merge #:find-system-in-dist #:find-release-in-dist #:system-index-url #:release-index-url #:available-versions-url #:available-versions #:version #:subscription-url #:new-version-available-p #:dist-difference #:fetch-dist #:initialize-release-index #:initialize-system-index #:with-consistent-dists) ;; Dist updates (:export #:available-update #:update-release-differences #:show-update-report #:update-in-place #:install-dist #:subscription-inhibition-file #:inhibit-subscription #:uninhibit-subscription #:subscription-inhibited-p #:subscription-unavailable #:subscribedp #:subscribe #:unsubscribe) ;; Releases (:export #:release #:project-name #:system-files #:archive-url #:archive-size #:ensure-archive-file #:archive-content-sha1 #:archive-file-md5 #:prefix #:local-archive-file #:ensure-local-archive-file #:check-local-archive-file #:invalid-local-archive #:invalid-local-archive-file #:invalid-local-archive-release #:missing-local-archive #:badly-sized-local-archive #:delete-and-retry) ;; Systems (:export #:dist #:release #:preference #:system-file-name #:required-systems) ;; Misc (:export #:standard-dist-enumeration-function #:*dist-enumeration-functions* #:find-asdf-system-file #:system-definition-searcher #:system-apropos #:system-apropos-list #:dependency-tree #:clean #:unknown-dist)) (defpackage #:ql-dist-user (:documentation "A package that uses QL-DIST; useful for playing around in without clobbering any QL-DIST internals.") (:use #:cl #:ql-dist)) (defpackage #:ql-bundle (:documentation "A package for supporting the QL:BUNDLE-SYSTEMS function.") (:use #:cl #:ql-dist #:ql-impl-util) (:shadow #:find-system #:find-release) (:export #:bundle #:ensure-system #:ensure-release #:write-bundle #:add-systems-recursively #:object-not-found #:system-not-found #:system-not-found-system #:release-not-found #:bundle-directory-exists #:bundle-directory-exists-directory)) (defpackage #:quicklisp-client (:documentation "The Quicklisp client package, intended for end-user Quicklisp commands and configuration parameters.") (:nicknames #:quicklisp #:ql) (:use #:cl #:ql-util #:ql-impl-util #:ql-dist #:ql-http #:ql-setup #:ql-config #:ql-minitar #:ql-gunzipper) (:shadow #:uninstall) (:shadowing-import-from #:ql-dist #:dist-version #:dist-url) (:export #:dist-version #:dist-url) (:export #:quickload #:*quickload-prompt* #:*quickload-verbose* #:*quickload-explain* #:system-not-found #:system-not-found-name #:uninstall #:uninstall-dist #:qmerge #:*quicklisp-home* #:*initial-dist-url* #:*proxy-url* #:config-value #:setup #:provided-systems #:system-apropos #:system-apropos-list #:system-list #:client-version #:client-url #:available-client-versions #:install-client #:update-client #:update-dist #:update-all-dists #:available-dist-versions #:add-to-init-file #:use-only-quicklisp-systems #:write-asdf-manifest-file #:where-is-system #:help #:register-local-projects #:local-projects-searcher #:*local-project-directories* #:list-local-projects #:list-local-systems #:who-depends-on #:bundle-systems)) (in-package #:quicklisp-client)
9,088
Common Lisp
.lisp
318
19.58805
71
0.551634
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
36e044603fd74b8f2537cf10fb37cff6b1d08c37774fd13ace0dc2f8a16aea2f
30,440
[ 266698 ]
30,441
http.lisp
johncorn271828_X_Orrery/quicklisp/http.lisp
;;; ;;; A simple HTTP client ;;; (in-package #:ql-http) ;;; Octet data (deftype octet () '(unsigned-byte 8)) (defun make-octet-vector (size) (make-array size :element-type 'octet :initial-element 0)) (defun octet-vector (&rest octets) (make-array (length octets) :element-type 'octet :initial-contents octets)) ;;; ASCII characters as integers (defun acode (char) (cond ((eql char :cr) 13) ((eql char :lf) 10) (t (let ((code (char-code char))) (if (<= 0 code 127) code (error "Character ~S is not in the ASCII character set" char)))))) (defvar *whitespace* (list (acode #\Space) (acode #\Tab) (acode :cr) (acode :lf))) (defun whitep (code) (member code *whitespace*)) (defun ascii-vector (string) (let ((vector (make-octet-vector (length string)))) (loop for char across string for code = (char-code char) for i from 0 if (< 127 code) do (error "Invalid character for ASCII -- ~A" char) else do (setf (aref vector i) code)) vector)) (defun ascii-subseq (vector start end) "Return a subseq of octet-specialized VECTOR as a string." (let ((string (make-string (- end start)))) (loop for i from 0 for j from start below end do (setf (char string i) (code-char (aref vector j)))) string)) (defun ascii-downcase (code) (if (<= 65 code 90) (+ code 32) code)) (defun ascii-equal (a b) (eql (ascii-downcase a) (ascii-downcase b))) (defmacro acase (value &body cases) (flet ((convert-case-keys (keys) (mapcar (lambda (key) (etypecase key (integer key) (character (char-code key)) (symbol (ecase key (:cr 13) (:lf 10) ((t) t))))) (if (consp keys) keys (list keys))))) `(case ,value ,@(mapcar (lambda (case) (destructuring-bind (keys &rest body) case `(,(if (eql keys t) t (convert-case-keys keys)) ,@body))) cases)))) ;;; Pattern matching (for finding headers) (defclass matcher () ((pattern :initarg :pattern :reader pattern) (pos :initform 0 :accessor match-pos) (matchedp :initform nil :accessor matchedp))) (defun reset-match (matcher) (setf (match-pos matcher) 0 (matchedp matcher) nil)) (define-condition match-failure (error) ()) (defun match (matcher input &key (start 0) end error) (let ((i start) (end (or end (length input))) (match-end (length (pattern matcher)))) (with-slots (pattern pos) matcher (loop (cond ((= pos match-end) (let ((match-start (- i pos))) (setf pos 0) (setf (matchedp matcher) t) (return (values match-start (+ match-start match-end))))) ((= i end) (return nil)) ((= (aref pattern pos) (aref input i)) (incf i) (incf pos)) (t (if error (error 'match-failure) (if (zerop pos) (incf i) (setf pos 0))))))))) (defun ascii-matcher (string) (make-instance 'matcher :pattern (ascii-vector string))) (defun octet-matcher (&rest octets) (make-instance 'matcher :pattern (apply 'octet-vector octets))) (defun acode-matcher (&rest codes) (make-instance 'matcher :pattern (make-array (length codes) :element-type 'octet :initial-contents (mapcar 'acode codes)))) ;;; "Connection Buffers" are a kind of callback-driven, ;;; pattern-matching chunky stream. Callbacks can be called for a ;;; certain number of octets or until one or more patterns are seen in ;;; the input. cbufs automatically refill themselves from a ;;; connection as needed. (defvar *cbuf-buffer-size* 8192) (define-condition end-of-data (error) ()) (defclass cbuf () ((data :initarg :data :accessor data) (connection :initarg :connection :accessor connection) (start :initarg :start :accessor start) (end :initarg :end :accessor end) (eofp :initarg :eofp :accessor eofp)) (:default-initargs :data (make-octet-vector *cbuf-buffer-size*) :connection nil :start 0 :end 0 :eofp nil) (:documentation "A CBUF is a connection buffer that keeps track of incoming data from a connection. Several functions make it easy to treat a CBUF as a kind of chunky, callback-driven stream.")) (define-condition cbuf-progress () ((size :initarg :size :accessor cbuf-progress-size :initform 0))) (defun call-processor (fun cbuf start end) (signal 'cbuf-progress :size (- end start)) (funcall fun (data cbuf) start end)) (defun make-cbuf (connection) (make-instance 'cbuf :connection connection)) (defun make-stream-writer (stream) "Create a callback for writing data to STREAM." (lambda (data start end) (write-sequence data stream :start start :end end))) (defgeneric size (cbuf) (:method ((cbuf cbuf)) (- (end cbuf) (start cbuf)))) (defgeneric emptyp (cbuf) (:method ((cbuf cbuf)) (zerop (size cbuf)))) (defgeneric refill (cbuf) (:method ((cbuf cbuf)) (when (eofp cbuf) (error 'end-of-data)) (setf (start cbuf) 0) (setf (end cbuf) (read-octets (data cbuf) (connection cbuf))) (cond ((emptyp cbuf) (setf (eofp cbuf) t) (error 'end-of-data)) (t (size cbuf))))) (defun process-all (fun cbuf) (unless (emptyp cbuf) (call-processor fun cbuf (start cbuf) (end cbuf)))) (defun multi-cmatch (matchers cbuf) (let (start end) (dolist (matcher matchers (values start end)) (multiple-value-bind (s e) (match matcher (data cbuf) :start (start cbuf) :end (end cbuf)) (when (and s (or (null start) (< s start))) (setf start s end e)))))) (defun cmatch (matcher cbuf) (if (consp matcher) (multi-cmatch matcher cbuf) (match matcher (data cbuf) :start (start cbuf) :end (end cbuf)))) (defun call-until-end (fun cbuf) (handler-case (loop (process-all fun cbuf) (refill cbuf)) (end-of-data () (return-from call-until-end)))) (defun show-cbuf (context cbuf) (format t "cbuf: ~A ~D - ~D~%" context (start cbuf) (end cbuf))) (defun call-for-n-octets (n fun cbuf) (let ((remaining n)) (loop (when (<= remaining (size cbuf)) (let ((end (+ (start cbuf) remaining))) (call-processor fun cbuf (start cbuf) end) (setf (start cbuf) end) (return))) (process-all fun cbuf) (decf remaining (size cbuf)) (refill cbuf)))) (defun call-until-matching (matcher fun cbuf) (loop (multiple-value-bind (start end) (cmatch matcher cbuf) (when start (call-processor fun cbuf (start cbuf) end) (setf (start cbuf) end) (return))) (process-all fun cbuf) (refill cbuf))) (defun ignore-data (data start end) (declare (ignore data start end))) (defun skip-until-matching (matcher cbuf) (call-until-matching matcher 'ignore-data cbuf)) ;;; Creating HTTP requests as octet buffers (defclass octet-sink () ((storage :initarg :storage :accessor storage)) (:default-initargs :storage (make-array 1024 :element-type 'octet :fill-pointer 0 :adjustable t)) (:documentation "A simple stream-like target for collecting octets.")) (defun add-octet (octet sink) (vector-push-extend octet (storage sink))) (defun add-octets (octets sink &key (start 0) end) (setf end (or end (length octets))) (loop for i from start below end do (add-octet (aref octets i) sink))) (defun add-string (string sink) (loop for char across string for code = (char-code char) do (add-octet code sink))) (defun add-strings (sink &rest strings) (mapc (lambda (string) (add-string string sink)) strings)) (defun add-newline (sink) (add-octet 13 sink) (add-octet 10 sink)) (defun sink-buffer (sink) (subseq (storage sink) 0)) (defvar *proxy-url* (config-value "proxy-url")) (defun full-proxy-path (host port path) (format nil "~:[http~;https~]://~A~:[:~D~;~*~]~A" (= port 443) host (or (= port 80) (= port 443)) port path)) (defun user-agent-string () "Return a string suitable for using as the User-Agent value in HTTP requests. Includes Quicklisp version and CL implementation and version information." (labels ((requires-encoding (char) (not (or (alphanumericp char) (member char '(#\. #\- #\_))))) (encode (string) (substitute-if #\_ #'requires-encoding string)) (version-string (string) (if (string-equal string nil) "unknown" (let* ((length (length string)) (start (or (position-if #'digit-char-p string) 0)) (space (or (position #\Space string :start start) length)) (limit (min space length (+ start 24)))) (encode (subseq string start limit)))))) ;; FIXME: Be more configurable, and take/set the version from ;; somewhere else. (format nil "quicklisp-client/~A ~A/~A" ql-info:*version* (encode (lisp-implementation-type)) (version-string (lisp-implementation-version))))) (defun make-request-buffer (host port path &key (method "GET")) "Return an octet vector suitable for sending as an HTTP 1.1 request." (setf method (string method)) (when *proxy-url* (setf path (full-proxy-path host port path))) (let ((sink (make-instance 'octet-sink))) (flet ((add-line (&rest strings) (apply #'add-strings sink strings) (add-newline sink))) (add-line method " " path " HTTP/1.1") (add-line "Host: " host (if (= port 80) "" (format nil ":~D" port))) (add-line "Connection: close") (add-line "User-Agent: " (user-agent-string)) (add-newline sink) (sink-buffer sink)))) (defun sink-until-matching (matcher cbuf) (let ((sink (make-instance 'octet-sink))) (call-until-matching matcher (lambda (buffer start end) (add-octets buffer sink :start start :end end)) cbuf) (sink-buffer sink))) ;;; HTTP headers (defclass header () ((data :initarg :data :accessor data) (status :initarg :status :accessor status) (name-starts :initarg :name-starts :accessor name-starts) (name-ends :initarg :name-ends :accessor name-ends) (value-starts :initarg :value-starts :accessor value-starts) (value-ends :initarg :value-ends :accessor value-ends))) (defmethod print-object ((header header) stream) (print-unreadable-object (header stream :type t) (prin1 (status header) stream))) (defun matches-at (pattern target pos) (= (mismatch pattern target :start2 pos) (length pattern))) (defun header-value-indexes (field-name header) (loop with data = (data header) with pattern = (ascii-vector (string-downcase field-name)) for start across (name-starts header) for i from 0 when (matches-at pattern data start) return (values (aref (value-starts header) i) (aref (value-ends header) i)))) (defun ascii-header-value (field-name header) (multiple-value-bind (start end) (header-value-indexes field-name header) (when start (ascii-subseq (data header) start end)))) (defun all-field-names (header) (map 'list (lambda (start end) (ascii-subseq (data header) start end)) (name-starts header) (name-ends header))) (defun headers-alist (header) (mapcar (lambda (name) (cons name (ascii-header-value name header))) (all-field-names header))) (defmethod describe-object :after ((header header) stream) (format stream "~&Decoded headers:~% ~S~%" (headers-alist header))) (defun content-length (header) (let ((field-value (ascii-header-value "content-length" header))) (when field-value (let ((value (ignore-errors (parse-integer field-value)))) (or value (error "Content-Length header field value is not a number -- ~A" field-value)))))) (defun chunkedp (header) (string= (ascii-header-value "transfer-encoding" header) "chunked")) (defun location (header) (ascii-header-value "location" header)) (defun status-code (vector) (let* ((space (position (acode #\Space) vector)) (c1 (- (aref vector (incf space)) 48)) (c2 (- (aref vector (incf space)) 48)) (c3 (- (aref vector (incf space)) 48))) (+ (* c1 100) (* c2 10) (* c3 1)))) (defun force-downcase-field-names (header) (loop with data = (data header) for start across (name-starts header) for end across (name-ends header) do (loop for i from start below end for code = (aref data i) do (setf (aref data i) (ascii-downcase code))))) (defun skip-white-forward (pos vector) (position-if-not 'whitep vector :start pos)) (defun skip-white-backward (pos vector) (let ((nonwhite (position-if-not 'whitep vector :end pos :from-end t))) (if nonwhite (1+ nonwhite) pos))) (defun contract-field-value-indexes (header) "Header field values exclude leading and trailing whitespace; adjust the indexes in the header accordingly." (loop with starts = (value-starts header) with ends = (value-ends header) with data = (data header) for i from 0 for start across starts for end across ends do (setf (aref starts i) (skip-white-forward start data)) (setf (aref ends i) (skip-white-backward end data)))) (defun next-line-pos (vector) (let ((pos 0)) (labels ((finish (&optional (i pos)) (return-from next-line-pos i)) (after-cr (code) (acase code (:lf (finish pos)) (t (finish (1- pos))))) (pending (code) (acase code (:cr #'after-cr) (:lf (finish pos)) (t #'pending)))) (let ((state #'pending)) (loop (setf state (funcall state (aref vector pos))) (incf pos)))))) (defun make-hvector () (make-array 16 :fill-pointer 0 :adjustable t)) (defun process-header (vector) "Create a HEADER instance from the octet data in VECTOR." (let* ((name-starts (make-hvector)) (name-ends (make-hvector)) (value-starts (make-hvector)) (value-ends (make-hvector)) (header (make-instance 'header :data vector :status 999 :name-starts name-starts :name-ends name-ends :value-starts value-starts :value-ends value-ends)) (mark nil) (pos (next-line-pos vector))) (unless pos (error "Unable to process HTTP header")) (setf (status header) (status-code vector)) (labels ((save (value vector) (vector-push-extend value vector)) (mark () (setf mark pos)) (clear-mark () (setf mark nil)) (finish () (if mark (save mark value-ends) (save pos value-ends)) (force-downcase-field-names header) (contract-field-value-indexes header) (return-from process-header header)) (in-new-line (code) (acase code ((#\Tab #\Space) (setf mark nil) #'in-value) (t (when mark (save mark value-ends)) (clear-mark) (save pos name-starts) (in-name code)))) (after-cr (code) (acase code (:lf #'in-new-line) (t (in-new-line code)))) (in-name (code) (acase code (#\: (save pos name-ends) (save (1+ pos) value-starts) #'in-value) ((:cr :lf) (finish)) ((#\Tab #\Space) (error "Unexpected whitespace in header field name")) (t (unless (<= 0 code 127) (error "Unexpected non-ASCII header field name")) #'in-name))) (in-value (code) (acase code (:lf (mark) #'in-new-line) (:cr (mark) #'after-cr) (t #'in-value)))) (let ((state #'in-new-line)) (loop (incf pos) (when (<= (length vector) pos) (error "No header found in response")) (setf state (funcall state (aref vector pos)))))))) ;;; HTTP URL parsing (defclass url () ((hostname :initarg :hostname :accessor hostname :initform nil) (port :initarg :port :accessor port :initform 80) (path :initarg :path :accessor path :initform "/"))) (defun parse-urlstring (urlstring) (setf urlstring (string-trim " " urlstring)) (let* ((pos (mismatch urlstring "http://" :test 'char-equal)) (mark pos) (url (make-instance 'url))) (labels ((save () (subseq urlstring mark pos)) (mark () (setf mark pos)) (finish () (return-from parse-urlstring url)) (hostname-char-p (char) (position char "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_." :test 'char-equal)) (at-start (char) (case char (#\/ (setf (port url) nil) (mark) #'in-path) (t #'in-host))) (in-host (char) (case char ((#\/ :end) (setf (hostname url) (save)) (mark) #'in-path) (#\: (setf (hostname url) (save)) (mark) #'in-port) (t (unless (hostname-char-p char) (error "~S is not a valid URL" urlstring)) #'in-host))) (in-port (char) (case char ((#\/ :end) (setf (port url) (parse-integer urlstring :start (1+ mark) :end pos)) (mark) #'in-path) (t (unless (digit-char-p char) (error "Bad port in URL ~S" urlstring)) #'in-port))) (in-path (char) (case char ((#\# :end) (setf (path url) (save)) (finish))) #'in-path)) (let ((state #'at-start)) (loop (when (<= (length urlstring) pos) (funcall state :end) (finish)) (setf state (funcall state (aref urlstring pos))) (incf pos)))))) (defun url (thing) (if (stringp thing) (parse-urlstring thing) thing)) (defgeneric request-buffer (method url) (:method (method url) (setf url (url url)) (make-request-buffer (hostname url) (port url) (path url) :method method))) (defun urlstring (url) (format nil "~@[http://~A~]~@[:~D~]~A" (hostname url) (and (/= 80 (port url)) (port url)) (path url))) (defmethod print-object ((url url) stream) (print-unreadable-object (url stream :type t) (prin1 (urlstring url) stream))) (defun merge-urls (url1 url2) (setf url1 (url url1)) (setf url2 (url url2)) (make-instance 'url :hostname (or (hostname url1) (hostname url2)) :port (or (port url1) (port url2)) :path (or (path url1) (path url2)))) ;;; Requesting an URL and saving it to a file (defparameter *maximum-redirects* 10) (defvar *default-url-defaults* (url "http://src.quicklisp.org/")) (defun read-http-header (cbuf) (let ((header-data (sink-until-matching (list (acode-matcher :lf :lf) (acode-matcher :cr :cr) (acode-matcher :cr :lf :cr :lf)) cbuf))) (process-header header-data))) (defun read-chunk-header (cbuf) (let* ((header-data (sink-until-matching (acode-matcher :cr :lf) cbuf)) (end (or (position (acode :cr) header-data) (position (acode #\;) header-data)))) (values (parse-integer (ascii-subseq header-data 0 end) :radix 16)))) (defun save-chunk-response (stream cbuf) "For a chunked response, read all chunks and write them to STREAM." (let ((fun (make-stream-writer stream)) (matcher (acode-matcher :cr :lf))) (loop (let ((chunk-size (read-chunk-header cbuf))) (when (zerop chunk-size) (return)) (call-for-n-octets chunk-size fun cbuf) (skip-until-matching matcher cbuf))))) (defun save-response (file header cbuf &key (if-exists :rename-and-delete)) (with-open-file (stream file :direction :output :if-exists if-exists :element-type 'octet) (let ((content-length (content-length header))) (cond ((chunkedp header) (save-chunk-response stream cbuf)) (content-length (call-for-n-octets content-length (make-stream-writer stream) cbuf)) (t (call-until-end (make-stream-writer stream) cbuf)))))) (defun call-with-progress-bar (size fun) (let ((progress-bar (make-progress-bar size))) (start-display progress-bar) (flet ((update (condition) (update-progress progress-bar (cbuf-progress-size condition)))) (handler-bind ((cbuf-progress #'update)) (funcall fun))) (finish-display progress-bar))) (define-condition fetch-error (error) ()) (define-condition unexpected-http-status (fetch-error) ((status-code :initarg :status-code :reader unexpected-http-status-code) (url :initarg :url :reader unexpected-http-status-url)) (:report (lambda (condition stream) (format stream "Unexpected HTTP status for ~A: ~A" (unexpected-http-status-url condition) (unexpected-http-status-code condition))))) (define-condition too-many-redirects (fetch-error) ((url :initarg :url :reader too-many-redirects-url) (redirect-count :initarg :redirect-count :reader too-many-redirects-count)) (:report (lambda (condition stream) (format stream "Too many redirects (~:D) for ~A" (too-many-redirects-count condition) (too-many-redirects-url condition))))) (defun fetch (url file &key (follow-redirects t) quietly (if-exists :rename-and-delete) (maximum-redirects *maximum-redirects*)) "Request URL and write the body of the response to FILE." (setf url (merge-urls url *default-url-defaults*)) (setf file (merge-pathnames file)) (let ((redirect-count 0) (original-url url) (connect-url (or (url *proxy-url*) url)) (stream (if quietly (make-broadcast-stream) *trace-output*))) (loop (when (<= maximum-redirects redirect-count) (error 'too-many-redirects :url original-url :redirect-count redirect-count)) (with-connection (connection (hostname connect-url) (port connect-url)) (let ((cbuf (make-instance 'cbuf :connection connection)) (request (request-buffer "GET" url))) (write-octets request connection) (let ((header (read-http-header cbuf))) (loop while (= (status header) 100) do (setf header (read-http-header cbuf))) (cond ((= (status header) 200) (let ((size (content-length header))) (format stream "~&; Fetching ~A~%" url) (if (and (numberp size) (plusp size)) (format stream "; ~$KB~%" (/ size 1024)) (format stream "; Unknown size~%")) (if quietly (save-response file header cbuf :if-exists if-exists) (call-with-progress-bar (content-length header) (lambda () (save-response file header cbuf :if-exists if-exists)))))) ((not (<= 300 (status header) 399)) (error 'unexpected-http-status :url url :status-code (status header)))) (if (and follow-redirects (<= 300 (status header) 399)) (let ((new-urlstring (ascii-header-value "location" header))) (when (not new-urlstring) (error "Redirect code ~D received, but no Location: header" (status header))) (incf redirect-count) (setf url (merge-urls new-urlstring url)) (format stream "~&; Redirecting to ~A~%" url)) (return (values header (and file (probe-file file)))))))))))
26,922
Common Lisp
.lisp
736
26.244565
80
0.540691
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
1640b9a9ee90de627cb5c158d260001e4c1e2a6f416f925f0d5ff90d43ab4118
30,441
[ 322153 ]
30,442
setup.lisp
johncorn271828_X_Orrery/quicklisp/setup.lisp
(in-package #:quicklisp) (defun show-wrapped-list (words &key (indent 4) (margin 60)) (let ((*print-right-margin* margin) (*print-pretty* t) (*print-escape* nil) (prefix (make-string indent :initial-element #\Space))) (pprint-logical-block (nil words :per-line-prefix prefix) (pprint-fill *standard-output* (sort (copy-seq words) #'string<) nil)) (fresh-line) (finish-output))) (defun recursively-install (name) (labels ((recurse (name) (let ((system (find-system name))) (unless system (error "Unknown system ~S" name)) (ensure-installed system) (mapcar #'recurse (required-systems system)) name))) (with-consistent-dists (recurse name)))) (defclass load-strategy () ((name :initarg :name :accessor name) (asdf-systems :initarg :asdf-systems :accessor asdf-systems) (quicklisp-systems :initarg :quicklisp-systems :accessor quicklisp-systems))) (defmethod print-object ((strategy load-strategy) stream) (print-unreadable-object (strategy stream :type t) (format stream "~S (~D asdf, ~D quicklisp)" (name strategy) (length (asdf-systems strategy)) (length (quicklisp-systems strategy))))) (defgeneric quicklisp-releases (strategy) (:method (strategy) (remove-duplicates (mapcar 'release (quicklisp-systems strategy))))) (defgeneric quicklisp-release-table (strategy) (:method ((strategy load-strategy)) (let ((table (make-hash-table))) (dolist (system (quicklisp-systems strategy)) (push system (gethash (release system) table nil))) table))) (define-condition system-not-found (error) ((name :initarg :name :reader system-not-found-name)) (:report (lambda (condition stream) (format stream "System ~S not found" (system-not-found-name condition)))) (:documentation "This condition is signaled by QUICKLOAD when a system given to load is not available via ASDF or a Quicklisp dist.")) (defun compute-load-strategy (name) (setf name (string-downcase name)) (let ((asdf-systems '()) (quicklisp-systems '())) (labels ((recurse (name) (let ((asdf-system (asdf:find-system name nil)) (quicklisp-system (find-system name))) (cond (asdf-system (push asdf-system asdf-systems)) (quicklisp-system (push quicklisp-system quicklisp-systems) (dolist (subname (required-systems quicklisp-system)) (recurse subname))) (t (cerror "Try again" 'system-not-found :name name) (recurse name)))))) (with-consistent-dists (recurse name))) (make-instance 'load-strategy :name name :asdf-systems (remove-duplicates asdf-systems) :quicklisp-systems (remove-duplicates quicklisp-systems)))) (defun show-load-strategy (strategy) (format t "To load ~S:~%" (name strategy)) (let ((asdf-systems (asdf-systems strategy)) (releases (quicklisp-releases strategy))) (when asdf-systems (format t " Load ~D ASDF system~:P:~%" (length asdf-systems)) (show-wrapped-list (mapcar 'asdf:component-name asdf-systems))) (when releases (format t " Install ~D Quicklisp release~:P:~%" (length releases)) (show-wrapped-list (mapcar 'name releases))))) (defvar *macroexpand-progress-in-progress* nil) (defun macroexpand-progress-fun (old-hook &key (char #\.) (chars-per-line 50) (forms-per-char 250)) (let ((output-so-far 0) (seen-so-far 0)) (labels ((finish-line () (when (plusp output-so-far) (dotimes (i (- chars-per-line output-so-far)) (write-char char)) (terpri) (setf output-so-far 0))) (show-string (string) (let* ((length (length string)) (new-output (+ length output-so-far))) (cond ((< chars-per-line new-output) (finish-line) (write-string string) (setf output-so-far length)) (t (write-string string) (setf output-so-far new-output)))) (finish-output)) (show-package (name) ;; Only show package markers when compiling. Showing ;; them when loading shows a bunch of ASDF system ;; package noise. (when *compile-file-pathname* (finish-line) (show-string (format nil "[package ~(~A~)]" name))))) (lambda (fun form env) (when (and (consp form) (eq (first form) 'cl:defpackage) (ignore-errors (string (second form)))) (show-package (second form))) (incf seen-so-far) (when (<= forms-per-char seen-so-far) (setf seen-so-far 0) (write-char char) (finish-output) (incf output-so-far) (when (<= chars-per-line output-so-far) (setf output-so-far 0) (terpri) (finish-output))) (funcall old-hook fun form env))))) (defun call-with-macroexpand-progress (fun) (let ((*macroexpand-hook* (if *macroexpand-progress-in-progress* *macroexpand-hook* (macroexpand-progress-fun *macroexpand-hook*))) (*macroexpand-progress-in-progress* t)) (funcall fun) (terpri))) (defun apply-load-strategy (strategy) (map nil 'ensure-installed (quicklisp-releases strategy)) (call-with-macroexpand-progress (lambda () (format t "~&; Loading ~S~%" (name strategy)) (asdf:oos 'asdf:load-op (name strategy) :verbose nil)))) (defun autoload-system-and-dependencies (name &key prompt) "Try to load the system named by NAME, automatically loading any Quicklisp-provided systems first, and catching ASDF missing dependencies too if possible." (setf name (string-downcase name)) (with-simple-restart (abort "Give up on ~S" name) (let ((strategy (compute-load-strategy name)) (tried-so-far (make-hash-table :test 'equalp))) (show-load-strategy strategy) (when (or (not prompt) (press-enter-to-continue)) (tagbody retry (handler-case (apply-load-strategy strategy) (asdf:missing-dependency-of-version (c) ;; Nothing Quicklisp can do to recover from this, so just ;; resignal (error c)) (asdf:missing-dependency (c) (let ((parent (asdf::missing-required-by c)) (missing (asdf::missing-requires c))) (typecase parent (asdf:system (if (gethash missing tried-so-far) (error "Dependency looping -- already tried to load ~ ~A" missing) (setf (gethash missing tried-so-far) missing)) (autoload-system-and-dependencies missing :prompt prompt) (go retry)) (t ;; Error isn't from a system dependency, so there's ;; nothing to autoload (error c))))))))) name)) (defvar *initial-dist-url* "http://beta.quicklisp.org/dist/quicklisp.txt") (defun dists-initialized-p () (not (not (ignore-errors (truename (qmerge "dists/")))))) (defun quickstart-parameter (name &optional default) (let* ((package (find-package '#:quicklisp-quickstart)) (symbol (and package (find-symbol (string '#:*quickstart-parameters*) package))) (plist (and symbol (symbol-value symbol))) (parameter (and plist (getf plist name)))) (or parameter default))) (defun maybe-initial-setup () "Run the steps needed when Quicklisp setup is run for the first time after the quickstart installation." (let ((quickstart-proxy-url (quickstart-parameter :proxy-url)) (quickstart-initial-dist-url (quickstart-parameter :initial-dist-url))) (when (and quickstart-proxy-url (not *proxy-url*)) (setf *proxy-url* quickstart-proxy-url) (setf (config-value "proxy-url") quickstart-proxy-url)) (unless (dists-initialized-p) (let ((target (qmerge "dists/quicklisp/distinfo.txt")) (url (or quickstart-initial-dist-url *initial-dist-url*))) (ensure-directories-exist target) (install-dist url :prompt nil))))) (defun setup () (unless (member 'system-definition-searcher asdf:*system-definition-search-functions*) (setf asdf:*system-definition-search-functions* (append asdf:*system-definition-search-functions* (list 'local-projects-searcher 'system-definition-searcher)))) (let ((files (nconc (directory (qmerge "local-init/*.lisp")) (directory (qmerge "local-init/*.cl"))))) (with-simple-restart (abort "Stop loading local setup files") (dolist (file (sort files #'string< :key #'pathname-name)) (with-simple-restart (skip "Skip local setup file ~S" file) ;; Don't try to load Emacs lock files, other hidden files (unless (char= (char (pathname-name file) 0) #\.) (load file)))))) (maybe-initial-setup) (ensure-directories-exist (qmerge "local-projects/")) (pushnew :quicklisp *features*) t)
9,973
Common Lisp
.lisp
228
32.548246
79
0.575776
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
45b796a52c53a0795a287c4b00b98829201d5d5069e3e414a6b7c1b8b6cba3d9
30,442
[ 344998 ]
30,444
utils.lisp
johncorn271828_X_Orrery/quicklisp/utils.lisp
;;;; utils.lisp (in-package #:ql-util) (defun write-line-to-file (string file) (with-open-file (stream file :direction :output :if-exists :supersede) (write-line string stream))) (defvar *do-not-prompt* nil "When *DO-NOT-PROMPT* is true, PRESS-ENTER-TO-CONTINUE returns true without user interaction.") (defmacro without-prompting (&body body) "Evaluate BODY in an environment where PRESS-ENTER-TO-CONTINUE always returns true without prompting for the user to press enter." `(let ((*do-not-prompt* t)) ,@body)) (defun press-enter-to-continue () (when *do-not-prompt* (return-from press-enter-to-continue t)) (format *query-io* "~&Press Enter to continue.~%") (let ((result (read-line *query-io*))) (zerop (length result)))) (defun replace-file (from to) "Like RENAME-FILE, but deletes TO if it exists, first." (when (probe-file to) (delete-file to)) (rename-file from to)) (defun copy-file (from to &key (if-exists :rename-and-delete)) "Copy the file FROM to TO." (let* ((buffer-size 8192) (buffer (make-array buffer-size :element-type '(unsigned-byte 8)))) (with-open-file (from-stream from :element-type '(unsigned-byte 8)) (with-open-file (to-stream to :element-type '(unsigned-byte 8) :direction :output :if-exists if-exists) (let ((length (file-length from-stream))) (multiple-value-bind (full leftover) (floor length buffer-size) (dotimes (i full) (read-sequence buffer from-stream) (write-sequence buffer to-stream)) (read-sequence buffer from-stream) (write-sequence buffer to-stream :end leftover))))) (probe-file to))) (defun ensure-file-exists (pathname) (open pathname :direction :probe :if-does-not-exist :create)) (defun delete-file-if-exists (pathname) (when (probe-file pathname) (delete-file pathname))) (defun split-spaces (line) (let ((words '()) (mark 0) (pos 0)) (labels ((finish () (setf pos (length line)) (save) (return-from split-spaces (nreverse words))) (save () (when (< mark pos) (push (subseq line mark pos) words))) (mark () (setf mark pos)) (in-word (char) (case char (#\Space (save) #'in-space) (t #'in-word))) (in-space (char) (case char (#\Space #'in-space) (t (mark) #'in-word)))) (let ((state #'in-word)) (dotimes (i (length line) (finish)) (setf pos i) (setf state (funcall state (char line i)))))))) (defun first-line (file) (with-open-file (stream file) (values (read-line stream)))) (defun (setf first-line) (line file) (with-open-file (stream file :direction :output :if-exists :rename-and-delete) (write-line line stream))) (defun file-size (file) (with-open-file (stream file :element-type '(unsigned-byte 8)) (file-length stream))) (defun safely-read (stream) "Read one form from STREAM with *READ-EVAL* bound to NIL." (let ((*read-eval* nil)) (read stream))) (defun safely-read-file (file) "Read the first form from FILE with SAFELY-READ." (with-open-file (stream file) (safely-read stream))) (defun make-versions-url (url) "Given an URL that looks like http://foo/bar.ext, return http://foo/bar-versions.txt." (let ((suffix-pos (position #\. url :from-end t))) (unless suffix-pos (error "Can't make a versions URL from ~A" url)) (let ((extension (subseq url suffix-pos))) (concatenate 'string (subseq url 0 suffix-pos) "-versions" extension))))
4,061
Common Lisp
.lisp
108
28.564815
76
0.572771
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
36f80b773bd0162b978aa9a9b67ff19133fc75db4553357f9db55eccde189143
30,444
[ 306785, 348595 ]
30,446
dist.lisp
johncorn271828_X_Orrery/quicklisp/dist.lisp
;;;; dist.lisp (in-package #:ql-dist) ;;; Generic functions (defgeneric dist (object) (:documentation "Return the dist of OBJECT.")) (defgeneric available-versions (object) (:documentation "Return a list of version information for OBJECT.")) (defgeneric system-index-url (object) (:documentation "Return the URL for the system index of OBJECT.")) (defgeneric release-index-url (object) (:documentation "Return the URL for the release index of OBJECT.")) (defgeneric available-versions-url (object) (:documentation "Return the URL for the available versions data file of OBJECT.")) (defgeneric release (object) (:documentation "Return the release of OBJECT.")) (defgeneric system (object) (:documentation "Return the system of OBJECT.")) (defgeneric name (object) (:documentation "Return the name of OBJECT.")) (defgeneric find-system (name) (:documentation "Return a system with the given NAME, or NIL if no system is found. If multiple systems have the same name, the one with the highest preference is returned.")) (defgeneric find-release (name) (:documentation "Return a release with the given NAME, or NIL if no system is found. If multiple releases have the same name, the one with the highest preference is returned.")) (defgeneric find-systems-named (name) (:documentation "Return a list of all systems in all enabled dists with the given NAME, sorted by preference.")) (defgeneric find-releases-named (name) (:documentation "Return a list of all releases in all enabled dists with the given NAME, sorted by preference.")) (defgeneric base-directory (object) (:documentation "Return the base directory pathname of OBJECT.") (:method ((object pathname)) (merge-pathnames object))) (defgeneric relative-to (object pathname) (:documentation "Merge PATHNAME with the base-directory of OBJECT.") (:method (object pathname) (merge-pathnames pathname (base-directory object)))) (defgeneric enabledp (object) (:documentation "Return true if OBJECT is enabled.")) (defgeneric enable (object) (:documentation "Enable OBJECT.")) (defgeneric disable (object) (:documentation "Disable OBJECT.")) (defgeneric installedp (object) (:documentation "Return true if OBJECT is installed.")) (defgeneric install (object) (:documentation "Install OBJECT.")) (defgeneric ensure-installed (object) (:documentation "Ensure that OBJECT is installed.") (:method (object) (unless (installedp object) (install object)) object)) (defgeneric uninstall (object) (:documentation "Uninstall OBJECT.")) (defgeneric metadata-name (object) (:documentation "The metadata-name of an object is used to form the pathname for a few different object metadata files.")) (defgeneric install-metadata-file (object) (:documentation "The pathname to a file describing the installation status of OBJECT.")) (defgeneric subscription-inhibition-file (object) (:documentation "The file whose presence indicates the inhibited subscription status of OBJECT.") (:method (object) (relative-to object "subscription-inhibited.txt"))) (defgeneric inhibit-subscription (object) (:documentation "Inhibit subscription for OBJECT.") (:method (object) (ensure-file-exists (subscription-inhibition-file object)))) (defgeneric uninhibit-subscription (object) (:documentation "Remove inhibition of subscription for OBJECT.") (:method (object) (delete-file-if-exists (subscription-inhibition-file object)))) (defgeneric subscription-inhibited-p (object) (:documentation "Return T if subscription to OBJECT is inhibited.") (:method (object) (not (not (probe-file (subscription-inhibition-file object)))))) (define-condition subscription-unavailable (error) ((object :initarg :object :reader subscription-unavailable-object))) (defgeneric subscribedp (object) (:documentation "Return true if OBJECT is subscribed to updates.")) (defgeneric subscribe (object) (:documentation "Subscribe to updates of OBJECT, if possible. If no updates are available, a condition of type SUBSCRIPTION-UNAVAILABLE is raised.") (:method (object) (uninhibit-subscription object) (unless (subscribedp object) (error 'subscription-unavailable :object object)) t)) (defgeneric unsubscribe (object) (:documentation "Unsubscribe from updates to OBJECT.") (:method (object) (inhibit-subscription object))) (defgeneric preference-parent (object) (:documentation "Return a value suitable for checking if OBJECT has no specific preference set.") (:method (object) (declare (ignore object)) nil)) (defgeneric preference-file (object) (:documentation "Return the file from which preference information is loaded for OBJECT.") (:method (object) (relative-to object "preference.txt"))) (defgeneric preference (object) (:documentation "Returns a value used when comparing multiple systems or releases with the same name. Objects with higher preference are returned by FIND-SYSTEM and FIND-RELEASE.") (:method ((object null)) 0) (:method (object) (with-open-file (stream (preference-file object) :if-does-not-exist nil) (if stream (values (parse-integer (read-line stream))) (preference (preference-parent object)))))) (defgeneric (setf preference) (preference object) (:documentation "Set the preference for OBJECT. Objects with higher preference are returned by FIND-SYSTEM and FIND-RELEASE.") (:method (preference object) (check-type preference integer) (let ((preference-file (preference-file object))) (ensure-directories-exist preference-file) (with-open-file (stream (preference-file object) :direction :output :if-exists :supersede) (format stream "~D" preference))) preference)) (defgeneric forget-preference (object) (:documentation "Remove specific preference information for OBJECT.") (:method (object) (delete-file-if-exists (preference-file object)))) (defgeneric short-description (object) (:documentation "Return a short string describing OBJECT.")) (defgeneric provided-releases (object) (:documentation "Return a list of releases provided by OBJECT.")) (defgeneric provided-systems (object) (:documentation "Return a list of systems provided by OBJECT.")) (defgeneric installed-releases (dist) (:documentation "Return a list of all releases installed for DIST.") (:method (dist) (remove-if-not #'installedp (provided-releases dist)))) (defgeneric installed-systems (dist) (:documentation "Return a list of all systems installed for DIST.") (:method (dist) (remove-if-not #'installedp (provided-systems dist)))) (defgeneric new-version-available-p (dist) (:documentation "Return true if a new version of DIST is available.")) (defgeneric find-system-in-dist (system-name dist) (:documentation "Return a system with the given NAME in DIST, or NIL if no system is found.")) (defgeneric find-release-in-dist (release-name dist) (:documentation "Return a release with the given NAME in DIST, or NIL if no release is found.")) (defgeneric ensure-system-index-file (dist) (:documentation "Return the pathname for the system index file of DIST, fetching it from a remote source first if necessary.")) (defgeneric ensure-system-cdb-file (dist) (:documentation "Return the pathname for the system cdb file of DIST, creating it if necessary.")) (defgeneric ensure-release-index-file (dist) (:documentation "Return the pathname for the release index file of DIST, fetching it from a remote source first if necessary.")) (defgeneric ensure-release-cdb-file (dist) (:documentation "Return the pathname for the release cdb file of DIST, creating it if necessary.")) (defgeneric initialize-release-index (dist) (:documentation "Initialize the release index of DIST.")) (defgeneric initialize-system-index (dist) (:documentation "Initialize the system index of DIST.")) (defgeneric local-archive-file (release) (:documentation "Return the pathname to where the archive file of RELEASE should be stored.")) (defgeneric ensure-local-archive-file (release) (:documentation "If the archive file for RELEASE is not available locally, fetch it and return the pathname to it.")) (defgeneric check-local-archive-file (release) (:documentation "Check the local archive file of RELEASE for validity, including size and signature checks. Signals errors in the case of invalid files.")) (defgeneric archive-url (release) (:documentation "Return the full URL for fetching the archive file of RELEASE.")) (defgeneric installed-asdf-system-file (object) (:documentation "Return the path to the installed ASDF system file for OBJECT, or NIL if there is no installed system file.")) (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro destructure-line (lambda-list line &body body) `(destructuring-bind ,lambda-list (split-spaces ,line) ,@body)) (defun call-for-each-line (fun file) (with-open-file (stream file) (loop for line = (read-line stream nil) while line do (funcall fun line)))) (defmacro for-each-line ((line file) &body body) `(call-for-each-line (lambda (,line) ,@body) ,file))) (defun make-line-instance (line class &rest initargs) "Create an instance from words in an index file line. The last initarg collects all the trailing arguments, if any." (let* ((words (split-spaces line)) (args (mapcan #'list (butlast initargs) words)) (trailing (subseq words (1- (length initargs))))) (apply #'make-instance class (first (last initargs)) trailing args))) (defun ignorable-line (line) (labels ((blank-char-p (char) (member char '(#\Space #\Tab))) (blankp (line) (every #'blank-char-p line)) (ignorable (line) (or (zerop (length line)) (blankp line) (eql (char line 0) #\#)))) (ignorable line))) (defvar *initarg-case-converter* (cond ((string= :string "string") #'string-downcase) ((string= :string "STRING") #'string-upcase))) (defun config-file-initargs (file) (flet ((initarg-keyword (string) ;; A concession to mlisp (intern (funcall *initarg-case-converter* string) 'keyword))) (let ((initargs '())) (for-each-line (line file) (unless (ignorable-line line) (destructure-line (initarg value) line (let ((keyword (initarg-keyword (string-right-trim ":" initarg)))) (push value initargs) (push keyword initargs))))) initargs))) ;;; ;;; A few generic things ;;; (defmethod dist ((name symbol)) (dist (string name))) (defmethod dist ((name string)) (find-dist (string-downcase name))) (defmethod release ((name symbol)) (release (string name))) (defmethod release ((name string)) (find-release (string-downcase name))) (defmethod system ((name symbol)) (system (string name))) (defmethod system ((name string)) (find-system (string-downcase name))) ;;; ;;; Dists ;;; ;;; A dist is a set of releases. ;;; (defclass dist () ((base-directory :initarg :base-directory :accessor base-directory) (name :initarg :name :accessor name) (version :initarg :version :accessor version) (system-index-url :initarg :system-index-url :accessor system-index-url) (release-index-url :initarg :release-index-url :accessor release-index-url) (available-versions-url :initarg :available-versions-url :accessor available-versions-url) (archive-base-url :initarg :archive-base-url :accessor archive-base-url) (canonical-distinfo-url :initarg :canonical-distinfo-url :accessor canonical-distinfo-url) (distinfo-subscription-url :initarg :distinfo-subscription-url :accessor distinfo-subscription-url) (system-index :initarg :system-index :accessor system-index) (release-index :initarg :release-index :accessor release-index) (provided-systems :initarg :provided-systems :accessor provided-systems) (provided-releases :initarg :provided-releases :accessor provided-releases) (local-distinfo-file :initarg :local-distinfo-file :accessor local-distinfo-file)) (:default-initargs :name "unnamed" :version "unknown" :distinfo-subscription-url nil)) (defmethod short-description ((dist dist)) (format nil "~A ~A" (name dist) (version dist))) (defmethod print-object ((dist dist) stream) (print-unreadable-object (dist stream :type t) (write-string (short-description dist) stream))) (defun cdb-lookup (dist key cdb) (ql-cdb:lookup key (relative-to dist cdb))) (defmethod slot-unbound (class (dist dist) (slot (eql 'available-versions-url))) (declare (ignore class)) (setf (available-versions-url dist) (make-versions-url (distinfo-subscription-url dist)))) (defmethod ensure-system-index-file ((dist dist)) (let ((pathname (relative-to dist "systems.txt"))) (or (probe-file pathname) (nth-value 1 (fetch (system-index-url dist) pathname))))) (defmethod ensure-system-cdb-file ((dist dist)) (let* ((system-file (ensure-system-index-file dist)) (cdb-file (make-pathname :type "cdb" :defaults system-file))) (or (probe-file cdb-file) (ql-cdb:convert-index-file system-file :cdb-file cdb-file :index 2)))) (defmethod ensure-release-index-file ((dist dist)) (let ((pathname (relative-to dist "releases.txt"))) (or (probe-file pathname) (nth-value 1 (fetch (release-index-url dist) pathname))))) (defmethod ensure-release-cdb-file ((dist dist)) (let* ((release-file (ensure-release-index-file dist)) (cdb-file (make-pathname :type "cdb" :defaults release-file))) (or (probe-file cdb-file) (ql-cdb:convert-index-file release-file :cdb-file cdb-file :index 0)))) (defmethod slot-unbound (class (dist dist) (slot (eql 'provided-systems))) (declare (ignore class)) (initialize-system-index dist) (setf (slot-value dist 'provided-systems) (loop for system being each hash-value of (system-index dist) collect system))) (defmethod slot-unbound (class (dist dist) (slot (eql 'provided-releases))) (declare (ignore class)) (initialize-release-index dist) (setf (slot-value dist 'provided-releases) (loop for system being each hash-value of (release-index dist) collect system))) (defun dist-name-pathname (name) "Return the pathname that would be used for an installed dist with the given NAME." (qmerge (make-pathname :directory (list :relative "dists" name)))) (defmethod slot-unbound (class (dist dist) (slot (eql 'base-directory))) (declare (ignore class)) (setf (base-directory dist) (dist-name-pathname (name dist)))) (defun make-dist-from-file (file &key (class 'dist)) "Load dist info from FILE and use it to create a dist instance." (let ((initargs (config-file-initargs file))) (apply #'make-instance class :local-distinfo-file file :allow-other-keys t initargs))) (defmethod install-metadata-file ((dist dist)) (relative-to dist "distinfo.txt")) (defun find-dist (name) (find name (all-dists) :key #'name :test #'string=)) (defmethod enabledp ((dist dist)) (not (not (probe-file (relative-to dist "enabled.txt"))))) (defmethod enable ((dist dist)) (ensure-file-exists (relative-to dist "enabled.txt")) t) (defmethod disable ((dist dist)) (delete-file-if-exists (relative-to dist "enabled.txt")) t) (defmethod installedp ((dist dist)) (let ((installed (find-dist (name dist)))) (equalp (version installed) (version dist)))) (defmethod uninstall ((dist dist)) (when (installedp dist) (dolist (system (provided-systems dist)) (asdf:clear-system (name system))) (ql-impl-util:delete-directory-tree (base-directory dist)) t)) (defun make-release-from-line (line dist) (let ((release (make-line-instance line 'release :project-name :archive-url :archive-size :archive-md5 :archive-content-sha1 :prefix :system-files))) (setf (dist release) dist) (setf (archive-size release) (parse-integer (archive-size release))) release)) (defmethod find-release-in-dist (release-name (dist dist)) (let* ((index (release-index dist)) (release (gethash release-name index))) (or release (let ((line (cdb-lookup dist release-name (ensure-release-cdb-file dist)))) (when line (setf (gethash release-name index) (make-release-from-line line dist))))))) (defparameter *dist-enumeration-functions* '(standard-dist-enumeration-function) "ALL-DISTS calls each function in this list with no arguments, and appends the results into a list of dist objects, removing duplicates. Functions might be called just once for a batch of related operations; see WITH-CONSISTENT-DISTS.") (defun standard-dist-enumeration-function () "The default function used for producing a list of dist objects." (loop for file in (directory (qmerge "dists/*/distinfo.txt")) collect (make-dist-from-file file))) (defun all-dists () "Return a list of all known dists." (remove-duplicates (apply 'append (mapcar 'funcall *dist-enumeration-functions*)))) (defun enabled-dists () "Return a list of all known dists for which ENABLEDP returns true." (remove-if-not #'enabledp (all-dists))) (defmethod install-metadata-file (object) (relative-to (dist object) (make-pathname :directory (list :relative "installed" (metadata-name object)) :name (name object) :type "txt"))) (defclass preference-mixin () () (:documentation "Instances of this class have a special location for their preference files.")) (defgeneric filesystem-name (object) (:method (object) ;; This is to work around system names like "foo/bar". (let* ((name (name object)) (slash (position #\/ name))) (if slash (subseq name 0 slash) name)))) (defmethod preference-file ((object preference-mixin)) (relative-to (dist object) (make-pathname :directory (list :relative "preferences" (metadata-name object)) :name (filesystem-name object) :type "txt"))) (defmethod distinfo-subscription-url :around ((dist dist)) (unless (subscription-inhibited-p dist) (call-next-method))) (defmethod subscribedp ((dist dist)) (distinfo-subscription-url dist)) ;;; ;;; Releases ;;; (defclass release (preference-mixin) ((project-name :initarg :project-name :accessor name :accessor project-name) (dist :initarg :dist :accessor dist :reader preference-parent) (provided-systems :initarg :provided-systems :accessor provided-systems) (archive-url :initarg :archive-url :accessor archive-url) (archive-size :initarg :archive-size :accessor archive-size) (archive-md5 :initarg :archive-md5 :accessor archive-md5) (archive-content-sha1 :initarg :archive-content-sha1 :accessor archive-content-sha1) (prefix :initarg :prefix :accessor prefix :reader short-description) (system-files :initarg :system-files :accessor system-files) (metadata-name :initarg :metadata-name :accessor metadata-name)) (:default-initargs :metadata-name "releases") (:documentation "Instances of this class represent a snapshot of a project at some point in time, which might be from version control, or from an official release, or from some other source.")) (defmethod print-object ((release release) stream) (print-unreadable-object (release stream :type t) (format stream "~A / ~A" (short-description release) (short-description (dist release))))) (define-condition invalid-local-archive (error) ((release :initarg :release :reader invalid-local-archive-release) (file :initarg :file :reader invalid-local-archive-file)) (:report (lambda (condition stream) (format stream "The archive file ~S for release ~S is invalid" (file-namestring (invalid-local-archive-file condition)) (name (invalid-local-archive-release condition)))))) (define-condition missing-local-archive (invalid-local-archive) () (:report (lambda (condition stream) (format stream "The archive file ~S for release ~S is missing" (file-namestring (invalid-local-archive-file condition)) (name (invalid-local-archive-release condition)))))) (define-condition badly-sized-local-archive (invalid-local-archive) ((expected-size :initarg :expected-size :reader badly-sized-local-archive-expected-size) (actual-size :initarg :actual-size :reader badly-sized-local-archive-actual-size)) (:report (lambda (condition stream) (format stream "The archive file ~S for ~S is the wrong size: ~ expected ~:D, got ~:D" (file-namestring (invalid-local-archive-file condition)) (name (invalid-local-archive-release condition)) (badly-sized-local-archive-expected-size condition) (badly-sized-local-archive-actual-size condition))))) (defmethod check-local-archive-file ((release release)) (let ((file (local-archive-file release))) (unless (probe-file file) (error 'missing-local-archive :file file :release release)) (let ((actual-size (file-size file)) (expected-size (archive-size release))) (unless (= actual-size expected-size) (error 'badly-sized-local-archive :file file :release release :actual-size actual-size :expected-size expected-size))))) (defmethod local-archive-file ((release release)) (relative-to (dist release) (make-pathname :directory '(:relative "archives") :defaults (file-namestring (path (url (archive-url release))))))) (defmethod ensure-local-archive-file ((release release)) (let ((pathname (local-archive-file release))) (tagbody :retry (or (probe-file pathname) (progn (ensure-directories-exist pathname) (fetch (archive-url release) pathname))) (restart-case (check-local-archive-file release) (delete-and-retry (&optional v) :report "Delete the archive file and fetch it again" (declare (ignore v)) (delete-file pathname) (go :retry)))) pathname)) (defmethod base-directory ((release release)) (relative-to (dist release) (make-pathname :directory (list :relative "software" (prefix release))))) (defmethod installedp ((release release)) (and (probe-file (install-metadata-file release)) (every #'installedp (provided-systems release)))) (defmethod install ((release release)) (let ((archive (ensure-local-archive-file release)) (tar (qmerge "tmp/release-install.tar")) (output (relative-to (dist release) (make-pathname :directory (list :relative "software")))) (tracking (install-metadata-file release))) (ensure-directories-exist tar) (ensure-directories-exist output) (ensure-directories-exist tracking) (gunzip archive tar) (unpack-tarball tar :directory output) (ensure-directories-exist tracking) (with-open-file (stream tracking :direction :output :if-exists :supersede) (write-line (qenough (base-directory release)) stream)) (let ((provided (provided-systems release)) (dist (dist release))) (dolist (file (system-files release)) (let ((system (find-system-in-dist (pathname-name file) dist))) (unless (member system provided) (error "FIND-SYSTEM-IN-DIST returned ~A but I expected one of ~A" system provided)) (let ((system-tracking (install-metadata-file system)) (system-file (merge-pathnames file (base-directory release)))) (ensure-directories-exist system-tracking) (unless (probe-file system-file) (error "Release claims to have ~A, but I can't find it" system-file)) (with-open-file (stream system-tracking :direction :output :if-exists :supersede) (write-line (qenough system-file) stream)))))) release)) (defmethod uninstall ((release release)) (when (installedp release) (dolist (system (installed-systems release)) (asdf:clear-system (name system)) (delete-file (install-metadata-file system))) (delete-file (install-metadata-file release)) (delete-file (local-archive-file release)) (ql-impl-util:delete-directory-tree (base-directory release)) t)) (defun call-for-each-index-entry (file fun) (labels ((blank-char-p (char) (member char '(#\Space #\Tab))) (blankp (line) (every #'blank-char-p line)) (ignorable (line) (or (zerop (length line)) (blankp line) (eql (char line 0) #\#)))) (with-open-file (stream file) (loop for line = (read-line stream nil) while line do (unless (ignorable line) (funcall fun line)))))) (defmethod slot-unbound (class (dist dist) (slot (eql 'release-index))) (declare (ignore class)) (setf (slot-value dist 'release-index) (make-hash-table :test 'equal))) ;;; ;;; Systems ;;; ;;; A "system" in the defsystem sense. ;;; (defclass system (preference-mixin) ((name :initarg :name :accessor name :reader short-description) (system-file-name :initarg :system-file-name :accessor system-file-name) (release :initarg :release :accessor release :reader preference-parent) (dist :initarg :dist :accessor dist) (required-systems :initarg :required-systems :accessor required-systems) (metadata-name :initarg :metadata-name :accessor metadata-name)) (:default-initargs :metadata-name "systems")) (defmethod print-object ((system system) stream) (print-unreadable-object (system stream :type t) (format stream "~A / ~A / ~A" (short-description system) (short-description (release system)) (short-description (dist system))))) (defmethod provided-systems ((system system)) (list system)) (defmethod initialize-release-index ((dist dist)) (let ((releases (ensure-release-index-file dist)) (index (release-index dist))) (call-for-each-index-entry releases (lambda (line) (let ((instance (make-line-instance line 'release :project-name :archive-url :archive-size :archive-md5 :archive-content-sha1 :prefix :system-files))) ;; Don't clobber anything previously loaded via CDB (unless (gethash (project-name instance) index) (setf (dist instance) dist) (setf (archive-size instance) (parse-integer (archive-size instance))) (setf (gethash (project-name instance) index) instance))))) (setf (release-index dist) index))) (defmethod initialize-system-index ((dist dist)) (initialize-release-index dist) (let ((systems (ensure-system-index-file dist)) (index (system-index dist))) (call-for-each-index-entry systems (lambda (line) (let ((instance (make-line-instance line 'system :release :system-file-name :name :required-systems))) ;; Don't clobber anything previously loaded via CDB (unless (gethash (name instance) index) (let ((release (find-release-in-dist (release instance) dist))) (setf (release instance) release) (if (slot-boundp release 'provided-systems) (pushnew instance (provided-systems release)) (setf (provided-systems release) (list instance)))) (setf (dist instance) dist) (setf (gethash (name instance) index) instance))))) (setf (system-index dist) index))) (defmethod slot-unbound (class (release release) (slot (eql 'provided-systems))) (declare (ignore class)) ;; FIXME: This isn't right, since the system index has systems that ;; don't match the defining system file name. (setf (slot-value release 'provided-systems) (mapcar (lambda (system-file) (find-system-in-dist (pathname-name system-file) (dist release))) (system-files release)))) (defmethod slot-unbound (class (dist dist) (slot (eql 'system-index))) (declare (ignore class)) (setf (slot-value dist 'system-index) (make-hash-table :test 'equal))) (defun make-system-from-line (line dist) (let ((system (make-line-instance line 'system :release :system-file-name :name :required-systems))) (setf (dist system) dist) (setf (release system) (find-release-in-dist (release system) dist)) system)) (defmethod find-system-in-dist (system-name (dist dist)) (let* ((index (system-index dist)) (system (gethash system-name index))) (or system (let ((line (cdb-lookup dist system-name (ensure-system-cdb-file dist)))) (when line (setf (gethash system-name index) (make-system-from-line line dist))))))) (defmethod preference ((system system)) (if (probe-file (preference-file system)) (call-next-method) (preference (release system)))) (defun thing-name-designator (designator) "Convert DESIGNATOR to a string naming a thing. Strings are used as-is, symbols are converted to their downcased symbol-name." (typecase designator (string designator) (symbol (string-downcase designator)) (t (error "~S is not a valid designator for a system or release" designator)))) (defun find-thing-named (find-fun name) (setf name (thing-name-designator name)) (let ((result '())) (dolist (dist (enabled-dists) (sort result #'> :key #'preference)) (let ((thing (funcall find-fun name dist))) (when thing (push thing result)))))) (defmethod find-systems-named (name) (find-thing-named #'find-system-in-dist name)) (defmethod find-releases-named (name) (find-thing-named #'find-release-in-dist name)) (defmethod find-system (name) (first (find-systems-named name))) (defmethod find-release (name) (first (find-releases-named name))) (defmethod install ((system system)) (ensure-installed (release system))) (defmethod install-metadata-file ((system system)) (relative-to (dist system) (make-pathname :name (system-file-name system) :type "txt" :directory '(:relative "installed" "systems")))) (defmethod installed-asdf-system-file ((system system)) (let ((metadata-file (install-metadata-file system))) (when (probe-file metadata-file) (with-open-file (stream metadata-file) (let* ((relative (read-line stream)) (full (qmerge relative))) (when (probe-file full) full)))))) (defmethod installedp ((system system)) (installed-asdf-system-file system)) (defmethod uninstall ((system system)) (uninstall (release system))) (defun find-asdf-system-file (name) "Return the ASDF system file in which the system named NAME is defined." (let ((system (find-system name))) (when system (installed-asdf-system-file system)))) (defun system-definition-searcher (name) "Like FIND-ASDF-SYSTEM-FILE, but this function can be used in ASDF:*SYSTEM-DEFINITION-SEARCH-FUNCTIONS*; it will only return system file names if they match NAME." (let ((system-file (find-asdf-system-file name))) (when (and system-file (string= (pathname-name system-file) name)) system-file))) (defun call-with-consistent-dists (fun) "Take a snapshot of the available dists and return the same list consistently each time ALL-DISTS is called in the dynamic scope of FUN." (let* ((all-dists (all-dists)) (*dist-enumeration-functions* (list (constantly all-dists)))) (funcall fun))) (defmacro with-consistent-dists (&body body) "See CALL-WITH-CONSISTENT-DISTS." `(call-with-consistent-dists (lambda () ,@body))) (defgeneric dependency-tree (system) (:method ((symbol symbol)) (dependency-tree (string-downcase symbol))) (:method ((string string)) (let ((system (find-system string))) (when system (dependency-tree system)))) (:method ((system system)) (with-consistent-dists (list* system (remove nil (mapcar 'dependency-tree (required-systems system))))))) (defmethod provided-systems ((object (eql t))) (let ((systems (loop for dist in (enabled-dists) appending (provided-systems dist)))) (sort systems #'string< :key #'name))) (defmethod provided-releases ((object (eql t))) (let ((releases (loop for dist in (enabled-dists) appending (provided-releases dist)))) (sort releases #'string< :key #'name))) (defgeneric system-apropos-list (term) (:method ((term symbol)) (system-apropos-list (symbol-name term))) (:method ((term string)) (setf term (string-downcase term)) (let ((result '())) (dolist (system (provided-systems t) (nreverse result)) (when (or (search term (name system)) (search term (name (release system)))) (push system result)))))) (defgeneric system-apropos (term) (:method (term) (map nil (lambda (system) (format t "~A~%" system)) (system-apropos-list term)) (values))) ;;; ;;; Clean up things ;;; (defgeneric clean (object) (:documentation "Remove any unneeded files or directories related to OBJECT.")) (defmethod clean ((dist dist)) (let* ((releases (provided-releases dist)) (known-archives (mapcar 'local-archive-file releases)) (known-directories (mapcar 'base-directory releases)) (present-archives (mapcar 'truename (directory-entries (relative-to dist "archives/")))) (present-directories (mapcar 'truename (directory-entries (relative-to dist "software/")))) (garbage-archives (set-difference present-archives known-archives :test 'equalp)) (garbage-directories (set-difference present-directories known-directories :test 'equalp))) (map nil 'delete-file garbage-archives) (map nil 'delete-directory-tree garbage-directories))) ;;; ;;; Available versions ;;; (defmethod available-versions ((dist dist)) (let ((temp (qmerge "tmp/dist-versions.txt")) (versions '()) (url (available-versions-url dist))) (when url (ensure-directories-exist temp) (delete-file-if-exists temp) (handler-case (fetch url temp) (unexpected-http-status () (return-from available-versions nil))) (with-open-file (stream temp) (loop for line = (read-line stream nil) while line do (destructuring-bind (version url) (split-spaces line) (setf versions (acons version url versions))))) versions))) ;;; ;;; User interface bits to re-export from QL ;;; (define-condition unknown-dist (error) ((name :initarg :name :reader unknown-dist-name)) (:report (lambda (condition stream) (format stream "No dist known by that name -- ~S" (unknown-dist-name condition))))) (defun find-dist-or-lose (name) (let ((dist (find-dist name))) (or dist (error 'unknown-dist :name name)))) (defun dist-url (name) (canonical-distinfo-url (find-dist-or-lose name))) (defun dist-version (name) (version (find-dist-or-lose name)))
38,116
Common Lisp
.lisp
975
31.792821
118
0.649149
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
17ba2b6a39ee22400de92f38e329cde2452618261656c8d0b5a4e595809f11b8
30,446
[ -1 ]
30,448
bundle-template.lisp
johncorn271828_X_Orrery/quicklisp/bundle-template.lisp
(cl:in-package #:cl-user) (eval-when (:compile-toplevel :load-toplevel :execute) (require "asdf") (unless (find-package '#:asdf) (error "ASDF could not be required"))) (let ((indicator '#:ql-bundle-v1) (searcher-name '#:ql-bundle-searcher) (base (make-pathname :name nil :type nil :defaults #. (or *compile-file-truename* *load-truename*)))) (labels ((file-lines (file) (with-open-file (stream file) (loop for line = (read-line stream nil) while line collect line))) (relative (pathname) (merge-pathnames pathname base)) (pathname-timestamp (pathname) #+clisp (nth-value 2 (ext:probe-pathname pathname)) #-clisp (file-write-date pathname)) (system-table (table pathnames) (dolist (pathname pathnames table) (setf (gethash (pathname-name pathname) table) (relative pathname)))) (initialize-bundled-systems-table (table data-source) (system-table table (file-lines data-source))) (local-projects-system-pathnames (data-source) (let ((files (directory (merge-pathnames "**/*.asd" data-source)))) (stable-sort (sort files #'string< :key #'namestring) #'< :key (lambda (file) (length (namestring file)))))) (initialize-local-projects-table (table data-source) (system-table table (local-projects-system-pathnames data-source))) (make-table (&key data-source init-function) (let ((table (make-hash-table :test 'equalp))) (setf (gethash "/data-source" table) data-source (gethash "/timestamp" table) (pathname-timestamp data-source) (gethash "/init" table) init-function) table)) (tcall (table key &rest args) (let ((fun (gethash key table))) (unless (and fun (functionp fun)) (error "Unknown function key ~S" key)) (apply fun args))) (created-timestamp (table) (gethash "/timestamp" table)) (data-source-timestamp (table) (pathname-timestamp (data-source table))) (data-source (table) (gethash "/data-source" table)) (stalep (table) ;; FIXME: Handle newly missing data sources? (< (created-timestamp table) (data-source-timestamp table))) (meta-key-p (key) (and (stringp key) (< 0 (length key)) (char= (char key 0) #\/))) (clear (table) ;; Don't clear "/foo" keys (maphash (lambda (key value) (declare (ignore value)) (unless (meta-key-p key) (remhash key table))) table)) (initialize (table) (tcall table "/init" table (data-source table)) (setf (gethash "/timestamp" table) (pathname-timestamp (data-source table))) table) (update (table) (clear table) (initialize table)) (lookup (system-name table) (when (stalep table) (update table)) (values (gethash system-name table))) (search-function (system-name) (let ((tables (get searcher-name indicator))) (dolist (table tables) (let* ((result (lookup system-name table)) (probed (and result (probe-file result)))) (when probed (return probed)))))) (make-bundled-systems-table () (initialize (make-table :data-source (relative "system-index.txt") :init-function #'initialize-bundled-systems-table))) (make-local-projects-table () (initialize (make-table :data-source (relative "local-projects/") :init-function #'initialize-local-projects-table))) (=matching-data-sources (&rest tables) (let ((data-sources (mapcar #'data-source tables))) (lambda (table) (member (data-source table) data-sources :test #'equalp)))) (check-for-existing-searcher (searchers) (block done (dolist (searcher searchers) (when (symbolp searcher) (let ((plist (symbol-plist searcher))) (loop for key in plist by #'cddr when (and (symbolp key) (string= key indicator)) do (setf indicator key) (setf searcher-name searcher) (return-from done t))))))) (clear-asdf (table) (maphash (lambda (system-name pathname) (declare (ignore pathname)) (asdf:clear-system system-name)) table))) (let ((existing (check-for-existing-searcher asdf:*system-definition-search-functions*))) (let* ((bundled (make-bundled-systems-table)) (local (make-local-projects-table)) (existing-tables (get searcher-name indicator)) (filter (=matching-data-sources bundled local))) (setf (get searcher-name indicator) (list* local bundled (delete-if filter existing-tables))) (clear-asdf local) (clear-asdf bundled)) (unless existing (setf (symbol-function searcher-name) #'search-function) (push searcher-name asdf:*system-definition-search-functions*))) t))
6,220
Common Lisp
.lisp
135
29.696296
80
0.496542
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
7e3ed1c351403ea480a3bea4637a0ee4b24c9db8ada39b8393e251bb1946cd11
30,448
[ 150924 ]
30,449
client.lisp
johncorn271828_X_Orrery/quicklisp/client.lisp
;;;; client.lisp (in-package #:quicklisp-client) (defvar *quickload-verbose* nil "When NIL, show terse output when quickloading a system. Otherwise, show normal compile and load output.") (defvar *quickload-prompt* nil "When NIL, quickload systems without prompting for enter to continue, otherwise proceed directly without user intervention.") (defvar *quickload-explain* t) (define-condition system-not-quickloadable (error) ((system :initarg :system :reader not-quickloadable-system))) (defun maybe-silence (silent stream) (or (and silent (make-broadcast-stream)) stream)) (defgeneric quickload (systems &key verbose silent prompt explain &allow-other-keys) (:documentation "Load SYSTEMS the quicklisp way. SYSTEMS is a designator for a list of things to be loaded.") (:method (systems &key (prompt *quickload-prompt*) (silent nil) (verbose *quickload-verbose*) &allow-other-keys) (let ((*standard-output* (maybe-silence silent *standard-output*)) (*trace-output* (maybe-silence silent *trace-output*))) (unless (consp systems) (setf systems (list systems))) (dolist (thing systems systems) (flet ((ql () (autoload-system-and-dependencies thing :prompt prompt))) (if verbose (ql) (call-with-quiet-compilation #'ql))))))) (defmethod quickload :around (systems &key verbose prompt explain &allow-other-keys) (declare (ignorable systems verbose prompt explain)) (with-consistent-dists (call-next-method))) (defun system-list () (provided-systems t)) (defun update-dist (dist &key (prompt t)) (when (stringp dist) (setf dist (find-dist dist))) (let ((new (available-update dist))) (cond (new (show-update-report dist new) (when (or (not prompt) (press-enter-to-continue)) (update-in-place dist new))) ((not (subscribedp dist)) (format t "~&You are not subscribed to ~S." (name dist))) (t (format t "~&You already have the latest version of ~S: ~A.~%" (name dist) (version dist)))))) (defun update-all-dists (&key (prompt t)) (let ((dists (remove-if-not 'subscribedp (all-dists)))) (format t "~&~D dist~:P to check.~%" (length dists)) (dolist (old dists) (with-simple-restart (skip "Skip update of dist ~S" (name old)) (update-dist old :prompt prompt))))) (defun available-dist-versions (name) (available-versions (find-dist-or-lose name))) (defun help () "For help with Quicklisp, see http://www.quicklisp.org/beta/") (defun uninstall (system-name) (let ((system (find-system system-name))) (cond (system (ql-dist:uninstall system)) (t (warn "Unknown system ~S" system-name) nil)))) (defun uninstall-dist (name) (let ((dist (find-dist name))) (when dist (ql-dist:uninstall dist)))) (defun write-asdf-manifest-file (output-file &key (if-exists :rename-and-delete) exclude-local-projects) "Write a list of system file pathnames to OUTPUT-FILE, one per line, in order of descending QL-DIST:PREFERENCE." (when (or (eql output-file nil) (eql output-file t)) (setf output-file (qmerge "manifest.txt"))) (with-open-file (stream output-file :direction :output :if-exists if-exists) (unless exclude-local-projects (register-local-projects) (dolist (system-file (list-local-projects)) (let* ((enough (enough-namestring system-file output-file)) (native (native-namestring enough))) (write-line native stream)))) (with-consistent-dists (let ((systems (provided-systems t)) (already-seen (make-hash-table :test 'equal))) (dolist (system (sort systems #'> :key #'preference)) ;; FIXME: find-asdf-system-file does another find-system ;; behind the scenes. Bogus. Should be a better way to go ;; from system object to system file. (let* ((system-file (find-asdf-system-file (name system))) (enough (and system-file (enough-namestring system-file output-file))) (native (and enough (native-namestring enough)))) (when (and native (not (gethash native already-seen))) (setf (gethash native already-seen) native) (format stream "~A~%" native))))))) (probe-file output-file)) (defun where-is-system (name) "Return the pathname to the source directory of ASDF system with the given NAME, or NIL if no system by that name can be found known." (let ((system (asdf:find-system name nil))) (when system (asdf:system-source-directory system))))
5,006
Common Lisp
.lisp
114
35.157895
84
0.619487
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
6cabecd91e7fc16aed2126f4140c6fb5c6f7760b96f56c483f22916da1dfde8c
30,449
[ 37957, 143155 ]
30,450
impl.lisp
johncorn271828_X_Orrery/quicklisp/impl.lisp
(in-package #:ql-impl) (eval-when (:compile-toplevel :load-toplevel :execute) (defun error-unimplemented (&rest args) (declare (ignore args)) (error "Not implemented"))) (defvar *interfaces* (make-hash-table) "A table of defined interfaces and their documentation.") (defun show-interfaces () "Display information about what interfaces are defined." (maphash (lambda (interface info) (destructuring-bind (arguments docstring) info (let ((*package* (find-package :keyword))) (format t "(~S ~:[()~;~:*~A~]~@[~% ~S~])~%" interface arguments docstring)))) *interfaces*)) (defmacro neuter-package (name) `(eval-when (:compile-toplevel :load-toplevel :execute) (let ((definition (fdefinition 'error-unimplemented))) (do-external-symbols (symbol ,(string name)) (unless (fboundp symbol) (setf (fdefinition symbol) definition)))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun feature-expression-passes-p (expression) (cond ((keywordp expression) (member expression *features*)) ((consp expression) (case (first expression) (or (some 'feature-expression-passes-p (rest expression))) (and (every 'feature-expression-passes-p (rest expression))))) (t (error "Unrecognized feature expression -- ~S" expression))))) (defmacro define-implementation-package (feature package-name &rest options) (let* ((output-options '((:use) (:export #:lisp))) (prep (cdr (assoc :prep options))) (class-option (cdr (assoc :class options))) (class (first class-option)) (superclasses (rest class-option)) (import-options '()) (effectivep (feature-expression-passes-p feature))) (dolist (option options) (ecase (first option) ((:prep :class)) ((:import-from :import) (push option import-options)) ((:export :shadow :intern :documentation) (push option output-options)) ((:reexport-from) (push (cons :export (cddr option)) output-options) (push (cons :import-from (cdr option)) import-options)))) `(progn ,@(when effectivep `((eval-when (:compile-toplevel :load-toplevel :execute) ,@prep))) (defclass ,class ,superclasses ()) (defpackage ,package-name ,@output-options ,@(when effectivep import-options)) ,@(when effectivep `((setf *implementation* (make-instance ',class)))) ,@(unless effectivep `((neuter-package ,package-name)))))) (defmacro definterface (name lambda-list &body options) (let* ((doc-option (find :documentation options :key #'first)) (doc (second doc-option))) (setf (gethash name *interfaces*) (list lambda-list doc))) (let* ((forbidden (intersection lambda-list lambda-list-keywords)) (gf-options (remove :implementation options :key #'first)) (implementations (set-difference options gf-options)) (implementation-arg (copy-symbol '%implementation))) (when forbidden (error "~S not allowed in definterface lambda list" forbidden)) (flet ((method-option (class body) `(:method ((,implementation-arg ,class) ,@lambda-list) ,@body))) (let ((generic-name (intern (format nil "%~A" name)))) `(progn (defgeneric ,generic-name (lisp ,@lambda-list) ,@gf-options ,@(mapcan (lambda (implementation) (destructuring-bind (class &rest body) (rest implementation) (mapcar (lambda (class) (method-option class body)) (if (consp class) class (list class))))) implementations)) (defun ,name ,lambda-list (,generic-name *implementation* ,@lambda-list))))))) (defmacro defimplementation (name-and-options lambda-list &body body) (destructuring-bind (name &key (for t) qualifier) (if (consp name-and-options) name-and-options (list name-and-options)) (unless for (error "You must specify an implementation name.")) (let ((generic-name (find-symbol (format nil "%~A" name))) (implementation-arg (copy-symbol '%implementation))) (unless generic-name (error "~S does not name an implementation function" name)) `(defmethod ,generic-name ,@(when qualifier (list qualifier)) ,(list* `(,implementation-arg ,for) lambda-list) ,@body)))) ;;; Bootstrap implementations (defvar *implementation* nil) (defclass lisp () ()) ;;; Allegro Common Lisp (define-implementation-package :allegro #:ql-allegro (:documentation "Allegro Common Lisp - http://www.franz.com/products/allegrocl/") (:class allegro) (:reexport-from #:socket #:make-socket) (:reexport-from #:excl #:file-directory-p #:delete-directory #:delete-directory-and-files #:read-vector)) ;;; Armed Bear Common Lisp (define-implementation-package :abcl #:ql-abcl (:documentation "Armed Bear Common Lisp - http://common-lisp.net/project/armedbear/") (:class abcl) (:reexport-from #:ext #:make-socket #:get-socket-stream)) ;;; Clozure CL (define-implementation-package :ccl #:ql-ccl (:documentation "Clozure Common Lisp - http://www.clozure.com/clozurecl.html") (:class ccl) (:reexport-from #:ccl #:delete-directory #:make-socket #:native-translated-namestring)) ;;; CLASP (define-implementation-package :clasp #:ql-clasp (:documentation "CLASP - http://github.com/drmeister/clasp") (:class clasp) (:prep (require 'sockets)) (:intern #:host-network-address) (:reexport-from #:si #:rmdir #:file-kind) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:host-ent-address #:inet-socket #:socket-connect #:socket-make-stream)) ;;; GNU CLISP (define-implementation-package :clisp #:ql-clisp (:documentation "GNU CLISP - http://clisp.cons.org/") (:class clisp) (:reexport-from #:socket #:socket-connect) (:reexport-from #:ext #:delete-dir #:rename-directory #:probe-directory #:probe-pathname #:read-byte-sequence)) ;;; CMUCL (define-implementation-package :cmu #:ql-cmucl (:documentation "CMU Common Lisp - http://www.cons.org/cmucl/") (:class cmucl) (:reexport-from #:system #:make-fd-stream) (:reexport-from #:unix #:unix-rmdir) (:reexport-from #:extensions #:connect-to-inet-socket #:*gc-verbose*)) (defvar ql-cmucl:*gc-verbose*) ;;; Scieneer CL (define-implementation-package :scl #:ql-scl (:documentation "Scieneer Common Lisp - http://www.scieneer.com/scl/") (:class scl) (:reexport-from #:system #:make-fd-stream) (:reexport-from #:unix #:unix-rmdir) (:reexport-from #:extensions #:connect-to-inet-socket #:unix-namestring)) ;;; LispWorks (define-implementation-package :lispworks #:ql-lispworks (:documentation "LispWorks - http://www.lispworks.com/") (:class lispworks) (:prep (require "comm")) (:reexport-from #:lw #:file-directory-p #:delete-directory) (:reexport-from #:comm #:open-tcp-stream #:get-host-entry)) ;;; ECL (define-implementation-package :ecl #:ql-ecl (:documentation "ECL - http://ecls.sourceforge.net/") (:class ecl) (:prep (require 'sockets)) (:intern #:host-network-address) (:reexport-from #:si #:rmdir #:file-kind) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:host-ent-address #:inet-socket #:socket-connect #:socket-make-stream)) ;;; MKCL (define-implementation-package :mkcl #:ql-mkcl (:documentation "ManKai Common Lisp - http://common-lisp.net/project/mkcl/") (:class mkcl) (:prep (require 'sockets)) (:intern #:host-network-address) (:reexport-from #:si #:rmdir #:file-kind) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:host-ent-address #:inet-socket #:socket-connect #:socket-make-stream)) ;;; SBCL (define-implementation-package :sbcl #:ql-sbcl (:class sbcl) (:documentation "Steel Bank Common Lisp - http://www.sbcl.org/") (:prep (require 'sb-posix) (require 'sb-bsd-sockets)) (:intern #:host-network-address) (:reexport-from #:sb-posix #:rmdir) (:reexport-from #:sb-ext #:compiler-note #:native-namestring) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:inet-socket #:host-ent-address #:socket-connect #:socket-make-stream))
9,763
Common Lisp
.lisp
258
27.748062
78
0.566899
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
d43b62abd3820074d35bbaadd9e1c5f7a1c98f5b54e06df7754cc972876c4764
30,450
[ -1 ]
30,454
bundle.lisp
johncorn271828_X_Orrery/quicklisp/bundle.lisp
;;;; bundle.lisp (in-package #:ql-bundle) ;;; Bundling is taking a set of Quicklisp-provided systems and ;;; creating a directory structure and metadata in which those systems ;;; can be loaded without involving Quicklisp. ;;; ;;; This works only for systems that are directly provided by ;;; Quicklisp. It can't reach out into ASDF-land and copy sources ;;; around. (defgeneric find-system (system bundle)) (defgeneric add-system (system bundle)) (defgeneric ensure-system (system bundle)) (defgeneric find-release (relase bundle)) (defgeneric add-release (release bundle)) (defgeneric ensure-release (release bundle)) (defgeneric write-loader-script (bundle stream)) (defgeneric write-system-index (bundle stream)) (defgeneric unpack-release (release target)) (defgeneric unpack-releases (bundle target)) (defgeneric write-bundle (bundle target)) ;;; Implementation ;;; Conditions (define-condition bundle-error (error) ()) (define-condition object-not-found (bundle-error) ((name :initarg :name :reader object-not-found-name) (type :initarg :type :reader object-not-found-type)) (:report (lambda (condition stream) (format stream "~A ~S not found" (object-not-found-type condition) (object-not-found-name condition)))) (:default-initargs :type "Object")) (define-condition system-not-found (object-not-found) ((name :reader system-not-found-system)) (:default-initargs :type "System")) (define-condition release-not-found (object-not-found) () (:default-initargs :type "Release")) (define-condition bundle-directory-exists (bundle-error) ((directory :initarg :directory :reader bundle-directory-exists-directory)) (:report (lambda (condition stream) (format stream "Bundle directory ~A already exists" (bundle-directory-exists-directory condition))))) (defclass bundle () ((release-table :initarg :release-table :reader release-table) (system-table :initarg :system-table :reader system-table)) (:default-initargs :release-table (make-hash-table :test 'equalp) :system-table (make-hash-table :test 'equalp))) (defmethod print-object ((bundle bundle) stream) (print-unreadable-object (bundle stream :type t) (format stream "~D release~:P, ~D system~:P" (hash-table-count (release-table bundle)) (hash-table-count (system-table bundle))))) (defmethod provided-releases ((bundle bundle)) (let ((releases '())) (maphash (lambda (name release) (declare (ignore name)) (push release releases)) (release-table bundle)) (sort releases 'string< :key 'name))) (defmethod provided-systems ((bundle bundle)) (sort (mapcan #'provided-systems (provided-releases bundle)) 'string< :key 'name)) (defmethod find-system (name (bundle bundle)) (values (gethash name (system-table bundle)))) (defmethod add-system (name (bundle bundle)) (let ((system (ql-dist:find-system name))) (unless system (error 'system-not-found :name name)) (ensure-release (name (release system)) bundle) system)) (defmethod ensure-system (name (bundle bundle)) (or (find-system name bundle) (add-system name bundle))) (defmethod find-release (name (bundle bundle)) (values (gethash name (release-table bundle)))) (defmethod add-release (name (bundle bundle)) (let ((release (ql-dist:find-release name))) (unless release (error 'release-not-found :name name)) (setf (gethash (name release) (release-table bundle)) release) (let ((system-table (system-table bundle))) (dolist (system (provided-systems release)) (setf (gethash (name system) system-table) system))) release)) (defmethod ensure-release (name (bundle bundle)) (or (find-release name bundle) (add-release name bundle))) (defun add-systems-recursively (names bundle) (with-consistent-dists (labels ((add-one (name) (let ((system (ensure-system name bundle))) (dolist (required-system-name (required-systems system)) (add-one required-system-name))))) (map nil #'add-one names))) bundle) (defmethod unpack-release (release target) (let ((*default-pathname-defaults* (truename (ensure-directories-exist target))) (archive (ensure-local-archive-file release)) (temp-tar (ensure-directories-exist (ql-setup:qmerge "tmp/bundle.tar")))) (ql-gunzipper:gunzip archive temp-tar) (ql-minitar:unpack-tarball temp-tar :directory "software/") (delete-file temp-tar) release)) (defmethod unpack-releases ((bundle bundle) target) (dolist (release (provided-releases bundle)) (unpack-release release target)) bundle) (defmethod write-system-index ((bundle bundle) stream) (dolist (release (provided-releases bundle)) ;; Working with strings, here, intentionally not with pathnames (let ((prefix (concatenate 'string "software/" (prefix release)))) (dolist (system-file (system-files release)) (format stream "~A/~A~%" prefix system-file))))) (defmethod write-loader-script ((bundle bundle) stream) (let ((template-lines (load-time-value (with-open-file (stream #. (merge-pathnames "bundle-template" (or *compile-file-truename* *load-truename*))) (loop for line = (read-line stream nil) while line collect line))))) (dolist (line template-lines) (write-line line stream)))) (defun coerce-to-directory (pathname) ;; Cribbed from quicklisp-bootstrap/quicklisp.lisp (let ((name (file-namestring pathname))) (if (or (null name) (equal name "")) pathname (make-pathname :defaults pathname :name nil :type nil :directory (append (pathname-directory pathname) (list name)))))) (defmethod write-bundle ((bundle bundle) target) (unpack-releases bundle target) (let ((index-file (merge-pathnames "system-index.txt" target)) (loader-file (merge-pathnames "bundle.lisp" target)) (local-projects (merge-pathnames "local-projects/" target))) (ensure-directories-exist local-projects) (with-open-file (stream index-file :direction :output :if-exists :supersede) (write-system-index bundle stream)) (with-open-file (stream loader-file :direction :output :if-exists :supersede) (write-loader-script bundle stream)) (probe-file loader-file))) (defun ql:bundle-systems (system-names &key to (overwrite t)) "In the directory TO, construct a self-contained bundle of libraries based on SYSTEM-NAMES. For each system named, and its recursive required systems, unpack its release archive in TO/software/, and write a system index, compatible with the output of QL:WRITE-ASDF-MANIFEST-FILE, to TO/system-index.txt. Write a loader script to TO/bundle.lisp that, when loaded via CL:LOAD, configures ASDF to load systems from the bundle before any other system. SYSTEM-NAMES must name systems provided directly by Quicklisp." (unless to (error "TO argument must be provided")) (let* ((bundle (make-instance 'bundle)) (to (coerce-to-directory to)) (software (merge-pathnames "software/" to))) (when (and (probe-directory to) (not overwrite)) (cerror "Overwrite it" 'bundle-directory-exists :directory to)) (when (probe-directory software) (delete-directory-tree software)) (add-systems-recursively system-names bundle) (values (write-bundle bundle to) bundle)))
7,945
Common Lisp
.lisp
193
34.42487
81
0.667747
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
7ca125013ecf78505ad458ccc6f828b0246f5a428560968c8960974aeb6c2df8
30,454
[ 93519 ]
30,456
misc.lisp
johncorn271828_X_Orrery/quicklisp/misc.lisp
;;;; misc.lisp (in-package #:quicklisp-client) ;;; ;;; This stuff will probably end up somewhere else. ;;; (defun use-only-quicklisp-systems () (asdf:initialize-source-registry '(:source-registry :ignore-inherited-configuration)) (asdf:map-systems 'asdf:clear-system) t) (defun who-depends-on (system-name) "Return a list of names of systems that depend on SYSTEM-NAME." (loop for system in (provided-systems t) when (member system-name (required-systems system) :test 'string=) collect (name system)))
536
Common Lisp
.lisp
15
32.533333
74
0.723404
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
6b3456e20dcecfbfee65bed705146dfa4101d283758ff7ad6d5c6168540babf7
30,456
[ 365225, 380702 ]
30,457
network.lisp
johncorn271828_X_Orrery/quicklisp/network.lisp
;;; ;;; Low-level networking implementations ;;; (in-package #:ql-network) (definterface host-address (host) (:implementation t host) (:implementation sbcl (ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host)))) (definterface open-connection (host port) (:documentation "Open and return a network connection to HOST on the given PORT.") (:implementation t (declare (ignore host port)) (error "Sorry, quicklisp in implementation ~S is not supported yet." (lisp-implementation-type))) (:implementation allegro (ql-allegro:make-socket :remote-host host :remote-port port)) (:implementation abcl (let ((socket (ql-abcl:make-socket host port))) (ql-abcl:get-socket-stream socket :element-type '(unsigned-byte 8)))) (:implementation ccl (ql-ccl:make-socket :remote-host host :remote-port port)) (:implementation clasp (let* ((endpoint (ql-clasp:host-ent-address (ql-clasp:get-host-by-name host))) (socket (make-instance 'ql-clasp:inet-socket :protocol :tcp :type :stream))) (ql-clasp:socket-connect socket endpoint port) (ql-clasp:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation clisp (ql-clisp:socket-connect port host :element-type '(unsigned-byte 8))) (:implementation cmucl (let ((fd (ql-cmucl:connect-to-inet-socket host port))) (ql-cmucl:make-fd-stream fd :element-type '(unsigned-byte 8) :binary-stream-p t :input t :output t))) (:implementation scl (let ((fd (ql-scl:connect-to-inet-socket host port))) (ql-scl:make-fd-stream fd :element-type '(unsigned-byte 8) :input t :output t))) (:implementation ecl (let* ((endpoint (ql-ecl:host-ent-address (ql-ecl:get-host-by-name host))) (socket (make-instance 'ql-ecl:inet-socket :protocol :tcp :type :stream))) (ql-ecl:socket-connect socket endpoint port) (ql-ecl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation mkcl (let* ((endpoint (ql-mkcl:host-ent-address (ql-mkcl:get-host-by-name host))) (socket (make-instance 'ql-mkcl:inet-socket :protocol :tcp :type :stream))) (ql-mkcl:socket-connect socket endpoint port) (ql-mkcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation lispworks (ql-lispworks:open-tcp-stream host port :direction :io :errorp t :read-timeout nil :element-type '(unsigned-byte 8) :timeout 5)) (:implementation sbcl (let* ((endpoint (ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host))) (socket (make-instance 'ql-sbcl:inet-socket :protocol :tcp :type :stream))) (ql-sbcl:socket-connect socket endpoint port) (ql-sbcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full)))) (definterface read-octets (buffer connection) (:documentation "Read from CONNECTION into BUFFER. Returns the number of octets read.") (:implementation t (read-sequence buffer connection)) (:implementation allegro (ql-allegro:read-vector buffer connection)) (:implementation clisp (ql-clisp:read-byte-sequence buffer connection :no-hang nil :interactive t))) (definterface write-octets (buffer connection) (:documentation "Write the contents of BUFFER to CONNECTION.") (:implementation t (write-sequence buffer connection) (finish-output connection))) (definterface close-connection (connection) (:implementation t (ignore-errors (close connection)))) (definterface call-with-connection (host port fun) (:documentation "Establish a network connection to HOST on PORT and call FUN with that connection as the only argument. Unconditionally closes the connection afterwareds via CLOSE-CONNECTION in an unwind-protect. See also WITH-CONNECTION.") (:implementation t (let (connection) (unwind-protect (progn (setf connection (open-connection host port)) (funcall fun connection)) (when connection (close-connection connection)))))) (defmacro with-connection ((connection host port) &body body) `(call-with-connection ,host ,port (lambda (,connection) ,@body)))
5,625
Common Lisp
.lisp
129
29.612403
75
0.544278
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
357328ba3c3daa11d6163e12f3c3e1c9167e7ccd887f1068e70771be5a2b0362
30,457
[ 173134, 399982 ]
30,458
local-projects.lisp
johncorn271828_X_Orrery/quicklisp/local-projects.lisp
;;;; local-projects.lisp ;;; ;;; Local project support. ;;; ;;; Local projects can be placed in <quicklisp>/local-projects/. New ;;; entries in that directory are automatically scanned for system ;;; files for use with QL:QUICKLOAD. ;;; ;;; This works by keeping a cache of system file pathnames in ;;; <quicklisp>/local-projects/system-index.txt. Whenever the ;;; timestamp on the local projects directory is newer than the ;;; timestamp on the system index file, the entire tree is re-scanned ;;; and cached. ;;; ;;; This will pick up system files that are created as a result of ;;; creating new project directory in <quicklisp>/local-projects/, ;;; e.g. unpacking a tarball or zip file, checking out a project from ;;; version control, etc. It will NOT pick up a system file that is ;;; added sometime later in a subdirectory; for that, the ;;; REGISTER-LOCAL-PROJECTS function is needed to rebuild the system ;;; file index. ;;; ;;; In the event there are multiple systems of the same name in the ;;; directory tree, the one with the shortest pathname namestring is ;;; used. This is intended to ignore stuff like _darcs pristine ;;; directories. ;;; ;;; Work in progress! ;;; (in-package #:quicklisp-client) (defparameter *local-project-directories* (list (qmerge "local-projects/")) "The default local projects directory.") (defun system-index-file (pathname) "Return the system index file for the directory PATHNAME." (merge-pathnames "system-index.txt" pathname)) (defun local-project-system-files (pathname) "Return a list of system files under PATHNAME." (let* ((wild (merge-pathnames "**/*.asd" pathname)) (files (sort (directory wild) #'string< :key #'namestring))) (stable-sort files #'< :key (lambda (file) (length (namestring file)))))) (defun make-system-index (pathname) "Create a system index file for all system files under PATHNAME. Current format is one native namestring per line." (with-open-file (stream (system-index-file pathname) :direction :output :if-exists :rename-and-delete) (dolist (system-file (local-project-system-files pathname)) (let ((system-path (enough-namestring system-file pathname))) (write-line (native-namestring system-path) stream))) (probe-file stream))) (defun find-valid-system-index (pathname) "Find a valid system index file for PATHNAME; one that both exists and has a newer timestamp than PATHNAME." (let* ((file (system-index-file pathname)) (probed (probe-file file))) (when (and probed (<= (directory-write-date pathname) (file-write-date probed))) probed))) (defun ensure-system-index (pathname) "Find or create a system index file for PATHNAME." (or (find-valid-system-index pathname) (make-system-index pathname))) (defun find-system-in-index (system index-file) "If any system pathname in INDEX-FILE has a pathname-name matching SYSTEM, return its full pathname." (with-open-file (stream index-file) (loop for namestring = (read-line stream nil) while namestring when (string= system (pathname-name namestring)) return (truename (merge-pathnames namestring index-file))))) (defun local-projects-searcher (system-name) "This function is added to ASDF:*SYSTEM-DEFINITION-SEARCH-FUNCTIONS* to use the local project directory and cache to find systems." (dolist (directory *local-project-directories*) (when (probe-directory directory) (let ((system-index (ensure-system-index directory))) (when system-index (let ((system (find-system-in-index system-name system-index))) (when system (return system)))))))) (defun list-local-projects () "Return a list of pathnames to local project system files." (let ((result (make-array 16 :fill-pointer 0 :adjustable t)) (seen (make-hash-table :test 'equal))) (dolist (directory *local-project-directories* (coerce result 'list)) (let ((index (ensure-system-index directory))) (when index (with-open-file (stream index) (loop for line = (read-line stream nil) while line do (let ((pathname (merge-pathnames line index))) (unless (gethash (pathname-name pathname) seen) (setf (gethash (pathname-name pathname) seen) t) (vector-push-extend (merge-pathnames line index) result)))))))))) (defun register-local-projects () "Force a scan of the local projects directory to create the system file index." (map nil 'make-system-index *local-project-directories*)) (defun list-local-systems () "Return a list of local project system names." (mapcar #'pathname-name (list-local-projects)))
4,975
Common Lisp
.lisp
110
38.809091
73
0.673124
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
5e37b414d94cb8c4ffc0f33c7b386119bfbac0d735bcbd0ea8f701ed5ab3076c
30,458
[ 461280 ]
30,460
parse-number.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/parse-number-1.4/parse-number.lisp
;;;; -*- Mode: Lisp -*- ;;;; Defines functions to parse any number type, without using the reader ;;;; ;;;; Author: Matthew Danish -- mrd.debian.org ;;;; ;;;; Copyright 2002 Matthew Danish. ;;;; All rights reserved. ;;;; ;;;; Redistribution and use in source and binary forms, with or without ;;;; modification, are permitted provided that the following conditions ;;;; are met: ;;;; 1. Redistributions of source code must retain the above copyright ;;;; notice, this list of conditions and the following disclaimer. ;;;; 2. Redistributions in binary form must reproduce the above copyright ;;;; notice, this list of conditions and the following disclaimer in the ;;;; documentation and/or other materials provided with the distribution. ;;;; 3. Neither the name of the author nor the names of its contributors ;;;; may be used to endorse or promote products derived from this software ;;;; without specific prior written permission. ;;;; ;;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ;;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;;;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE ;;;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ;;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ;;;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ;;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ;;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF ;;;; SUCH DAMAGE. (defpackage #:org.mapcar.parse-number (:use #:common-lisp) (:nicknames #:parse-number) (:export #:parse-number #:parse-real-number #:parse-positive-real-number #:invalid-number #:invalid-number-value #:invalid-number-reason)) (in-package #:org.mapcar.parse-number) (define-condition invalid-number (parse-error) ((value :reader invalid-number-value :initarg :value :initform nil) (reason :reader invalid-number-reason :initarg :reason :initform "Not specified")) (:report (lambda (c s) (format s "Invalid number: ~S [Reason: ~A]" (invalid-number-value c) (invalid-number-reason c))))) (declaim (type cons *white-space-characters*)) (defparameter *white-space-characters* '(#\Space #\Tab #\Return #\Linefeed)) (declaim (inline white-space-p)) (defun white-space-p (x) (declare (optimize (speed 3) (safety 0)) (type character x)) (and (find x *white-space-characters*) t)) (declaim (inline parse-integer-and-places)) (defun parse-integer-and-places (string start end &key (radix 10)) (declare (optimize (speed 3) (safety 1)) (type string string) (type fixnum start end radix)) (multiple-value-bind (integer end-pos) (if (= start end) (values 0 0) (parse-integer string :start start :end end :radix radix)) ;; cl:parse-integer will consume trailing whitespace, thus end-pos may be ;; larger than the number of digits. Instead of trimming whitespace ;; beforehand we count it here (let ((relevant-digits (- end-pos start (loop :for pos :from (- end-pos 1) :downto start :while (member (char string pos) *white-space-characters*) :count 1)))) (cons integer relevant-digits)))) (defun parse-integers (string start end splitting-points &key (radix 10)) (declare (optimize (speed 3) (safety 1)) (type string string) (type fixnum start end radix)) (values-list (loop for left = start then (1+ right) for point in splitting-points for right = point collect (parse-integer-and-places string left right :radix radix) into integers finally (return (nconc integers (list (parse-integer-and-places string left end :radix radix ))))))) (declaim (inline number-value places)) (defun number-value (x) (car x)) (defun places (x) (cdr x)) ;; Numbers which could've been parsed, but intentionally crippled not to: ;; #xFF.AA ;; #o12e3 ;; Numbers which CL doesn't parse, but this does: ;; #10r3.2 ;; #2r 11 (defun parse-number (string &key (start 0) (end nil) (radix 10) ((:float-format *read-default-float-format*) *read-default-float-format*)) "Given a string, and start, end, and radix parameters, produce a number according to the syntax definitions in the Common Lisp Hyperspec." (flet ((invalid-number (reason) (error 'invalid-number :value (subseq string start end) :reason reason))) (let ((end (or end (length string)))) (if (and (eql (char string start) #\#) (member (char string (1+ start)) '(#\C #\c))) (let ((\(-pos (position #\( string :start start :end end)) (\)-pos (position #\) string :start start :end end))) (when (or (not \(-pos) (not \)-pos) (position #\( string :start (1+ \(-pos) :end end) (position #\) string :start (1+ \)-pos) :end end)) (invalid-number "Mismatched/missing parenthesis")) (let ((real-pos (position-if-not #'white-space-p string :start (1+ \(-pos) :end \)-pos))) (unless real-pos (invalid-number "Missing real part")) (let ((delimiting-space (position-if #'white-space-p string :start (1+ real-pos) :end \)-pos))) (unless delimiting-space (invalid-number "Missing imaginary part")) (let ((img-pos (position-if-not #'white-space-p string :start (1+ delimiting-space) :end \)-pos))) (unless img-pos (invalid-number "Missing imaginary part")) (let ((img-end-pos (position-if #'white-space-p string :start (1+ img-pos) :end \)-pos))) (complex (parse-real-number string :start real-pos :end delimiting-space :radix radix) (parse-real-number string :start img-pos :end (or img-end-pos \)-pos) :radix radix))))))) (parse-real-number string :start start :end end :radix radix))))) (defun parse-real-number (string &key (start 0) (end nil) (radix 10) ((:float-format *read-default-float-format*) *read-default-float-format*)) "Given a string, and start, end, and radix parameters, produce a number according to the syntax definitions in the Common Lisp Hyperspec -- except for complex numbers." (let ((end (or end (length string)))) (case (char string start) ((#\-) (* -1 (parse-positive-real-number string :start (1+ start) :end end :radix radix))) ((#\#) (case (char string (1+ start)) ((#\x #\X) (parse-real-number string :start (+ start 2) :end end :radix 16)) ((#\b #\B) (parse-real-number string :start (+ start 2) :end end :radix 2)) ((#\o #\O) (parse-real-number string :start (+ start 2) :end end :radix 8)) (t (if (digit-char-p (char string (1+ start))) (let ((r-pos (position #\r string :start (1+ start) :end end :key #'char-downcase))) (unless r-pos (error 'invalid-number :value (subseq string start end) :reason "Missing R in #radixR")) (parse-real-number string :start (1+ r-pos) :end end :radix (parse-integer string :start (1+ start) :end r-pos))))))) (t (parse-positive-real-number string :start start :end end :radix radix))))) (defun base-for-exponent-marker (char) (case char ((#\d #\D) 10.0d0) ((#\e #\E) (coerce 10 *read-default-float-format*)) ((#\f #\F) 10.0f0) ((#\s #\S) 10.0s0) ((#\l #\L) 10.0l0))) (defun make-float/frac (radix exp-marker whole-place frac-place exp-place) (let* ((base (base-for-exponent-marker exp-marker)) (exp (expt base (number-value exp-place)))) (+ (* exp (number-value whole-place)) (/ (* exp (number-value frac-place)) (expt (float radix base) (places frac-place)))))) (defun make-float/whole (exp-marker whole-place exp-place) (* (number-value whole-place) (expt (base-for-exponent-marker exp-marker) (number-value exp-place)))) (defun parse-positive-real-number (string &key (start 0) (end nil) (radix 10) ((:float-format *read-default-float-format*) *read-default-float-format*)) "Given a string, and start, end, and radix parameters, produce a number according to the syntax definitions in the Common Lisp Hyperspec -- except for complex numbers and negative numbers." (let ((end (or end (length string))) (first-char (char string start))) (flet ((invalid-number (reason) (error 'invalid-number :value (subseq string start end) :reason reason))) (case first-char ((#\-) (invalid-number "Invalid usage of -")) ((#\/) (invalid-number "/ at beginning of number")) ((#\d #\D #\e #\E #\l #\L #\f #\F #\s #\S) (when (= radix 10) (invalid-number "Exponent-marker at beginning of number")))) (let (/-pos .-pos exp-pos exp-marker) (loop for index from start below end for char = (char string index) do (case char ((#\/) (if /-pos (invalid-number "Multiple /'s in number") (setf /-pos index))) ((#\.) (if .-pos (invalid-number "Multiple .'s in number") (setf .-pos index))) ((#\e #\E #\f #\F #\s #\S #\l #\L #\d #\D) (when (= radix 10) (when exp-pos (invalid-number "Multiple exponent-markers in number")) (setf exp-pos index) (setf exp-marker (char-downcase char))))) when (eql index (1- end)) do (case char ((#\/) (invalid-number "/ at end of number")) ((#\d #\D #\e #\E #\s #\S #\l #\L #\f #\F) (when (= radix 10) (invalid-number "Exponent-marker at end of number"))))) (cond ((and /-pos .-pos) (invalid-number "Both . and / cannot be present simultaneously")) ((and /-pos exp-pos) (invalid-number "Both an exponent-marker and / cannot be present simultaneously")) ((and .-pos exp-pos) (if (< exp-pos .-pos) (invalid-number "Exponent-markers must occur after . in number") (if (/= radix 10) (invalid-number "Only decimal numbers can contain exponent-markers or decimal points") (multiple-value-bind (whole-place frac-place exp-place) (parse-integers string start end (list .-pos exp-pos) :radix radix) (make-float/frac radix exp-marker whole-place frac-place exp-place))))) (exp-pos (if (/= radix 10) (invalid-number "Only decimals can contain exponent-markers") (multiple-value-bind (whole-place exp-place) (parse-integers string start end (list exp-pos) :radix radix) (make-float/whole exp-marker whole-place exp-place)))) (/-pos (multiple-value-bind (numerator denominator) (parse-integers string start end (list /-pos) :radix radix) (if (>= (number-value denominator) 0) (/ (number-value numerator) (number-value denominator)) (invalid-number "Misplaced - sign")))) (.-pos (if (/= radix 10) (invalid-number "Only decimal numbers can contain decimal points") (multiple-value-bind (whole-part frac-part) (parse-integers string start end (list .-pos) :radix 10) (cond ((minusp (places frac-part)) (if (and (zerop (number-value whole-part)) (zerop (places whole-part))) (invalid-number "Only the . is present") (number-value whole-part))) ((>= (number-value frac-part) 0) (coerce (+ (number-value whole-part) (/ (number-value frac-part) (expt 10 (places frac-part)))) *read-default-float-format*)) (t (invalid-number "Misplaced - sign")))))) (t (values (parse-integer string :start start :end end :radix radix))))))))
12,822
Common Lisp
.lisp
325
31.704615
191
0.596474
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
d50f3dde8c9c80c7d1ff878c0cf32aebc966f6368a361235c979037246d62a6e
30,460
[ 146226 ]
30,461
release.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/trivial-features-20150923-git/release.lisp
#!/usr/bin/env clisp ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- (defpackage :release-script (:use #:cl #:regexp)) (in-package :release-script) ;;;; Configuration ------------------------------------------------------------ (defparameter *project-name* "trivial-features") (defparameter *asdf-file* (format nil "~A.asd" *project-name*)) (defparameter *host* "common-lisp.net") (defparameter *release-dir* (format nil "public_html/tarballs/~A/" *project-name*)) (defparameter *version-file* nil) (defparameter *version-file-dir* nil) ;;;; -------------------------------------------------------------------------- ;;;; Utilities (defun ensure-list (x) (if (listp x) x (list x))) (defmacro string-case (expression &body clauses) `(let ((it ,expression)) ; yes, anaphoric, deal with it. (cond ,@(loop for clause in clauses collect `((or ,@(loop for alternative in (ensure-list (first clause)) collect (or (eq t alternative) `(string= it ,alternative)))) ,@(rest clause)))))) (defparameter *development-mode* t) (defun die (format-control &rest format-args) (format *error-output* "~?" format-control format-args) (if *development-mode* (cerror "continue" "die") (ext:quit 1))) (defun numeric-split (string) (if (digit-char-p (char string 0)) (multiple-value-bind (number next-position) (parse-integer string :junk-allowed t) (cons number (when (< next-position (length string)) (numeric-split (subseq string next-position))))) (let ((next-digit-position (position-if #'digit-char-p string))) (if next-digit-position (cons (subseq string 0 next-digit-position) (numeric-split (subseq string next-digit-position))) (list string))))) (defun natural-string-< (s1 s2) (labels ((aux< (l1 l2) (cond ((null l1) (not (null l2))) ((null l2) nil) (t (destructuring-bind (x . xs) l1 (destructuring-bind (y . ys) l2 (cond ((and (numberp x) (stringp y)) t) ((and (numberp y) (stringp x)) nil) ((and (numberp x) (numberp y)) (or (< x y) (and (= x y) (aux< xs ys)))) (t (or (string-lessp x y) (and (string-equal x y) (aux< xs ys))))))))))) (aux< (numeric-split s1) (numeric-split s2)))) ;;;; Running commands (defparameter *dry-run* nil) (defun cmd? (format-control &rest format-args) (let ((cmd (format nil "~?" format-control format-args))) (with-open-stream (s1 (ext:run-shell-command cmd :output :stream)) (loop for line = (read-line s1 nil nil) while line collect line)))) ;; XXX: quote arguments. (defun cmd (format-control &rest format-args) (when *development-mode* (format *debug-io* "CMD: ~?~%" format-control format-args)) (let ((ret (ext:run-shell-command (format nil "~?" format-control format-args)))) (or (null ret) (zerop ret)))) (defun cmd! (format-control &rest format-args) (or (apply #'cmd format-control format-args) (die "cmd '~?' failed." format-control format-args))) (defun maybe-cmd! (format-control &rest format-args) (if *dry-run* (format t "SUPPRESSING: ~?~%" format-control format-args) (apply #'cmd! format-control format-args))) ;;;; (defun find-current-version () (subseq (reduce (lambda (x y) (if (natural-string-< x y) y x)) (cmd? "git tag -l v\\*")) 1)) (defun parse-version (string) (mapcar (lambda (x) (parse-integer x :junk-allowed t)) (loop repeat 3 ; XXX: parameterize for el in (regexp-split "\\." (find-current-version)) collect el))) (defun check-for-unrecorded-changes (&optional force) (unless (cmd "git diff --exit-code") (write-line "Unrecorded changes.") (if force (write-line "Continuing anyway.") (die "Aborting.~@ Use -f or --force if you want to make a release anyway.")))) (defun new-version-number-candidates (current-version) (let ((current-version (parse-version current-version))) (labels ((alternatives (before after) (when after (cons (append before (list (1+ (first after))) (mapcar (constantly 0) (rest after))) (alternatives (append before (list (first after))) (rest after)))))) (loop for alt in (alternatives nil current-version) collect (reduce (lambda (acc next) (format nil "~a.~a" acc next)) alt))))) (defun ask-user-for-version (current-version next-versions) (format *query-io* "Current version is ~A. Which will be the next one?~%" current-version) (loop for i from 1 and version in next-versions do (format *query-io* "~T~A) ~A~%" i version)) (format *query-io* "? ") (finish-output *query-io*) (nth (1- (parse-integer (read-line) :junk-allowed t)) next-versions)) (defun git-tag-tree (version) (write-line "Tagging the tree...") (maybe-cmd! "git tag \"v~A\"" version)) (defun add-version-to-system-file (version path-in path-out) (with-open-file (in path-in :direction :input) (with-open-file (out path-out :direction :output) (loop for line = (read-line in nil nil) while line do (write-line line out) when (string= #1="(defsystem " line :end2 (min (length #1#) (length line))) do (format out " :version ~s~%" version))))) (defun create-dist (version distname) (write-line "Creating distribution...") (cmd! "mkdir \"~a\"" distname) (cmd! "git archive master | tar xC \"~A\"" distname) (format t "Updating ~A with new version: ~A~%" *asdf-file* version) (let* ((asdf-file-path (format nil "~A/~A" distname *asdf-file*)) (tmp-asdf-file-path (format nil "~a.tmp" asdf-file-path))) (add-version-to-system-file version asdf-file-path tmp-asdf-file-path) (cmd! "mv \"~a\" \"~a\"" tmp-asdf-file-path asdf-file-path))) (defun tar-and-sign (distname tarball) (write-line "Creating and signing tarball...") (cmd! "tar czf \"~a\" \"~a\"" tarball distname) (cmd! "gpg -b -a \"~a\"" tarball)) (defparameter *remote-directory* (format nil "~A:~A" *host* *release-dir*)) (defun upload-tarball (tarball signature remote-directory) (write-line "Copying tarball to web server...") (maybe-cmd! "scp \"~A\" \"~A\" \"~A\"" tarball signature remote-directory) (format t "Uploaded ~A and ~A.~%" tarball signature)) (defun update-remote-links (tarball signature host release-dir project-name) (format t "Updating ~A_latest links...~%" project-name) (maybe-cmd! "ssh \"~A\" ln -sf \"~A\" \"~A/~A_latest.tar.gz\"" host tarball release-dir project-name) (maybe-cmd! "ssh \"~A\" ln -sf \"~A\" \"~A/~A_latest.tar.gz.asc\"" host signature release-dir project-name)) (defun upload-version-file (version version-file host version-file-dir) (format t "Uploading ~A...~%" version-file) (maybe-cmd! "echo -n \"~A\" > \"~A\"" version version-file) (maybe-cmd! "scp \"~A\" \"~A\":\"~A\"" version-file host version-file-dir) (maybe-cmd! "rm \"~A\"" version-file)) (defun maybe-clean-things-up (tarball signature) (when (y-or-n-p "Clean local tarball and signature?") (cmd! "rm \"~A\" \"~A\"" tarball signature))) (defun run (force version) (check-for-unrecorded-changes force) ;; figure out what version we'll be preparing. (unless version (let* ((current-version (find-current-version)) (next-versions (new-version-number-candidates current-version))) (setf version (or (ask-user-for-version current-version next-versions) (die "invalid selection."))))) (git-tag-tree version) (let* ((distname (format nil "~A_~A" *project-name* version)) (tarball (format nil "~A.tar.gz" distname)) (signature (format nil "~A.asc" tarball))) ;; package things up. (create-dist version distname) (tar-and-sign distname tarball) ;; upload. (upload-tarball tarball signature *remote-directory*) (update-remote-links tarball signature *host* *release-dir* *project-name*) (when *version-file* (upload-version-file version *version-file* *host* *version-file-dir*)) ;; clean up. (maybe-clean-things-up tarball signature) ;; documentation. ;; (write-line "Building and uploading documentation...") ;; (maybe-cmd! "make -C doc upload-docs") ;; push tags and any outstanding changes. (write-line "Pushing tags and changes...") (maybe-cmd! "git push --tags origin master"))) ;;;; Do it to it (let ((force nil) (version nil) (args ext:*args*)) (loop while args do (string-case (pop args) (("-h" "--help") (write-line "No help, sorry. Read the source.") (ext:quit 0)) (("-f" "--force") (setf force t)) (("-v" "--version") (setf version (pop args))) (("-n" "--dry-run") (setf *dry-run* t)) (t (die "Unrecognized argument '~a'" it)))) (run force version))
9,676
Common Lisp
.lisp
209
37.516746
83
0.57408
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
dfee06e578a57c09cc593a623e931251e48e0376951468923090ed79294dad01
30,461
[ 238487, 257480 ]
30,470
tf-ecl.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/trivial-features-20150923-git/src/tf-ecl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-ecl.lisp --- ECL implementation of trivial-features. ;;; ;;; Copyright (C) 2007-2009, 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) ;;;; Endianness (pushnew (let ((ptr (ffi:allocate-foreign-object :unsigned-short))) (unwind-protect (progn (setf (ffi:deref-pointer ptr :unsigned-short) #xfeff) (ecase (ffi:deref-pointer ptr :unsigned-byte) (#xfe (intern "BIG-ENDIAN" "KEYWORD")) (#xff (intern "LITTLE-ENDIAN" "KEYWORD")))) (ffi:free-foreign-object ptr))) *features*) ;;;; OS ;;; ECL already pushes :DARWIN, :LINUX, :UNIX (except on Darwin) and :BSD. #+darwin (pushnew :unix *features*) #+win32 (pushnew :windows *features*) ;;;; CPU ;;; FIXME: add more #+powerpc7450 (pushnew :ppc *features*) #+x86_64 (pushnew :x86-64 *features*) #+(or i386 i486 i586 i686) (pushnew :x86 *features*) #+(or armv5l armv6l armv7l) (pushnew :arm *features*) #+mipsel (pushnew :mips *features*)
2,185
Common Lisp
.lisp
47
42.659574
74
0.69061
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
1d63b75df82f02dceb3fc504ca35e8e0e3551df82deea683ec0672a6844913ad
30,470
[ 318414 ]
30,473
tf-clisp.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/trivial-features-20150923-git/src/tf-clisp.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-clisp.lisp --- CLISP trivial-features implementation. ;;; ;;; 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 :cl-user) ;;;; Endianness (pushnew (intern (symbol-name (if sys::*big-endian* '#:big-endian '#:little-endian)) '#:keyword) *features*) ;;;; OS ;;; CLISP already exports :UNIX. #+win32 (pushnew :windows *features*) #-win32 (eval-when (:compile-toplevel :load-toplevel :execute) (pushnew (with-standard-io-syntax (read-from-string (format nil ":~(~A~)" (posix:uname-sysname (posix:uname))))) *features*)) #+(or darwin freebsd netbsd openbsd) (pushnew :bsd *features*) ;;;; CPU ;;; FIXME: not complete (let ((cpu (cond ((or (member :pc386 *features*) (member (machine-type) '("x86" "x86_64") :test #'string-equal)) (if (member :word-size=64 *features*) '#:x86-64 '#:x86)) ((string= (machine-type) "POWER MACINTOSH") '#:ppc) ((or (member (machine-type) '("SPARC" "SPARC64") :test #'string-equal)) (if (member :word-size=64 *features*) '#:sparc64 '#:sparc))))) (when cpu (pushnew (intern (symbol-name cpu) '#:keyword) *features*)))
2,610
Common Lisp
.lisp
62
34.870968
74
0.615839
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
4667934e2c0d0afd03e317b7d909accb71ba7ca534ea5fff2ee6c323ced7cd60
30,473
[ 415066 ]
30,477
package.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/trivial-features-20150923-git/tests/package.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; package.lisp --- TRIVIAL-FEATURES-TESTS package definition. ;;; ;;; 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 :cl-user) (defpackage :trivial-features-tests (:use :common-lisp :regression-test :alexandria :cffi) (:export #:run))
1,448
Common Lisp
.lisp
32
43.3125
70
0.736917
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
98c50963c7b619a6206d6992f0cd52e00df4771b17bef537cb952b8fd0572523
30,477
[ 408313, 477316 ]
30,478
tests.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/trivial-features-20150923-git/tests/tests.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tests.lisp --- trivial-features tests. ;;; ;;; 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 :trivial-features-tests) (defun run () (let ((*package* (find-package :trivial-features-tests))) (do-tests) (null (regression-test:pending-tests)))) ;;;; Support Code #-windows (progn ;; Hmm, why not just use OSICAT-POSIX:UNAME? (defcfun ("uname" %uname) :int (buf :pointer)) ;; Get system identification. (defun uname () (with-foreign-object (buf '(:struct utsname)) (when (= (%uname buf) -1) (error "uname() returned -1")) (macrolet ((utsname-slot (name) `(foreign-string-to-lisp (foreign-slot-pointer buf 'utsname ',name)))) (values (utsname-slot sysname) ;; (utsname-slot nodename) ;; (utsname-slot release) ;; (utsname-slot version) (utsname-slot machine)))))) (defun mutually-exclusive-p (features) (= 1 (loop for feature in features when (featurep feature) count 1))) ;;;; Tests (deftest endianness.1 (with-foreign-object (p :uint16) (setf (mem-ref p :uint16) #xfeff) (ecase (mem-ref p :uint8) (#xfe (featurep :big-endian)) (#xff (featurep :little-endian)))) t) (defparameter *bsds* '(:darwin :netbsd :openbsd :freebsd)) (defparameter *unices* (list* :linux *bsds*)) #+windows (deftest os.1 (featurep (list* :or :unix *unices*)) nil) #-windows (deftest os.1 (featurep (make-keyword (string-upcase (uname)))) t) (deftest os.2 (if (featurep :bsd) (mutually-exclusive-p *bsds*) (featurep `(:not (:or ,@*bsds*)))) t) (deftest os.3 (if (featurep `(:or ,@*unices*)) (featurep :unix) t) t) (deftest os.4 (if (featurep :windows) (not (featurep :unix)) t) t) (deftest cpu.1 (mutually-exclusive-p '(:ppc :ppc64 :x86 :x86-64 :alpha :mips)) t) #+windows (deftest cpu.2 (case (get-system-info) (:intel (featurep :x86)) (:amd64 (featurep :x86-64)) (:ia64 nil) ; add this feature later! (t t)) t) #-windows (deftest cpu.2 (let ((machine (nth-value 1 (uname)))) (cond ((member machine '("x86" "x86_64") :test #'string=) (ecase (foreign-type-size :pointer) (4 (featurep :x86)) (8 (featurep :x86-64)))) (t (format *debug-io* "~&; NOTE: unhandled machine type, ~a, in CPU.2 test.~%" machine) t))) t) ;; regression test: sometimes, silly logic leads to pushing nil to ;; *features*. (deftest nil.1 (featurep nil) nil) (deftest nil.2 (featurep :nil) nil)
3,881
Common Lisp
.lisp
112
29.535714
77
0.634231
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
944cada3ff229d815c79c5be7924812a6e33f190bd78b5f3f8c12db399724dba
30,478
[ 30508, 332799 ]
30,480
package.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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. ;;; (defpackage #:cffi-grovel (:use #:common-lisp #:alexandria) (:import-from #:cffi-sys #:native-namestring) (:export ;; Class name #:grovel-file #:process-grovel-file ;; Error conditions #:grovel-error #:missing-definition) (:export ;; Class name #:wrapper-file #:process-wrapper-file))
1,520
Common Lisp
.lisp
38
38.052632
70
0.732613
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
91e4672c2de74b3f8979110c711e5ae1744d623483348f81011faba0cca998ff
30,480
[ 146293 ]
30,481
asdf.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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) (defun ensure-pathname (thing) (if (typep thing 'logical-pathname) (translate-logical-pathname thing) (pathname thing))) (defclass cc-flags-mixin () ((cc-flags :initform nil :accessor cc-flags-of :initarg :cc-flags))) (defmethod asdf:perform :around ((op asdf:compile-op) (file cc-flags-mixin)) (declare (ignorable op)) (let ((*cc-flags* (append (ensure-list (cc-flags-of file)) *cc-flags*))) (call-next-method))) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass process-op (#-asdf3 asdf:operation #+asdf3 asdf: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 (asdf: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 asdf:input-files ((op process-op) (c process-op-input)) (list (asdf:component-pathname c))) (defmethod asdf:component-depends-on ((op process-op) (c process-op-input)) `(#-asdf3 (asdf:load-op ,@(asdf::component-load-dependencies c)) #+asdf3 (asdf:prepare-op ,c) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:compile-op) (c process-op-input)) (declare (ignorable op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:load-source-op) (c process-op-input)) (declare (ignorable op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:perform ((op asdf:compile-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) (defmethod asdf:perform ((op asdf:load-source-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) ;;;# ASDF component: GROVEL-FILE (eval-when (:compile-toplevel :load-toplevel :execute) (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 asdf:output-files ((op process-op) (c grovel-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file))) (list output-file c-file (exe-filename c-file)))) (defmethod asdf:perform ((op process-op) (c grovel-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-grovel-file input-file output-file))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) ;;;# ASDF component: WRAPPER-FILE (eval-when (:compile-toplevel :load-toplevel :execute) (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) (asdf:component-name c))) (defmethod asdf:output-files ((op process-op) (c wrapper-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file)) (lib-soname (wrapper-soname c))) (list output-file c-file (lib-filename (make-soname lib-soname output-file))))) (defmethod asdf:perform ((op process-op) (c wrapper-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-wrapper-file input-file output-file (wrapper-soname c)))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) ;; Allow for naked :grovel-file and :wrapper-file in asdf definitions. (eval-when (:compile-toplevel :load-toplevel :execute) (setf (find-class 'asdf::cffi-grovel-file) (find-class 'grovel-file)) (setf (find-class 'asdf::cffi-wrapper-file) (find-class 'wrapper-file)))
7,356
Common Lisp
.lisp
146
44.171233
88
0.680301
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
76e4704841d30ea64abb154ac67259c27d9b69e4dbcbe7c71225603c722198c3
30,481
[ 489772 ]
30,490
package.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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 #: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 function operations. #:defcfun #:foreign-funcall #:foreign-funcall-pointer #: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-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 ))
4,795
Common Lisp
.lisp
157
25.611465
70
0.678124
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
4aa93329b1b5599b0c35d97b659d732db6da3c8c49d5ce85d5438a9fe596e27d
30,490
[ 367877 ]
30,492
types.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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 (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-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) ; XXX: skip for now. form ; use expand-into-foreign-memory when available. `(%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." (let* ((type (follow-typedefs (parse-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) "Copy elements from ptr into a Lisp array. If POINTER is a null pointer, returns NIL." (unless (null-pointer-p pointer) (let* ((type (follow-typedefs (parse-type array-type))) (el-type (element-type type)) (dimensions (dimensions type)) (array (make-array dimensions))) (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 (follow-typedefs (parse-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 (follow-typedefs (parse-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 (follow-typedefs (parse-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 (follow-typedefs (parse-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 (follow-typedefs (parse-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." `(setf (foreign-struct-slot-value ,ptr ',(slot-name slot)) ,value)) ;;;## 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))))) (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)) ;; determine offsets (dolist (slotdef slots) (destructuring-bind (slotname type &key (count 1) offset) slotdef (when (eq (canonicalize-foreign-type type) :void) (error "void type not allowed in structure definition: ~S" 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)) (notice-foreign-type name struct :struct)))) (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 (follow-typedefs (parse-type type))) (info (gethash slot-name (slots struct)))) (unless info (error "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))) (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: slot-name - in which case slot-name will be bound to the value of the slot or: (:pointer slot-name) - in which case slot-name will be bound to the pointer to that slot." (let ((ptr-var (gensym "PTR"))) `(let ((,ptr-var ,ptr)) (symbol-macrolet ,(loop :for var :in vars :collect (if (listp var) (if (eq (first var) :pointer) `(,(second var) (foreign-slot-pointer ,ptr-var ',type ',(second var))) (error "Malformed slot specification ~a; must be:`name' or `(:pointer name)'" var)) `(,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)) (dolist (slotdef slots) (destructuring-bind (slotname type &key (count 1)) slotdef (when (eq (canonicalize-foreign-type type) :void) (error "void type not allowed in union definition: ~S" 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) (notice-foreign-type name union :union)))) (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 #+darwin :int #-darwin :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) ;;; 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. (eval-when (:compile-toplevel :load-toplevel :execute) (macrolet ((match-types (sized-types mtypes) `(progn ,@(loop for (type . size-or-type) in sized-types for m = (car (member (if (keywordp size-or-type) (foreign-type-size size-or-type) size-or-type) mtypes :key #'foreign-type-size)) when m collect `(defctype ,type ,m))))) ;; 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))))
43,021
Common Lisp
.lisp
893
40.920493
93
0.649873
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
c0ac4e371ac873e229c5763f98edad892bcd27151b3c555305c30a98fe9101c5
30,492
[ 77112 ]
30,495
enum.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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) ;;;# 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 (foreign-typedef enhanced-foreign-type) ((keyword-values :initform (make-hash-table :test 'eq) :reader keyword-values) (value-keywords :initform (make-hash-table) :reader value-keywords)) (:documentation "Describes a foreign enumerated type.")) (defun make-foreign-enum (type-name base-type values) "Makes a new instance of the foreign-enum class." (let ((type (make-instance 'foreign-enum :name type-name :actual-type (parse-type base-type))) (default-value 0)) (dolist (pair values) (destructuring-bind (keyword &optional (value default-value)) (ensure-list pair) (check-type keyword keyword) (check-type value integer) (if (gethash keyword (keyword-values type)) (error "A foreign enum cannot contain duplicate keywords: ~S." keyword) (setf (gethash keyword (keyword-values type)) value)) ;; This is completely arbitrary behaviour: we keep the last we ;; 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 type)) keyword) (setq default-value (1+ value)))) type)) (defmacro defcenum (name-and-options &body enum-list) "Define an foreign enumerated type." (discard-docstring enum-list) (destructuring-bind (name &optional (base-type :int)) (ensure-list name-and-options) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-type ',name (make-foreign-enum ',name ',base-type ',enum-list))))) (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 (parse-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 keyword) (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 (parse-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 (parse-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 (keywordp value) (%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)) (%foreign-enum-keyword type value :errorp t)) (defmethod expand-to-foreign (value (type foreign-enum)) (once-only (value) `(if (keywordp ,value) (%foreign-enum-value ,type ,value :errorp t) ,value))) ;;;# 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-typedef enhanced-foreign-type) ((symbol-values :initform (make-hash-table :test 'eq) :reader symbol-values) (value-symbols :initform (make-hash-table) :reader value-symbols)) (:documentation "Describes a foreign bitfield type.")) (defun make-foreign-bitfield (type-name base-type values) "Makes a new instance of the foreign-bitfield class." (let ((type (make-instance 'foreign-bitfield :name type-name :actual-type (parse-type base-type))) (bit-floor 1)) (dolist (pair values) ;; bit-floor rule: find the greatest single-bit int used so far, ;; and store its left-shift (destructuring-bind (symbol &optional (value (prog1 bit-floor (setf bit-floor (ash bit-floor 1))) value-p)) (ensure-list pair) (check-type symbol symbol) (when value-p (check-type value integer) (when (and (>= value bit-floor) (single-bit-p value)) (setf bit-floor (ash value 1)))) (if (gethash symbol (symbol-values type)) (error "A foreign bitfield cannot contain duplicate symbols: ~S." symbol) (setf (gethash symbol (symbol-values type)) value)) (push symbol (gethash value (value-symbols type))))) type)) (defmacro defbitfield (name-and-options &body masks) "Define an foreign enumerated type." (discard-docstring masks) (destructuring-bind (name &optional (base-type :int)) (ensure-list name-and-options) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-type ',name (make-foreign-bitfield ',name ',base-type ',masks))))) (defun foreign-bitfield-symbol-list (bitfield-type) "Return a list of SYMBOLS defined in BITFIELD-TYPE." (hash-keys-to-list (symbol-values (parse-type bitfield-type)))) (defun %foreign-bitfield-value (type symbols) (reduce #'logior symbols :key (lambda (symbol) (check-type symbol symbol) (or (gethash symbol (symbol-values type)) (error "~S is not a valid symbol for bitfield type ~S." symbol type))))) (defun foreign-bitfield-value (type symbols) "Convert a list of symbols into an integer according to the TYPE bitfield." (let ((type-obj (parse-type type))) (if (not (typep type-obj 'foreign-bitfield)) (error "~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." (if (and (constantp type) (constantp symbols)) (let ((type-obj (parse-type (eval type)))) (if (not (typep type-obj 'foreign-bitfield)) (error "~S is not a foreign bitfield type." type) (%foreign-bitfield-value type-obj (eval symbols)))) form)) (defun %foreign-bitfield-symbols (type value) (check-type value integer) (loop for mask being the hash-keys in (value-symbols type) using (hash-value symbols) when (= (logand value mask) mask) append symbols)) (defun foreign-bitfield-symbols (type value) "Convert an integer VALUE into a list of matching symbols according to the bitfield TYPE." (let ((type-obj (parse-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." (if (and (constantp type) (constantp value)) (let ((type-obj (parse-type (eval type)))) (if (not (typep type-obj 'foreign-bitfield)) (error "~S is not a foreign bitfield type." type) `(quote ,(%foreign-bitfield-symbols type-obj (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))))
10,791
Common Lisp
.lisp
231
40.683983
77
0.677208
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
ae509ac1b412a8692c5d513dd87229d3e47a458ce0e565ebd051529605fee18b
30,495
[ 429628 ]
30,496
strings.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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))) (funcall (encoder mapping) string start end ptr 0) (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 ans should 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,271
Common Lisp
.lisp
276
40.09058
81
0.625713
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
5cdfe7a13ea3e8886b992a38c92d3408eabceb04431403450a0456af85caea2a
30,496
[ 371185, 445060 ]
30,497
utils.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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 &optional force) "Discards the first element of the list in body-var if it's a string and the only element (or if FORCE is T)." `(when (and (stringp (car ,body-var)) (or ,force (cdr ,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,914
Common Lisp
.lisp
77
41.805195
79
0.609922
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
32aeea86179937d693df57f60609f6de7359ec1c168c2f791154bd174aacbb75
30,497
[ 294180, 355619 ]
30,499
cffi-openmcl.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/src/cffi-openmcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cffi-openmcl.lisp --- CFFI-SYS implementation for OpenMCL. ;;; ;;; 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 #:ccl) (:import-from #:alexandria #:once-only #:if-let) (:export #:canonicalize-symbol-name-case #:foreign-pointer #:pointerp ; ccl: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 #:%foreign-symbol-pointer #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Misfeatures (pushnew 'flat-namespace *features*) ;;;# Symbol Case (defun canonicalize-symbol-name-case (name) (declare (string name)) (string-upcase name)) ;;;# 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." (ccl::malloc size)) (defun foreign-free (ptr) "Free a PTR allocated by FOREIGN-ALLOC." ;; TODO: Should we make this a dead macptr? (ccl::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)) (%stack-block ((,var ,size-var)) ,@body))) ;;;# Misc. Pointer Operations (deftype foreign-pointer () 'ccl:macptr) (defun null-pointer () "Construct and return a null pointer." (ccl:%null-ptr)) (defun null-pointer-p (ptr) "Return true if PTR is a null pointer." (ccl:%null-ptr-p ptr)) (defun inc-pointer (ptr offset) "Return a pointer OFFSET bytes past PTR." (ccl:%inc-ptr ptr offset)) (defun pointer-eq (ptr1 ptr2) "Return true if PTR1 and PTR2 point to the same address." (ccl:%ptr-eql ptr1 ptr2)) (defun make-pointer (address) "Return a pointer pointing to ADDRESS." (ccl:%int-to-ptr address)) (defun pointer-address (ptr) "Return the address pointed to by PTR." (ccl:%ptr-to-int ptr)) ;;;# 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))) (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body) "Bind PTR-VAR to a foreign pointer to the data in VECTOR." `(ccl:with-pointer-to-ivector (,ptr-var ,vector) ,@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)))) (define-mem-accessors (:char %get-signed-byte) (:unsigned-char %get-unsigned-byte) (:short %get-signed-word) (:unsigned-short %get-unsigned-word) (:int %get-signed-long) (:unsigned-int %get-unsigned-long) #+(or 32-bit-target windows-target) (:long %get-signed-long) #+(and (not windows-target) 64-bit-target) (:long ccl::%%get-signed-longlong) #+(or 32-bit-target windows-target) (:unsigned-long %get-unsigned-long) #+(and 64-bit-target (not windows-target)) (:unsigned-long ccl::%%get-unsigned-longlong) (:long-long ccl::%get-signed-long-long) (:unsigned-long-long ccl::%get-unsigned-long-long) (:float %get-single-float) (:double %get-double-float) (:pointer %get-ptr)) ;;;# Calling Foreign Functions (defun convert-foreign-type (type-keyword) "Convert a CFFI type keyword to an OpenMCL type." (ecase type-keyword (:char :signed-byte) (:unsigned-char :unsigned-byte) (:short :signed-short) (:unsigned-short :unsigned-short) (:int :signed-int) (:unsigned-int :unsigned-int) (:long :signed-long) (:unsigned-long :unsigned-long) (:long-long :signed-doubleword) (:unsigned-long-long :unsigned-doubleword) (:float :single-float) (:double :double-float) (:pointer :address) (:void :void))) (defun %foreign-type-size (type-keyword) "Return the size in bytes of a foreign type." (/ (ccl::foreign-type-bits (ccl::parse-foreign-type (convert-foreign-type type-keyword))) 8)) ;; There be dragons here. See the following thread for details: ;; http://clozure.com/pipermail/openmcl-devel/2005-June/002777.html (defun %foreign-type-alignment (type-keyword) "Return the alignment in bytes of a foreign type." (/ (ccl::foreign-type-alignment (ccl::parse-foreign-type (convert-foreign-type type-keyword))) 8)) (defun convert-foreign-funcall-types (args) "Convert foreign types for a call to FOREIGN-FUNCALL." (loop for (type arg) on args by #'cddr collect (convert-foreign-type type) if arg collect arg)) (defun convert-external-name (name) "Add an underscore to NAME if necessary for the ABI." #+darwin (concatenate 'string "_" name) #-darwin name) (defmacro %foreign-funcall (function-name args &key library convention) "Perform a foreign function call, document it more later." (declare (ignore library convention)) `(external-call ,(convert-external-name function-name) ,@(convert-foreign-funcall-types args))) (defmacro %foreign-funcall-pointer (ptr args &key convention) (declare (ignore convention)) `(ff-call ,ptr ,@(convert-foreign-funcall-types args))) ;;;# Callbacks ;;; The *CALLBACKS* hash table maps CFFI callback names to OpenMCL "macptr" ;;; entry points. It is safe to store the pointers directly because ;;; OpenMCL will update the address of these pointers when a saved image ;;; is loaded (see CCL::RESTORE-PASCAL-FUNCTIONS). (defvar *callbacks* (make-hash-table)) ;;; Create a package to contain the symbols for callback functions. We ;;; want to redefine callbacks with the same symbol so the internal data ;;; structures are reused. (defpackage #:cffi-callbacks (:use)) ;;; Intern a symbol in the CFFI-CALLBACKS package used to name the internal ;;; callback for NAME. (defun intern-callback (name) (intern (format nil "~A::~A" (if-let (package (symbol-package name)) (package-name package) "#") (symbol-name name)) '#:cffi-callbacks)) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (let ((cb-name (intern-callback name))) `(progn (defcallback ,cb-name (,@(when (eq convention :stdcall) '(:discard-stack-args)) ,@(mapcan (lambda (sym type) (list (convert-foreign-type type) sym)) arg-names arg-types) ,(convert-foreign-type rettype)) ,body) (setf (gethash ',name *callbacks*) (symbol-value ',cb-name))))) (defun %callback (name) (or (gethash name *callbacks*) (error "Undefined callback: ~S" name))) ;;;# Loading Foreign Libraries (defun %load-foreign-library (name path) "Load the foreign library NAME." (declare (ignore name)) (open-shared-library path)) (defun %close-foreign-library (name) "Close the foreign library NAME." ;; C-S-L sometimes ends in an endless loop ;; with :COMPLETELY T (close-shared-library name :completely nil)) (defun native-namestring (pathname) (ccl::native-translated-namestring pathname)) ;;;# Foreign Globals (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (foreign-symbol-address (convert-external-name name)))
10,662
Common Lisp
.lisp
269
35.211896
90
0.675589
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
6e55e786276d0fbabc999bf7807321f76a8cf38d3daa65ecda724010770061f6
30,499
[ 29660, 381656 ]
30,500
early-types.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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 *type-parsers* (make-hash-table :test 'equal) "Hash table of defined type parsers.") (defun find-type-parser (symbol &optional (namespace :default)) "Return the type parser for SYMBOL." (or (gethash (cons namespace symbol) *type-parsers*) (if (eq namespace :default) (error "unknown CFFI type: ~S." symbol) (error "unknown CFFI type: (~S ~S)." namespace symbol)))) (defun (setf find-type-parser) (func symbol &optional (namespace :default)) "Set the type parser for SYMBOL." (setf (gethash (cons namespace symbol) *type-parsers*) func)) ;;; 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 (eq (type-of 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) (let ((seen (make-hash-table :test 'eq))) (labels ((%check (cur-type) (when (typep cur-type 'foreign-typedef) (when (gethash (name cur-type) seen) (error "Detected cycle in type ~S." type)) (setf (gethash (name cur-type) seen) t) (%check (actual-type cur-type))))) (%check type)))) ;;; 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-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 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-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 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))) ;;;# 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))))
23,445
Common Lisp
.lisp
516
41.552326
108
0.716483
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
18378e9f89e36d20b834ea83661acfed7177ed7ecd3985305ea6dc3a969598e9
30,500
[ 382006 ]
30,504
functions.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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 (follow-typedefs (parse-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))) (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 '%foreign-funcall) ,thing ,(append (mapcan #'list (nconc fixed-ctypes (mapcar #'promote-varargs-type varargs-ctypes)) (append fixed-syms (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)))))) ;;; For now, the only difference between this macro and ;;; FOREIGN-FUNCALL is that it does argument promotion for that ;;; variadic argument. This could be useful to call an hypothetical ;;; %foreign-funcall-varargs on some hypothetical lisp on an ;;; hypothetical platform that has different calling conventions for ;;; varargs functions. :-) (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))
18,653
Common Lisp
.lisp
396
37.808081
173
0.624403
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
ee07bf6232f51a47e6e760d1324a15b727fd90781857683da758c09b3929eb4e
30,504
[ 407440 ]
30,505
libraries.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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)) #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 ((path (make-pathname :name framework-name :directory (append (pathname-directory directory) (list (format nil "~A.framework" framework-name)))))) (when (probe-file path) (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) (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-handle (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 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))))))) (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)) (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) "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)) (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 (filter-pathname name) 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))))))) (defun %do-load-foreign-library (library search-path) (flet ((%do-load (lib name spec) (when (foreign-library-spec lib) (with-slots (handle pathname) lib (setf (values handle pathname) (load-foreign-library-helper name spec (foreign-library-search-path lib))))) 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>)." (let ((library (filter-pathname library))) (restart-case (progn (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) 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))
18,386
Common Lisp
.lisp
402
38.303483
79
0.65085
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
09ce0e6a9ebf0b5759140053be4d9e37c8628be89559eb429eb0b7229fe0301e
30,505
[ 53333 ]
30,506
cffi-allegro.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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 :always) #+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,242
Common Lisp
.lisp
389
36.210797
80
0.658669
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
e64e1a22541a58e6dca707da6ae0ecc482cf801916b92e5bb33b24909b6bf270
30,506
[ 282195 ]
30,508
structures.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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))))))) (defun convert-into-foreign-memory (value type ptr) (let ((ptype (parse-type type))) (if (typep ptype 'foreign-built-in-type) value (translate-into-foreign-memory value ptype ptr))) ptr) (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,978
Common Lisp
.lisp
129
47.116279
328
0.67364
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
9e6ec89519b37c6720bee5b963a5985c1f7a27587db8c1c29d0320a06ad1be1e
30,508
[ 209912, 339716 ]
30,509
fsbv.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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)) (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) ;;; Call and return struct by value (deftest fsbv.2 (doublepair '(1 . 2)) (2 . 4)) ;;; return struct by value (deftest fsbv.makepair (makepair) (-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) ;;; Typedef fsbv test (defcfun ("sumpair" sumpair2) :int (p struct-pair-typedef1)) (deftest fsbv.5 (sumpair2 '(1 . 2)) 3) ;;; 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))
2,793
Common Lisp
.lisp
81
32.17284
70
0.706909
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
95c40aeafc1d92739e27b649044c57af8fd084f2d36ddc92e9f7dd7d980722df
30,509
[ 180184 ]
30,510
package.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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))
1,441
Common Lisp
.lisp
30
46.833333
70
0.737402
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
74766e403945b4bb8d5f299f409d9674de85e55611c78166ea83498e1e6c1047
30,510
[ 236263 ]
30,511
defcfun.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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 rt::*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 rt::*expected-failures*) (deftest defcfun.noop (noop) #|no values|#) ;;;# Calling varargs functions (defcfun "sprintf" :int "sprintf docstring" (str (:pointer :char)) (control :string) &rest) ;;; CLISP and ABCL discard macro docstrings. #+(or clisp abcl) (pushnew 'defcfun.varargs.docstrings rt::*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 "%.2f" :float (float pi))) "3.14") (deftest defcfun.varargs.double (with-foreign-pointer-as-string (s 100) (sprintf s "%.2f" :double (float pi 1.0d0))) "3.14") #+(and scl long-float) (deftest defcfun.varargs.long-double (with-foreign-pointer-as-string (s 100) (setf (mem-ref s :char) 0) (sprintf s "%.2Lf" :long-double pi)) "3.14") (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 cmu (and sbcl (or (not linkage-table) win32))) (pushnew 'defcfun.undefined rt::*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,360
Common Lisp
.lisp
428
40.929907
87
0.683565
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
daae6634a3e483bb834a682a6f5d9b23dd3316a974b06350f7813075be836ef3
30,511
[ 467317 ]
30,515
enum.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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) (defcenum numeros (: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 :int)) (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) ;;;# Bitfield tests ;;; Regression test: defbitfield was misbehaving when the first value ;;; was provided. (deftest bitfield.1 (eval '(defbitfield bf1 (:foo 0))) bf1) (defbitfield bf2 one two four eight sixteen 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)) (defbitfield bf3 (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 0) one) ;;; Yet another edge case with the 0... (deftest bitfield.4 (foreign-bitfield-value 'bf4 '(one)) 1) (deftest bitfield.4b (values (foreign-bitfield-symbols 'bf4 0) (foreign-bitfield-symbols 'bf4 1)) (zero) (zero one)) (deftest bitfield.translators (with-foreign-object (bf 'bf4 2) (setf (mem-aref bf 'bf4 0) 0) (setf (mem-aref bf 'bf4 1) 1) (values (mem-aref bf 'bf4 0) (mem-aref bf 'bf4 1))) (zero) (zero one))
3,406
Common Lisp
.lisp
112
27.098214
73
0.690476
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
2a9db3d22d9bac27ee15cafcdac24f2180bde8e46f818fc633f02939689bf5ca
30,515
[ 389394 ]
30,518
bindings.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/tests/bindings.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; libtest.lisp --- Setup CFFI bindings for libtest. ;;; ;;; 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) (define-foreign-library (libtest :type :test) (:darwin (:or "libtest.dylib" "libtest32.dylib")) (:unix (:or "libtest.so" "libtest32.so")) (:windows "libtest.dll") (t (:default "libtest"))) (define-foreign-library (libtest2 :type :test) (:darwin (:or "libtest2.dylib" "libtest2_32.dylib")) (:unix (:or "libtest2.so" "libtest2_32.so")) (t (:default "libtest2"))) (define-foreign-library (libfsbv :type :test) (:darwin (:or "libfsbv.dylib" "libfsbv32.dylib")) (:unix (:or "libfsbv.so" "libfsbv_32.so")) (:windows "libfsbv.dll") (t (:default "libfsbv"))) (define-foreign-library libc (:windows "msvcrt.dll")) (define-foreign-library libm #+(and lispworks darwin) ; not sure why the full path is necessary (:darwin "/usr/lib/libm.dylib") (t (:default "libm"))) (defun call-within-new-thread (fn &rest args) (let (result error (cv (bordeaux-threads:make-condition-variable)) (lock (bordeaux-threads:make-lock))) (bordeaux-threads:with-lock-held (lock) (bordeaux-threads:make-thread (lambda () (multiple-value-setq (result error) (ignore-errors (apply fn args))) (bordeaux-threads:with-lock-held (lock) (bordeaux-threads:condition-notify cv)))) (bordeaux-threads:condition-wait cv lock) (values result error)))) ;;; As of OSX 10.6.6, loading CoreFoundation on something other than ;;; the initial thread results in a crash. (deftest load-core-foundation (progn #+bordeaux-threads (call-within-new-thread 'load-foreign-library '(:framework "CoreFoundation")) t) t) ;;; Return the directory containing the source when compiling or ;;; loading this file. We don't use *LOAD-TRUENAME* because the fasl ;;; file may be in a different directory than the source with certain ;;; ASDF extensions loaded. (defun load-directory () (let ((here #.(or *compile-file-truename* *load-truename*))) (make-pathname :name nil :type nil :version nil :defaults here))) (defun load-test-libraries () (let ((*foreign-library-directories* (list (load-directory)))) (load-foreign-library 'libtest) (load-foreign-library 'libtest2) #+fsbv (load-foreign-library 'libfsbv) (load-foreign-library 'libc) #+(or abcl lispworks) (load-foreign-library 'libm))) #-(:and :ecl (:not :dffi)) (load-test-libraries) #+(:and :ecl (:not :dffi)) (ffi:load-foreign-library #.(make-pathname :name "libtest" :type "so" :defaults (or *compile-file-truename* *load-truename*))) ;;; check libtest version (defparameter *required-dll-version* "20120107") (defcvar "dll_version" :string) (unless (string= *dll-version* *required-dll-version*) (error "version check failed: expected ~s but libtest reports ~s" *required-dll-version* *dll-version*)) ;;; The maximum and minimum values for single and double precision C ;;; floating point values, which may be quite different from the ;;; corresponding Lisp versions. (defcvar "float_max" :float) (defcvar "float_min" :float) (defcvar "double_max" :double) (defcvar "double_min" :double) (defun run-cffi-tests (&key (compiled nil)) (let ((regression-test::*compile-tests* compiled) (*package* (find-package '#:cffi-tests))) (format t "~&;;; running tests (~Acompiled)" (if compiled "" "un")) (do-tests) (set-difference (regression-test:pending-tests) regression-test::*expected-failures*))) (defun run-all-cffi-tests () (append (run-cffi-tests :compiled nil) (run-cffi-tests :compiled t))) (defmacro expecting-error (&body body) `(handler-case (progn ,@body :no-error) (error () :error)))
5,039
Common Lisp
.lisp
118
38.779661
74
0.690942
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
643ca9a9588af26cfe0e6bb4a8be9a14689bdb0ac1989b1dbfa3d35dd1b436ee
30,518
[ 311354 ]
30,519
misc-types.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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)
8,802
Common Lisp
.lisp
239
32.828452
77
0.669998
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
fefa907ac0ed527e2aa1bccbef4871e7e251f787c0a5eb6e48ee1b1e43067751
30,519
[ 238425, 268175 ]
30,520
grovel.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/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")) 0 "test ") (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))))) (uiop:with-temporary-file (:stream grovel-stream :pathname grovel-file) ;; Write the grovel file (with-open-stream (*standard-output* grovel-stream) (write `(ctype ,base-type-name ,base-type)) (write `(,enum-type (,enum-name :base-type ,base-type-name) ((:value ,constant-name))))) ;; Get the value of :inaddr-broadcast (let ((lisp-file (cffi-grovel:process-grovel-file grovel-file))) (unwind-protect (progn (load lisp-file) (cffi:foreign-enum-value enum-name :value)) (uiop/filesystem:delete-file-if-exists lisp-file)))))) (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)
3,687
Common Lisp
.lisp
71
42.140845
114
0.606312
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
3b958f7cf8b788a046efa8bb440ca1abf84b9ed42d4aff2ac345724768159e7e
30,520
[ 46884 ]
30,525
cstruct.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/libffi/cstruct.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cstruct.lisp --- Hook to defcstruct ;;; ;;; 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) (defun slot-multiplicity (slot) (if (typep slot 'aggregate-struct-slot) (slot-count slot) 1)) (defun 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))) (defmethod libffi-type-pointer ((type foreign-struct-type)) (or (call-next-method) (set-libffi-type-pointer type (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 = (libffi-type-pointer (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)) (error "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) ;; The ffi-type (foreign-slot-value ptr '(:struct ffi-type) 'size) 0 (foreign-slot-value ptr '(:struct ffi-type) 'alignment) 0 (foreign-slot-value ptr '(:struct ffi-type) 'type) +type-struct+ (foreign-slot-value ptr '(:struct ffi-type) 'elements) type-pointer-array) ptr))))
3,068
Common Lisp
.lisp
70
35.285714
80
0.619238
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
21411743ca866bc2ed0cc4d802f2dc62feb6e9c91c2adedd2fc105059f9d1d1a
30,525
[ 166903 ]
30,526
built-in-types.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/libffi/built-in-types.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; built-in-types.lisp -- Define libffi-type-pointers for built-in types and typedefs ;;; ;;; 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) (defun set-libffi-type-pointer-for-built-in (type &optional (libffi-name type)) (set-libffi-type-pointer type (foreign-symbol-pointer (format nil "ffi_type_~(~a~)" libffi-name)))) ;;; Set the type pointers for non-integer built-in types (dolist (type (append *built-in-float-types* *other-builtin-types*)) (set-libffi-type-pointer-for-built-in type)) ;;; Set the type pointers for integer built-in types (dolist (type *built-in-integer-types*) (set-libffi-type-pointer-for-built-in type (format nil "~aint~d" (if (string-equal type "unsigned" :end1 (min 8 (length (string type)))) "u" "s") (* 8 (foreign-type-size type))))) ;;; Set the type pointer on demand for alias (e.g. typedef) types (defmethod libffi-type-pointer ((type foreign-type-alias)) (libffi-type-pointer (follow-typedefs type))) ;;; Luis thinks this is unnecessary; FOREIGN-ENUM inherits from FOREIGN-TYPE-ALIAS. #+(or) (defmethod libffi-type-pointer ((type foreign-enum)) (libffi-type-pointer (actual-type type)))
2,364
Common Lisp
.lisp
51
44.333333
86
0.731686
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
681d9e0266f75ebd076102754b09cde639ed4fc4ffe8f4e82b48d3893d9982ed
30,526
[ 26919 ]
30,527
libffi-unix.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/libffi/libffi-unix.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; libffi-unix.lisp -- libffi CFFI-Grovel definitions for unix systems. ;;; ;;; 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) #+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") (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"))) (cenum abi ((:default-abi "FFI_DEFAULT_ABI")) ((:sysv "FFI_SYSV")) ((:unix64 "FFI_UNIX64"))) (ctype ffi-abi "ffi_abi") (ctype :sizet "size_t") (ctype ushort "unsigned short") (ctype unsigned "unsigned") (cstruct ffi-type "struct _ffi_type" (size "size" :type :sizet) (alignment "alignment" :type ushort) (type "type" :type ushort) (elements "elements" :type :pointer)) #| ;;; Will not compile ;;; error: invalid application of `sizeof' to incomplete type `struct ffi_cif' ;;; When structs are defined with the name at the end, apparently they ;;; are intended to be "opaque types". (cstruct ffi-cif "struct ffi_cif" (abi "abi" :type ffi-abi) (nargs "nargs" :type unsigned) (arg-types "arg_types" :type :pointer) (return-type "rtype" :type :pointer) (bytes "bytes" :type :unsigned) (flags "flags" :type :unsigned)) |# (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,310
Common Lisp
.lisp
85
37.552941
78
0.706413
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
25721cb422a8e7369f5248b9a7364a9447df84c06bfaa871aa5c616a1e738a62
30,527
[ 405666 ]
30,528
functions.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/libffi/functions.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; functions.lisp -- Calling foreign functions ;;; ;;; 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) (defvar *cif-table* (make-hash-table :test 'equal) "A hash table of foreign functions and pointers to the foreign cif (Call InterFace) structure for that function.") (define-condition foreign-function-not-prepared (error) ((foreign-function-name :initarg :foreign-function-name :reader foreign-function-name)) (:report (lambda (condition stream) (format stream "Foreign function ~a did not prepare correctly" (foreign-function-name condition)))) (:documentation "Preparation of foreign function did not succeed, according to return from libffi library.")) (defun prepare-function (foreign-function-name return-type argument-types &optional (abi :default-abi)) "Generate or retrieve the CIF needed to call the function through libffi." (or (gethash foreign-function-name *cif-table*) (let* ((number-of-arguments (length argument-types)) (cif (foreign-alloc '(:struct ffi-cif))) (ffi-argtypes (foreign-alloc :pointer :count number-of-arguments))) (loop for type in argument-types for i from 0 do (setf (mem-aref ffi-argtypes :pointer i) (libffi-type-pointer (parse-type type)))) (unless (eql :OK (prep-cif cif abi number-of-arguments (libffi-type-pointer (parse-type return-type)) ffi-argtypes)) (error 'foreign-function-not-prepared :foreign-function-name foreign-function-name)) (setf (gethash foreign-function-name *cif-table*) cif) cif))) (defun unprepare-function (foreign-function-name) "Remove prepared definitions for the named foreign function. Returns foreign-function-name if function had been prepared, NIL otherwise." (let ((ptr (gethash foreign-function-name *cif-table*))) (when ptr (foreign-free (foreign-slot-value ptr '(:struct ffi-cif) 'argument-types)) (foreign-free ptr) (remhash foreign-function-name *cif-table*) foreign-function-name))) (defun translate-objects-ret (symbols function-arguments types return-type call-form) (if (eql return-type :void) (translate-objects symbols function-arguments types return-type call-form t) (if (typep (parse-type return-type) 'translatable-foreign-type) ;; just return the pointer so that expand-from-foreign ;; can apply translate-from-foreign (translate-objects symbols function-arguments types return-type call-form t) ;; built-in types won't be translated by ;; expand-from-foreign, we have to do it here `(mem-ref ,(translate-objects symbols function-arguments types return-type call-form t) ,(canonicalize-foreign-type return-type))))) (defun ffcall-body-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 ((number-of-arguments (length argument-types))) `(with-foreign-objects ((argvalues :pointer ,number-of-arguments) ,@(unless (eql return-type :void) `((result ',return-type)))) ,(translate-objects-ret symbols function-arguments types return-type `(progn (loop :for arg :in (list ,@symbols) :for count :from 0 :do (setf (mem-aref argvalues :pointer count) arg)) (call (prepare-function ,function ',return-type ',argument-types ',abi) ,(if pointerp function `(foreign-symbol-pointer ,function)) ,(if (eql return-type :void) '(null-pointer) 'result) argvalues) ,(if (eql return-type :void) '(values) 'result)))))) (setf *foreign-structures-by-value* 'ffcall-body-libffi) (pushnew :fsbv *features*)
5,276
Common Lisp
.lisp
105
42.961905
140
0.673964
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
e51ec5ab3df5c453dd8a64a6d32694a9cffbec31d28f7e2ad37c34d5965f701e
30,528
[ 41750 ]
30,529
cif.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/libffi/cif.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cif.lisp --- Structure and function call function in libffi ;;; ;;; 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) ;;; Structs (defcstruct ffi-cif (abi ffi-abi) (number-of-arguments unsigned) (argument-types :pointer) (return-type :pointer) (bytes unsigned) (flags unsigned)) ;;; Functions ;;; See file:///usr/share/doc/libffi-dev/html/The-Basics.html#The-Basics (defcfun ("ffi_prep_cif" prep-cif) status (ffi-cif :pointer) (ffi-abi abi) (nargs :uint) (rtype :pointer) (argtypes :pointer)) (defcfun ("ffi_call" call) :void (ffi-cif :pointer) (function :pointer) (rvalue :pointer) (avalues :pointer))
1,838
Common Lisp
.lisp
48
36.541667
72
0.733184
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
88010d06663f2c038cd1bfd31a206b31a2f3dcfef760dd7b46c71e7e1bf250e3
30,529
[ 399635 ]
30,530
libffi-win32.lisp
johncorn271828_X_Orrery/dists/quicklisp/software/cffi_0.16.1/libffi/libffi-win32.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; libffi-win32.lisp -- libffi CFFI-Grovel definitions for Windows. ;;; Note that despite the name, this includes 64 bit Windows as well as 32 bit. ;;; ;;; Copyright (C) 2009, 2010, 2011, 2012, 2015 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. ;;; ;; by CRLF0710, modified from Liam Healy 2009-02-22 09:24:33EST libffi-unix.lisp (in-package #:cffi) (pkg-config-cflags "libffi" :optional t) (include "ffi.h") (cenum status ((:OK "FFI_OK")) ((:bad-typedef "FFI_BAD_TYPEDEF")) ((:bad-abi "FFI_BAD_ABI"))) #+x86-64 (cenum abi ((:default-abi "FFI_DEFAULT_ABI")) ((:win64 "FFI_WIN64"))) #-x86-64 (cenum abi ((:default-abi "FFI_DEFAULT_ABI")) ((:sysv "FFI_SYSV")) ((:stdcall "FFI_STDCALL"))) (ctype ffi-abi "ffi_abi") (ctype :sizet "size_t") (ctype ushort "unsigned short") (ctype unsigned "unsigned") (cstruct ffi-type "struct _ffi_type" (size "size" :type :sizet) (alignment "alignment" :type ushort) (type "type" :type ushort) (elements "elements" :type :pointer)) (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"))
2,828
Common Lisp
.lisp
68
40.191176
86
0.712623
johncorn271828/X_Orrery
0
0
0
GPL-3.0
9/19/2024, 11:39:23 AM (Europe/Amsterdam)
accdf47333304f476c7101c170b12bea1f6a7e6247f21003d64a5bbc02384e61
30,530
[ 391010 ]