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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,025 | family-1-orig5.racer | lambdamikel_DLMAPS/src/query/test-cases/family-1-orig5.racer |
(in-knowledge-base family smith-family)
(signature :atomic-concepts (human person female male woman man
parent mother father
grandmother aunt uncle
sister brother
only-child)
:attributes ((cardinal age))
:roles ((has-descendant :transitive t)
(has-child :parent has-descendant
:inverse has-parent
:domain parent
:range person)
(has-sibling :domain (or sister brother)
:range (or sister brother))
(has-sister :parent has-sibling
:range (some has-gender female))
(has-brother :parent has-sibling
:range (some has-gender male))
(has-gender :feature t))
:features ((has-father :parent has-parent :range father)
(has-mother :parent has-parent :range mother))
;:individuals (alice betty charles doris eve)
)
(implies person (and human (some has-gender (or female male))))
(disjoint female male)
(implies woman (and person (some has-gender female)))
(implies man (and person (some has-gender male)))
(equivalent parent (and person (some has-child person)))
(equivalent mother (and woman parent))
(equivalent father (and man parent))
(equivalent grandmother
(and mother
(some has-child
(some has-child person))))
(equivalent aunt (and woman (some has-sibling parent)))
(equivalent uncle (and man (some has-sibling parent)))
(equivalent brother (and man (some has-sibling person)))
(equivalent sister (and woman (some has-sibling person)))
(instance alice mother)
(related alice betty has-child)
(related alice charles has-child)
(instance betty mother)
(related betty doris has-child)
(related betty eve has-child)
(instance charles brother)
(related charles betty has-sibling)
(related doris eve has-sister)
(related eve doris has-sister)
;;;
(related eve charles has-father)
(instance alice (= age 80))
(instance betty (= age 50))
(instance charles (= age 55))
(instance eve (= age 18))
(instance doris (= age 24))
(related betty alice has-mother)
(related charles alice has-mother)
(related doris betty has-mother)
(related eve betty has-mother)
(constrained alice alice-age age)
(constraints (= alice-age 80))
| 2,581 | Common Lisp | .l | 1 | 2,578 | 2,581 | 0.586982 | lambdamikel/DLMAPS | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 4dd0614f9bfed61775952363efdc235db3a810a12461a438beba3e4ad1b89417 | 13,025 | [
-1
] |
13,076 | package.lisp | GrammaTech_elf/package.lisp | ;; Copyright (C) 2011 Eric Schulte
(defpackage #:elf
(:use
:common-lisp
:alexandria
:com.gigamonkeys.binary-data
:metabang-bind
:split-sequence
#-ecl :trivial-shell
:cl-ppcre
:flexi-streams
)
(:shadow
:class
:get
:type
:rotate)
(:export
;; dynamic variables
:*calculate-edits* :*endian* :*class*
;; functions
:bytes-to-int :int-to-bytes
:bits-to-int :int-to-bits
:named-section :elf-p :elf-header
:get-endianness
:read-elf :write-elf
:show-dynamic :show-symbols :show-file-layout :show-memory-layout
:mapslots :generic-copy :copy-elf :named-symbol :symbols :dyn-symbols
:all-symbols
:file-offset-of-ea
;; Classes
:section
:section-header :section-header-32 :section-header-64
:elf-sym :elf-sym-32 :elf-sym-64
:program-header :program-header-32 :program-header-64
:elf-rel :elf-rel-32 :elf-rel-64
:elf-rela :elf-rela-32 :elf-rela-64
:elf-dyn :elf-dyn-32 :elf-dyn-64
;; Modification functions
:index-of-ea
:sections-holding-ea
:section-holding-ea
:subseq-ea
:word-at-ea
:bits-at-ea
:insert
:index-of-off
:sections-holding-off
:section-holding-off
:subseq-off
:word-at-off
;; disassembly functionality
:disassemblable :objdump :csurf :sw-project :disassemble-section
:elf-const :objdump-const
:objdump-cmd :objdump :parse-objdump-line :objdump-parse
:*single-value-objdump-hack*
:csurf-cmd
:csurf-script
;; methods
:un-type :ptr :val :binding :offset :vma
:size :type :flags :alignment :read-value :write-value
:address :link :info :addralign :entsize :vaddr :paddr
:filesz :memsz :align :sym-name :other :value :shndx :disasm
:rel-sym :rel-type :rel-info :magic-number :entry
;; section class
:elf :sh :ph :name :data
;; elf class
:header :section-table :program-table :sections :ordering
:instruction :opcode :operands
;; ARM
:arm-data
:arm-instruction
:to-bits :to-bytes :from-bits :from-bytes
:ldr/str
:ldm/stm
:bx
:b/bl
:data-processing
:make-arm-branch
:set-arm-branch
:make-arm-data-transfer
:set-arm-data-transfer
:make-arm-stack
:set-arm-stack
:make-arm-data-processing
:set-arm-data-processing
:make-arm-word
:set-arm-word
))
| 2,299 | Common Lisp | .lisp | 89 | 21.910112 | 72 | 0.683567 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 08c7a0c71944dffd0968d79327399d96cc0aafd09d455fe1e1b3a5bec8168150 | 13,076 | [
-1
] |
13,077 | util.lisp | GrammaTech_elf/util.lisp | ;;; util.lisp --- utility functions for elf.lisp
;; For information on the elf format see the following
;; http://www.muppetlabs.com/~breadbox/software/ELF.txt
;; Copyright (C) 2011-2013 Eric Schulte
;; Licensed under the Gnu Public License Version 3 or later
;;; Code:
(in-package :elf)
(defun indexed (sequence)
(loop for el in sequence as n from 0
collect (list n el)))
(defun chunks (list size)
"Return subsequent chunks of LIST of size SIZE."
(loop :for i :below (1+ (- (length list) size)) :by size :collect
(subseq list i (+ i size))))
#+sbcl
(locally (declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(sb-alien:define-alien-routine (#-win32 "tempnam" #+win32 "_tempnam" tempnam)
sb-alien:c-string
(dir sb-alien:c-string)
(prefix sb-alien:c-string)))
(defun temp-file-name ()
#+clisp
(let ((stream (gensym)))
(eval `(with-open-stream (,stream (ext:mkstemp nil))
(pathname ,stream))))
#+sbcl
(tempnam nil nil)
#+ccl
(ccl:temp-pathname)
#+allegro
(system:make-temp-file-name)
#+lispworks
(hcl:make-temp-file)
#-(or sbcl clisp ccl allegro lispworks)
(error "no temporary file backend for this lisp."))
(defmacro with-temp-file (file &rest body)
"SPEC is the variable used to reference the file w/optional extension.
After BODY is executed the temporary file is removed. Note that the
temporary file may have been created by `temp-file-name', so it should
be removed or overwritten in BODY if necessary."
`(let ((,file (temp-file-name)))
(unwind-protect (progn ,@body)
(when (probe-file ,file) (delete-file ,file)))))
(defun file-to-string (path)
(with-open-file (in path)
(let ((seq (make-string (file-length in))))
(read-sequence seq in)
seq)))
(defun shell (command)
#+ecl (ext:system command)
#+ccl (with-temp-file stdout-file
(with-temp-file stderr-file
(multiple-value-bind (stdout stderr errno)
;; Workaround Clozure bug with large outputs
;; by writing stdout/stderr to file and slurping
;; the file back up to return.
(shell-command (format nil "~a 1>~a 2>~a"
command
stdout-file stderr-file))
(declare (ignorable stdout stderr))
(values (file-to-string stdout-file)
(file-to-string stderr-file)
errno))))
#-(or ccl ecl) (shell-command command))
(defun trim (str &key (chars '(#\Space #\Tab #\Newline)))
(loop until (or (emptyp str) (not (member (aref str 0) chars)))
do (setf str (subseq str 1)))
(loop until (or (emptyp str) (not (member (aref str (1- (length str))) chars)))
do (setf str (subseq str 0 (1- (length str)))))
str)
;;; generic forensic functions over arbitrary objects
(defun my-slot-definition-name (el)
#+sbcl
(sb-mop::slot-definition-name el)
#+ccl
(ccl:slot-definition-name el)
#+ecl
(error "ECL does not support `my-slot-definition-name'")
#-(or sbcl ccl ecl)
(clos::slot-definition-name el))
(defun my-class-slots (el)
#+sbcl
(sb-mop::class-slots el)
#+ccl
(ccl:class-slots el)
#+ecl
(error "ECL does not support `my-class-slots'")
#-(or sbcl ccl ecl)
(clos::class-slots el))
(defun mapslots (func obj)
"Map func over the slots of the clos object OBJ."
(mapcar func
(mapcar #'my-slot-definition-name
(my-class-slots (class-of obj)))))
(defun generic-copy (obj &optional trace)
"A generic copy method, may run way too long on partially circular elements."
(let ((trace1 (concatenate 'list (list obj) trace)))
(cond
((or (numberp obj) (symbolp obj)) obj)
((stringp obj) (copy-seq obj))
((member obj trace) obj) ; don't follow circular structures
((or (listp obj) (vectorp obj))
(coerce (mapcar (lambda (el) (generic-copy el trace1)) (coerce obj 'list))
(cond ((listp obj) 'list) ((vectorp obj) 'vector))))
((my-class-slots (class-of obj))
(let ((new (make-instance (class-name (class-of obj)))))
(mapslots
(lambda (slot) (setf (slot-value new slot)
(generic-copy (slot-value obj slot) trace1)))
obj)
new))
(t (error "~&don't know how to copy ~a" obj)))))
(defun show-it (hd &key (out t))
"Print the fields of a elf, section or program header.
Optional argument OUT specifies an output stream."
(format (or out t) "~&")
(mapcar
(lambda (slot)
(let ((val (slot-value hd slot)))
(format out "~s:~a " slot val)
(list slot val)))
(mapcar #'my-slot-definition-name (my-class-slots (class-of hd)))))
(defun list-it (hd)
"Return the fields of an elf, section, or program header."
(show-it hd :out nil))
(defun equal-it (obj1 obj2 &optional trace)
"Equal over objects and lists."
(let ((trace1 (concatenate 'list (list obj1 obj2) trace)))
(cond
((or (member obj1 trace) (member obj2 trace)) t)
((or (and (listp obj1) (listp obj2)) (and (vectorp obj1) (vectorp obj2)))
(and (equal (length obj1) (length obj2))
(reduce (lambda (acc pair)
(and acc (equal-it (car pair) (cdr pair) trace1)))
(if (vectorp obj1)
(mapcar #'cons (coerce obj1 'list) (coerce obj2 'list))
(mapcar #'cons obj1 obj2))
:initial-value t)))
((my-class-slots (class-of obj1))
(reduce (lambda (acc slot)
(and acc (equal-it (slot-value obj1 slot) (slot-value obj2 slot)
trace1)))
(mapcar #'my-slot-definition-name
(my-class-slots (class-of obj1)))
:initial-value t))
(t (equal obj1 obj2)))))
(defun different-it (obj1 obj2 &optional trace)
(let ((trace1 (concatenate 'list (list obj1 obj2) trace)))
(cond
((or (member obj1 trace) (member obj2 trace)) t)
((or (and (vectorp obj1) (vectorp obj2))
(and (proper-list-p obj1) (proper-list-p obj2)))
(and (or (equal (length obj1) (length obj2))
(format t "~&different lengths ~a!=~a"
(length obj1) (length obj2)))
(reduce (lambda-bind (acc (i (a b)))
(and acc (or (different-it a b trace1)
(format t "~& at ~d ~a!=~a" i a b))))
(indexed
(if (vectorp obj1)
(mapcar #'list (coerce obj1 'list) (coerce obj2 'list))
(mapcar #'list obj1 obj2)))
:initial-value t)))
((and (consp obj1) (consp obj2))
(and (different-it (car obj1) (car obj2))
(different-it (cdr obj1) (cdr obj2))))
((my-class-slots (class-of obj1))
(reduce (lambda (acc slot)
(and acc (or (different-it
(slot-value obj1 slot) (slot-value obj2 slot)
trace1)
(format t "~& ~a" slot))))
(mapcar #'my-slot-definition-name
(my-class-slots (class-of obj1)))
:initial-value t))
(t (or (equal obj1 obj2) (format t "~&~a!=~a" obj1 obj2))))))
| 7,523 | Common Lisp | .lisp | 176 | 33.420455 | 81 | 0.570493 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 1a8066aad6c3a6d8c7e1c050c1e0d3d691b6d29fa27bc556bb9f7b48dc7640bf | 13,077 | [
-1
] |
13,078 | elf.lisp | GrammaTech_elf/elf.lisp | ;;; elf.lisp --- A Common Lisp library for manipulating ELF files
;; Copyright (C) 2011-2013 Eric Schulte
;; Licensed under the Gnu Public License Version 3 or later
;;; Commentary
;; See [ELF.txt](ELF.txt) for more information on the elf format.
;; Much of the code in `elf.lisp` is a direct translation of the elf
;; data structures described in the ELF.txt document augmented with
;; specific information translated from `/usr/include/elf.h`.
;;
;; Example Usage
;; =============
;;
;; load the elf library
;; ---------------------
;; First load the up the `elf` library.
;;
;; (require :elf)
;; (in-package :elf)
;;
;; create a simple elf binary and confirm it is an elf file
;; ---------------------------------------------------------
;; For the remainder of this example, we'll use a simple elf binary
;; executable named =hello=, compiled from the following C code.
;;
;; echo 'main(){puts("hello world");}'|gcc -x c - -o hello
;;
;; We can check that this is indeed an elf file by checking the magic
;; number at the start of the file.
;;
;; (elf-p "hello") ; => T
;;
;; We can also view an elf files header information without parsing
;; the entire file.
;;
;; (elf::show-it (elf-header "hello") :out nil)
;;
;; read an elf object, and view it's header information
;; ----------------------------------------------------
;; Then we read the binary file into an elf object.
;;
;; (defvar *elf* (read-elf "hello"))
;;
;; Using the `show-it` function from the elf package we can inspect
;; the header at the top of the elf file.
;;
;; (elf::show-it (header *elf*) :out nil)
;;
;; view section-table and program-table information
;; -------------------------------------------------
;; We can list the names of the sections of the elf file.
;;
;; (mapcar #'name (sections *elf*))
;; ;; => ("" ".interp" ".note.ABI-tag" ".note.gnu.build-id"...
;;
;; We can list the segments in the program table, and view both the
;; layout of the elements of the elf file, both in it's binary file
;; and when it is an executable image in memory.
;;
;; ;; looking at the program table
;; (mapc #'elf::show-it (program-table *elf*))
;; TYPE:PHDR FLAGS:5 OFFSET:64 VADDR:4194368 PADDR:4194368 FILE...
;; TYPE:INTERP FLAGS:4 OFFSET:512 VADDR:4194816 PADDR:4194816 F...
;; TYPE:LOAD FLAGS:5 OFFSET:0 VADDR:4194304 PADDR:4194304 FILES...
;; TYPE:LOAD FLAGS:6 OFFSET:1744 VADDR:6293200 PADDR:6293200 FI...
;; TYPE:DYNAMIC FLAGS:6 OFFSET:1768 VADDR:6293224 PADDR:6293224...
;; TYPE:NOTE FLAGS:4 OFFSET:540 VADDR:4194844 PADDR:4194844 FIL...
;; TYPE:GNU_EH_FRAME FLAGS:4 OFFSET:1472 VADDR:4195776 PADDR:41...
;; TYPE:GNU_STACK FLAGS:6 OFFSET:0 VADDR:0 PADDR:0 FILESZ:0 MEM...
;;
;; ;; view the contents of elf, as they exist in the file
;; (show-file-layout *elf*)
;; START OFFSET CONTENTS END
;; 0 NONE HEADER 64
;; 64 NONE PROGRAM-TABLE 512
;; 512 512 .interp 540
;; 540 540 .note.ABI-tag 572
;; 572 572 .note.gnu.build-id 608
;; 608 608 .gnu.hash 636
;; 636 NONE FILLER 640
;; 640 640 .dynsym 736
;; 736 736 .dynstr 797
;; ...
;;
;; ;; view the contents of elf, as they exist in the file
;; (show-memory-layout *elf*)
;; addr contents end
;; -------------------------------------
;; 0x400000 LOAD 0x4006CC
;; 0x400040 PHDR 0x400200
;; 0x400200 INTERP 0x40021C
;; 0x400200 .interp 0x40021C
;; 0x40021C NOTE 0x400260
;; 0x40021C .note.ABI-tag 0x40023C
;; ...
;;
;; write an elf object to disk
;; ----------------------------
;; We can write out the elf file to disk.
;;
;; ;; write out the elf file, the results should be identical to
;; ;; the original
;; (write-elf *elf* "hello2")
;;
;; The resulting file will be identical to the original file from
;; which the elf object was read.
;;
;; diff hello hello2
;;
;; manipulate the contents of an elf object
;; -----------------------------------------
;; We can manipulate these elf objects, and then write the results
;; back out to disk. For example we can change the code in the
;; `.text` section of the file, and then write the results back out to
;; disk.
;;
;; ;; change the .text section -- this doesn't break the program
;; (aref (data (named-section *elf* ".text")) 40) ; => 144
;; (setf (aref (data (named-section *elf* ".text")) 40) #xc3)
;; (aref (data (named-section *elf* ".text")) 40) ; => 195
;;
;; ;; When we write the modified elf to a file, the resulting file
;; ;; will be different than the original hello (in one byte) but
;; ;; will still execute since we changed a byte off of the
;; ;; execution path
;; (write-elf *elf* "hello2")
;;
;; Meta information like the relevant program and section headers, as
;; well as symbol information in the `.dynamic` section of the file
;; will be automatically updated.
;;
;; (let ((text (named-section *elf* ".text")))
;; (setf (data text)
;; (concatenate 'vector
;; (data text)
;; (make-array 16 :initial-element #x90))))
;; (write-elf *elf* "hello3")
;;
;; Note however that the resulting file will segfault on evaluation,
;; because even though the meta-data of the elf file is updated
;; automatically, there are hard-coded offsets and memory locations in
;; the compiled data contained in the elf file, which can not be
;; automatically updated.
;;; Code:
(in-package :elf)
;;; Basic Binary types
;; strings
(define-binary-type string (length)
(:reader (in)
(let ((string (make-string length)))
(dotimes (i length)
(setf (char string i) (code-char (read-byte in))))
string))
(:writer (out string)
(dotimes (i length)
(write-byte (char-code (char string i)) out))))
(define-binary-type terminated-string ()
(:reader (in)
(with-output-to-string (s)
(loop for char = (code-char (read-byte in))
until (char= char +null+) do (write-char char s))))
(:writer (out string)
(loop for char across string
do (write-byte (char-code char) out)
finally (write-byte (char-code +null+) out))))
;; raw bytes
(define-binary-type raw-bytes (length)
(:reader (in)
(let ((buf (make-array length :element-type '(unsigned-byte 8))))
(read-sequence buf in)
buf))
(:writer (out buf)
(write-sequence buf out)))
(define-binary-type raw-bits (length)
(:reader (in)
(let ((buf (make-array length :element-type '(unsigned-byte 1))))
(read-sequence buf in)
buf))
(:writer (out buf)
(write-sequence buf out)))
;; dictionaries
(defmacro define-elf-dictionary
(name num dictionary &key (signed nil) (class-dependent nil))
(let ((byte-form `(if ,class-dependent
(case *class*
(:32-bit ,num)
(:64-bit ,(* 2 num))
(t (error 'bad-elf-class :class *class*)))
,num)))
`(define-binary-type ,name ()
(:reader (in)
(let ((byte (bytes-from in ,byte-form ,signed)))
(or (cdr (assoc byte ',dictionary)) byte)))
(:writer (out val)
(bytes-to out ,byte-form
(if (numberp val)
val
(car (rassoc val ',dictionary))) ,signed)))))
(defmacro define-bit-dictionary (name num dictionary)
`(define-binary-type ,name ()
(:reader (in)
(let ((value
(bits-to-int
(let ((buf (make-array ,num
:element-type '(unsigned-byte 1))))
(read-sequence buf in)
buf))))
(or (cdr (assoc value ',dictionary)) value)))
(:writer (out val)
(write-sequence
(int-to-bits (if (numberp val)
val
(car (rassoc val ',dictionary))) ,num)
out))))
;; integers and bytes
(defvar *endian* :little
"Controls the endianness of how bytes are read.")
(defvar *class* nil
"Word size of the machine, (e.g. :32-bit or :64-bit).")
(define-condition bad-elf-class (error)
((class :initarg :class :reader class)))
(defun bytes-to-int (bytes &optional signed-p (byte-size 8) &aux steps)
(dotimes (n (length bytes)) (setf steps (cons (* n byte-size) steps)))
(unless (listp bytes) (setf bytes (coerce bytes 'list)))
(let ((value 0))
(mapc (lambda (bit b) (setf (ldb (byte byte-size bit) value) b))
(if (eq *endian* :little) (reverse steps) steps) bytes)
(if (and signed-p (> value (expt 2 (1- (* byte-size (length bytes))))))
(- (expt 2 (1- (* byte-size (length bytes)))) value)
value)))
(defun int-to-bytes (int size &optional signed-p (byte-size 8) &aux steps)
(dotimes (n size) (setf steps (cons (* n byte-size) steps)))
(let ((buf (make-array size
:element-type `(unsigned-byte ,byte-size)
:fill-pointer 0)))
(when (and signed-p (< int 0))
(setf int (+ (expt 2 (1- (* byte-size size))) (- 0 int))))
(mapc (lambda (bit) (vector-push (ldb (byte byte-size bit) int) buf))
(if (eq *endian* :little) (reverse steps) steps))
buf))
(defun bits-to-int (bits &optional signed-p)
(bytes-to-int bits signed-p 1))
(defun int-to-bits (byte size &optional signed-p)
(int-to-bytes byte size signed-p 1))
(defun bytes-from (in bytes &optional signed-p (byte-size 8))
(let ((buf (make-array bytes :element-type `(unsigned-byte ,byte-size))))
(read-sequence buf in)
(bytes-to-int (coerce buf 'list) signed-p)))
(defun bytes-to (out bytes value &optional signed-p (byte-size 8))
(write-sequence (int-to-bytes value bytes signed-p byte-size) out))
(define-binary-type unsigned-integer (bytes byte-size)
(:reader (in) (bytes-from in bytes nil (or byte-size 8)))
(:writer (out value) (bytes-to out bytes value nil (or byte-size 8))))
(define-binary-type signed-integer (bytes)
(:reader (in) (bytes-from in bytes 'signed))
(:writer (out value) (bytes-to out bytes value 'signed)))
(define-binary-type class-dependent-unsigned-integer (bytes)
(:reader (in)
(case *class*
(:32-bit (bytes-from in bytes))
(:64-bit (bytes-from in (* 2 bytes)))
(t (error 'bad-elf-class :class *class*))))
(:writer (out value)
(case *class*
(:32-bit (bytes-to out bytes value))
(:64-bit (bytes-to out (* 2 bytes) value))
(otherwise (error 'bad-elf-class :class *class*)))))
(define-binary-type class-dependent-signed-integer (bytes)
(:reader (in)
(case *class*
(:32-bit (bytes-from in bytes 'signed))
(:64-bit (bytes-from in (* 2 bytes) 'signed))
(t (error 'bad-elf-class :class *class*))))
(:writer (out value)
(case *class*
(:32-bit (bytes-to out bytes value 'signed))
(:64-bit (bytes-to out (* 2 bytes) value 'signed))
(otherwise (error 'bad-elf-class :class *class*)))))
(define-binary-type char () (unsigned-integer :bytes 1))
(define-binary-type half () (unsigned-integer :bytes 2))
(define-binary-type word () (unsigned-integer :bytes 4))
(define-binary-type sword () (signed-integer :bytes 4))
(define-binary-type addr () (class-dependent-unsigned-integer :bytes 4))
(define-binary-type off () (class-dependent-unsigned-integer :bytes 4))
(define-binary-type xword () (class-dependent-unsigned-integer :bytes 4))
(define-binary-type sxword () (class-dependent-signed-integer :bytes 4))
;; ELF dictionaries -- ELF header
(define-elf-dictionary elf-type 2
((0 . :none)
(1 . :relocatable)
(2 . :executable)
(3 . :shared-object)
(4 . :core)))
(define-elf-dictionary elf-machine 2
((0 . :none)
(1 . :m32)
(2 . :sparc)
(3 . :386)
(4 . :68k)
(5 . :88k)
(7 . :860)
(8 . :mips)
(9 . :s370)
(10 . :mips_rs3_le)
(15 . :parisc)
(17 . :vpp500)
(18 . :sparc32plus)
(19 . :960)
(20 . :ppc)
(21 . :ppc64)
(22 . :s390)
(36 . :v800)
(37 . :fr20)
(38 . :rh32)
(39 . :rce)
(40 . :arm)
(41 . :fake_alpha)
(42 . :sh)
(43 . :sparcv9)
(44 . :tricore)
(45 . :arc)
(46 . :h8_300)
(47 . :h8_300h)
(48 . :h8s)
(49 . :h8_500)
(50 . :ia_64)
(51 . :mips_x)
(52 . :coldfire)
(53 . :68hc12)
(54 . :mma)
(55 . :pcp)
(56 . :ncpu)
(57 . :ndr1)
(58 . :starcore)
(59 . :me16)
(60 . :st100)
(61 . :tinyj)
(62 . :x86_64)
(63 . :pdsp)
(66 . :fx66)
(67 . :st9plus)
(68 . :st7)
(69 . :68hc16)
(70 . :68hc11)
(71 . :68hc08)
(72 . :68hc05)
(73 . :svx)
(74 . :st19)
(75 . :vax)
(76 . :cris)
(77 . :javelin)
(78 . :firepath)
(79 . :zsp)
(80 . :mmix)
(81 . :huany)
(82 . :prism)
(83 . :avr)
(84 . :fr30)
(85 . :d10v)
(86 . :d30v)
(87 . :v850)
(88 . :m32r)
(89 . :mn10300)
(90 . :mn10200)
(91 . :pj)
(92 . :openrisc)
(93 . :arc_a5)
(94 . :xtensa)
(95 . :num)))
(define-elf-dictionary elf-version 4
((0 . :invalid) (1 . :current)))
(let ((dictionary '((0 . :invalid) (1 . :32-bit) (2 . :64-bit))))
;; this special dictionary will set the value of the *class* special
;; variable as it reads the file class from the elf header
(define-binary-type elf-class ()
(:reader (in)
(let ((byte (bytes-from in 1)))
(setf *class* (or (cdr (assoc byte dictionary)) byte))))
(:writer (out val)
(let ((value (if (numberp val) val (car (rassoc val dictionary)))))
(bytes-to out 1 value)))))
;; section header table
(define-elf-dictionary sh-type 4
((0 . :null)
(1 . :progbits)
(2 . :symtab)
(3 . :strtab)
(4 . :rela)
(5 . :hash)
(6 . :dynamic)
(7 . :note)
(8 . :nobits)
(9 . :rel)
(10 . :shlib)
(11 . :dynsym)))
(define-elf-dictionary sh-flags 4
((1 . :writable)
(2 . :allocatable)
(4 . :executable))
:class-dependent t)
;; program header table
(define-elf-dictionary ph-type 4
((0 . :null)
(1 . :load)
(2 . :dynamic)
(3 . :interp)
(4 . :note)
(5 . :shlib)
(6 . :phdr)
(1685382480 . :gnu_eh_frame)
(1685382481 . :gnu_stack)
(1685382482 . :gnu_relro)
(1879048186 . :sunwbss)
(1879048187 . :sunwstack)))
;; .dynamic section tag
(define-elf-dictionary dyn-tag 4
((0 . :null)
(1 . :needed)
(2 . :pltrelsz)
(3 . :pltgot)
(4 . :hash)
(5 . :strtab)
(6 . :symtab)
(7 . :rela)
(8 . :relasz)
(9 . :relaent)
(10 . :strsz)
(11 . :syment)
(12 . :init)
(13 . :fini)
(14 . :soname)
(15 . :rpath)
(16 . :symbolic)
(17 . :rel)
(18 . :relsz)
(19 . :relent)
(20 . :pltrel)
(21 . :debug)
(22 . :textrel)
(23 . :jmprel))
:signed t :class-dependent t)
;;; Classes, readers and writers
(define-binary-class elf-header ()
(;; elf ident
(magic-number (string :length 4))
(file-class elf-class)
(data-encoding char)
(ident-version char)
(padding (raw-bytes :length 8))
(ei-size char)
;; elf header
(type elf-type)
(machine elf-machine)
(version elf-version)
(entry addr)
(phoff off)
(shoff off)
(flags word)
(eh-size half)
(ph-ent-size half)
(ph-num half)
(sh-ent-size half)
(sh-num half)
(sh-str-ind half)))
(defun elf-header-size ()
(case *class*
(:32-bit 52)
(:64-bit 64)
(otherwise (error 'bad-elf-class :class *class*))))
(define-binary-class section-header ()
((name word)
(type sh-type)
(flags sh-flags)
(address addr)
(offset off)
(size xword)
(link word)
(info word)
(addralign xword)
(entsize xword)))
;; Program Header flag permissions
;;
(defvar pf-x #x1 "Program header flag execute bit.")
(defvar pf-w #x2 "Program header flag write bit.")
(defvar pf-r #x3 "Program header flag read bit.")
(defvar pf-maskos #x0ff00000 "Program header flag Unspecified bit.")
(defvar pf-maskproc #xf0000000 "Program header flag Unspecified bit.")
;;
;; Possible values and meanings.
;;
;; | Flags | Value | Exact | Allowable |
;; |----------------+-------+----------------------+----------------------|
;; | none | 0 | All access denied | All access denied |
;; | PF_X | 1 | Execute only | Read, execute |
;; | PF_W | 2 | Write only | Read, write, execute |
;; | PF_W+PF_X | 3 | Write, execute | Read, write, execute |
;; | PF_R | 4 | Read only | Read, execute |
;; | PF_R+PF_X | 5 | Read, execute | Read, execute |
;; | PF_R+PF_W | 6 | Read, write | Read, write, execute |
;; | PF_R+PF_W+PF_X | 7 | Read, write, execute | Read, write, execute |
(define-binary-class program-header-32 ()
((type ph-type)
(offset off)
(vaddr addr)
(paddr addr)
(filesz word)
(memsz word)
(flags word)
(align word)))
(define-binary-class program-header-64 ()
((type ph-type)
(flags word)
(offset off)
(vaddr addr)
(paddr addr)
(filesz xword)
(memsz xword)
(align xword)))
(defun program-header-type ()
"Return the appropriate type of program header given the value of *CLASS*."
(case *class*
(:32-bit 'program-header-32)
(:64-bit 'program-header-64)
(otherwise (error 'bad-elf-class :class *class*))))
(defclass elf-rel () ())
(define-binary-class elf-rel-32 (elf-rel)
((offset addr)
(info word)))
(define-binary-class elf-rel-64 (elf-rel)
((offset addr)
(info xword)))
(defun elf-rel-type ()
"Return the appropriate type of elf relocation given the value of *CLASS*."
(case *class*
(:32-bit 'elf-rel-32)
(:64-bit 'elf-rel-64)
(otherwise (error 'bad-elf-class :class *class*))))
(defgeneric rel-sym (rel)
(:documentation "Shift bits in REL based on its class."))
(defmethod rel-sym ((rel elf-rel))
(ash (info rel)
(ecase (class-name (class-of rel))
((elf-rel-32 elf-rela-32) -8)
((elf-rel-64 elf-rela-64) -32))))
(defvar rel-types
'((:386
(0 . :none)
(1 . :32)
(2 . :pc32)
(3 . :got32)
(4 . :plt32)
(5 . :copy)
(6 . :glob-dat)
(7 . :jmp-slot)
(8 . :relative)
(9 . :gotoff)
(10 . :gotpc))
(:x86_64
(0 . :none)
(1 . :32)
(2 . :pc32)
(3 . :got32)
(4 . :plt32)
(5 . :copy)
(6 . :glob_dat)
(7 . :jmp_slot)
(8 . :relative)
(9 . :gotoff)
(10 . :gotpc)
(11 . :32plt)
(14 . :tls_tpoff)
(15 . :tls_ie)
(16 . :tls_gotie)
(17 . :tls_le)
(18 . :tls_gd)
(19 . :tls_ldm)
(20 . :16)
(21 . :pc16)
(22 . :8)
(23 . :pc8)
(24 . :tls_gd_32)
(25 . :tls_gd_push)
(26 . :tls_gd_call)
(27 . :tls_gd_pop)
(28 . :tls_ldm_32)
(29 . :tls_ldm_push)
(30 . :tls_ldm_call)
(31 . :tls_ldm_pop)
(32 . :tls_ldo_32)
(33 . :tls_ie_32)
(34 . :tls_le_32)
(35 . :tls_dtpmod32)
(36 . :tls_dtpoff32)
(37 . :tls_tpoff32)
(39 . :tls_gotdesc)
(40 . :tls_desc_call)
(41 . :tls_desc)
(42 . :irelative)
(43 . :num)))
"Association list of type meaning by machine type.")
(defgeneric rel-type (rel header)
(:documentation "The interpretation of the type is machine specific."))
(defmethod rel-type ((rel elf-rel) (header elf-header))
(let ((val (logand (info rel)
(ecase (class-name (class-of rel))
((elf-rel-32 elf-rela-32) #xff)
((elf-rel-64 elf-rela-64) #xffffffff)))))
(flet ((get (item lst) (cdr (assoc item lst))))
(or (get val (get (machine header) rel-types)) val))))
(defun rel-info (sym type)
"Convert a symbol and type back into the info field of an elf-rel."
(case *class*
(:32-bit (+ (ash sym 8) (logand type #xff)))
(:64-bit (+ (ash sym 32) type))
(otherwise (error 'bad-elf-class :class *class*))))
(define-binary-class elf-rela-32 (elf-rel)
((offset addr)
(info word)
(addend sword)))
(define-binary-class elf-rela-64 (elf-rel)
((offset addr)
(info xword)
(addend sxword)))
(defun elf-rela-type ()
"Return type of elf relocation (w/addend) given the value of *CLASS*."
(case *class*
(:32-bit 'elf-rela-32)
(:64-bit 'elf-rela-64)
(otherwise (error 'bad-elf-class :class *class*))))
(defclass elf-sym ()
((sym-name :initform nil :accessor sym-name)))
(define-binary-class elf-sym-32 (elf-sym)
((name word)
(value addr)
(size word)
(info char)
(other char)
(shndx half)))
(define-binary-class elf-sym-64 (elf-sym)
((name word)
(info char)
(other char)
(shndx half)
(value addr)
(size xword)))
(defun elf-sym-type ()
"Return the appropriate type of elf symbol given the value of *CLASS*."
(case *class*
(:32-bit 'elf-sym-32)
(:64-bit 'elf-sym-64)
(otherwise (error 'bad-elf-class :class *class*))))
(defun name-symbols (sec)
"Assign names to the symbols contained in SEC."
(when (member (type sec) '(:symtab :dynsym))
(with-slots (elf sh type) sec
(let* ((name-sec (nth (link sh) (sections elf)))
(tab (coerce (data name-sec) 'list)))
(mapcar (lambda (sym)
(setf (sym-name sym)
(coerce (loop for code in (subseq tab (name sym))
until (equal code 0)
collect (code-char code))
'string)))
(data sec))))))
(defclass elf-dyn () ())
(define-binary-class elf-dyn-32 (elf-dyn)
((tag dyn-tag)
(un (raw-bytes :length 4))))
(define-binary-class elf-dyn-64 (elf-dyn)
((tag dyn-tag)
(un (raw-bytes :length 8))))
(defun elf-dyn-type ()
"Return the appropriate type of dynamic symbol given the value of *CLASS*."
(case *class*
(:32-bit 'elf-dyn-32)
(:64-bit 'elf-dyn-64)
(otherwise (error 'bad-elf-class :class *class*))))
;;; TODO: implement a type for elements of the .plt table
;;; (similar to what's currently used to parse data for .dynsym)
(defgeneric word-size (dyn)
(:documentation "Return the word size for the given class."))
(defmethod word-size ((dyn elf-dyn-32)) 4)
(defmethod word-size ((dyn elf-dyn-64)) 8)
(defgeneric un-type (dyn))
(defmethod un-type ((dyn elf-dyn))
(let ((val (list :pltrel :relent :relsz :rpath :soname :syment
:strsz :relaent :relasz :pltrelsz :needed))
(ptr (list :pltgot :hash :strtab :symtab :rela :init
:fini :rel :debug :jmprel))
(ignored (list :null :symbolic :textrel)))
(cond ((member (tag dyn) val) :val)
((member (tag dyn) ptr) :ptr)
((member (tag dyn) ignored) :ignored))))
(defgeneric ptr (dyn))
(defmethod ptr ((dyn elf-dyn))
(when (equal (un-type dyn) :ptr) (bytes-to-int (un dyn))))
(defgeneric (setf ptr) (new dyn))
(defmethod (setf ptr) (new (dyn elf-dyn))
(if (equal :ptr (un-type dyn))
(setf (un dyn) (coerce (int-to-bytes new (word-size dyn)) 'vector))
(error "Can't set ptr for dynamic section of type ~a" (tag dyn))))
(defgeneric val (dyn))
(defmethod val ((dyn elf-dyn))
(when (equal (un-type dyn) :val) (bytes-to-int (un dyn) 'signed)))
(defgeneric (setf val) (new dyn))
(defmethod (setf val) (new (dyn elf-dyn))
(if (equal :val (un-type dyn))
(setf (un dyn) (coerce (int-to-bytes
new (word-size dyn) 'signed) 'vector))
(error "Can't set val for dynamic section of type ~a" (tag dyn))))
(defun dynamic-entry (sec)
"Return the entry in .dynamic associated with SEC."
(let* ((tags (dolist (dyn (data (named-section (elf sec) ".dynamic")))
(when (keywordp (tag dyn))
(cons (symbol-name (tag dyn)) dyn))))
(dyn (cdr (assoc (string-upcase (subseq (name sec) 1))
tags :test #'string=))))
(when (and dyn (equal (vma sec) (ptr dyn))) dyn)))
(defgeneric binding (sym))
(defmethod binding ((symbol elf-sym))
(ecase (ash (info symbol) -4)
(0 :LOCAL)
(1 :GLOBAL)
(2 :WEAK)
(10 :LOOS)
(12 :HIOS)
(13 :LOPROC)
(15 :HIPROC)))
(defmethod (setf binding) (new (symbol elf-sym))
(setf (info symbol)
(+ (ash (ecase new
(:LOCAL 0)
(:GLOBAL 1)
(:WEAK 2)
(:LOOS 10)
(:HIOS 12)
(:LOPROC 13)
(:HIPROC 15)) 4)
(logand (info symbol) #xf))))
(defmethod type ((symbol elf-sym))
(ecase (logand (info symbol) #xf)
(0 :NOTYPE)
(1 :OBJECT)
(2 :FUNC)
(3 :SECTION)
(4 :FILE)
(5 :COMMON)
(10 :LOOS)
(12 :HIOS)
(13 :LOPROC)
(15 :HIPROC)))
(defmethod (setf type) (new (symbol elf-sym))
(setf (info symbol)
(+ (ash (info symbol) -4)
(logand (ecase new
(:NOTYPE 0)
(:OBJECT 1)
(:FUNC 2)
(:SECTION 3)
(:FILE 4)
(:COMMON 5)
(:LOOS 10)
(:HIOS 12)
(:LOPROC 13)
(:HIPROC 15)) #xf))))
(defclass section ()
((elf :initarg :elf :accessor elf)
(sh :initarg :sh :accessor sh)
(ph :initarg :ph :accessor ph)
(name :initarg :name :accessor name)
(data :initarg :data :reader data :writer set-data)))
(defmethod print-object ((section section) stream)
(print-unreadable-object (section stream :type t)
(with-slots (name) section
(format stream "~S" name)))
section)
(defmethod offset ((sec section))
(offset (or (sh sec) (ph sec))))
(defmethod (setf offset) (new (sec section))
(if (sh sec)
(progn
(setf (offset (sh sec)) new)
(when (and (ph sec) (= (offset sec) (offset (ph sec))))
(setf (offset (ph sec)) new)))
(setf (offset (ph sec)) new)))
(defgeneric vma (section)
(:documentation "Return the virtual memory address for SECTION."))
(defmethod vma ((sec section))
(when (ph sec) (+ (vaddr (ph sec)) (- (offset sec) (offset (ph sec))))))
(defgeneric (setf vma) (new section))
(defmethod (setf vma) (new (sec section))
(declare (ignorable new))
(error "Don't set the VMA, this is calculated from the ph and offset."))
(defmethod size ((sec section))
(if (sh sec) (size (sh sec)) (filesz (ph sec))))
(defmethod (setf size) (new (sec section))
(let ((delta (- new (size sec))))
(when (sh sec)
(setf (size (sh sec)) new))
(when (ph sec)
;; TODO: probably need a better test here at some point
(when (= (filesz (ph sec)) (memsz (ph sec)))
(setf (memsz (ph sec)) (+ delta (memsz (ph sec)))))
(setf (filesz (ph sec)) (+ delta (filesz (ph sec)))))))
(defmethod type ((sec section))
(type (or (sh sec) (ph sec))))
(defmethod (setf type) (new (sec section))
(if (sh sec)
(setf (type (sh sec)) new)
(setf (type (ph sec)) new)))
(defmethod flags ((sec section))
(flags (concatenate 'list (ph sec) (sh sec))))
(defmethod (setf flags) (new (sec section))
(declare (ignorable new))
(error "TODO: setting flags not yet implemented"))
(defgeneric alignment (section))
(defmethod alignment ((sec section))
(if (ph sec) (align (ph sec)) (addralign (sh sec))))
(defgeneric (setf alignment) (new section))
(defmethod (setf alignment) (new (sec section))
(declare (ignorable new))
(error "TODO: setting alignment is not yet implemented"))
(defclass elf ()
((header :initarg :header :accessor header)
(section-table :initarg :section-table :accessor section-table)
(program-table :initarg :program-table :accessor program-table)
;; This list holds the actual data sections of the ELF file. This
;; list is populated using the section-table if it exists or the
;; program-table otherwise.
(sections :initarg :sections :accessor sections)
;; The ordering list is used to write a modified ELF file back to
;; disk. It includes the header, section-table, and program-table,
;; as well as all sections which contain data which lives in the
;; ELF file.
;;
;; Every element of ordering is of the form (offset size value)
;; where offset is the offset in the file at which the value should
;; be written, size indicates the size of the value, and value
;; indicates the value to be written. Value may be :header,
;; :section-table or :program-table to write the respective headers
;; or an index into the sections list to write the data of that
;; section.
;;
;; In some cases ELF files have sections with overlapping
;; representations in the file (e.g., because some program data
;; must start at offset 0 overlapping the elf header). In these
;; cases last section written will override previously written
;; sections, and the sections are written in the order they appear
;; in the ordering list.
;;
;; TODO: In those cases where multiple sections point to the same
;; file data, only one copy of the file data should exist,
;; and each section should point to the same copy (s.t.,
;; setting that data in one section will change it in all
;; sections). Ideally more specialized sections should have
;; priority in setting data.
(ordering :initarg :ordering :accessor ordering)))
(defun program-header-for-section (pt sec)
"Return the program header in PT associated with SEC.
Note: a section may be included in multiple program headers, but for
now lets just select the one with the tightest bounds on the
section (in the file)."
(first (sort (remove-if (complement (lambda (ph)
(and (>= (offset sec) (offset ph))
(< (+ (offset sec) (size sec))
(+ (offset ph) (filesz ph))))))
pt) (lambda (a b) (> (filesz a) (filesz b))))))
(defmethod read-value ((type (eql 'elf)) in &key)
(elf-read-value type in))
(defmethod read-value ((type (eql 'objdump)) in &key)
(elf-read-value type in))
(defmethod read-value ((type (eql 'csurf)) in &key)
(elf-read-value type in))
(defmethod read-value ((type (eql 'elf-const)) in &key)
(elf-read-value type in))
(defmethod read-value ((type (eql 'objdump-const)) in &key)
(elf-read-value type in))
(defun elf-read-value (type in)
;; Read an elf object from a binary input stream.
(flet ((raw-bytes (from size)
(file-position in from)
(read-value 'raw-bytes in :length size))
(range-minus (from take)
(cond
((or (< (cdr take) (car from)) ; no overlap
(> (car take) (cdr from)))
(list from))
((and (<= (car take) (car from)) ; from front
(<= (cdr take) (cdr from)))
(list (cons (cdr take) (cdr from))))
((and (>= (cdr take) (cdr from)) ; from back
(>= (car take) (car from)))
(list (cons (car from) (car take))))
((and (>= (car take) (car from)) ; from middle
(<= (cdr take) (cdr from)))
(list (cons (car from) (car take))
(cons (cdr take) (cdr from))))
((and (<= (car take) (car from)) ; complete overlap
(>= (cdr take) (cdr from)))
nil)
(:otherwise (error "bad range-minus ~S" (list from take))))))
(let ((e (make-instance type)))
(with-slots (header section-table program-table sections ordering) e
(setf header (elf-header-endianness-warn (read-value 'elf-header in))
program-table
(unless (zerop (phoff header))
(progn (file-position in (phoff header))
(loop for x from 0 to (1- (ph-num header))
collect
(read-value (program-header-type) in))))
section-table
(unless (zerop (shoff header))
(progn (file-position in (shoff header))
(loop for x from 0 to (1- (sh-num header))
collect (read-value 'section-header in)))))
;; initialize the list of sections
(let ((str-off (when (and section-table (sh-str-ind header))
(offset (nth (sh-str-ind header) section-table)))))
(flet ((header-to-section (h)
(let ((section (make-instance 'section)))
(with-slots (elf sh ph name data) section
(setf elf e)
(if section-table
(setf sh h
ph (program-header-for-section
program-table section))
(setf sh nil
ph h))
(setf name
(when str-off
(progn (file-position in (+ str-off (name h)))
(read-value 'terminated-string in))))
(setf
data ;; data can vary based on the specific section
(cond
((or (string= ".dynsym" name)
(string= ".symtab" name))
(file-position in (offset h))
(loop for x from 0 to (1- (/ (size h) (entsize h)))
collect (read-value (elf-sym-type) in)))
((string= ".dynamic" name)
(file-position in (offset h))
(loop for x from 0 to (1- (/ (size h) (entsize h)))
collect (read-value (elf-dyn-type) in)))
((equal :rel (type h))
(file-position in (offset h))
(loop for x from 0 to (1- (/ (size h) (entsize h)))
collect (read-value (elf-rel-type) in)))
((equal :rela (type h))
(file-position in (offset h))
(loop for x from 0 to (1- (/ (size h) (entsize h)))
collect (read-value (elf-rela-type) in)))
(t (raw-bytes (offset h) (size section))))))
section)))
(setf sections (mapcar #'header-to-section
(or section-table program-table)))))
;; compile the ordering of the sections
(let* ((parts (append
;; sections
(remove-if (lambda-bind ((offset size num))
(declare (ignorable num))
;; In the section table inconsequential
;; sections are indicated by having an
;; offset of 0, while in the program
;; table an offset of 0 is common, but
;; sections with 0 filesz may be ignored.
(zerop (if section-table offset size)))
(mapcar (lambda-bind ((num sec))
(list (offset sec) (size sec) num))
(indexed sections)))
;; special parts
(list (list 0 (elf-header-size) :header))
(unless (zerop (shoff header))
(list (list (shoff header)
(* (sh-num header) (sh-ent-size header))
:section-table)))
(unless (zerop (phoff header))
(list (list (phoff header)
(* (ph-num header) (ph-ent-size header))
:program-table)))
(list (list (file-length in) 0 :end))))
(filler
(mapcar
(lambda-bind ((start . end))
(list start (- end start) (raw-bytes start (- end start))))
(remove-if
(lambda-bind ((start . end)) (= start end))
(reduce (lambda (left this)
(mapcan (lambda (range) (range-minus range this)) left))
(mapcar (lambda-bind ((off size data))
(declare (ignorable data))
(cons off (+ off size)))
parts)
:initial-value (list (cons 0 (file-length in))))))))
(setf ordering (sort (append parts filler) #'< :key #'first))))
;; initialize symbol names in .symtab and .dynsym
(mapcar #'name-symbols
(remove nil
(mapcar (lambda (name) (named-section e name))
'(".symtab" ".dynsym"))))
e)))
(defmethod write-value ((type (eql 'elf)) out value &key
&aux (data (make-array
(caar (remove-if-not
(lambda (g) (eql (lastcar g) :end))
(ordering value)))
:element-type '(unsigned-byte 8)
:initial-element #x0)))
;; Write an elf object to a binary output stream.
(with-slots (header section-table program-table sections ordering) value
(macrolet
((bytes (&rest body)
`(with-output-to-sequence (o :element-type '(unsigned-byte 8))
,@body)))
(mapc (lambda-bind ((offset . bytes))
(loop :for n :below (length bytes)
:do (setf (aref data (+ offset n)) (aref bytes n))))
(mapcar
(lambda-bind ((offset size data))
(declare (ignorable size))
(cons
offset
(cond
((numberp data) ; numbered section
(let ((sec (nth data (sections value))))
(unless (equal :nobits (type sec))
(cond
((or (string= ".dynsym" (name sec))
(string= ".symtab" (name sec)))
(bytes (dolist (sym (data sec))
(write-value (elf-sym-type) o sym))))
((string= ".dynamic" (name sec))
(bytes (dolist (dyn (data sec))
(write-value (elf-dyn-type) o dyn))))
((equal :rel (type sec))
(bytes (dolist (rel (data sec))
(write-value (elf-rel-type) o rel))))
((equal :rela (type sec))
(bytes (dolist (rel (data sec))
(write-value (elf-rela-type) o rel))))
(t (data sec))))))
((eq :header data) ; header
(bytes (write-value 'elf-header o header)))
((eq :section-table data) ; section table
(bytes (mapc (lambda (c) (write-value 'section-header o c))
section-table)))
((eq :program-table data) ; program table
(bytes (mapc (lambda (c) (write-value (program-header-type) o c))
program-table)))
((vectorp data) data)))) ; raw filler
ordering))))
(dolist (b (coerce data 'list)) (write-byte b out)))
(defun copy-elf (elf)
(unless (member (class-name (class-of elf))
'(elf objdump csurf))
(error "~&`copy-elf' called on non-elf object: ~a" elf))
(let ((e (make-instance 'elf)))
(with-slots (header section-table program-table sections ordering) e
(setf
header (generic-copy (header elf))
section-table (generic-copy (section-table elf))
program-table (generic-copy (program-table elf))
sections
(let ((ish (indexed (section-table elf)))
(iph (indexed (program-table elf))))
(flet ((copy-between-tables (hd i-tab to-tab)
(when hd
(let ((ind (caar (member-if (lambda (ih) (equal hd (cadr ih)))
i-tab))))
(unless ind (error "~&header:~a not in table:~a" hd i-tab))
(nth ind to-tab)))))
(mapcar
(lambda (sec)
(let ((s (make-instance 'section)))
(with-slots (elf sh ph name data) s
(setf elf e
sh (copy-between-tables (sh sec) ish section-table)
ph (copy-between-tables (ph sec) iph program-table)
name (name sec)
data (copy-seq (data sec)))
s)))
(sections elf))))
ordering (generic-copy (ordering elf))))
e))
(defgeneric (setf data) (new section)
(:documentation
"Update the contents of section to new, and update all headers appropriately."))
(defmethod (setf data) (new (sec section))
;; step through the ordered sections, updating where required
(with-slots (elf sh name data) sec
(let* ((old-length (* (length data) (if (vectorp data) 1 (entsize sh))))
(new-length (* (length new) (if (vectorp new) 1 (entsize sh))))
(end-point (+ (offset sec) old-length))
(delta (- new-length old-length))
;; a delta to decremented as sections change sizes
(sec-deltas (list (cons end-point delta)))
last)
(unless (= old-length new-length)
(setf
(ordering elf)
(loop for chunk in (ordering elf)
if (equal chunk name)
do (setf last (+ (offset sec) new-length))
else do
(let ((d (cdar sec-deltas)))
(when (and last (> d 0))
(cond
;; TODO: when .got or .got.plt sections move, the
;; related offsets in relocation sections will
;; need to be updated
((stringp chunk) ; section
(let ((sec (named-section elf chunk)))
(when (not (zerop (address sh)))
(when-let ((dyn (dynamic-entry sec)))
(setf (ptr dyn) (+ (address sh) d)))
(setf (address sh) (+ (address sh) d)))
(setf (offset sec) last)
(setf last (+ (offset sec) (size sec)))))
((vectorp chunk) ; padding bytes
(if (> d (length chunk))
(progn (setq d (- d (length chunk)))
(setq chunk nil))
(progn (setq last (+ last (- (length chunk) d)))
(setq chunk (subseq chunk d))
(setq d 0))))
((equal :program-table chunk) ; program header
(let ((header (header elf)))
(setf (phoff header) (+ (phoff header) d))
(setf last (+ (phoff header)
(* (ph-num header) (ph-ent-size header))))))
((equal :section-table chunk) ; section header
(let ((header (header elf)))
(setf (shoff header) (+ (shoff header) d))
(setf last (+ (shoff header)
(* (sh-num header)
(sh-ent-size header))))))))
(setf sec-deltas (cons (cons last d) sec-deltas)))
when chunk collect chunk)))
;; sec-deltas should be in increasing order by offset w/o changed section
(setq sec-deltas (nreverse (butlast sec-deltas)))
;; update the dynamic symbols used at run time
#+do-dyn-update ;; TODO: check if this ever /causes/ execution errors
(let ((ds (make-array (length data) :initial-element 0)))
(flet ((adj (address)
(+ address
(if (and (>= address (offset sec))
(<= address (+ (offset sec) (size sec))))
;; inside of the changed section
(aref ds (- address (offset sec)))
;; after the changed section
(or (cdr (assoc-if (lambda (p) (> address p)) sec-deltas))
0)))))
(dolist (sym (data (named-section elf ".dynsym")))
(with-slots (value) sym
(setf value (adj value))))
(dolist (dynsym (data (named-section elf ".dynamic")))
(when (ptr dynsym)
(setf (ptr dynsym) (adj (ptr dynsym)))))))
;; update size and the contents of the section
(setf (size sec) new-length)
(set-data new sec))))
;;; Misc functions
(defun named-section (elf name)
"Return the section in ELF named NAME."
(first (remove-if (lambda (sec) (not (string= name (name sec)))) (sections elf))))
(defgeneric symbols (elf)
(:documentation "Return the symbols contained in ELF."))
(defmethod symbols ((elf elf))
(let ((ssect (named-section elf ".symtab")))
(if (null ssect)
NIL
(data ssect))))
(defgeneric dyn-symbols (elf)
(:documentation "Return the dynamic symbols contained in ELF."))
(defmethod dyn-symbols ((elf elf))
(let ((dsect (named-section elf ".dynsym")))
(if (null dsect)
NIL
(data dsect))))
(defgeneric all-symbols (elf)
(:documentation "Return the present and dynamic symbols contained in ELF."))
(defmethod all-symbols ((elf elf))
(append (symbols elf) (dyn-symbols elf)))
(defun named-symbol (elf name)
"Return the symbol in ELF named NAME."
(first (remove-if (lambda (sec) (not (string= name (sym-name sec))))
(all-symbols elf))))
(defvar elf-magic-numbers
'((#\Rubout #\E #\L #\F)
(#\Rubout #\C #\G #\C)))
(defun elf-p (file)
"Return t if file is an ELF file (using the magic number test)."
(with-open-file (in file :element-type '(unsigned-byte 8))
(car (member (coerce (read-value 'string in :length 4) 'list)
elf-magic-numbers :test #'equalp))))
(defgeneric get-endianness (in)
(:documentation "Read the endianness byte of a file and set *ENDIAN* appropriately.
On an existing file stream this does not change the file-position of the stream.")
(:method ((in pathname))
(with-open-file (s in :direction :input :element-type '(unsigned-byte 8))
(get-endianness s)))
(:method ((in string))
(with-open-file (s in :direction :input :element-type '(unsigned-byte 8))
(get-endianness s)))
(:method ((in file-stream))
(when (< (file-length in) 6)
(error "File associated with ~a is too short to be an ELF file" in))
(let ((initial-pos (file-position in)))
(unwind-protect
(progn
(file-position in 5)
(let ((b (read-byte in 5)))
(case b
;; https://www.amazon.com/Little-Big-John-Crowley/dp/0061120057
(1 (setf *endian* :little))
(2 (setf *endian* :big))
(t (error "Endian byte of ~a is ~a; should be 1 or 2"
in b)))))
(file-position in initial-pos))
*endian*)))
(defun elf-header-endianness-warn (header)
"Raise a warning if HEADER was read using the wrong endianness."
(when (if (eq *endian* :little)
(= (data-encoding header) 2)
(= (data-encoding header) 1))
(warn "Header read with wrong encoding ~S while data-encoding ~S."
*endian* (data-encoding header)))
header)
(defun elf-header (file)
(with-open-file (in file :element-type '(unsigned-byte 8))
(elf-header-endianness-warn (read-value 'elf-header in))))
(defun read-elf (file &optional (type 'elf))
(with-open-file (in file :element-type '(unsigned-byte 8))
(read-value type in)))
(defun write-elf (elf file)
(with-open-file (out file :direction :output :element-type '(unsigned-byte 8)
:if-exists :supersede)
(write-value 'elf out elf))
nil)
(defun show-rel (elf)
"Print information on the symbols stored in a relocatable section.
Note: the output should resemble the output of readelf -r."
(let ((sec-f "~&~%Relocation section '~a' at offset 0x~x contains ~a entries:")
(rel-h "~& Offset Info Type Sym. Name")
(rel-f "~&~12,'0x ~12,'0x ~12:@<~a~> ~12:@<~a~>"))
(with-slots (header) elf
(dolist (sec (sections elf))
(when (member (type sec) '(:rel :rela))
(with-slots (sh name data) sec
(let ((syms (symbols elf)))
(format t sec-f name (offset sh) (length data))
(format t rel-h)
(mapc
(lambda (rel) ;; offset info type sym.name
(format t rel-f
(offset rel)
(info rel)
(rel-type rel header)
(sym-name (nth (rel-sym rel) syms))))
data))))))))
(defun show-dynamic (elf)
"Show the dynamic symbols of ELF in a manner similar to readelf."
(let ((dynamic (named-section elf ".dynamic")))
(format t "~&Dynamic section at offset 0x~x contains ~d entries:~%"
(offset dynamic) (length (data dynamic)))
(format t " Tag Name/Value~%")
(loop for dyn in (data dynamic)
do (format t " ~10a ~a~%" (tag dyn) (or (val dyn) (ptr dyn)))
until (equal :null (tag dyn)))))
(defun show-symbols (elf)
"Show all symbols in ELF in a manner similar to readelf."
(flet ((string-at (data offset)
(coerce (loop for ch in (subseq data offset)
until (= (char-code ch) 0)
collect ch)
'string)))
(let ((dynsym (named-section elf ".dynsym"))
(dynstr (let ((dynstr (named-section elf ".dynstr")))
(when dynstr
(mapcar #'code-char (coerce (data dynstr) 'list)))))
(symtab (named-section elf ".symtab"))
(strtab (mapcar #'code-char
(coerce (data (named-section elf ".strtab")) 'list))))
(dolist (tab (list dynsym symtab))
(when tab
(format t "~&~%Symbol table '~a' contains ~d entries:~%"
(name tab) (length (data tab)))
(format t " Num: Value Size Type Bind Name~%")
(loop for sym in (data tab) as i from 0
do (format t "~6d: ~8x ~5d ~8a ~6a ~a~%"
i (value sym) (size sym) (type sym) (binding sym)
(string-at
(if (string= ".dynstr" (name tab)) dynstr strtab)
(name sym)))))))))
(defun list-file-layout (elf)
(mapcar (lambda-bind ((offset size data))
(list offset
;; an identifier for the section data
(cond
((numberp data) (name (nth data (sections elf))))
((stringp data) data)
((vectorp data) :filler)
(t data))
;; the size in the file
(let ((sec (cond
((numberp data)(nth data (sections elf)))
((stringp data) (named-section elf data))
(t nil))))
(+ offset (if (and sec (equal :nobits (type sec)))
0
size)))))
(ordering elf)))
(defun show-file-layout (elf)
"Show the layout of the elements of an elf file with binary offset."
(format t "~:{~&~8a ~18a ~8a~}~%" (cons (list 'offset 'contents 'end)
(list-file-layout elf))))
(defun memory-sorted-sections (elf)
"Return the sections of the ELF file sorted by their order in memory.
Each element of the resulting list is a triplet of (offset size header)."
(with-slots (sections section-table program-table) elf
(stable-sort
(remove-if
#'null
(append
(mapcar (lambda (head)
(when (not (zerop (vaddr head)))
(list (vaddr head) (memsz head) head)))
program-table)
(when section-table
(mapcar (lambda (sec)
(when (or (not (zerop (address (sh sec))))
(and (zerop (address (sh sec)))
(member (flags (sh sec))
'(:allocatable))
(equal :progbits (type (sh sec)))))
(list (address (sh sec)) (size sec) sec)))
sections))))
#'< :key #'car)))
(defun list-memory-layout (elf)
(mapcar
(lambda (trio)
(bind (((beg size header) trio))
(list beg
(cond
((subtypep (type-of header) (program-header-type))
(type header))
((subtypep (type-of header) 'section)
(name header)))
(+ beg size))))
(memory-sorted-sections elf)))
(defun show-memory-layout (elf)
"Show the layout of the elements of an elf file with binary offset."
(format t "~&addr contents end ~%")
(format t "-------------------------------------~%")
(mapc (lambda-bind ((addr contents end))
(format t "~&0x~6,'0x ~18a 0x~6,'0x~%" addr contents end))
(list-memory-layout elf))
nil)
(defgeneric file-offset-of-ea (elf ea)
(:documentation "Return the file offset in ELF of EA."))
(defmethod file-offset-of-ea ((obj elf) ea)
(let ((section (section-holding-ea obj ea)))
(+ (offset (sh section)) (- ea (address (sh section))))))
;;; Modification functions
(defmethod index-of-ea ((obj section) ea)
(- ea (address (sh obj))))
(defun sections-holding-ea (elf ea-start &optional ea-end)
(remove-if-not
(lambda (sec)
(let* ((beg (address (sh sec)))
(end (+ beg (size sec))))
(and (>= ea-start beg)
(< ea-start end)
(or (not ea-end) (< ea-end end)))))
(sections elf)))
(defun section-holding-ea (obj ea-start &optional ea-end)
(let ((sections (sections-holding-ea obj ea-start ea-end)))
(assert sections (obj ea-start ea-end)
"No section in ~a found to contain [~a,~a]" obj ea-start ea-end)
(assert (= 1 (length sections)) (obj ea-start ea-end)
"Region [~a,~a] spand multiple sections in ~a" obj ea-start ea-end)
(first sections)))
(defmethod subseq-ea ((obj elf) ea-start &optional ea-end)
(subseq-ea (section-holding-ea obj ea-start ea-end) ea-start ea-end))
(defmethod (setf subseq-ea) (new (obj elf) ea-start &optional ea-end)
(setf (subseq-ea (section-holding-ea obj ea-start) ea-start ea-end) new))
(defmethod subseq-ea ((obj section) ea-start &optional ea-end)
(let ((base (address (sh obj))))
(subseq (data obj) (- ea-start base) (when ea-end (- ea-end base)))))
(defmethod (setf subseq-ea) (new (obj section) ea-start &optional ea-end)
(let ((base (address (sh obj))))
(setf (subseq (data obj) (- ea-start base) (when ea-end (- ea-end base)))
new)))
(defmethod word-at-ea ((obj section) ea)
(subseq-ea obj ea (+ 4 ea)))
(defmethod word-at-ea ((obj elf) ea)
(subseq-ea (section-holding-ea obj ea) ea (+ 4 ea)))
(defmethod (setf word-at-ea) (new (obj section) ea)
(setf (subseq-ea obj ea (+ 4 ea)) new))
(defmethod (setf word-at-ea) (new (obj elf) ea)
(setf (subseq-ea (section-holding-ea obj ea) ea (+ 4 ea)) new))
(defgeneric insert (obj data ea)
(:documentation "Write DATA into OBJ at EA overwriting previous contents."))
(defmethod insert ((obj section) data ea)
(setf (subseq-ea obj ea (+ ea (length data))) data))
(defmethod insert ((obj elf) data ea)
(setf (subseq-ea obj ea (+ ea (length data))) data))
(defmethod bits-at-ea ((obj section) ea)
(int-to-bits (bytes-to-int (subseq-ea obj ea (+ 4 ea))) (* 4 8)))
(defmethod bits-at-ea ((obj elf) ea)
(int-to-bits (bytes-to-int
(subseq-ea (section-holding-ea obj ea) ea (+ 4 ea))) (* 4 8)))
(defmethod (setf bits-at-ea) (new (obj section) ea)
(let ((bytes (int-to-bytes (bits-to-int new) (/ (length new) 8))))
(setf (subseq-ea obj ea (+ (length bytes) ea)) bytes)))
(defmethod (setf bits-at-ea) (new (obj elf) ea)
(let ((bytes (int-to-bytes (bits-to-int new) (/ (length new) 8))))
(setf (subseq-ea (section-holding-ea obj ea)
ea (+ (length bytes) ea)) bytes)))
;; Switching from memory reference to file reference
(defun sections-holding-off (elf off-start &optional off-end)
"Return the section holding the requested file locations.
Note, this does not return filler if the requested file location is
just filler bytes."
(mapcar (lambda-bind ((beg size value))
(declare (ignorable beg size))
(nth value (sections elf)))
(remove-if-not
(lambda-bind ((beg size value))
(let ((end (+ beg size)))
(and (numberp value)
(>= off-start beg)
(<= off-start end)
(or (not off-end) (< off-end end)))))
(ordering elf))))
(defun section-holding-off (obj off-start &optional off-end)
(let ((sections (sections-holding-off obj off-start off-end)))
(assert sections (obj off-start off-end)
"No section in ~a found to contain [~a,~a]" obj off-start off-end)
;; When multiple sections holds this value, return the last (this
;; is the one which will overwrite the others when saving).
(lastcar sections)))
(defmethod subseq-off ((obj elf) off-start &optional off-end)
(subseq-off (section-holding-off obj off-start off-end) off-start off-end))
(defmethod (setf subseq-off) (new (obj elf) off-start &optional off-end)
(setf (subseq-off (section-holding-off obj off-start) off-start off-end) new))
(defmethod subseq-off ((obj section) off-start &optional off-end)
(let ((base (offset (sh obj))))
(subseq (data obj) (- off-start base) (when off-end (- off-end base)))))
(defmethod (setf subseq-off) (new (obj section) off-start &optional off-end)
(let ((base (offset (sh obj))))
(setf (subseq (data obj) (- off-start base) (when off-end (- off-end base)))
new)))
(defmethod word-at-off ((obj section) off)
(subseq-off obj off (+ 4 off)))
(defmethod word-at-off ((obj elf) off)
(subseq-off (section-holding-off obj off) off (+ 4 off)))
(defmethod (setf word-at-off) (new (obj section) off)
(setf (subseq-off obj off (+ 4 off)) new))
(defmethod (setf word-at-off) (new (obj elf) off)
(setf (subseq-off (section-holding-off obj off) off (+ 4 off)) new))
| 60,598 | Common Lisp | .lisp | 1,460 | 32.440411 | 85 | 0.536402 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 4a18ff7f149423f80ea1121822eda5f55ac3d1114fc32fba762c5bd8147bda71 | 13,078 | [
-1
] |
13,079 | arm.lisp | GrammaTech_elf/arm.lisp | ;;; arm.lisp --- Support for reading and writing ARM instructions
;;; Commentary.
;;
;; This file provides methods for reading/writing ARM instructions
;; from/to streams of bits. It is implemented largely from the
;; ARM7-TDMI-manual-pt2.pdf and page numbers in comments below refer
;; to said.
;;
;; TODO:
;; - nice print methods so that these instructions are easily readable
;; at the REPL
;; - instruction disambiguation (see `arm-decode' below)
;;; Code.
(in-package :elf)
(defclass arm-data () ())
(defclass arm-instruction (arm-data) ())
(defmethod initialize-instance :after ((obj arm-instruction) &key)
(setf (ignored obj) nil))
(defmethod from-bits ((obj arm-data) bits)
(setf obj (read-value (type-of obj) (make-in-memory-input-stream bits))))
(defmethod from-bytes ((obj arm-data) bytes)
(from-bits obj (apply #'concatenate 'bit-vector
(mapcar (lambda (byte)
(int-to-bits (bytes-to-int (list byte)) 8))
bytes))))
(defmethod to-bits ((obj arm-data))
(with-output-to-sequence (out :element-type '(unsigned-byte 1))
(write-value (type-of obj) out obj)))
(defmethod to-bytes ((obj arm-data))
(mapcar (lambda (bits) (int-to-bytes (bits-to-int bits) 1))
(chunks (to-bits obj) 8)))
;;; Constituents
(define-bit-dictionary condition-field 4
;; Condition Field p.5
((0 . :eq) ; equal
(1 . :ne) ; not equal
(2 . :cs) ; unsigned higher or same
(3 . :cc) ; unsigned lower
(4 . :mi) ; negative
(5 . :pl) ; positive or zero
(6 . :vs) ; overflow
(7 . :vc) ; no overflow
(8 . :hi) ; unsigned higher
(9 . :ls) ; unsigned lower or same
(10 . :ge) ; greater or equal
(11 . :lt) ; less than
(12 . :gt) ; greater than
(13 . :le) ; less than or equal
(14 . :al) ; always
(15 . :err))) ; never used
(define-bit-dictionary immediate 1
((0 . :register) (1 . :immediate)))
(define-bit-dictionary pre/post 1
((0 . :post) (1 . :pre)))
(define-bit-dictionary up/down 1
((0 . :down) (1 . :up)))
(define-bit-dictionary byte/word 1
((0 . :word) (1 . :byte)))
(define-bit-dictionary write-back 1
((0 . :no-write-back) (1 . :write-back)))
(define-bit-dictionary load/store 1
((0 . :store) (1 . :load)))
(define-bit-dictionary psr 1
((0 . :no-psr) (1 . :psr)))
(define-bit-dictionary link-bit 1
((0 . :branch) (1 . :branch-w-link)))
(define-bit-dictionary set-condition-codes 1
((0 . :no-set) (1 . :set)))
(define-bit-dictionary opcodes 4
((0 . :AND)
(2 . :SUB)
(3 . :RSB)
(4 . :ADD)
(5 . :ADC)
(6 . :SBC)
(7 . :RSC)
(8 . :TST)
(9 . :TEQ)
(10 . :CMP)
(11 . :CMN)
(12 . :ORR)
(13 . :MOV)
(14 . :BIC)
(15 . :MVN)
(1 . :EOR)))
(define-binary-type register ()
(:reader (in)
(bits-to-int
(let ((buf (make-array 4 :element-type '(unsigned-byte 1))))
(read-sequence buf in)
buf)))
(:writer (out value)
(write-sequence (int-to-bits value 4) out)))
(define-binary-type register-list () (raw-bits :length 16))
(define-binary-type forced (value)
(:reader (in)
(let ((buf (make-array (length value)
:element-type '(unsigned-byte 1))))
(read-sequence buf in)
;; TODO: Should define a special disasmbly error instead
;; of using assertions.
(unless (equal value buf)
(warn "Bits ~a do not match SPEC mandated ~a when decoding ~a"
buf value (type-of (car *in-progress-objects*))))
buf))
(:writer (out ignore) (declare (ignore ignore)) (write-sequence value out)))
(define-binary-type numerical-value (length)
(:reader (in)
(bits-to-int
(let ((buf (make-array length :element-type '(unsigned-byte 1))))
(read-sequence buf in)
buf)))
(:writer (out value) (write-sequence (int-to-bits value length) out)))
;;; ARM Instructions
(define-binary-class ldr/str (arm-instruction)
;; LDR/STR opcodes p. 28
;; 31 28 19 15 11 0
;; [ Cond 4 ] [01] [I] [P] [U] [B] [W] [L] [ Rn 4] [ Rd 4] [ Offset 12 ]
((offset (numerical-value :length 12))
(rd register)
(rn register)
(l load/store)
(w write-back)
(b byte/word)
(u up/down)
(p pre/post)
(i immediate)
(ignored (forced :value #*10))
(conditions condition-field)))
(define-binary-class ldm/stm (arm-instruction)
;; LDM/STM (push pop) p. 40
;; 31 28 15
;; [ cond 4 ] [ 100 ] [P] [U] [S] [W] [L] [ Rn ] [ Register list ]
((registers register-list)
(rn register)
(l load/store)
(w write-back)
(s psr)
(u up/down)
(p pre/post)
(ignored (forced :value #*001))
(conditions condition-field)))
(define-binary-class bx (arm-instruction)
((rn register)
(ignored (forced :value #*100011111111111101001000))
(conditions condition-field)))
(define-binary-type b-offset (arm-instruction)
(:reader (in)
(let ((buf (make-array 24 :element-type '(unsigned-byte 1))))
(read-sequence buf in)
(let* ((signed (not (zerop (bit buf 23))))
(base
(bits-to-int
(concatenate 'simple-bit-vector
#*00
buf
(if signed #*111111 #*000000)))))
(if signed (- base (expt 2 32)) base))))
(:writer (out value)
(let ((buf (int-to-bits
(if (negative-integer-p value)
(+ (expt 2 32) value)
value)
32)))
(write-sequence (subseq buf 2 26) out))))
(define-binary-class b/bl (arm-instruction)
((offset b-offset)
(l link-bit)
(ignored (forced :value #*101))
(conditions condition-field)))
(define-binary-class data-processing (arm-instruction)
((operand2 (raw-bits :length 12))
(rd register)
(rn register)
(s set-condition-codes)
(opcode opcodes)
(i immediate)
(ignored (forced :value #*00))
(conditions condition-field)))
(define-binary-class register-operand (arm-data)
((rm register)
(shift (numerical-value :length 8))))
(define-binary-class immediate-operand (arm-data)
((imm (numerical-value :length 8))
(rotate (numerical-value :length 4))))
(define-binary-class .word (arm-data)
((imm (numerical-value :length 32))))
;;; Interpret data-processing operand2 based on value of immediate operand
(defmethod reconcile-immediate-operand ((obj data-processing))
(let ((bits (operand2 obj)))
(format t "BITS:~S~%" bits)
(setf (operand2 obj)
(from-bits (make-instance
(case (i obj)
(:immediate 'immediate-operand)
(:register 'register-operand)))
bits)))
obj)
(defmethod (setf i) :after (new (obj data-processing))
(when (slot-boundp obj 'operand2) (reconcile-immediate-operand obj)))
(defmethod (setf operand2) :after (new (obj data-processing))
(when (and (slot-boundp obj 'i)
(subtypep 'SIMPLE-BIT-VECTOR (type-of (operand2 obj))))
(reconcile-immediate-operand obj)))
(defmethod read-value :around ((type (eql 'data-processing)) stream &key)
(reconcile-immediate-operand (call-next-method)))
(defmethod write-value :around ((type (eql 'data-processing)) stream value &key)
(let ((temp (operand2 value)))
(setf (operand2 value) (to-bits (operand2 value)))
(call-next-method)
(setf (operand2 value) temp)))
;;; Convenience methods
(defun make-arm-branch (mnemonic offset)
(make-instance 'b/bl
:conditions (ecase mnemonic
((:bl :b) :al)
(:bne :ne)
(:beq :eq))
:l (ecase mnemonic
(:bl :branch-w-link)
((:b :bne :beq) :branch))
:offset offset))
(defmethod set-arm-branch ((obj elf) mnemonic to from)
(setf (bits-at-ea obj from)
(to-bits (make-arm-branch mnemonic (- to from 8))))
obj)
(defun make-arm-data-transfer (mnemonic reg offset)
(make-instance 'ldr/str
:conditions :al
:i :register
:l (ecase mnemonic (:ldr :load) (:str :store))
:w :no-write-back
:b :word
:u (if (< offset 0) :down :up)
:p :pre
:rn 15 ; <- PC
:rd reg
:offset (abs offset)))
(defmethod set-arm-data-transfer ((obj elf) mnemonic place reg from)
(setf (bits-at-ea obj place)
(to-bits (make-arm-data-transfer mnemonic reg (- from place 8))))
obj)
(defun make-arm-stack (mnemonic registers)
(make-instance 'ldm/stm
:conditions :al
:p (ecase mnemonic (:push :pre) (:pop :post))
:u (ecase mnemonic (:push :down) (:pop :up))
:s :no-psr
:w :write-back
:l (ecase mnemonic (:push :store) (:pop :load))
:rn 13
:registers (let ((bits (make-array 16 :element-type 'bit
:initial-element 0)))
(dolist (reg registers) (setf (bit bits reg) 1))
bits)))
(defmethod set-arm-stack ((obj elf) mnemonic place registers)
(setf (bits-at-ea obj place) (to-bits (make-arm-stack mnemonic registers)))
obj)
(defun make-arm-data-processing (mnemonic register immediate)
(make-instance 'data-processing
:operand2 (make-instance 'immediate-operand
:rotate 0
:imm immediate)
:rd register
:rn 0
:s :set
:opcode mnemonic
:i :immediate
:conditions :al))
(defmethod set-arm-data-processing ((obj elf) mnemonic place register immediate)
(setf (bits-at-ea obj place)
(to-bits (make-arm-data-processing mnemonic register immediate)))
obj)
(defun make-arm-word (immediate)
(make-instance '.word :imm immediate))
(defmethod set-arm-word ((obj elf) place immediate)
(setf (bits-at-ea obj place) (to-bits (make-arm-word immediate)))
obj)
(defmethod arm-decode ((obj elf) type ea)
;; TODO: shouldn't need a type argument.
(from-bits (make-instance type) (bits-at-ea obj ea)))
| 10,854 | Common Lisp | .lisp | 281 | 32.224199 | 80 | 0.555851 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 7d5dd7a22e1d3986685792962930ece4f332285df4fb8b23696c16f42c0ea633 | 13,079 | [
-1
] |
13,080 | instruction.lisp | GrammaTech_elf/instruction.lisp | ;;; instruction --- comparable machine code instructions
(in-package :elf)
(defclass instruction ()
((prefixes :initarg :prefixes :accessor prefixes :initform nil)
(opcode :initarg :opcode :accessor opcode)
(operands :initarg :operands :accessor operands :initform nil)))
(defclass objdump-instruction (instruction) ())
(defclass tsl-instruction (instruction) ())
(defmethod print-object ((obj instruction) stream)
(print-unreadable-object (obj stream :type t)
(prin1 (cons (opcode obj) (operands obj))
stream)))
(defgeneric from-string (instruction string)
(:documentation "Parse an instruction from a string representation."))
(defvar instruction-prefixes
(list "rep" "repe" "gs" "repz" "repne" "repnz"
"rex" "rex.WX" "rex.X" "rex.WRXB"
"cs" "ds" "fs" "es"
"data16" "lock" "notrack"))
(defmethod from-string ((obj objdump-instruction) string)
(unless (zerop (length string))
(let ((pieces (split-sequence #\Space string :remove-empty-subseqs t))
(depth 0))
(loop :while (member (car pieces) instruction-prefixes :test #'equal)
:do (push (pop pieces) (prefixes obj)))
;; TODO: handle data declarations e.g.,
;; 400645: 66 66 2e 0f 1f 84 00 data32 nopw %cs:0x0(%rax,%rax,1)
(setf (opcode obj) (make-keyword (string-upcase (first pieces))))
(setf (operands obj)
(when (and (second pieces)
(not (member (opcode obj)
(list :data32))))
(mapcar #'parse-operand
;; Split the instruction encoding STRING into
;; opcode and operands.
(split-sequence-if (lambda (char)
(case char
(#\( (incf depth) nil)
(#\) (decf depth) nil)
(#\, (zerop depth))))
(second pieces))))))
obj))
(defun parse-operand (string) ; Currently as printed by objdump.
"Parse an assembly instruction operand."
;; FIXME: The quality of this translation is sufficient for
;; comparison and for notional reading, but insufficient for
;; more rigorous semantic applications (e.g., QFBV).
(flet ((parse-register (string)
(multiple-value-bind (match matches)
(scan-to-strings
"([xyz]\?m{2}[0-9][0-5]\?|[abcdesixlp]\+|r[1-9][0-5]\?)"
(subseq string 1))
(unless match (error "Failed to parse register ~S" string))
(make-keyword (string-upcase (aref matches 0))))))
(case (aref string 0)
(#\% (parse-register string)) ; register
(#\$ (parse-integer string :start 3 :radix 16)) ; literal
(#\( `(,(parse-register (subseq string 1)))) ; register memory
(#\* (parse-operand (subseq string 1))) ; discard leading *
(#\0 ; positive offset or literal
(if (string= string "0")
0
(multiple-value-bind (num index)
(parse-integer string :start 2 :radix 16 :junk-allowed t)
(if (= index (length string))
num
`(+ (,(parse-register (subseq string (1+ index)))) ,num)))))
(#\- ; negative offset or literal
(multiple-value-bind (num index)
(parse-integer string :start 3 :radix 16 :junk-allowed t)
(if (= index (length string))
num
`(- (,(parse-register (subseq string (1+ index)))) ,num))))
((#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 ; address
#\a #\b #\c #\d #\e #\f #\A #\B #\C #\D #\E #\F)
(parse-integer string :radix 16 :junk-allowed t))
(t (error "Unhandled operand ~S" string)))))
(defmethod from-string ((obj tsl-instruction) string)
(unless (zerop (length string))
;; Important part is in the parens (last parent is always last character).
(let* ((index (let ((index 0))
(loop :do (incf index)
:until (or (> index (length string))
(equal (aref string index) #\()))
index))
(ops (split-sequence
#\, (subseq string (1+ index) (1- (length string))))))
(setf (opcode obj) (parse-tsl-operand (nth 3 ops)))
(setf (operands obj) (mapcar #'parse-tsl-operand (subseq ops 4)))
obj)))
(defmethod parse-tsl-operand (string)
(when (equal (aref string 0) #\Space) (setf string (subseq string 1)))
(flet ((beginning (substring)
(and (>= (length string) (length substring))
(string= (subseq string 0 (length substring)) substring))))
(cond
((beginning "MOV") :mov)
((beginning "EAX") :eax)
((beginning "RegDirect32") (list (parse-tsl-operand
(subseq string
(1+ (length "RegDirect32"))
(1- (length string))))))
((beginning "Immediate32") (parse-integer
(subseq string
(1+ (length "RegDirect32"))
(1- (length string)))))
(t string))))
| 5,452 | Common Lisp | .lisp | 107 | 38.009346 | 80 | 0.521462 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 21870e2ac4edf75626f86a4531ed1010d5a107c7a9634ad04c4f029376b85872 | 13,080 | [
-1
] |
13,081 | elf-test.lisp | GrammaTech_elf/test/elf-test.lisp | ;;; elf-test.lisp --- Tests for elf.lisp
;; Copyright (C) 2011-2013 Eric Schulte
;; Licensed under the Gnu Public License Version 3 or later
;;; Code:
(in-package :elf/test)
(defsuite test)
(in-suite test)
;;; testing components
(defvar *test-class* :32-bit "architecture to test (e.g. 32-bit or 64-bit)")
(defvar *tmp-file* nil "temporary file used for testing")
(defvar *elf* nil "variable to hold elf object")
(defun elf-test-relative-path (rel-path-string)
(asdf/system:system-relative-pathname
"elf/test" (concatenate 'string "test/" rel-path-string)))
(defixture hello-elf
(:setup
(setf *tmp-file* (elf-test-relative-path "hello.tmp"))
(when (probe-file *tmp-file*) (delete-file *tmp-file*))
(setf *elf* (read-elf (case *test-class*
(:32-bit (elf-test-relative-path "hello32"))
(:64-bit (elf-test-relative-path "hello64"))))))
(:teardown
(when (probe-file *tmp-file*)
(delete-file *tmp-file*))))
(deftest test-write-elf (elf path)
(is (progn (write-elf elf path) (probe-file path))))
(deftest test-read-elf (path)
(let (out)
(is (setf out (read-elf path)))
out))
(defun run-elf-tests ()
(let ((*test-class* :32-bit)) (test))
(let ((*test-class* :64-bit)) (test)))
(defun system-class ()
(ecase (parse-integer (elf::shell "getconf LONG_BIT"))
(32 :32-bit)
(64 :64-bit)))
;;; tests which run
(deftest test-magic-number ()
(with-fixture hello-elf
(let ((magic-number (concatenate 'string (string (code-char #x7f)) "ELF")))
(is (equal magic-number (magic-number (header *elf*)))))))
(deftest test-section-sizes ()
(with-fixture hello-elf
(dolist (sec (sections *elf*))
(unless (or (member (name sec) '(".dynsym" ".dynamic" ".symtab")
:test #'string=)
(member (elf:type sec) '(:rel :rela)))
(is (= (size (sh sec)) (length (data sec)))
"section:~a data:~a != size:~a"
(name sec) (length (data sec)) (size (sh sec)))))))
(deftest test-idempotent-read-write ()
(with-fixture hello-elf
(is (equal *test-class* *class*))
(test-write-elf *elf* *tmp-file*)
(is (elf::equal-it *elf* (test-read-elf *tmp-file*)))))
(deftest test-write-working-executable ()
(with-fixture hello-elf
(test-write-elf *elf* *tmp-file*)
(is (probe-file *tmp-file*))
#-ccl
(when (equal (system-class) *test-class*)
(elf::shell (format nil "chmod +x ~a" *tmp-file*))
(is (equal "hello world" (elf::trim (elf::shell *tmp-file*)))))))
(deftest test-tweaked-text-working-executable ()
(with-fixture hello-elf
;; change a `noop' which is not on the execution path to a `ret'
(setf (aref (data (named-section *elf* ".text")) 42) #xc3)
(test-write-elf *elf* *tmp-file*)
(is (probe-file *tmp-file*))
#-ccl
(when (equal (system-class) *test-class*)
(elf::shell (format nil "chmod +x ~a" *tmp-file*))
(is (equal "hello world" (elf::trim (elf::shell *tmp-file*)))))))
(deftest test-data-setf-changes ()
(with-fixture hello-elf
(let ((first-data (copy-seq (data (named-section *elf* ".text")))))
(setf (aref (data (named-section *elf* ".text")) 42) #xc3)
(is (not (elf::equal-it first-data
(data (named-section *elf* ".text"))))))))
(deftest test-objdump ()
(with-fixture hello-elf
(is (stringp (objdump (named-section *elf* ".text"))))))
(deftest test-objdump-parse ()
(with-fixture hello-elf
(let ((sym-names (mapcar #'sym-name (symbols *elf*))))
(mapc
(lambda-bind (((value . name) . addrs))
(is (numberp value))
(is (stringp name))
(is (listp addrs))
(is (member name sym-names :test #'string=)))
(objdump-parse (objdump (named-section *elf* ".text")))))))
(deftest test-objdump-parse-empty-instructions ()
(let ((lines (with-open-file (in (elf-test-relative-path "main.txt"))
(loop for line = (read-line in nil :eof)
until (eq line :eof)
collect line))))
(is (elf::equal-it '(0) (second (nth 12 (parse-objdump-line lines)))))))
(deftest test-equality-of-data-and-objdump-bytes ()
(with-fixture hello-elf
(let ((.text (named-section *elf* ".text")))
(is (elf::equal-it (coerce (data .text) 'list)
(apply #'append
(apply #'append
(mapcar
(lambda (sym) (mapcar #'second (cdr sym)))
(objdump-parse (objdump .text))))))))))
(deftest test-addresses-compared-w/objdump-output ()
(with-fixture hello-elf
(let ((.text (named-section *elf* ".text")))
(is (elf::equal-it
(apply #'append
(mapcar
(lambda-bind ((addr bytes disasm))
(declare (ignorable disasm))
(mapcar (lambda (_)
(declare (ignorable _))
(prog1 addr (incf addr))) bytes))
(apply #'append
(mapcar #'cdr
(objdump-parse
(objdump (named-section *elf* ".text")))))))
(let ((addr (address (sh .text))))
(mapcar (lambda (_)
(declare (ignorable _))
(prog1 addr (incf addr)))
(coerce (data .text) 'list))))))))
;;; elf-test.lisp ends here
| 5,573 | Common Lisp | .lisp | 129 | 34.248062 | 79 | 0.558427 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | b039657c70cfd933ba07cd80af245e59961c6eb4acdee61b6429201d6ad7f9c7 | 13,081 | [
-1
] |
13,082 | package.lisp | GrammaTech_elf/test/package.lisp | ;; Copyright (C) 2013 Eric Schulte
(defpackage #:elf/test
(:use
:common-lisp
:alexandria
:metabang-bind
:elf
:stefil
:trivial-timeout)
(:shadow :type)
(:export :run-elf-tests :test))
| 208 | Common Lisp | .lisp | 11 | 15.727273 | 35 | 0.664975 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 0ef456df54473900d749603d4a46681b2d956c0ad28156e35790f09235129e80 | 13,082 | [
-1
] |
13,083 | elf.asd | GrammaTech_elf/elf.asd | ;; Copyright (C) 2011-2013 Eric Schulte
(defsystem "elf"
:name "elf"
:author "Eric Schulte <[email protected]>"
:description "Common Lisp library for manipulation of ELF files."
:version "0.1"
:depends-on
#.(if (handler-case (progn (require :sb-capstone) t)
(error () nil))
'(alexandria
com.gigamonkeys.binary-data
metabang-bind
split-sequence
#-ecl trivial-shell
cl-ppcre
flexi-streams
#+sbcl sb-capstone)
'(alexandria
com.gigamonkeys.binary-data
metabang-bind
split-sequence
#-ecl trivial-shell
cl-ppcre
flexi-streams))
:components ((:file "package")
(:file "util" :depends-on ("package"))
(:file "elf" :depends-on ("package" "util"))
(:file "arm" :depends-on ("package" "util" "elf"))
(:file "instruction" :depends-on ("package"))
(:file #.(if (handler-case (progn (require :sb-capstone) t)
(error () nil))
"disassemblable"
"disassemblable-light")
:depends-on ("package" "util" "elf" "instruction")))
:in-order-to ((test-op (load-op "elf/test")))
:perform (test-op (o c) (symbol-call :elf/test '#:test)))
(defsystem "elf/test"
:description "Test the elf library."
:version "0.0.0"
:depends-on
(alexandria metabang-bind elf stefil trivial-timeout)
:components
((:static-file "COPYING")
(:module "test"
:components
((:file "package")
(:file "elf-test" :depends-on ("package"))))))
| 1,697 | Common Lisp | .asd | 47 | 26.382979 | 74 | 0.548211 | GrammaTech/elf | 7 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 2978115aec393c80707504af832fc8e27004233c8fe61db941fd3487f97a0b2b | 13,083 | [
-1
] |
13,107 | package.lisp | jnjcc_cl-qrencode-deprecated/package.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; package.lisp
;;;; This file contains the package defintions.
;;;;
(defpackage #:cl-qrencode
(:use #:cl #:zpng)
(:import-from #:zpng
#:png
#:data-array
#:write-png)
(:export #:qrencode
#:sdebug
#:undebug)) | 916 | Common Lisp | .lisp | 26 | 33.384615 | 71 | 0.726659 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 5c85607535013203e08fbf3bd9202d42142a032c07a6915c694425a3c34f3c24 | 13,107 | [
-1
] |
13,108 | qr-bstring.lisp | jnjcc_cl-qrencode-deprecated/src/qr-bstring.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-bstring.lisp
;;;; This file contains utilities that convert QR-INPUT to binary string (bstring,
;;;; bitstream, or bit sequence, we may say).
;;;;
(in-package #:cl-qrencode)
;;; 1. Encode *Mode Indicator*.
;;; defined in qr-spec.lisp as (mode->bstring)
;;; 2. Encode *Character Count Indicator*: bit sequence which defines the data string
;;; length in a mode.
(defun decimal->bstring (num bits)
"Use BITS bits to translate NUM of decimal into binary."
(declare (type number num bits))
(when (< (- (expt 2 bits) 1) num)
(error 'qr-bad-arguments :file-name "qr-bstring.lisp" :function-name "decmimal->bstring"
:arguments '(num bits) :how "Bits not enough to hold num."))
(let ((bstring ""))
(dotimes (i bits)
(if (logbitp i num)
(setf bstring (concatenate 'string bstring "1"))
(setf bstring (concatenate 'string bstring "0"))))
(reverse bstring)))
;;; 3. Encode input data string.
(defvar *encode-functions*
'(numeric->bstring alnum->bstring binary->bstring kanji->bstring)
"Functions to encode input data string, defined in qr-data-bstring.lisp.")
(defun data->bstring (data mode)
(declare (type string data)
(type symbol mode))
(let* ((idx (mode->index mode))
(encode (nth idx *encode-functions*)))
(funcall encode data)))
;;; 4. padding-bits
(defun padding-bits (blength)
"Padding bits into bstring of length BLENGTH so that the length can be times of 8."
(declare (type number blength))
(make-string (- 8 (mod blength 8)) :initial-element #\0))
(defun padding-pad-codeword (remain-bits)
"Padding Pad Codewords 11101100 & 00010001 to fill data codeword capacity of symbol.
We have assured that REMAIN-BITS is multiple of 8 in function (padding-bits)."
(declare (type number remain-bits))
(when (not (= (mod remain-bits 8) 0))
(error 'qr-bad-arguments :file-name "qr-bstring.lisp"
:function-name "padding-pad-codeword" :arguments remain-bits
:how "BLENGTH shall be times of eight, something went wrong..."))
(let ((bytes (/ remain-bits 8))
(result ""))
(dotimes (idx bytes)
(if (evenp idx)
(setf result (concatenate 'string result
"11101100"))
(setf result (concatenate 'string result
"00010001"))))
result))
;;; The overall function to encode qr-input to bstring.
(defun input->bstring (input)
(declare (type qr-input input))
(let ((bstring ""))
(with-slots (version mode data-bstring (correct correction)) input
(setf bstring (concatenate 'string bstring
(mode->bstring mode)
(decimal->bstring (length (data input))
(count-indicator-bits version mode))
data-bstring))
; 5. Padding bits
(let ((len (length bstring)))
(setf bstring (concatenate 'string bstring
(padding-bits len))))
; 6. Padding Pad codewords
(let ((len (length bstring)))
(setf bstring (concatenate 'string bstring
(padding-pad-codeword (- (data-bits-capacity version correct)
len)))))
(let ((blocks (bstring->blocks bstring version correct)))
(do-errc blocks version correct)
(setf bstring (blocks->bstring blocks version correct)))
; 7. Any remainder bits needed? *MODULE-CAPACITY-TABLE*
(setf bstring (concatenate 'string bstring
(make-string (remainder-bits version) :initial-element #\0))))
bstring))
| 4,029 | Common Lisp | .lisp | 93 | 39.548387 | 92 | 0.70046 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 138774bfdce542a777336b4caae8130ed1d3510fa5fa1e7bb6e49a8d9a7d7a73 | 13,108 | [
-1
] |
13,109 | qr-encode.lisp | jnjcc_cl-qrencode-deprecated/src/qr-encode.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-encode.lisp
;;;; This file contains The Lord of the Rings
;;;;
(in-package #:cl-qrencode)
;;------------------------------------------------------------------------------
;; 1. Convert input into bstring: we've done that in qr-bstring.lisp
;; 2. Data allocation based on the bstring.
;;------------------------------------------------------------------------------
;; A dark module is 1/4, a light module is 0/3.
;; NOTICE: do not change these definitions
(defvar *blank* 2 "for encoding region")
;; 1/0 are resvered for masking
(defvar *fdark* 4 "function pattern dark module")
(defvar *flight* 3 "function pattern light module")
(defun make-matrix (version &key (blank *blank*))
"Make an empty matrix based on the version of current input,
we use BLANK to indicate the emptyness."
(declare (type number version))
(let ((modules (matrix-modules version)))
(make-array `(,modules ,modules) :initial-element blank)))
(defun dark-module-p (matrix i j)
(or (= (aref matrix i j) 1)
(= (aref matrix i j) 4)))
(defun same-color-p (color1 color2)
(case color1
((0 1) (or (= color1 color2) (= (+ color1 3) color2)))
((3 4) (or (= color1 color2) (= (- color1 3) color2)))
(otherwise (= color1 color2))))
;;------------------------------------------------------------------------------
;; The QRCode symbol is consisted of two parts: Function Patterns & Encoding region.
;; Here is the first main part: Function Patterns
;;------------------------------------------------------------------------------
;; (1) Position Detection Patterns
(defun paint-square (matrix x y n color)
"Paint a square of size N from upleft (X, Y) in MATRIX to COLOR"
(let ((maxx (+ x (- n 1)))
(maxy (+ y (- n 1))))
(loop for i from x to maxx do
(loop for j from y to maxy do
(setf (aref matrix i j) color)))
matrix))
(defun paint-one-position (matrix x y)
"Paint one Positioin Detection Pattern with upper left at (X, Y)."
(setf matrix (paint-square matrix x y 7 *fdark*))
(setf matrix (paint-square matrix (+ x 1) (+ y 1) 5 *flight*))
(paint-square matrix (+ x 2) (+ y 2) 3 *fdark*))
(defun paint-position (matrix version) ; modules)
"Paint all three Position Detection Patterns. The reason why we use VERSION instead of
MODULES as an argument is that we want provide a common interface to users."
(let ((modules (matrix-modules version)))
(setf matrix (paint-one-position matrix 0 0))
(setf matrix (paint-one-position matrix 0 (- modules 7)))
(paint-one-position matrix (- modules 7) 0)))
;; (2) Separators for Position Detection Pattern.
(defun paint-separator (matrix version) ; modules)
"Paint Separator for Position Detection Pattern. VERSION-MODULES reason as above."
(let ((modules (matrix-modules version)))
(loop for j from 0 to 7 do ; Horizontal separators.
(setf (aref matrix 7 j) *flight*)
(setf (aref matrix 7 (- modules j 1)) *flight*)
(setf (aref matrix (- modules 8) j) *flight*))
(loop for i from 0 to 7 do ; Vertical separators.
(setf (aref matrix i 7) *flight*)
(setf (aref matrix (- modules i 1) 7) *flight*)
(setf (aref matrix i (- modules 8)) *flight*))
matrix))
;; (3) Timing Patterns.
(defun paint-timing (matrix version) ;modules)
(let ((modules (matrix-modules version)))
(loop for idx from 8 to (- modules 9) do
(if (evenp idx)
(progn
(setf (aref matrix 6 idx) *fdark*) ; Horizontal
(setf (aref matrix idx 6) *fdark*)); Vertical
(progn
(setf (aref matrix 6 idx) *flight*)
(setf (aref matrix idx 6) *flight*))))
matrix))
;; NOTICE: to be precise, FI and VI belongs to Encoding Region
(defun reserve-information (matrix version &key (blank *blank*)) ; instead of MODULES
"Reserve modules for Format information and Version information, by 'reserve', we
mean set the modules to *FLIGHT*."
; First, reserve Format information modules
(let ((modules (matrix-modules version)))
(loop for j from 0 to 7 do ; Horizontal
(when (= (aref matrix 8 j) blank)
(setf (aref matrix 8 j) *flight*))
(setf (aref matrix 8 (- modules j 1)) *flight*))
(setf (aref matrix 8 8) *flight*)
(loop for i from 0 to 7 do ; Vertical
(when (= (aref matrix i 8) blank)
(setf (aref matrix i 8) *flight*))
(setf (aref matrix (- modules i 1) 8) *flight*))
(setf (aref matrix (- modules 8) 8) *fdark*)
; Reserve Version information modules for Version 7 ~ 40
(when (>= version 7)
(loop for j from 0 to 5 do
(loop for i from (- modules 11) to (- modules 9) do
(setf (aref matrix i j) *flight*)
(setf (aref matrix j i) *flight*))))
matrix))
;; Sum up the common Funtion Patterns above.
(defun paint-common-pattern (matrix version &key (blank *blank*))
"Paint Function Patterns that are common to all Versions:
Position Detection Pattern & Separator & Timing."
(setf matrix (paint-position matrix version))
(setf matrix (paint-separator matrix version))
(setf matrix (paint-timing matrix version))
(reserve-information matrix version :blank blank))
;; (4) Paint Alignment Patterns. Of course, Alignment is a kind of Function
;; Pattern, but a little different(depends on version), so we list it separately.
;; NOTICE: Alignment Patterns, only in version 2 or higher
(defun paint-one-align (matrix x y)
"Note: here, (X, Y) is the center of the square."
(setf matrix (paint-square matrix (- x 2) (- y 2) 5 *fdark*))
(setf matrix (paint-square matrix (- x 1) (- y 1) 3 *flight*))
(paint-square matrix x y 1 *fdark*))
(defun paint-alignment (matrix version)
"Paint all the Alignment Patterns under VERSION, Alignment Pattern varies from version
to version."
(let ((centers (align-centers version)))
(loop for center in centers do
(setf matrix (paint-one-align matrix (first center) (second center))))
matrix))
(defun paint-function-pattern (matrix version &key (blank *blank*))
"The first main part: Function Pattern."
(setf matrix (paint-common-pattern matrix version :blank blank))
(paint-alignment matrix version))
(defun function-pattern (version &key (blank *blank*))
"For debug purpose; Matrix status after painting Function Patterns."
(let ((matrix (make-matrix version :blank blank)))
(print (paint-function-pattern matrix version :blank blank))
(values)))
;;------------------------------------------------------------------------------
;; The QRCode symbol is consisted of two parts: Function patterns & Encoding regions.
;; Here is the second main part: Encoding Region.
;;------------------------------------------------------------------------------
;; Symbol character placement.
(defun blank-p (matrix i j &optional (blank *blank*))
(let ((width (floor (sqrt (array-total-size matrix)))))
(and (<= 0 i (- width 1))
(<= 0 j (- width 1))
(= (aref matrix i j) blank))))
(defun paint-encoding (bstring matrix version &key (blank *blank*))
"The second main part: Paint the Encoding Region."
(let* ((modules (matrix-modules version))
(i (- modules 1))
(j (- modules 1))
(direction -1) ; -1 means upwards, 1 means downwards
(len (length bstring)))
(do ((idx 0))
((= idx len))
(when (blank-p matrix i j blank)
;(format t "~%(~A, ~A) ~A~%" i j idx)
(setf (aref matrix i j) (- (char-code (aref bstring idx))
(char-code #\0)))
(incf idx))
(when (and (>= (- j 1) 0)
(blank-p matrix i (- j 1) blank))
;(format t "~%(~A, ~A) ~A~%" i (- j 1) idx)
(setf (aref matrix i (- j 1)) (- (char-code (aref bstring idx))
(char-code #\0)))
(incf idx))
(if (< -1 (+ i direction) modules)
(incf i direction)
(progn
(setf direction (- direction))
(decf j 2))))
matrix))
(defun encoding-region (bstring matrix version &key (blank *blank*))
"For debug purpose; Matrix status after painting Encoding Region."
(when (= (aref matrix 0 0) blank)
(error 'qr-bad-arguments :file-name "qr-encode.lisp"
:function-name "encoding-region" :arguments 'matrix
:how "This function must be called after PAINT-FUNTION-PATTERN."))
(print (paint-encoding bstring matrix version blank)))
(defun infochar->color (char)
"Helper function, translate information bstring character into color:
*flight* / *fdark*"
(+ 3 (- (char-code char)
(char-code #\0))))
;; After masking, paint format information
(defun paint-format (fbstring matrix modules)
(assert (= (length fbstring) 15))
(let ((idx 0)
(idx2 0))
; horizontal 14 ~ 8
(loop for j from 0 to 7 do
(when (= (aref matrix 8 j) *flight*)
(setf (aref matrix 8 j) (infochar->color (aref fbstring idx)))
(incf idx)))
; vertical 14 ~ 8
(loop for i from (- modules 1) downto (- modules 7) do
(setf (aref matrix i 8) (infochar->color (aref fbstring idx2)))
(incf idx2))
; horizontal 7 ~ 0
(loop for j from (- modules 8) downto (- modules 1) do
(setf (aref matrix 8 j) (infochar->color (aref fbstring idx)))
(incf idx))
; vertical 7 ~ 0
(loop for i from 8 downto 0 do
(when (= (aref matrix i 8) *flight*)
(setf (aref matrix i 8) (infochar->color (aref fbstring idx2)))
(incf idx2))))
matrix)
;; Paint Version information
(defun paint-version (vbstring matrix modules)
(assert (= (length vbstring) 18))
(let ((j 5)
(i (- modules 9))
(start (- modules 9))
(border (- modules 11)))
(loop for idx from 0 to 17 do
(setf (aref matrix i j) (infochar->color (aref vbstring idx)))
(setf (aref matrix j i) (infochar->color (aref vbstring idx)))
(if (>= (- i 1) border)
(decf i)
(progn
(decf j)
(setf i start))))))
(defun codeword-placement (bstring version correct &key (blank *blank*))
(let* ((matrix (make-matrix version :blank blank)))
(setf matrix (paint-function-pattern matrix version :blank blank))
;(print matrix)
(setf matrix (paint-encoding bstring matrix version :blank blank))
; mask pattern
(multiple-value-bind (matrix pat)
(mask-matrix matrix)
; format information
(let ((fbstring (concatenate 'string (aref *errc-indicator* (corrlev->index correct))
(aref *mask-pattern-ref* pat))))
(paint-format (info->bstring fbstring) matrix (matrix-modules version)))
; Version information
(when (>= version 7)
(let ((vbstring (decimal->bstring version 6)))
(paint-version (info->bstring vbstring :format-p nil) matrix (matrix-modules version))))
(dbg :qr-matrix "~A~%" matrix)
matrix)))
(defun reserved-module-p (x y version)
"If (X, Y) is reserved by Function Pattern, or Format Information, or Version
Information: they cannot be masked."
(let ((modules (matrix-modules version)))
(or (and (<= 0 x 8) (<= 0 y 8)) ; 1) Upper-Left Position Detection Pattern
(and (<= 0 x 8) (<= (- modules 8) y (- modules 1))) ; 2) Upper-Right PDP
(and (<= 0 y 8) (<= (- modules 8) x (- modules 1))) ; 3) Lower-Left PDP
)))
;;------------------------------------------------------------------------------
;; One Ring to Rule Them All, One Ring to Find Them,
;; One Ring to Bring Them All and In the Darkness Blind Them:
;; This function wraps all we need.
;;------------------------------------------------------------------------------
(defun qrencode (text &key (fpng "out.png") (version 1) (mode :binary)
(correction :level-q) (pixsize 9) (margin 6))
(declare (type string text) (type number version)
(type symbol mode correction))
; (sdebug :qr-input :qr-errc :qr-matrix)
(sdebug :qr-input-core)
(let* ((input (string->input text :version version
:mode mode :correction correction))
(bstring (input->bstring input)))
(dbg :qr-input "~A" bstring)
(dbg :qr-input "~A" (length bstring))
; version adusted
(with-slots (version) input
(let ((matrix (codeword-placement bstring version correction)))
(matrix->png matrix fpng version pixsize margin))))
(format t "png file `~A' wrote..." fpng)
(values))
| 12,601 | Common Lisp | .lisp | 282 | 41.340426 | 91 | 0.641265 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 1e8e582d9fc2a2232709db2efc1d91539dee7f11602e1850eaabffeb20ef0135 | 13,109 | [
-1
] |
13,110 | qr-condition.lisp | jnjcc_cl-qrencode-deprecated/src/qr-condition.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-condition.lisp
;;;; This file contains utilies that do error handling.
;;;;
(in-package #:cl-qrencode)
; Self-explaining, no comments needed...
(define-condition qr-condition (error)
((file-name :accessor file-name
:initarg :file-name
:initform nil)
(function-name :accessor function-name
:initarg :function-name
:initform nil))
(:report (lambda (condition stream)
(format stream "qr-condition occurred at `~A' in `~A'"
(function-name condition)
(file-name condition)))))
(define-condition qr-bad-arguments (qr-condition)
((arguments :accessor arguments
:initarg :arguments)
(what :accessor what
:initform "Bad argument(s)")
(how :accessor how
:initarg :how))
(:report (lambda (condition stream)
(if (and (function-name condition) (file-name condition))
(progn
(format stream "Function `~A' in file `~A' says:~%`~A': `~A'~%"
(function-name condition)
(file-name condition)
(what condition)
(arguments condition))
(format stream "~A~%" (how condition)))
(format stream "~A~%" (what condition))))))
(define-condition qr-not-implemented (qr-condition)
((mode :accessor mode
:initarg :mode
:initform "KANJI mode")
(what :accessor what
:initform "not implemented yet in current version."))
(:report (lambda (condition stream)
(format stream "~A ~A~%" (mode condition)
(what condition)))))
;; For testcases
(define-condition qr-test-failure (qr-condition)
((arguments :accessor arguments
:initarg :arguments))
(:report (lambda (condition stream)
(format stream "Function ~A fails with arguments ~A"
(function-name condition) (arguments condition))))) | 2,409 | Common Lisp | .lisp | 63 | 34.507937 | 71 | 0.701154 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 48b4e85b05d5a48eea2dab001aee559089a55872afd4a15ad76bf515f013ec44 | 13,110 | [
-1
] |
13,111 | qr-input.lisp | jnjcc_cl-qrencode-deprecated/src/qr-input.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-input.lisp
;;;; This file contains utilities that convert string to QR-INPUT class.
;;;;
(in-package #:cl-qrencode)
(defclass qr-input ()
; VERSION: 1~40
((version :initarg :version :initform 1 :accessor version)
; MODE indicator: :numberic, :alphanumeric, :binary, or :kanji
(mode :initarg :mode :initform :binary :reader mode)
; Correction: :level-l :level-m :level-q :level-h
(correction :initarg :correction :initform :level-q :reader correction)
; Raw input data
(data :initarg :data :reader data)
; Data encoded into bstring, depends on MODE only
(data-bstring :initarg :data-bstring :accessor data-bstring)))
(defmethod print-object ((input qr-input) stream)
(fresh-line)
(format stream ">>>>>>>>>>>>>>>>>>>>>>>>>>>>~%")
(format stream "Object of class QR-INPUT:~%~T")
(format stream "Data:~T`~A'~%~TVersion:~T~A~%~TMode:~T~A~%~TCorrection Level:~T~A"
(data input) (version input) (mode input) (correction input))
(format stream "~%<<<<<<<<<<<<<<<<<<<<<<<<<<<<~%"))
(defmethod encode-input ((input qr-input))
(with-slots (version mode data data-bstring) input
(setf data-bstring (data->bstring data mode))
; Terminator
(setf data-bstring (concatenate 'string data-bstring
"0000")))
input)
(defmethod adjust-version ((input qr-input) data-len)
"Assume we can find a version to hold all data"
(with-slots (version mode correction data data-bstring) input
(loop for ver from version to 41 do
(when (= ver 41)
(setf version 41)
(return))
; mode indicator length, character count indicator length
(let ((mil 4)
(cil (count-indicator-bits ver mode)))
(when (<= (* (ceiling (+ mil cil data-len) 8) 8)
(data-bits-capacity ver correction))
(unless (= version ver)
(dbg :qr-input-core "Version reset from ~A to ~A~%" version ver)
(setf version ver))
(return))))))
(defun string->input (text &key (version 1) (mode :binary) (correction :level-q))
"Put the input text into the QR-INPUT instance, with version adjusted"
(declare (type string text) (type symbol mode correction))
(setf version (max version 1))
(setf version (min version 40))
(let ((input (make-instance 'qr-input :data text
:version version :mode mode :correction correction)))
(let ((len (length (data-bstring (encode-input input)))))
(adjust-version input len))
input)) | 3,107 | Common Lisp | .lisp | 69 | 41.391304 | 84 | 0.686016 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | c204f4cf3be042b8ca3adb8fde1d41cb0c59eae37d6f76b37ec541ff3c21249b | 13,111 | [
-1
] |
13,112 | qr-utils.lisp | jnjcc_cl-qrencode-deprecated/src/qr-utils.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-utils.lisp
;;;; This file contains some basic utilies.
;;;;
(in-package #:cl-qrencode)
;; Use it or not, I list it here.
(defmacro while (test &rest body)
"I always wonder why there is no WHILE in Common Lisp."
`(do ()
((not ,test) nil)
,@body))
;; Adapted from P. Norvig's PAIP
(defvar *dbg-ids* nil)
(defun sdebug (&rest ids)
(setf *dbg-ids* (union ids *dbg-ids*)))
(defun undebug (&rest ids)
(setf *dbg-ids* (if (null ids)
nil
(set-difference *dbg-ids* ids))))
(defun dbg (id format-string &rest args)
(when (member id *dbg-ids*)
(fresh-line *debug-io*)
(apply #'format *debug-io* format-string args))) | 1,349 | Common Lisp | .lisp | 36 | 35.055556 | 71 | 0.699771 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 6d1b93b353ec3f4551b865719f8d5a7fd5ecf89734505ce318c6ec8a3606d1a6 | 13,112 | [
-1
] |
13,113 | qr-data-bstring.lisp | jnjcc_cl-qrencode-deprecated/src/qr-data-bstring.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-data-bstring.lisp
;;;; This file contains utilies that convert QR-INPUT to binary string (bstring,
;;;; or bitstream, we may say).
;;;; In particular, this file contains the four functions for encoding real data.
;;;;
(in-package #:cl-qrencode)
;; (0) NUMERIC mode: input data string is divided into groups of three digits.
(defun group->decimal (num-group)
"NUM-GROUP is either 1 digit, 2 digits, or 3 digits long, encode them into decimal."
(declare (type string num-group))
(let ((len (length num-group))
(result 0))
(when (or (< len 1) (> len 3))
(error 'qr-bad-arguments :file-name "qr-data-bstring.lisp"
:function-name "group->decimal" :arguments '(num-group)
:how "Under NUMERIC mode, input is divided into groups of 3 (or less) digits."))
(dotimes (idx len)
(let ((ch (char num-group idx)))
(when (not (digit-char-p ch))
(error 'qr-bad-arguments :file-name "qr-data-bstring.lisp"
:function-name "group->decimal" :arguments '(num-group)
:how "Non-digit character appears under NUMERIC mode"))
(setf result (+ (* result 10) (- (char-code ch) (char-code #\0))))))
result))
(defun group->bstring (num-group)
"Encode NUM-GROUP into bstring."
(declare (type string num-group))
(case (length num-group)
(3 (decimal->bstring (group->decimal num-group) 10)) ;10 bits long for 3 digits
(2 (decimal->bstring (group->decimal num-group) 7)) ;7 bits long for 2 digits
(1 (decimal->bstring (group->decimal num-group) 4)) ;4 bits long for 1 digits
(t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp"
:function-name "group->bstring" :arguments '(num-group)
:how "Under NUMERIC mode, input is diviede into groups of 3 (or less) digits."))))
(defun numeric->bstring (data)
"Convert input DATA string to bstring under NUMERIC mode."
(declare (type string data))
(let ((len (length data))
(bstring ""))
(do ((idx 0 (incf idx 3)))
((>= idx len) nil)
(cond
((> len (+ idx 2)) ; more than 3 chars left
(setf bstring (concatenate 'string bstring
(group->bstring (subseq data idx (+ idx 3))))))
((= len (+ idx 2)) ; 2 chars left
(setf bstring (concatenate 'string bstring
(group->bstring (subseq data idx (+ idx 2))))))
((= len (+ idx 1)) ; only 1 char left
(setf bstring (concatenate 'string bstring
(group->bstring (subseq data idx (+ idx 1))))))))
bstring))
;; (1) ALPHANUMERIC mode: data is divided into groups of two characters, we call it "pair"
(defun char->decimal (char)
"Only digits, capital letters, and some special characters available."
(declare (type character char))
(cond
((char<= #\0 char #\9)
(- (char-code char) (char-code #\0)))
((char<= #\A char #\Z)
(+ (- (char-code char) (char-code #\A)) 10))
((char= char #\Space) 36)
((char= char #\$) 37)
((char= char #\%) 38)
((char= char #\*) 39)
((char= char #\+) 40)
((char= char #\-) 41)
((char= char #\.) 42)
((char= char #\/) 43)
((char= char #\:) 44)
(t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp"
:function-name "char->decimal" :arguments char
:how "Character not recognized under ALPHANUMERIC mode."))))
(defun pair->decimal (alpha-pair)
"ALPHA-PAIR is either 2 char or 1 char long, encode them into decimal."
(declare (type string alpha-pair))
(setf alpha-pair (string-upcase alpha-pair))
(let ((len (length alpha-pair)))
(cond
((= len 1) (char->decimal (char alpha-pair 0)))
((= len 2) (+ (* 45 (char->decimal (char alpha-pair 0)))
(char->decimal (char alpha-pair 1))))
(t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp"
:function-name "pair->decimal" :arguments alpha-pair
:how "Under ALPHANUMERIC mode, data is divided into pair of 2.")))))
(defun pair->bstring (alpha-pair)
"Encode ALPHA-PAIR to bstring: 11 bits for two char long, 6 bits for 1 char long."
(declare (type string alpha-pair))
(let ((len (length alpha-pair)))
(cond
((= len 2) (decimal->bstring (pair->decimal alpha-pair) 11))
((= len 1) (decimal->bstring (pair->decimal alpha-pair) 6))
(t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp"
:function-name "pair->bstring" :arguments alpha-pair
:how "Under ALPHANUMERIC mode, data is divided into pair of 2.")))))
(defun alnum->bstring (data)
"Convert input DATA string to bstring under ALPHANUMERIC mode."
(declare (type string data))
(let ((len (length data))
(data (string-upcase data))
(bstring ""))
(do ((idx 0 (incf idx 2)))
((>= idx len) nil)
(if (>= (+ idx 1) len) ; only 1 char left
(setf bstring (concatenate 'string bstring
(pair->bstring (subseq data idx (+ idx 1)))))
(setf bstring (concatenate 'string bstring
(pair->bstring (subseq data idx (+ idx 2)))))))
bstring))
;; (3) BINARY mode: each value is directly encoded in 8 bit long binary representation
;; TODO: JIS X 0201 character sets? I have to look into it.
(defun binary->bstring (data)
"Convert input DATA string to bstring under BINARY mode."
(declare (type string data))
(labels ((concat (prev cur) ; PREV is the result by now
(concatenate 'string prev
(decimal->bstring (char-code cur) 8))))
(reduce #'concat data :initial-value "")))
;; (4) KANJI mode: Shift JIS system, two bytes for a single character. JIS X 0208
(defun word->decimal (kanji-word)
"Encode a KANJI-WORD to decimal."
; Use BABEL library to erase SBCL-specific problem.
; Thanks to xach <https://github.com/xach>
(let ((result (babel-encodings::ucs-to-cp932 (char-code kanji-word)))
(subtractor 0))
(setf subtractor (cond
((<= #x8140 result #x9FFC) #x8140)
((<= #xE040 result #xEBBF) #xC140)))
(decf result subtractor)
(setf result (+ (* (ash result -8) #xC0)
(boole boole-and result #xFF)))))
(defun word->bstring (kanji-word)
"Encode a KANJI-WORD to bstring using 13 bits."
(decimal->bstring (word->decimal kanji-word) 13))
(defun kanji->bstring (data)
"Convert input DATA string to bstring under KANJI mode."
(declare (type string data))
(let ((result ""))
(loop for kanji-word across data do
(setf result (concatenate 'string result
(word->bstring kanji-word))))
result)) | 6,976 | Common Lisp | .lisp | 156 | 40.858974 | 90 | 0.665884 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | adce8373e9186810ca62ce42bbd81f32ea30f424a7fc62c29af5fff2da589bcd | 13,113 | [
-1
] |
13,114 | qr-mask.lisp | jnjcc_cl-qrencode-deprecated/src/qr-mask.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-mask.lisp
;;;; This file contains data mask
(in-package #:cl-qrencode)
(defun copy-matrix (matrix)
(let* ((width (floor (sqrt (array-total-size matrix))))
(ret (make-array `(,width ,width))))
(loop for i from 0 to (- width 1) do
(loop for j from 0 to (- width 1) do
(setf (aref ret i j) (aref matrix i j))))
ret))
;; masking applied to encoding region (excluding FI && VI)
(defun mask-matrix-single (matrix indicator)
"Mask matrix using INDICATOR-th mask pattern"
(let ((ret (copy-matrix matrix))
(width (floor (sqrt (array-total-size matrix))))
(mask-p (mask-condition indicator)))
(loop for i from 0 to (- width 1) do
(loop for j from 0 to (- width 1) do
(when (and (or (= (aref ret i j) 0)
(= (aref ret i j) 1))
(funcall mask-p i j))
(setf (aref ret i j) (mod (+ (aref ret i j) 1) 2)))))
ret))
(defun mask-matrix (matrix)
"Returns masked matrix & mask pattern reference"
; 8 mask patterns
(let ((result (make-array 8))
(penalty 0)
(pattern 0))
(loop for i from 0 to 7 do
(setf (aref result i) (mask-matrix-single matrix i)))
(loop for i from 0 to 7 do
(let ((mpenalty (mask-penalty (aref result i))))
(when (or (= i 0)
(> penalty mpenalty))
(setf penalty mpenalty)
(setf pattern i))))
(values (aref result pattern) pattern)))
(defun mask-penalty (matrix)
(let ((width (floor (sqrt (array-total-size matrix))))
(penalty 0))
; feature 1: N1 = 3
(loop for row from 0 to (- width 1) do
(loop for col from 0 to (- width 1) do
(let ((nr-same 0)
(color (aref matrix row col)))
(loop for r from -1 to 1 do
(unless (or (< (+ row r) 0) (<= width (+ row r)))
(loop for c from -1 to 1 do
(unless (or (< (+ col c) 0) (<= width (+ col c))
(= r c 0))
(when (same-color-p color (aref matrix (+ row r) (+ col c)))
(incf nr-same))))))
(when (> nr-same 5)
(incf penalty (- nr-same 5))))))
; feature 2: N2 = 3
(loop for row from 0 to (- width 2) do
(loop for col from 0 to (- width 2) do
(let ((bcount 0))
(when (dark-module-p matrix row col)
(incf bcount))
(when (dark-module-p matrix (+ row 1) col)
(incf bcount))
(when (dark-module-p matrix row (+ col 1))
(incf bcount))
(when (dark-module-p matrix (+ row 1) (+ col 1))
(incf bcount))
(when (or (= bcount 0) (= bcount 4))
(incf penalty 3)))))
; feature 3: N3 = 40
(loop for row from 0 to (- width 1) do
(loop for col from 0 to (- width 7) do
(when (and (dark-module-p matrix row col)
(not (dark-module-p matrix row (+ col 1)))
(dark-module-p matrix row (+ col 2))
(dark-module-p matrix row (+ col 3))
(dark-module-p matrix row (+ col 4))
(not (dark-module-p matrix row (+ col 5)))
(dark-module-p matrix row (+ col 6)))
(incf penalty 40))))
(loop for row from 0 to (- width 7) do
(loop for col from 0 to (- width 1) do
(when (and (dark-module-p matrix row col)
(not (dark-module-p matrix (+ row 1) col))
(dark-module-p matrix (+ row 2) col)
(dark-module-p matrix (+ row 3) col)
(dark-module-p matrix (+ row 4) col)
(not (dark-module-p matrix (+ row 5) col))
(dark-module-p matrix (+ row 6) col))
(incf penalty 40))))
; feature 4: N4 = 10; TODO: too much redundancy!!
(let ((darkcount 0)
(ratio 0))
(loop for row from 0 to (- width 1) do
(loop for col from 0 to (- width 1) do
(when (dark-module-p matrix row col)
(incf darkcount))))
(setf ratio (/ (abs (- (/ (* 100 darkcount) width width) 50)) 5))
(incf penalty (* ratio 10)))
penalty))
| 4,339 | Common Lisp | .lisp | 114 | 33.780702 | 71 | 0.619625 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 4fbcf1f8f51ccfedebcb15406821094316666409023d6c9f993e5bf9850ed64e | 13,114 | [
-1
] |
13,115 | qr-blocks.lisp | jnjcc_cl-qrencode-deprecated/src/qr-blocks.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-blocks.lisp
;;;; This file contains
(in-package #:cl-qrencode)
(defclass qr-block ()
((block-id :initarg :block-id :accessor block-id) ; 1 or 2?
(data-codewords :initarg :data-codewords :accessor data-codewords)
(errc-codewords :initarg :errc-codewords :initform nil :accessor errc-codewords)))
(defun bstring->blocks (bstring version correct)
(let ((blocks nil))
; block 1 & 2
(loop for blk from 1 to 2 do
(let ((nr-blk (nr-block version correct blk))
(sz-blk (* (nr-data-codewords version correct blk) 8))
(data ""))
(loop for i from 1 to nr-blk do
(setf data (subseq bstring 0 sz-blk))
(setf bstring (subseq bstring sz-blk))
(let ((blkobj (make-instance 'qr-block :data-codewords data
:block-id blk)))
(push blkobj blocks)))))
(reverse blocks)))
(defun block-errc (ablock version correct)
(let ((bstring (data-codewords ablock))
(blk (block-id ablock)))
(setf (errc-codewords ablock) (errcobj->bstring
(generate-errcobj bstring version correct blk)))
(fresh-line)))
(defun do-errc (blocks version correct)
(loop for ablock in blocks do
(block-errc ablock version correct)))
(defun blocks->bstring (blocks version correct)
(let ((bstring "")
(nr-blk (length blocks))
(idx (max (nr-data-codewords version correct 1)
(nr-data-codewords version correct 2)))
(idx2 (nr-errc-codewords version correct)))
(loop for i from 0 to (- idx 1) do
(loop for j from 1 to nr-blk do
(and (< (* 8 i) (length (data-codewords (nth (- j 1) blocks))))
(setf bstring (concatenate 'string bstring
(subseq (data-codewords (nth (- j 1) blocks))
(* 8 i)
(* 8 (+ i 1))))))))
(loop for i from 0 to (- idx2 1) do
(loop for j from 1 to nr-blk do
(setf bstring (concatenate 'string bstring
(subseq (errc-codewords (nth (- j 1) blocks))
(* 8 i)
(* 8 (+ i 1)))))))
bstring)) | 2,635 | Common Lisp | .lisp | 64 | 37.046875 | 85 | 0.672649 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 7322903bf06ecd8489b41bc8e5449604729af91fb306b07f295985490ee0814d | 13,115 | [
-1
] |
13,116 | qr-image.lisp | jnjcc_cl-qrencode-deprecated/src/qr-image.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-image.lisp
;;;; This file contains utilities to encode symbol into images.
;;;; For now, only png format, using zpng library
(in-package #:cl-qrencode)
(defun set-color (pngarray x y color)
(setf (aref pngarray x y 0) color)
(setf (aref pngarray x y 1) color)
(setf (aref pngarray x y 2) color))
(defun matrix->png (matrix fpng version pixsize margin)
(let* ((modules (matrix-modules version))
(size (+ (* modules pixsize) (* margin 2)))
(qrpng (make-instance 'zpng:png :width size :height size))
(qrarray (zpng:data-array qrpng)))
(do ((x 0 (1+ x)))
((>= x size))
(do ((y 0 (1+ y)))
((>= y size))
(if (and (<= margin x (- size margin 1))
(<= margin y (- size margin 1)))
(let ((i (floor (- x margin) pixsize))
(j (floor (- y margin) pixsize)))
(if (dark-module-p matrix i j)
(set-color qrarray x y 0)
(set-color qrarray x y 255)))
(set-color qrarray x y 255))))
(zpng:write-png qrpng fpng :if-exists :supersede))) | 1,676 | Common Lisp | .lisp | 40 | 39.175 | 71 | 0.681568 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | d040e0292a649bf59de62119d5aa906c52c7b6c55032ab7c8fc242509fb93399 | 13,116 | [
-1
] |
13,117 | qr-spec.lisp | jnjcc_cl-qrencode-deprecated/src/qr-spec.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-spec.lisp
;;;; This file contains some data structures for the QR specifications.
;;;;
(in-package #:cl-qrencode)
;;------------------------------------------------------------------------------
;; (0) First, we need to encode the data mode we are using into bstring. There are
;; four encodable character sets: :NUMERIC, :ALPHANUMERIC, :BINARY, :KANJI
;;------------------------------------------------------------------------------
;; TODO: Also, there should be mode indicators for Structured Append(0011),
;; FNC1(0101 | 1001) and ECI(0111) mode. -- Ch8.4
(defvar *mode-indicator* #("0001" "0010" "0100" "1000" "0011" "0101" "1001" "0111")
"Four-bit identifier indicating in which mode the NEXT data sequence is
encoded.")
(defun mode->index (mode &key (default-p nil))
"DEFAULT-P means if we want use default value for non-recognizable MODE."
(declare (type symbol mode))
(case mode
(:numeric 0)
(:alphanumeric 1)
(:binary 2) ; 8-bit byte data
(:kanji 3)
(t (if default-p
1
(error 'qr-bad-arguments :file-name "qr-spec.lisp" :function-name "mode->index"
:arguments '(mode) :how "Allowed mode only includes `:numeric', `:alphanumeric',
`:binary' and `:kanji'")))))
;;; Encode Mode Indicator into bstring
(defun mode->bstring (mode)
(declare (type symbol mode))
(let ((idx (mode->index mode :default-p t)))
(aref *mode-indicator* idx)))
;;------------------------------------------------------------------------------
;; (1) Second, we need to encode the character count of the data into bstring,
;; which is the so-called Character Count Indicator. The number of bits we
;; use to encode it is decided according to the version and the mode of QRCode.
;;------------------------------------------------------------------------------
(defvar *count-indicator-bits-table*
; :numeric, :alpahnumeric, :binary, :kanji
#2A((10 9 8 8) ; Version 1 ~ 9
(12 11 16 10) ; Version 10 ~ 26
(14 13 16 12)) ; Version 27 ~ 40
"Number of bits in Character Count Indicator, which varies according to the
mode and symbol version in use.")
(defun count-indicator-bits (version mode)
"# of bits used to represent length of data."
(let (i j)
(setf i (cond
((<= 1 version 9) 0)
((<= 10 version 26) 1)
((<= 27 version 40) 2)
(t (error 'qr-bad-arguments :file-name "qr-spec.lisp"
:function-name "count-indicator-bits" :arguments '(version)
:how "Version ranges from 1 to 40."))))
(setf j (mode->index mode))
(aref *count-indicator-bits-table* i j)))
(defvar *data-capacity-table*
; http://www.denso-wave.com/qrcode/vertable1-e.html
; Version 1 ~ 40, depends on version and error correction level
; Table 7 ~ Table 11
#2A((152 128 104 72) (272 224 176 128) (440 352 272 208)
(640 512 384 288) (864 688 496 368) ; Version 1 ~ 5
(1088 864 608 480) (1248 992 704 528) (1552 1232 880 688)
(1856 1456 1056 800) (2192 1728 1232 976) ; Version 6 ~ 10
(2592 2032 1440 1120) (2960 2320 1648 1264) (3424 2672 1952 1440)
(3688 2920 2088 1576) (4184 3320 2360 1784) ; Version 11 ~ 15
(4712 3624 2600 2024) (5176 4056 2936 2264) (5768 4504 3176 2504)
(6360 5016 3560 2728) (6888 5352 3880 3080) ; Version 16 ~ 20
(7456 5712 4096 3248) (8048 6256 4544 3536) (8752 6880 4912 3712)
(9392 7312 5312 4112) (10208 8000 5744 4304) ; Version 21 ~ 25
(10960 8496 6032 4768) (11744 9024 6464 5024) (12248 9544 6968 5288)
(13048 10136 7288 5608) (13880 10984 7880 5960) ; Version 26 ~ 30
(14744 11640 8264 6344) (15640 12328 8920 6760) (16568 13048 9368 7208)
(17528 13800 9848 7688) (18488 14496 10288 7888) ; Version 31 ~ 35
(19472 15312 10832 8432) (20528 15936 11408 8768) (21616 16816 12016 9136)
(22496 17728 12656 9776) (23648 18672 13328 10208)); Version 36 ~ 40
"Data bits capacity for each version and correction level, including mode indicator
and character count indicator, _not_ including error correction bits. And of course,
for each mode, the character capacity are different.")
(defun corrlev->index (correct &key (default-p nil))
"Get corresponding index for correct level, :level-q will be default."
(declare (type symbol correct))
(case correct
(:level-l 0)
(:level-m 1)
(:level-q 2)
(:level-h 3)
(t (if default-p
2
(error 'qr-bad-arguments :file-name "qr-spec.lisp"
:function-name "corrlev->index"
:arguments '(correct) :how "Allowded Correction Level only includes
`:level-l',`:level-m', `:level-q' and `:level-h'")))))
(defun data-bits-capacity (version correct)
(declare (type number version)
(type symbol correct))
(if (<= 1 version 40)
(let ((j (corrlev->index correct)))
(aref *data-capacity-table* (- version 1) j))
(error 'qr-bad-arguments :file-name "qr-spec.lisp" :function-name "data-bits-capacity"
:arguments '(version) :how "Version ranges from 1 to 40.")))
;;------------------------------------------------------------------------------
;; (3) Error Correction codewords: Table 13 ~ Table 22
;; NOTICE: I typed, this sucks
;;------------------------------------------------------------------------------
(defvar *errc-words-table*
; (Version, errc-level) ==> (# of error correction codeword for each blk, # of block 1,
; # of data codewords, # of block 2, # of data codewords)
; :level-l :level-m :level-q :level-h
#3A(
((7 1 19 0 0) (10 1 16 0 0) (13 1 13 0 0) (17 1 9 0 0)) ; Version 1
((10 1 34 0 0) (16 1 28 0 0) (22 1 22 0 0) (28 1 16 0 0))
((15 1 55 0 0) (26 1 44 0 0) (18 2 17 0 0) (22 2 13 0 0))
((20 1 80 0 0) (18 2 32 0 0) (26 2 24 0 0) (16 4 9 0 0))
((26 1 108 0 0) (24 2 43 0 0) (18 2 15 2 16) (22 2 11 2 12)) ; Version 5
((18 2 68 0 0) (16 4 27 0 0) (24 4 19 0 0) (28 4 15 0 0))
((20 2 78 0 0) (18 4 31 0 0) (18 2 14 4 15) (26 4 13 1 14))
((24 2 97 0 0) (22 2 38 2 39) (22 4 18 2 19) (26 4 14 2 15))
((30 2 116 0 0) (22 3 36 2 37) (20 4 16 4 17) (24 4 12 4 13))
((18 2 68 2 69) (26 4 43 1 44) (24 6 19 2 20) (28 6 15 2 16)) ; Version 10
((20 4 81 0 0) (30 1 50 4 51) (28 4 22 4 23) (24 3 12 8 13))
((24 2 92 2 93) (22 6 36 2 37) (26 4 20 6 21) (28 7 14 4 15))
((26 4 107 0 0) (22 8 37 1 38) (24 8 20 4 21) (22 12 11 4 12))
((30 3 115 1 116) (24 4 40 5 41) (20 11 16 5 17) (24 11 12 5 13))
((22 5 87 1 88) (24 5 41 5 42) (30 5 24 7 25) (24 11 12 7 13)) ; Version 15
((24 5 98 1 99) (28 7 45 3 46) (24 15 19 2 20) (30 3 15 13 16))
((28 10 46 1 47) (28 10 46 1 47) (28 1 22 15 23) (28 2 14 17 15))
((30 5 120 1 121) (26 9 43 4 44) (28 17 22 1 23) (28 2 14 19 15))
((28 3 113 4 114) (26 3 44 11 45) (26 17 21 4 22) (26 9 13 16 14))
((28 3 107 5 108) (26 3 41 13 42) (30 15 24 5 25) (28 15 15 10 16)) ; Version 20
((28 4 116 4 117) (26 17 42 0 0) (28 17 22 6 23) (30 19 16 6 17))
((28 2 111 7 112) (28 17 46 0 0) (30 7 24 16 25) (24 34 13 0 0))
((30 4 121 5 122) (28 4 47 14 48) (30 11 24 14 25) (30 16 15 14 16))
((30 6 117 4 118) (28 6 45 14 46) (30 11 24 16 25) (30 30 16 2 17))
((26 8 106 4 107) (28 8 47 13 48) (30 7 24 22 25) (30 22 15 13 16)) ; Version 25
((28 10 114 2 115) (28 19 46 4 47) (28 28 22 6 23) (30 33 16 4 17))
((30 8 122 4 123) (28 22 45 3 46) (30 8 23 26 24) (30 12 15 28 16))
((30 3 117 10 118) (28 3 45 23 46) (30 4 24 31 25) (30 11 15 31 16))
((30 7 116 7 117) (28 21 45 7 46) (30 1 23 37 24) (30 19 15 26 16))
((30 5 115 10 116) (28 19 47 10 48) (30 15 24 25 25) (30 23 15 25 16)) ; Version 30
((30 13 115 3 116) (28 2 46 29 47) (30 42 24 1 25) (30 23 15 28 16))
((30 17 115 0 0) (28 10 46 23 47) (30 10 24 35 25) (30 19 15 35 16))
((30 17 115 1 116) (28 14 46 21 47) (30 29 24 19 25) (30 11 15 46 16))
((30 13 115 6 116) (28 14 46 23 47) (30 44 24 7 25) (30 59 16 1 17))
((30 12 121 7 122) (28 12 47 26 48) (30 39 24 14 25) (30 22 15 41 16)) ; Version 35
((30 6 121 14 122) (28 6 47 34 48) (30 46 24 10 25) (30 2 15 64 16))
((30 17 122 4 123) (28 29 46 14 47) (30 49 24 10 25) (30 24 15 46 16))
((30 4 122 18 123) (28 13 46 32 47) (30 48 24 14 25) (30 42 15 32 16))
((30 20 117 4 118) (28 40 47 7 48) (30 43 24 22 25) (30 10 15 67 16))
((30 19 118 6 119) (28 18 47 31 48) (30 34 24 34 25) (30 20 15 61 16)) ; Version 40
))
(defun errc-words (version correct idx)
"IDX is 0 ~ 4, their corresponding meanings are explained above."
(let ((j (corrlev->index correct)))
(aref *errc-words-table* (- version 1) j idx)))
(defun nr-errc-codewords (version correct)
(declare (type number version)
(type symbol correct))
(errc-words version correct 0))
(defun nr-block (version correct blk)
(assert (or (= blk 1) (= blk 2)))
(errc-words version correct (- (* blk 2) 1)))
(defun nr-data-codewords (version correct blk)
(declare (type number version)
(type symbol correct))
(assert (or (= blk 1) (= blk 2)))
(errc-words version correct (* 2 blk)))
(defun nr-codewords (version correct)
"Both data codewords and error correction codewords."
(declare (type number version)
(type symbol correct))
(+ (nr-errc-codewords version correct)
(nr-data-codewords version correct)))
;;------------------------------------------------------------------------------
;; (4) We now must choose the best mask pattern.
;; First, we make an empty matrix of the size modules: Table 1
;;------------------------------------------------------------------------------
(defvar *module-capacity-table*
#2A(
(21 202 31 208 26 0) (25 235 31 359 44 7)
(29 243 31 567 70 7) (33 251 31 807 100 7)
(37 259 31 1079 134 7) (41 267 31 1383 172 7)
(45 390 67 1568 196 0) (49 398 67 1936 242 0)
(53 406 67 2336 292 0) (57 414 67 2768 346 0) ; Version 10
(61 422 67 3232 404 0) (65 430 67 3728 466 0)
(69 438 67 4256 532 0) (73 611 67 4651 581 3)
(77 619 67 5243 655 3) (81 627 67 5867 733 3)
(85 635 67 6523 815 3) (89 643 67 7211 901 3)
(93 651 67 7931 991 3) (97 659 67 8683 1085 3) ; Version 20
(101 882 67 9252 1156 4) (105 890 67 10068 1258 4)
(109 898 67 10916 1364 4) (113 906 67 11796 1474 4)
(117 914 67 12708 1588 4) (121 922 67 13652 1706 4)
(125 930 67 14628 1828 4) (129 1203 67 15371 1921 3)
(133 1211 67 16411 2051 3) (137 1219 67 17483 2185 3) ; Version 30
(141 1227 67 18587 2323 3) (145 1235 67 19723 2465 3)
(149 1243 67 20891 2611 3) (153 1251 67 22091 2761 3)
(157 1574 67 23008 2876 0) (161 1582 67 24272 3034 0)
(165 1590 67 25568 3196 0) (169 1598 67 26896 3362 0)
(173 1606 67 28256 3532 0) (177 1614 67 29648 3706 0)) ; Version 40
"Number of modules(as version increased, 4 modules added) A | Function pattern
modules B | Format and Version information modules C | Data modules(A^2-B-C) | Data
capacity codewords(including error correction) | Remainder bits.")
(defun module-capacity (version idx)
(when (or (not (<= 1 version 40))
(not (<= 0 idx 5)))
(error 'qr-bad-arguments :file-name "qr-spec.lisp"
:function-name "module-capacity" :arguments '(version idx)
:how "VERSION ranges from 1 to 40; IDX ranges from 0 to 5."))
(aref *module-capacity-table* (- version 1) idx))
(defun matrix-modules (version)
"Overall modules: (MATRIX-MODULES) * (MATRIX-MODULES)."
(if (<= 1 version 40)
(module-capacity version 0)
(error 'qr-bad-arguments :file-name "qr-spec.lisp"
:function-name "matrix-modules"
:arguments version
:how "Version ranges from 1 to 40.")))
(defun remainder-bits (version)
"Remainder bits to be added after the error correction codeword."
(if (<= 1 version 40)
(module-capacity version 5)
(error 'qr-bad-arguments :file-name "qr-spec.lisp"
:function-name "remainder-bits" :arguments version
:how "Version ranges from 1 to 40.")))
;; Table E.1
(defvar *align-coord-table*
#2A(
(0 ()) (1 (6 18)) (1 (6 22))
(1 (6 26)) (1 (6 30)) (1 (6 34))
(6 (6 22 38)) (6 (6 24 42)) (6 (6 26 46))
(6 (6 28 50)) (6 (6 30 54)) (6 (6 32 58))
(6 (6 34 62)) (13 (6 26 46 66)) (13 (6 26 48 70))
(13 (6 26 50 74)) (13 (6 30 54 78)) (13 (6 30 56 82))
(13 (6 30 58 86)) (13 (6 34 62 90)) (22 (6 28 50 72 94))
(22 (6 26 50 74 98)) (22 (6 30 54 78 102)) (22 (6 28 54 80 106))
(22 (6 32 58 84 110)) (22 (6 30 58 86 114)) (22 (6 34 62 90 118))
(33 (6 26 50 74 98 122)) (33 (6 30 54 78 102 126)) (33 (6 26 52 78 104 130))
(33 (6 30 56 82 108 134)) (33 (6 34 60 86 112 138)) (33 (6 30 58 86 114 142))
(33 (6 34 62 90 118 146)) (46 (6 30 54 78 102 126 150)) (46 (6 24 50 76 102 128 154))
(46 (6 28 54 80 106 132 158)) (46 (6 32 58 84 110 136 162)) (46 (6 26 54 82 110 138 166))
(46 (6 30 58 86 114 142 170)))
"# of Alignment Patterns, row/column coordinates of center modules.")
(defun valid-center-p (x y modules)
"The Alignment Center is not in the Finder Patterns."
(not (or (and (<= 0 x 8) (<= 0 y 8)) ; In the upper left finder pattern
(and (<= 0 x 8)
(<= (- modules 8) y (- modules 1))) ; In the upper right finder pattern
(and (<= (- modules 8) x (- modules 1))
(<= 0 y 8)))))
;; Annex E
(defun align-centers (version)
"Get the centers of the Alignment Patterns."
(let* ((modules (matrix-modules version))
(coords (aref *align-coord-table* (- version 1) 1))
(len (length coords))
(centers ()))
(dotimes (i len)
(loop for j from i to (- len 1) do
(let ((x (elt coords i))
(y (elt coords j)))
(when (valid-center-p x y modules)
(setf centers (append centers (list `(,x ,y)))))
(when (not (= x y))
(when (valid-center-p y x modules)
(setf centers (append centers (list `(,y ,x)))))))))
centers))
(defun mask-condition (indicator)
"There are 8 mask patterns, get the mask generation condition, modules which
meet the condition are reversed."
(declare (type number indicator))
(lambda (x y)
(case indicator
(0 (= (mod (+ x y) 2) 0))
(1 (= (mod x 2) 0))
(2 (= (mod y 3) 0))
(3 (= (mod (+ x y) 3) 0))
(4 (= (mod (+ (floor x 2)
(floor y 3))
2) 0))
(5 (= (+ (mod (* x y) 2)
(mod (* x y) 3)) 0))
(6 (= (mod (+ (mod (* x y) 2)
(mod (* x y) 3))
2) 0))
(7 (= (mod (+ (mod (* x y) 3)
(mod (+ x y) 2))
2) 0))
(t (error 'qr-bad-arguments :file-name "qr-spec.lisp" :function-name "masker"
:arguments '(indicator)
:how "There are only 8 mask patterns, so indicator ranges from 0 to 7.")))))
;;------------------------------------------------------------------------------
;; (5) Now, We paint the Format Information & Version Information in the matrix modules
;;------------------------------------------------------------------------------
(defvar *errc-indicator* #("01" "00" "11" "10")
"Table 25: :LEVEL-L, :LEVEL-M, :LEVEL-Q, :LEVEL-H")
(defvar *mask-pattern-ref* #("000" "001" "010" "011" "100" "101" "110" "111")
"Table 23: Mask Pattern Reference and generation conditions.")
(defvar *format-generator* '((0 . 10) (0 . 8) (0 . 5) (0 . 4) (0 . 2) (0 . 1) (0 . 0)) ; Note: here, 0 means a^0
"Format Information Generator Polynomial <x^10 + x^8 + x^5 + x^4 + x^2 + x + 1>.")
(defvar *version-generator* '((0 . 12) (0 . 11) (0 . 10) (0 . 9) (0 . 8) (0 . 5) (0 . 2) (0 . 0))
"Version Information Generator Polynomial <x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1>.") | 16,916 | Common Lisp | .lisp | 314 | 49.39172 | 112 | 0.562395 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 8a75b48bee5f4a0bd16f432fae0fc75ff4c013f707e2559c7c668640d22964bd | 13,117 | [
-1
] |
13,118 | qr-errc.lisp | jnjcc_cl-qrencode-deprecated/src/qr-errc.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-errc.lisp
;;;; This file contains utilities that generate error correction polynomial
;;;; using Reed-Solomon Error Correction, or BCH code.
;;;;
(in-package #:cl-qrencode)
;;------------------------------------------------------------------------------
;; This is the implementation of Polynomial using association list
;; ((cofficient . exponent) ...), where each element is called a term.
;; There are two kinds of polynomial as to our Reed-Solomon error correction:
;; 1. Message Polynomial: the cofficients are the codewords
;; 2. Generator Polynomial: the cofficients are the exponent of generator A
;;------------------------------------------------------------------------------
(defclass qr-polynomial ()
((polynomial :initarg :polynomial
:accessor polynomial
:initform nil)))
(defclass message-polynomial (qr-polynomial)
())
(defclass generator-polynomial (qr-polynomial)
())
(defun print-term (stream coff exp &key (message-p t) (last-p nil))
"Print one term of the polynomial. MESSAGE-POLYNOMIAL as default."
(let ((mul-sign nil)) ;; is there "*" or not
(if message-p
(cond
((and (= coff 1) (= exp 0)) (format stream "1"))
((not (= coff 1)) (progn
(format stream "~A" coff)
(setf mul-sign t))))
(cond
((and (= coff 0) (= exp 0)) (format stream "1"))
((= coff 1) (progn (format stream "a")
(setf mul-sign t)))
((not (= coff 0)) (progn (format stream "a^~A" coff)
(setf mul-sign t)))))
(cond ((= exp 1) (progn (when mul-sign
(format stream "*"))
(format stream "x")))
((not (= exp 0)) (progn (when mul-sign
(format stream "*"))
(format stream "x^~A" exp)))))
(when (not last-p)
(format stream " + ")))
(defmethod print-object ((msgobj message-polynomial) stream)
(fresh-line)
(format stream ">>>>>>>>>>>>>>>>>>>>>>>>>>>>~%")
(format stream "Object of class MESSAGE-POLYNOMIAL:~%~T")
(let* ((poly (polynomial msgobj))
(size (- (length poly) 1)))
(dotimes (i (+ size 1))
(let ((term (nth i poly)))
(print-term stream (car term) (cdr term) :message-p t
:last-p (= i size)))))
(format stream "~%<<<<<<<<<<<<<<<<<<<<<<<<<<<<~%"))
(defmethod print-object ((genobj generator-polynomial) stream)
(fresh-line)
(format stream ">>>>>>>>>>>>>>>>>>>>>>>>>>>>~%")
(format stream "Object of class GENERATOR-POLYNOMIAL:~%~T")
(let* ((poly (polynomial genobj))
(size (- (length poly) 1)))
(dotimes (i (+ size 1))
(let ((term (nth i poly)))
(print-term stream (car term) (cdr term) :message-p nil
:last-p (= i size)))))
(format stream "~%<<<<<<<<<<<<<<<<<<<<<<<<<<<<~%"))
;;------------------------------------------------------------------------------
;; This is (part of) the implementation of Galois Field GF(2^8)
;; 1. Assume A is the primitive element of GF(2^8), so A^255 = 1, we will consider as
;; A^256 = A^1, A^257 = A^2, etc.
;; 2. *GF* is order of GF(2^8)
;; 3. *LOG* represents the corresponding exponent of A for each element in GF(2^8)
;; 4. *AEXP* represents the corresponding result for each A^elem
;; 5. *PP* Prime Polynomial in use is x^8 + x^4 + x^3 + x^2 + 1, or 1,0001,1101, or 285
;;------------------------------------------------------------------------------
(defvar *GF* 256)
(defvar *PP* 285)
; Let's assume (log 0) == -1
(defvar *LOG* (make-array *GF* :initial-element -1))
; Let's set A^0 = 1
(defvar *AEXP* (make-array *GF* :initial-element 1))
; This function must be called first before using *LOG* and *AEXP*
(defun init-galois-field ()
"Generate the cyclic group from the generator A, or we can say, this is the notation
of multiplication for this GF(2^8)."
(loop for i from 1 to (- *GF* 1) do
(setf (aref *AEXP* i) (* (aref *AEXP* (- i 1))
2))
(when (>= (aref *AEXP* i) *GF*)
(setf (aref *AEXP* i) (boole boole-xor (aref *AEXP* i) *PP*)))
(setf (aref *LOG* (aref *AEXP* i)) i))
(setf (aref *LOG* 1) 0))
(defun sort-polynomial (polynomial &key (message-p t))
"Sort polynomial according to exponent of the X-part, if it is a message polynomial,
we shall delete those terms whose cofficient are 0."
(when message-p
(setf polynomial (remove-if #'zerop polynomial :key #'car)))
(sort polynomial #'> :key #'cdr))
; Addition Group for this Galois Field GF(2^8)
(defmethod addition ((msgobj message-polynomial) (genobj generator-polynomial))
"Addition for GF(2^8) between a message polynomial and a generator polynomial,
exclusive-or operation to ensure closure, in fact."
(let ((msgpoly (copy-tree (polynomial msgobj)))
(genpoly (copy-tree (polynomial genobj)))
(result (make-instance 'message-polynomial)))
(loop for term in genpoly do
(let ((xexp (cdr term)))
(if (rassoc xexp msgpoly)
(setf (car (rassoc xexp msgpoly))
(boole boole-xor (car (rassoc xexp msgpoly))
(aref *AEXP* (car term))))
(setf msgpoly (append msgpoly (list (cons (aref *AEXP* (car term))
(cdr term))))))))
(setf (polynomial result) (sort-polynomial msgpoly))
result))
(defmethod addition ((genobj generator-polynomial) (msgobj message-polynomial))
"This is a group, so the addition operation should be commutative."
(addition msgobj genobj))
(defmethod addition ((genobj1 generator-polynomial) (genobj2 generator-polynomial))
"Addition fo GF(2^8) between two generator polynomial: obtain corresponding integer
of A^exp, XOR them, and then obtain the corresponding exponent."
(let ((genpoly1 (polynomial genobj1))
(genpoly2 (polynomial genobj2))
(result (make-instance 'generator-polynomial)))
(loop for term in genpoly2 do
(let ((xexp (cdr term)))
(if (rassoc xexp genpoly1)
(setf (car (rassoc xexp genpoly1))
(aref *LOG* (boole boole-xor (aref *AEXP* (car (rassoc xexp genpoly1)))
(aref *AEXP* (car term)))))
(setf genpoly1 (append genpoly1 (list term))))))
(setf (polynomial result) (sort-polynomial genpoly1 :message-p nil))
result))
; Multiplication Group for Galois Field GF(256)
; delta value for exp of generator A, delta value for exp of x
(defun multiply-each-term (genpoly &key (adelta 0) (xdelta 1) (part :cdr))
"Helper function for multiply generator polynomial.
Once some exponent of A surpasses *GF*, we do the math [(exp % *GF*) + 1]."
(labels ((modulo (exp-sum)
(if (>= exp-sum *GF*)
(+ (mod exp-sum *GF*) 1)
exp-sum))
(adder (term)
(case part
(:car (cons (modulo (+ (car term) adelta))
(cdr term)))
(:cdr (cons (car term)
(modulo (+ (cdr term) xdelta))))
(:both (cons (modulo (+ (car term) adelta))
(modulo (+ (cdr term) xdelta)))))))
(mapcar #'adder genpoly)))
(defmethod multiplication ((genobj1 generator-polynomial) (genobj2 generator-polynomial))
"Multiplication for GF(2^8) between two generator polynomial.
We only consider genobj2 as ((0 . 1) (t . 0)), where t's max value is # of error
correction word _MINUS_ 1."
(let ((genpoly1 (polynomial genobj1))
(genpoly2 (polynomial genobj2))
(tmpobj1 (make-instance 'generator-polynomial))
(tmpobj2 (make-instance 'generator-polynomial))
(result (make-instance 'generator-polynomial)))
(setf (polynomial tmpobj1) (multiply-each-term genpoly1
:xdelta 1
:part :cdr))
(setf (polynomial tmpobj2) (multiply-each-term genpoly1
:adelta (car (second genpoly2))
:part :car))
(setf result (addition tmpobj1 tmpobj2))
(setf (polynomial result) (sort-polynomial (polynomial result) :message-p nil))
; (print (polynomial result))
result))
; Generate message polynomial from bstring
(defun bstring->decimal (bstring)
"Helper function, convert a sequence of 0-1 bstring to number."
(declare (type string bstring))
(let* ((bstring (reverse bstring))
(len (length bstring))
(result 0))
(dotimes (i len)
(when (char= (char bstring i) #\1)
(incf result (ash 1 i))))
result))
(defun generate-msgpoly (bstring version errc blk)
"Convert bstring to message polynomial, length should be times of 8."
(declare (type string bstring)
(type number version)
(type symbol errc))
(let ((exponents (- (+ (nr-data-codewords version errc blk)
(nr-errc-codewords version errc))
1))
(terms (/ (length bstring) 8))
(result (make-instance 'message-polynomial)))
(dotimes (i terms)
(let ((beg (* i 8)))
(setf (polynomial result) (append (polynomial result)
(list (cons (bstring->decimal (subseq bstring beg (+ beg 8)))
(- exponents i)))))))
(setf (polynomial result) (sort-polynomial (polynomial result) :message-p t))
result))
; Generate generator polynomial according to number of error correction words.
(defun generate-genobj (nr-errc-words)
"(x - A^0)(x - A^1)...(x - A^(n-1)), where A is the generator, and n
is the number of error correction words."
(declare (type number nr-errc-words))
; We are trying to use the generator group, so init them first
(init-galois-field)
(let ((result (make-instance 'generator-polynomial))
(multiplier (make-instance 'generator-polynomial)))
(setf (polynomial result) '((0 . 1) (0 . 0)))
(loop for i from 1 to (- nr-errc-words 1) do
(setf (polynomial multiplier) `((0 . 1) (,i . 0)))
(setf result (multiplication result multiplier)))
result))
(defun generate-errcobj-1 (errcobj max)
(let ((msgpoly (polynomial errcobj))
(newpoly nil))
(do ((term (first msgpoly))
(xexp (- max 1) (1- xexp)))
((< xexp 0))
(if (and (cdr term)
(= xexp (cdr term)))
(progn
(push term newpoly)
(setf msgpoly (rest msgpoly))
(setf term (first msgpoly)))
(push (cons 0 xexp) newpoly)))
(setf (polynomial errcobj) (reverse newpoly))))
(defun generate-errcobj (bstring version errc blk)
"Generate error correction polynomial. This in fact is the division operation of GF(2^8):
1. Multiply the generator polynomial so that the result's first term equals message polynomial.
2. XOR the multiply result so as to erase the first term of message polynomial.
3. Repeat 1 & 2 until the first term of result is less than generator polynomial."
(declare (type string bstring)
(type number version)
(type symbol errc))
(let* ((msgobj (generate-msgpoly bstring version errc blk))
(genobj (generate-genobj (nr-errc-codewords version errc)))
(genpoly (polynomial genobj))
(tmpobj (make-instance 'generator-polynomial)))
(dbg :qr-errc "Message Polynomial")
(dbg :qr-errc "~A" msgobj)
(dbg :qr-errc "Generator Polynomial:")
(dbg :qr-errc "~A" genobj)
(do ()
((< (cdr (first (polynomial msgobj)))
(cdr (first genpoly))))
(let ((adelta (aref *LOG* (car (first (polynomial msgobj)))))
(xdelta (- (cdr (first (polynomial msgobj)))
(cdr (first genpoly)))))
(setf (polynomial tmpobj) (multiply-each-term genpoly :adelta adelta
:xdelta xdelta :part :both))
(setf msgobj (addition msgobj tmpobj))))
(generate-errcobj-1 msgobj (cdr (first genpoly)))
(dbg :qr-errc "Errc Polynomial:")
(dbg :qr-errc "~A" msgobj)
msgobj))
; After all, we have to change the error correction polynomial back to bstring
(defun errcobj->bstring (errcobj)
"Walk through the polynomial, translate each cofficient back into bstring
using 8 bits."
(let ((errcpoly (polynomial errcobj))
(bstring ""))
(loop for term in errcpoly do
(setf bstring (concatenate 'string bstring
(decimal->bstring (car term) 8))))
bstring))
;;------------------------------------------------------------------------------
;; This is the Error Correction for Format Information and Version Information
;; 1. Bose-Chaudhuri-Hocquenghem(BCH) (15, 5) code for former, generator polynomial is
;; x^10 + x^8 + x^5 + x^4 + x^2 + x + 1
;; 2. Bose-Chaudhuri-Hocquenghem(BCH) (18, 6) code for latter, generator polynomial is
;; x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2
;; NOTE: This time, it is the exponent that matters, not the cofficient.
;;------------------------------------------------------------------------------
(defun info->msgobj (bstring &key (format-p t))
"Translate Format Information or Version Information BSTRING to a Message Polynomial.
Format Information is consisted of 5 bits: 2 *ERRC-INDICATOR*, 3 *MASK-PATTERN-REF*.
Version Information is consisted of 6 bits, all used to encode Version.
FORMAT-P means bstring is Format Information, otherwise, Version Information."
(declare (type string bstring))
(when (and format-p (not (= (length bstring) 5)))
(error 'qr-bad-arguments :file-name "qr-errc.lisp"
:function-name "info->msgpoly" :arguments bstring
:how "Format Information is consisted of 5 bits."))
(when (and (not format-p) (not (= (length bstring) 6)))
(error 'qr-bad-arguments :file-name "qr-errc.lisp"
:function-name "info->msgpoly" :arguments bstring
:how "Version Information is consisted of 6 bits."))
(let ((msgobj (make-instance 'message-polynomial))
(len (length bstring))
(xdelta 12)
poly)
(when format-p
(setf xdelta 10))
(dotimes (i len)
(when (char= (char bstring i) #\1)
(setf poly (append poly (list (cons 1 (- len 1 i)))))))
(setf (polynomial msgobj) (multiply-each-term poly :xdelta xdelta))
msgobj))
(defun info->errcpoly (bstring &key (format-p t))
"Do error correction for BSTRING. BCH(15, 5) to Format Information BSTRING, or
BCH(18, 6) for Version. Different from above, that coffients are all 1 for Message
Polynomial(0 for Generator Polynomial, of course)."
(declare (type string bstring))
(let ((msgobj (info->msgobj bstring :format-p format-p))
(genobj (make-instance 'generator-polynomial))
(tmpobj (make-instance 'generator-polynomial)))
(dbg :qr-errc "Format/Version Information Polynomial:")
(dbg :qr-errc "~A" msgobj)
(if format-p
(setf (polynomial genobj) *format-generator*)
(setf (polynomial genobj) *version-generator*))
(dbg :qr-errc "Format/Version Information Generator Polynomial:")
(dbg :qr-errc "~A" genobj)
(do ((genpoly (polynomial genobj)))
((< (cdr (first (polynomial msgobj)))
(cdr (first genpoly))))
(let ((xdelta (- (cdr (first (polynomial msgobj)))
(cdr (first genpoly)))))
(setf (polynomial tmpobj) (multiply-each-term genpoly :xdelta xdelta))
(setf msgobj (addition msgobj tmpobj))))
(if format-p
(dbg :qr-errc "Format Information Errc Polynomial:")
(dbg :qr-errc "Version Information Errc Polynomial:"))
(dbg :qr-errc "~A" msgobj)
msgobj))
(defun generate-info-errc (bstring &key (format-p t))
"Generate Error Correction bits for Format/Version Information"
(let* ((errcobj (info->errcpoly bstring :format-p format-p))
(nrerrc 12) ; # of Version Information Errc bits
(errcpoly (polynomial errcobj))
errcbits)
(when format-p
(setf nrerrc 10))
(setf errcbits (make-string nrerrc :initial-element #\0))
(labels ((set-bit (term)
(setf (char errcbits (- nrerrc 1 (cdr term))) #\1)))
(mapcar #'set-bit errcpoly))
errcbits))
(defun info->bstring (bstring &key (format-p t))
"Do Error Correction for the Format/Version Information, concatenate them, and,
for Format Information, XOR it with the mask 101010000010010."
(let ((errcbits (generate-info-errc bstring :format-p format-p))
(mask "101010000010010"))
(setf bstring (concatenate 'string bstring errcbits))
(when format-p
(setf bstring (map 'string #'(lambda (char1 char2)
(if (char= char1 char2) #\0 #\1))
bstring mask)))
bstring))
| 16,237 | Common Lisp | .lisp | 362 | 41.066298 | 95 | 0.654625 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 435024bcbfaa30c70665cc77d64ef96873683b6465d170468dd44751a0d3789d | 13,118 | [
-1
] |
13,119 | qr-bstring-testcase.lisp | jnjcc_cl-qrencode-deprecated/tests/qr-bstring-testcase.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-bstring-testcase.lisp
;;;; This file contains some testcases for utilities in qr-bstring.lisp.
;;;;
(in-package #:cl-qrencode)
;; Version 1.3.2?! That was a joke...
;;; Testcase adapted from Annex G
(defvar *input-text* "01234567")
(defvar *encode-data* "0001 0000001000 0000001100 0101011001 1000011 0000"
"Encode result using 1-M, :NUMERIC.")
(defvar *padding-result* "00010000 00100000 00001100 01010110 01100001 10000000"
"Padding bits.")
(defvar *pad-codeword* "00010000 00100000 00001100 01010110 01100001 10000000\
11101100 00010001 11101100 00010001 11101100 00010001 11101100 00010001 11101100 00010001")
(defun init-bstring-global ()
(setf *encode-data* (remove #\Space *encode-data*))
(setf *padding-result* (remove #\Space *padding-result*))
(setf *pad-codeword* (remove-if #'(lambda (char)
(or (char= char #\Space) (char= char #\Newline)))
*pad-codeword*)))
(defun test-function (input function output &key (test #'string=) (call-p t))
"CALL-P: whether or not we need to call FUNCTION."
(let ((func-name (symbol-name function)))
(when (not call-p)
(setf function #'identity))
(when (not (funcall test (funcall function input)
output))
(error 'qr-test-failure :function-name func-name
:arguments `(,(funcall function input) ,output)))))
(defun run-bstring-test (&key (version 1) (mode :numeric) (correct :level-m))
(init-bstring-global)
(let ((input (string->input *input-text* :version version
:mode mode :correction correct)))
(test-function input 'encode-data (remove #\Space *encode-data*))
(let ((bstring (encode-data input)))
(setf bstring (concatenate 'string bstring
(padding-bits (length bstring))))
(test-function bstring 'padding-bits (remove #\Space *padding-result*)
:call-p nil)
(setf bstring (concatenate 'string bstring
(padding-pad-codeword
(- (* (nr-data-codewords version correct) 8) (length bstring)))))
(test-function bstring 'padding-pad-codeword (remove #\Space *pad-codeword*)
:call-p nil)
(format t "`qr-bstring.lisp' seems good as for Annex G...~%")
bstring)))
| 2,844 | Common Lisp | .lisp | 59 | 44.610169 | 92 | 0.708528 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | b187a638b59306bf336423bec4a9aee643f34e872ec858c67dbde3b7019f7d72 | 13,119 | [
-1
] |
13,120 | qr-errc-testcase.lisp | jnjcc_cl-qrencode-deprecated/tests/qr-errc-testcase.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-errc-testcase.lisp
;;;; This file contains some testcase to Reed-Solomon Error Correction
;;;;
(in-package #:cl-qrencode)
;; Version 1.3.2?! That was a joke...
; INPUT: (coff1 exp1) (coff2 exp2), ...
; OUTPUT: ((coff1 . exp1) (coff2 . exp2) ...)
(defmacro make-message-poly-1 (&rest parts)
(let ((part (gensym)))
`(loop for ,part in ',parts collect (cons (first ,part) (second ,part)))))
; generator polynomial: the first coff1 must be 1
(defmacro make-generator-poly-1 (&rest parts)
(if (not (= (car (first parts)) 0))
(error 'qr-bad-arguments :file-name "qr-errc.lisp" :function-name "make-generator-poly"
:arguments '(parts) :how "The first cofficient of generator polynomial must be 1.")
(let ((part (gensym)))
`(loop for ,part in ',parts collect (cons (first ,part) (second ,part))))))
; "HELLO WORLD": Version 1, :level-q, alphanumeric mode
(defvar *msgpoly-helloworld* (make-message-poly-1 (32 25) (91 24) (11 23) (120 22)
(209 21) (114 20) (220 19) (77 18)
(67 17) (64 16) (236 15) (17 14)
(236 13)))
(defvar *genpoly-13* (make-generator-poly-1 (0 13) (74 12) (152 11) (176 10)
(100 9) (86 8) (100 7) (106 6)
(104 5) (130 4) (218 3) (206 2)
(140 1) (78 0)))
; "ABCDE123": Version 1, :level-h, alphanumeric mode
(defvar *msgpoly-abcde123* (make-message-poly-1 (32 25) (65 24) (205 23)
(69 22) (41 21) (220 20)
(46 19) (128 18) (236 17)))
(defvar *genpoly-17* (make-generator-poly-1 (0 17) (43 16) (139 15) (206 14)
(78 13) (43 12) (239 11) (123 10)
(206 9) (214 8) (147 7) (24 6)
(99 5) (150 4) (39 3) (243 2)
(163 1) (136 0)))
;;; Testcase adapted from Annex G
(defvar *errc-result* "00010000 00100000 00001100 01010110 01100001 10000000 11101100 00010001\
11101100 00010001 11101100 00010001 11101100 00010001 11101100 00010001 10100101 00100100\
11010100 11000001 11101101 00110110 11000111 10000111 00101100 01010101")
(defun init-errc-global ()
(setf *errc-result* (remove-if #'(lambda (char)
(or (char= char #\Newline) (char= char #\Space)))
*errc-result*)))
(defun run-errc-test (&key (version 1) (mode :numeric) (correct :level-m))
(init-errc-global)
(let* ((bstring (run-bstring-test :version version :mode mode :correct correct))
(errcobj (generate-errcobj bstring version correct)))
(setf bstring (concatenate 'string bstring
(errcobj->bstring errcobj)))
(when (not (string= *errc-result* bstring))
(error 'qr-test-failure :function-name (symbol-name 'errcobj->bstring)
:arguments `(,bstring ,*errc-result*)))
(format t "`qr-errc.lisp' seems good as for Annex G...~%")
bstring)) | 3,387 | Common Lisp | .lisp | 68 | 45.911765 | 95 | 0.66717 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | e2feb9b544cc130887b307a7027ece701d1cbd5f2c9eac6a43cdbd51a3e27425 | 13,120 | [
-1
] |
13,121 | qr-encode-testcase.lisp | jnjcc_cl-qrencode-deprecated/tests/qr-encode-testcase.lisp | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; qr-encode-testcase.lisp
;;;; This file contains some testcases for the encoder.
;;;;
(in-package #:cl-qrencode)
;; Version 1.3.2?! That was a joke...
(defvar *data* "00100000010000011100110101000101001010011101110000101\
110100000001110110000101010100111110100101011011101111101001010100111\
101111100101101000101001000110111011010101010111100000011000000100101\
01101101100111101"
"This is the result when encoding ABCDE123 using :alphanumeric mode and
:level-h error correction level.")
(setf *data* (remove #\Newline *data*))
;; FIXME: All right, from now on, I just consider Version 1
;; TODO: Further development needed as for Version 2 ~ 40.
;; We use 1 as black modules, 0 as white modules.
(defun char2int (pattern i)
(if (char= (char pattern i) #\0)
0
1))
(defun encode-finder (matrix)
(let ((pattern1 "1111111")
(pattern2 "1000001")
(pattern3 "1011101"))
(loop for i from 0 to 6 do
; 1. all pattern1
(setf (aref matrix i 0) (char2int pattern1 i))
(setf (aref matrix (+ i 14) 0) (char2int pattern1 i))
(setf (aref matrix i 6) (char2int pattern1 i))
(setf (aref matrix (+ i 14) 6) (char2int pattern1 i))
(setf (aref matrix i 14) (char2int pattern1 i))
(setf (aref matrix i 20) (char2int pattern1 i))
; 2. all pattern2
(setf (aref matrix i 1) (char2int pattern2 i))
(setf (aref matrix (+ i 14) 1) (char2int pattern2 i))
(setf (aref matrix i 5) (char2int pattern2 i))
(setf (aref matrix (+ i 14) 5) (char2int pattern2 i))
(setf (aref matrix i 15) (char2int pattern2 i))
(setf (aref matrix i 19) (char2int pattern2 i))
; 3. all pattern3
(loop for j from 2 to 4 do
(setf (aref matrix i j) (char2int pattern3 i))
(setf (aref matrix (+ i 14) j) (char2int pattern3 i))
(setf (aref matrix i (+ j 14)) (char2int pattern3 i))))
(loop for i from 0 to 7 do
(setf (aref matrix i 7) 0)
(setf (aref matrix (+ i 13) 7) 0)
(setf (aref matrix i 13) 0))
(loop for j from 0 to 7 do
(setf (aref matrix 7 j) 0)
(setf (aref matrix 13 j) 0)
(setf (aref matrix 7 (+ j 13)) 0)))
matrix)
(defun encode-timing (matrix)
(let ((pattern "10101"))
(loop for i from 8 to 12 do
(setf (aref matrix i 6) (char2int pattern (- i 8)))
(setf (aref matrix 6 i) (char2int pattern (- i 8))))
matrix))
(defun reserve-format (matrix)
(loop for i from 0 to 8 do
(when (= (aref matrix i 8) *blank*)
(setf (aref matrix i 8) 0))
(when (= (aref matrix 8 i) *blank*)
(setf (aref matrix 8 i) 0)))
(loop for i from 13 to 20 do
(setf (aref matrix i 8) 0))
(loop for j from 14 to 20 do
(setf (aref matrix 8 j) 0))
(setf (aref matrix 8 13) 1)
matrix)
(defun encode-fix-part (matrix)
"Here, we encode the Finder Pattern and Timing Pattern. Also, we reserve places
for Error Correction Level and Mask Pattern (Format Information, we may say)."
(reserve-format (encode-timing (encode-finder matrix))))
(defun encode-bstring (matrix bstring)
(let ((i 20) (j 20) (cnt 0)
(direction -1)
(length (length bstring)))
(do ()
((= cnt length))
(setf (aref matrix i j) (char2int bstring cnt))
(incf cnt)
(when (not (= (aref matrix (- i 1) j) *blank*))
(setf (aref matrix (- i 1) j) (char2int bstring cnt))
(incf cnt))
(if (and (>= (+ j direction) 0)
(<= (+ j direction) 20))
(incf j direction)
(progn
(decf i 2)
(setf direction (- direction))))))
matrix)
(defun generate-png (qr-file)
(let* ((matrix (make-matrix 1))
(qr-png (make-instance 'png :width (matrix-modules 1)
:height (matrix-modules 1)))
(png-array (data-array qr-png)))
(setf matrix (encode-fix-part matrix))
(setf matrix (encode-bstring matrix *data*))
(loop for x from 0 to 20 do
(loop for y from 0 to 20 do
(if (or (= (aref matrix x y) *blank*)
(= (aref matrix x y) 0))
(progn
(setf (aref png-array y x 0) 255)
(setf (aref png-array y x 1) 255)
(setf (aref png-array y x 2) 255))
(progn
(setf (aref png-array y x 0) 0)
(setf (aref png-array y x 1) 0)
(setf (aref png-array y x 2) 0)))))
(write-png qr-png qr-file :if-exists :supersede)))
| 4,893 | Common Lisp | .lisp | 126 | 34.968254 | 81 | 0.664274 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | bcce27f4c9dffe221abc026bab23744746ac2520f650b3357d35b822bdc9025a | 13,121 | [
-1
] |
13,122 | cl-qrencode.asd | jnjcc_cl-qrencode-deprecated/cl-qrencode.asd | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; cl-qrencode.asd
;;;; This file contains
; #-(or sbcl)
; (error "Unfortunately, this package only works under SBCL for now.")
(asdf:defsystem #:cl-qrencode
:name "cl-qrencode"
:description "QR Code encoder in pure Common Lisp."
:author "johnc <[email protected]>"
:version "1.0.2"
:maintainer "johnc <[email protected]>"
:licence "GPL"
:depends-on (#:zpng #:babel)
:components ((:file "package")
(:module "src"
:components ((:file "qr-utils")
(:file "qr-condition")
(:file "qr-spec")
(:file "qr-input")
(:file "qr-data-bstring")
(:file "qr-bstring")
(:file "qr-errc")
(:file "qr-encode")
(:file "qr-blocks")
(:file "qr-mask")
(:file "qr-image")))
(:module "tests"
:components ((:file "qr-bstring-testcase")
(:file "qr-encode-testcase")
(:file "qr-errc-testcase"))))) | 1,602 | Common Lisp | .asd | 43 | 32.790698 | 71 | 0.651252 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 5ba8b8d09bc78a6ac80944ba6263ac7dc15e73b1ac8894ee088349de77e9e7ac | 13,122 | [
-1
] |
13,137 | copyright.el | jnjcc_cl-qrencode-deprecated/utils/copyright.el | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;; copyright.el
;;;; This file contains
;; Version 1.3.2?! That was a joke...
(setq auto-insert-directory (expand-file-name "~/.emacs.d/templates/"))
(setq auto-insert-query nil) ;; Don't ask, just do the auto insertion
(define-auto-insert 'lisp-mode "lisp.tpl") ;; ~/.emacs.d/templates/lisp.tpl
(add-hook 'find-file-hooks 'auto-insert)
(defvar *prefix* ";;;;"
"Of course, \* notation is not common in Emacs Lisp, but, let's use it anyway.")
(defun qr-add-file-name ()
"Go to the comment line start with *PREFIX* and add the current buffer name."
(interactive)
(save-excursion
(save-restriction
(save-match-data
(widen)
(goto-char (point-min))
(search-forward *prefix*)
(let ((fname (file-name-nondirectory buffer-file-name)))
(when (not (looking-at fname))
(delete-region (point) (line-end-position))
(insert (concat " " fname)))))))) | 1,560 | Common Lisp | .l | 36 | 41.277778 | 82 | 0.718606 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | b94c0a2c67114ca1b1d86e317b70fd503d9164550bba670af646f8e8a03e2387 | 13,137 | [
-1
] |
13,138 | lisp.tpl | jnjcc_cl-qrencode-deprecated/utils/lisp.tpl | ;; Copyright (C) 2010, 2011 johnc <[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 2, 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/>.
;;;;
;;;; This file contains
| 715 | Common Lisp | .l | 16 | 43.5625 | 71 | 0.752149 | jnjcc/cl-qrencode-deprecated | 7 | 3 | 0 | GPL-2.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 2dbb8943d7298f271db3b87c630432cf10cb91205a6707024a7ebd1a20728b68 | 13,138 | [
-1
] |
13,156 | simple-usocket-irc-bot.lisp | nixeagle_nisp/simple-usocket-irc-bot.lisp | (defpackage #:simple-usocket-irc-bot
(:use :cl :usocket))
(in-package :simple-usocket-irc-bot)
(defvar *bot-socket* nil
"Global socket for a single bot connection.")
(defun connect! (host &key (port 6667))
(setq *bot-socket* (socket-connect host port)))
(defun format-irc-message (&rest args)
"Format ARGS into a valid irc message sans the newlines at the end."
(let ((result-string "")
(last-arg (apply #'concatenate 'string ":" (last args)))
(arg-list-but-last (append (butlast args))))
(concatenate 'string
(dolist (arg arg-list-but-last result-string)
(setq result-string (concatenate 'string result-string arg " ")))
last-arg)))
(defun send-irc-message (&rest args)
(prog1
(write-sequence (apply #'format-irc-message args) (socket-stream *bot-socket*))
(terpri (socket-stream *bot-socket*))
(force-output (socket-stream *bot-socket*))))
;;; Minimal sequence to write a bot that joins and quits immediately
;;; closing the socket while doing so.
;;;
;;; To run this and other code snippets, remove the #+ () line in front
;;; and hit C-c C-c in emacs.
#+ ()
(progn
(connect! "silicon.eighthbit.net")
(send-irc-message "NICK" "lispbot")
(send-irc-message "USER" "lisp" "0" "*" "hi from nixeagle!")
(send-irc-message "JOIN" "#offtopic")
(send-irc-message "PRIVMSG" "#offtopic" "Hi from nixeagle's simple lisp bot!")
(send-irc-message "QUIT" "bye now!")
(socket-close *bot-socket*))
;;; listen to the socket, don't hang if there is nothing to hear, but if
;;; there is, print it to #sonicircd
#+ ()
(when (listen (socket-stream *bot-socket*))
(send-irc-message "PRIVMSG" "#sonicircd" (read-line (socket-stream *bot-socket*))))
;;; This will loop forever waiting for input and doing something (again
;;; just printing to #sonicircd) when the bot hears something
#+ ()
(loop
(wait-for-input *bot-socket*
(send-irc-message "PRIVMSG" "#sonicircd"
(read-line (socket-stream *bot-socket*)))))
;;; Ask me about threading when you get tired of stopping the loop just to
;;; modify the bot's behavior, but you need to know how to put the bot's
;;; behavior in a function and so on so that the modifications to the
;;; function can be seen by the threaded bot (this is not difficult, just
;;; put (defun i-got-input-from-server! (&optional (socket *bot-socket*))
;;; <some code here>) and call that instead of directly printing in the
;;; loop.
;;; Close a socket with
#+ ()
(socket-close *bot-socket*) | 2,575 | Common Lisp | .lisp | 57 | 41 | 85 | 0.671844 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | b0012226462131ebe545e252b6c482aea4b87f76d2e456129598cf1727d36f49 | 13,156 | [
-1
] |
13,157 | user.lisp | nixeagle_nisp/user.lisp | ;;;; Package for including all sorts of interesting and useful libraries
;;;; for testing.
(in-package :cl-user)
(defpackage #:nisp.user
(:use :cl
;; implentation independent sockets
:alexandria
:anaphora
:eos
:usocket
:drakma) ;http-request
(:nicknames :nu :~))
(in-package :nisp.user)
;;; In custom userland, this userland has modifications from a standard
;;; userland.
(defmacro n.disasemble (form)
(let ((s (gensym)))
`(let ((,s (with-output-to-string (*standard-output*)
(disassemble ',(car form)))))
(print ,s)
(values
,form
(count #\Newline ,s)))))
(defun ensure-no-leading-single-quote (string)
"Append a leading ' to STRING if there is not already one."
(declare (type string string))
(if (char= (char string 0) #\')
(subseq string 1)
string))
(define-condition nisp-user-error (error)
())
(define-condition package-not-found-error (nisp-user-error)
((package :initarg :package :reader package-not-found-error-package))
(:report (lambda (condition stream)
(format stream "Package ~A is not loaded"
(package-not-found-error-package condition)))))
(define-condition swank-package-not-found-error (package-not-found-error)
()
(:default-initargs :package :swank))
(defgeneric eval-in-emacs (form &optional nowait))
(defmethod eval-in-emacs ((form string) &optional nowait)
(eval-in-emacs (read-from-string (ensure-no-leading-single-quote form))
nowait))
(defmethod eval-in-emacs (form &optional nowait)
(let ((swank::*emacs-connection* (swank::default-connection)))
(swank::eval-in-emacs form nowait)))
(defun my-setup-server (&optional (port 2288))
"Load up a swank instance ready to be connected to by emacs."
(swank:create-server :dont-close t :coding-system "utf-8-unix" :port port)
(setf swank:*use-dedicated-output-stream* nil))
(defmacro clock (form &optional (iterations 100000) (_count_ 0))
"Execute FORM ITERATIONS times.
The result is an alist of the form:
((time . rational) (iterations . integer) (result . <form result>))"
;; This macro has a bug, it evaluates FORM one extra time at the end
;; of the macro expression to display the result value.
(declare (type positive-fixnum)
(optimize (debug 0) (speed 3) (safety 0)
(space 1) (compilation-speed 3)))
(let ((start (gensym))
(total (gensym))
(avg (gensym)))
`(iter (with ,start = (get-internal-real-time))
(for _count_ :from 0 :to ,iterations)
,form
(finally (let* ((,total (the (or (integer 0 0) positive-fixnum)
(- (get-internal-real-time) ,start)))
(,avg (/ ,total
(* ,iterations
internal-time-units-per-second))))
(return
(list
(cons :time (list
(/ ,total internal-time-units-per-second)
(format nil "~f"
(/ ,total
internal-time-units-per-second))))
(cons :avg (list ,avg (format nil "~f" ,avg)))
(cons :result ,form))))))))
(defparameter *call-times* ())
(defvar *call-times-lock* (bt:make-lock))
(defun call-blocktimer (thunk)
(let ((start-time (get-internal-real-time)))
(prog1
(funcall thunk)
(let ((total-time
(/ (- (get-internal-real-time) start-time)
internal-time-units-per-second)))
(bt:with-lock-held (*call-times-lock*)
(push total-time
*call-times*))))))
(defun call-blocktimer-return-time (thunk)
(let ((start-time (get-internal-real-time)))
(progn
(funcall thunk)
(/ (- (get-internal-real-time) start-time)
internal-time-units-per-second))))
(defmacro blocktimer (&body body)
`(call-blocktimer (lambda () ,@body)))
;;; (+ 1 2)
(defmacro qtime (iterations &body body)
"Time BODY over ITERATIONS loops."
(with-gensyms (result unoptimized-result default-result)
`(let ((,result (call-blocktimer-return-time
(lambda ()
(declare (optimize (speed 3) (debug 1) (safety 0)))
(dotimes (i ,(expt 2 iterations))
,@body))))
(,default-result
(call-blocktimer-return-time
(lambda ()
(declare (optimize (speed 1) (debug 1) (safety 1)))
(dotimes (i ,(expt 2 iterations))
,@body))))
(,unoptimized-result
(call-blocktimer-return-time
(lambda ()
(declare (optimize (speed 0) (debug 3) (safety 3)))
(dotimes (i ,(expt 2 iterations))
,@body)))))
(values
(list ,(expt 2 iterations) (format nil "~f" ,unoptimized-result)
(format nil "~f" ,default-result) (format nil "~f" ,result))
(list (format nil "~,,' :D" (floor (/ (/ ,unoptimized-result ,(expt 2 iterations)))))
(format nil "~f" (/ ,unoptimized-result ,(expt 2 iterations))))
(list (format nil "~,,' :D" (floor (/ (/ ,default-result ,(expt 2 iterations)))))
(format nil "~f" (/ ,default-result ,(expt 2 iterations))))
(list (format nil "~,,' :D" (floor (/ (/ ,result ,(expt 2 iterations)))))
(format nil "~f" (/ ,result ,(expt 2 iterations))))
))))
;#+sbcl
;(my-setup-server)
(in-package :nisp.user)
(in-package :swank)
(defslimefun documentation-symbol (symbol-name)
(with-buffer-syntax ()
(multiple-value-bind (sym foundp) (parse-symbol symbol-name)
(if foundp
(let ((vdoc (documentation sym 'variable))
(fdoc (documentation sym 'function)))
(with-output-to-string (string)
(format string "Documentation for the symbol ~a:~2%" sym)
(unless (or vdoc fdoc)
(format string "Not documented." ))
(when vdoc
(format string "Variable:~% Value: ~A~%~%~a~2%" (with-output-to-string (*standard-output*) (let ((*print-right-margin* 70))
(pprint (symbol-value sym)))) vdoc))
(when fdoc
(format string "Function:~% Arglist: ~a~2% ~a"
(swank-backend:arglist sym)
fdoc))))
(format nil "No such symbol, ~a." symbol-name)))))
(define-method-combination hook (&optional (function 'progn))
((methods *))
"Call functions like they would be called on an emacs hook.
As with emacs hooks the order that methods are called in should not be
depended upon."
`(,function ,@(mapcar (lambda (method)
`(call-method ,method))
methods)))
(define-method-combination random-elt ()
((methods *))
`(progn
,@(mapcar (lambda (method)
`(call-method ,method))
methods)))
(defclass random-elt-generic-function
(cl:standard-generic-function)
()
(:metaclass closer-mop:funcallable-standard-class))
(defmethod compute-discriminating-function ((gf random-elt-generic-function))
(lambda (&rest args)
(declare (dynamic-extent args))
(funcall (method-function
(random-elt (compute-applicable-methods gf args)))
args nil))) | 7,780 | Common Lisp | .lisp | 176 | 33.25 | 148 | 0.556436 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 900c28c4e033e8e3c40c78d93628e3cde0909cf401b17db3251e5277bea425d9 | 13,157 | [
-1
] |
13,158 | nisp-hello.lisp | nixeagle_nisp/nisp-hello.lisp | ;;;; nisp-hello.lisp
;;; Copyright (c) 2010 Nixeagle
;;; Released under gplv3 or later
;;; Word list taken from file HELLO in GNU Emacs 23.1.91.1
(in-package :nisp-system)
(defpackage #:nisp.hello
(:use :cl :iterate)
(:export #:hello))
(in-package :nisp.hello)
#+breaks-cb's-weechat-with-screen '("مكيلع مالّسلا" "নমস্কার" "નમસ્તે")
(defvar +hello-words+
'("ሠላም" "⠓⠑⠇⠇⠕" "မင္ဂလာပာ" "printf (\"Hello, world!\n\");"
"Dobrý den" "Hej" "Goddag" "Halløj" "Hallo" "Dag" "Hello"
"Saluton (Eĥoŝanĝo ĉiuĵaŭde)" "Tere päevast" "Tere õhtust"
"Hei" "Hyvää päivää" "Bonjour" "Salut" "გამარჯობა" "coi"
"Guten Tag" "Grüß Gott" "Γειά σας" "નમસ્તે" "שלום" "Szép jó napot!"
"नमस्ते" "नमस्कार ।" "Ciao" "Buon giorno" "System.out.println(\"Sugeng siang!\");"
"ನಮಸ್ಕಾರ" "ជំរាបសួរ" "ສະບາຍດີ" "ຂໍໃຫ້ໂຊກດີ" "നമസ്കാരം" "Bonġu" "Saħħa"
"∀ p ∈ world • hello p □" "Hallo" "Dag" "Hei" "God dag" "ଶୁଣିବେ"
"Dzień dobry!" "Cześć!" "Здра́вствуйте!" "ආයුබෝවන්" "Dobrý deň" "Pozdravljeni!"
"¡Hola!" "Hej" "Goddag" "Hallå" "வணக்கம்" "నమస్కారం" "สวัสดีครับ" "สวัสดีค่ะ"
"བཀྲ་ཤིས་བདེ་ལེགས༎" "ሰላማት" "Merhaba" "Вітаю" "Chào bạn" "こんにちは" "コンニチハ"
"你好" "早晨, 你好" "안녕하세요" "안녕하십니까")
"List of \"hello\" in many languages.")
(defun hello (&optional (word-list +hello-words+))
"Return a random string saying hello from WORD-LIST."
(alexandria:random-elt word-list)) | 1,850 | Common Lisp | .lisp | 27 | 47.851852 | 86 | 0.615556 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | e8457d79c9bc9056419280dde24a38301f95d15f670e0719766c528ef647e7cb | 13,158 | [
-1
] |
13,159 | main-test-suite.lisp | nixeagle_nisp/main-test-suite.lisp |
;;This is not pretty at all conceptually, but we need nisp here for the time being otherwise things in package won't see all-tests.
(defpackage #:nisp
(:use :cl :eos))
(in-package :nisp)
| 191 | Common Lisp | .lisp | 4 | 45.75 | 131 | 0.745946 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 7b54e6bc51b936b30c404da3be55bf13e6329e37c80c44e3ce1171e98247b702 | 13,159 | [
-1
] |
13,160 | common-lisp-init.lisp | nixeagle_nisp/common-lisp-init.lisp | (require :asdf)
#-:ccl
(pushnew "/usr/share/common-lisp/systems/" asdf:*central-registry*)
(pushnew "/home/james/lisp/asdf/" asdf:*central-registry* :test #'equal)
(pushnew "/home/james/lisp/nisp/asdf/" asdf:*central-registry* :test #'equal)
(pushnew "/home/james/lisp/nisp/emacs/slime/" asdf:*central-registry* :test #'equal)
(pushnew "/home/james/lisp/nisp/emacs/slime/contrib/" asdf:*central-registry* :test #'equal)
#+:ccl
(pushnew "/home/james/lisp/asdf-install/asdf-install/"
asdf:*central-registry* :test #'equal)
(pushnew "/home/james/.asdf-install-dir/systems/" asdf:*central-registry*)
(asdf:load-system :asdf-install)
(asdf:load-system :swank)
(asdf:load-system :eos)
(declaim (optimize (debug 3) (safety 3) (speed 0) (space 0)
(compilation-speed 0)))
#+:ccl
(progn
(setq ccl:*fasl-save-definitions* t)
(setq ccl:*save-definitions* t))
(in-package :cl-user)
#+ ()
(asdf:operate 'asdf:load-op :nisp.user)
#+ ()
(in-package :nisp.user) | 983 | Common Lisp | .lisp | 25 | 36.8 | 92 | 0.703782 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 003768d8b52ba4985805db06e03d3b037c12b66f35d8a72617d3ceb07731c9db | 13,160 | [
-1
] |
13,161 | nisp-asdf.lisp | nixeagle_nisp/nisp-asdf.lisp | (in-package :nisp-asdf)
(defgeneric list-system-components (systems)
(:method (systems)
(check-type systems (or string keyword cons)))
(:documentation "Return components of SYSTEM-NAME"))
(defmethod list-system-components ((system-names cons))
(mapcar #'list-system-components system-names))
(defmethod list-system-components ((system-name symbol))
(asdf:module-components
(asdf:find-system system-name)))
(defmethod list-system-components ((system-name string))
(asdf:module-components (asdf:find-system system-name)))
#+ ()
(deftestsuite list-system-components (root-suite)
()
:test (pass-keyword-with-valid-package-name
(ensure-same (listp (list-system-components :nisp)) t))
:test (pass-string-with-valid-package-name
(ensure (listp (list-system-components "nisp"))))
:test (pass-multiple-args-in-a-list
(ensure (listp (list-system-components '(:nisp)))))
:test (pass-integer
(ensure-condition 'simple-type-error
(list-system-components 1)))
:test (pass-nil
(ensure-condition 'asdf::missing-component
(list-system-components nil)))
(:test
(pass-void-package-keyword
(:documentation "testing")
(ensure-condition 'asdf::missing-component
(list-system-components :this-does-not-exist-as-a-package)
) )
)
:documentation "list-system-components is a generic function.
The point of all the tests in this suite is to verify that the function
handles message passing as expected. We verify that strings, lists and
keywords all return valid results.") | 1,584 | Common Lisp | .lisp | 38 | 37.078947 | 71 | 0.717716 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | d4f0f24eca95b2363640120b8f575bcaf18596fed69286e2564401935e844888 | 13,161 | [
-1
] |
13,162 | mop2.lisp | nixeagle_nisp/mop2.lisp | (in-package :cl-user)
(asdf:load-system :closer-mop)
(defpackage #:nisp.mop2
(:use :cl)
(:shadowing-import-from :closer-mop :defmethod)
(:import-from :closer-mop :class-slots))
(in-package :nisp.mop2)
(defmethod closer-mop:class-slots ((class-symbol symbol))
"List all slots of CLASS-SYMBOL."
(funcall 'closer-mop:class-slots (find-class class-symbol))) | 365 | Common Lisp | .lisp | 10 | 34.4 | 62 | 0.734463 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | e8153f0f1690921bf7312222c48dfc543710b29041969f2f71d674bd79eb1dd2 | 13,162 | [
-1
] |
13,163 | alpha-experiments.lisp | nixeagle_nisp/alpha-experiments.lisp | (in-package :cl-user)
(defpackage #:nisp.alpha
(:use :common-lisp :iterate)
(:nicknames :alpha :a))
(in-package :nisp.alpha)
(defgeneric object->defstruct-description (object)
(:documentation "Convert OBJECT to defstruct-description."))
(defmethod object->defstruct-description ((object sb-kernel:defstruct-description))
"Return identity of OBJECT."
object)
(defmethod object->defstruct-description ((symbol symbol))
"Find structure description for SYMBOL.
This implies that SYMBOL actually refers to a structure."
(declare (type class-symbol symbol))
(sb-pcl::find-defstruct-description symbol))
(defmethod object->defstruct-description ((structure-instance structure-object))
"Find structure description for STRUCTURE-INSTANCE."
(object->defstruct-description (class-of structure-instance)))
(defmethod object->defstruct-description ((class structure-class))
"Find structure description for CLASS"
(object->defstruct-description (class-name class)))
(defun dd-name-equal-p (slot name-symbol)
"Return t if the name of SLOT is eql to NAME-SYMBOL."
(eql (sb-kernel:dsd-name slot) name-symbol))
;;; make work with arbitrary designator?
(defun structure-slots (structure-designator)
"List all slots of STRUCTURE-DESIGNATOR."
(declare (type structure-designator structure-designator))
(sb-vm::dd-slots (object->defstruct-description structure-designator)))
(defun structure-slot-by-name (structure-designator slot-name)
"Return description of SLOT-NAME in STRUCTURE-DESIGNATOR."
(declare (type structure-designator structure-designator)
(type class-symbol slot-name))
(iter (for slot :in (structure-slots structure-designator))
(finding (the sb-kernel:defstruct-slot-description slot)
:such-that (dd-name-equal-p slot slot-name))))
;;;; Testing structure operations
(defstruct 4-slot-structure a b c d)
(defparameter *4slot* (make-4-slot-structure :a "hi" :b 23 :d "hello!"))
| 1,955 | Common Lisp | .lisp | 39 | 47 | 83 | 0.762179 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | c5806f98560a7e756e727d01ed1690ca41d10f7878c8b18fa6bde55f024d3e63 | 13,163 | [
-1
] |
13,164 | nixeagle-swank-and-emacs.lisp | nixeagle_nisp/nixeagle-swank-and-emacs.lisp | ;;;-*- Mode:Lisp; Syntax:ANSI-Common-Lisp; Base:10; indent-tabs-mode:nil -*-
(defpackage #:nix-emacs
(:use :cl :swank)
(:documentation "Helpful functions for my (nixeagle's) emacs/swank
enjoyment."))
(in-package :nix-emacs)
(defun nix-pprint (values)
(swank::with-buffer-syntax ()
(let ((*PRINT-CIRCLE* nil)
(*PRINT-PRETTY* t)
(*PRINT-ESCAPE* t)
(*PRINT-ARRAY* t)
(*PRINT-LINES* nil)
(*PRINT-LEVEL* nil)
(*PRINT-LENGTH* nil)
(*PRINT-RIGHT-MARGIN* 72)
(*print-readably* nil))
(with-output-to-string (*standard-output*)
(dolist (o values)
(pprint o))))))
(defun describe-values (object)
(mapcar
(lambda (x)
(with-output-to-string (*standard-output*)
(describe x)))
(if (and (listp object) (listp (car object)))
(car object)
object)))
(defun nix-pprint-eval (string &optional extra)
(declare (ignore extra))
(swank::with-buffer-syntax ()
(let* ((*PRINT-CIRCLE* nil)
(*PRINT-PRETTY* t)
(*PRINT-ESCAPE* t)
(*PRINT-ARRAY* t)
(eos:*run-test-when-defined* t)
(*PRINT-LINES* nil)
(*PRINT-LEVEL* nil)
(*PRINT-LENGTH* nil)
(*print-right-margin* 78)
(*print-readably* nil)
(stand (make-string-output-stream))
(trace (make-string-output-stream))
(err (make-string-output-stream))
(*standard-output* stand)
(*trace-output* trace)
(*error-output* err)
(form (read-from-string string))
(values (multiple-value-list
(eval form))))
(list string
(get-output-stream-string stand)
(get-output-stream-string err)
(get-output-stream-string trace)
(nix-pprint values)
(describe-values values))))) | 1,911 | Common Lisp | .lisp | 56 | 25.375 | 76 | 0.555616 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | a7f343b386e7cc1401b628560477fd6793c8287e1f38806c87122c04d5183d75 | 13,164 | [
-1
] |
13,165 | nisp-dev-helper.lisp | nixeagle_nisp/nisp-dev-helper.lisp | (defpackage #:nisp-dev-helper
(:use :cl :nispbot)
(:export #:start-nispbot-instance))
(in-package :nisp-dev-helper)
(defun start-nispbot-instance (&optional (nick nispbot-config::*nickname*))
(setq nispbot::*nispbot* (nispbot::make-irc-bot nick "irc.eighthbit.net"))
(irc:start-background-message-handler nispbot::*nispbot*)
(sleep 3)
(nispbot::join-all-channels nispbot::*nispbot*)
(nispbot::reset-command-hook nispbot::*nispbot*))
(defvar nispbot::*freenode*)
(defun start-freenode-instance ()
"Quickie to get something up on freenode"
(setq nispbot::*freenode*
(irc:connect :connection-type 'nispbot::irc-bot
:nickname nispbot-config::*nickname*
:server "irc.freenode.net"
:password nispbot-config::*freenode-password*))
(irc:start-background-message-handler nispbot::*freenode*)
(sleep 3)
(irc:join nispbot::*freenode* "#botters")
(nispbot::reset-command-hook nispbot::*freenode*))
#+nil (defun generate-html-output ()
(progn
(write "")
(setf (lift::test-result-property *test-result* :style-sheet) "test-style.css")
(setf (lift::test-result-property *test-result* :title) "nisp")
(setf (lift::test-result-property *test-result* :if-exists) :supersede)
(lift::test-result-report *test-result* #p "/home/james/lisp/nisp/lift-tests/html/report" :html)
(setf (lift::test-result-property *test-result* :style-sheet) "test-style.css")
(setf (lift::test-result-property *test-result* :title) "nisp")
(setf (lift::test-result-property *test-result* :if-exists) :supersede)
(lift::test-result-report *test-result* (concatenate 'string "/home/james/lisp/nisp/lift-tests/save/report") :save)
(update-lift-nisp)))
#+nil (defun update-lift-nisp ()
"Currently a quick hack to upload test restuls and data using git to track history. This beats scp in several ways.
1. we get history tracking
2. we get compressed transfers as we only need send what changed"
(trivial-shell::shell-command "cd /home/james/lisp/nisp/lift-tests/; git status; git add --all; git commit -m \"Automatic commit\"; git push vps:repos/nisp-tests.git master:master"))
;; (defun generate-tinaa-docs ()
;; (use-package :tinaa)
;; (tinaa:document-system
;; 'asdf-system :nisp "/home/james/lisp/nisp/lift-tests/tinaa/")
;#+ (or) (trivial-shell::shell-command "scp -r /home/james/lisp/nisp/tinaa/* vps:paste/nisp/tinaa/"))
;;;;Old code
;; (trivial-shell::shell-command "scp /home/james/lisp/nisp/lift-tests/html/* vps:paste/nisp/")
;; (trivial-shell::shell-command "scp /home/james/lisp/nisp/lift-tests/save/* vps:paste/nisp/save/") | 2,702 | Common Lisp | .lisp | 47 | 52.319149 | 184 | 0.692512 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 516ede019fc38b99570bb6b6ea07563028c9ef64f0a6be436bcd77c6846f2027 | 13,165 | [
-1
] |
13,166 | package.lisp | nixeagle_nisp/network-tree/package.lisp | (defpackage #:nisp.network-tree
(:use :cl :alexandria :split-sequence :closer-mop :eos :iterate)
(:nicknames :network-tree)
(:export :network-tree-generic-function
:network-tree-method
#:remaining-parameters
#:parse-method-lambda-expression-body
#:find-network-tree-node
#:network-tree-node-keys)
;; This whole shadowing import block is taken from
;; closer-mop-packages.lisp in order to correctly import the
;; closer-mop package.
(:shadowing-import-from :closer-mop
#:built-in-class
#:class
#:direct-slot-definition
#:effective-slot-definition
#:eql-specializer
#:forward-referenced-class
#:funcallable-standard-class
#:funcallable-standard-object
#:generic-function
#:metaobject
#:method
#:method-combination
#:slot-definition
#:standard-accessor-method
#:standard-class
#:standard-generic-function
#:standard-direct-slot-definition
#:standard-effective-slot-definition
#:standard-method
#:standard-object
#:standard-reader-method
#:standard-slot-definition
#:standard-writer-method
#:defclass
#:defgeneric
#:define-method-combination
#:defmethod
#:classp
#:ensure-finalized
#:ensure-method
#:fix-slot-initargs
#:required-args
#:subclassp
#:accessor-method-slot-definition
#:add-dependent
#:add-direct-method
#:add-direct-subclass
#:class-default-initargs
#:class-direct-default-initargs
#:class-direct-slots
#:class-direct-subclasses
#:class-direct-superclasses
#:class-finalized-p
#:class-precedence-list
#:class-prototype
#:class-slots
#:compute-applicable-methods-using-classes
#:compute-class-precedence-list
#:compute-default-initargs
#:compute-discriminating-function
#:compute-effective-method
#:compute-effective-method-function
#:compute-effective-slot-definition
#:compute-slots
#:direct-slot-definition-class
#:effective-slot-definition-class
#:ensure-class
#:ensure-class-using-class
#:ensure-generic-function
#:ensure-generic-function-using-class
#:eql-specializer-object
#:extract-lambda-list
#:extract-specializer-names
#:finalize-inheritance
#:find-method-combination
#:funcallable-standard-instance-access
#:generic-function-argument-precedence-order
#:generic-function-declarations
#:generic-function-lambda-list
#:generic-function-method-class
#:generic-function-method-combination
#:generic-function-methods
#:generic-function-name
#:intern-eql-specializer
#:make-method-lambda
#:map-dependents
#:method-function
#:method-generic-function
#:method-lambda-list
#:method-specializers
#:reader-method-class
#:remove-dependent
#:remove-direct-method
#:remove-direct-subclass
#:set-funcallable-instance-function
#:slot-boundp-using-class
#:slot-definition-allocation
#:slot-definition-initargs
#:slot-definition-initform
#:slot-definition-initfunction
#:slot-definition-location
#:slot-definition-name
#:slot-definition-readers
#:slot-definition-writers
#:slot-definition-type
#:slot-makunbound-using-class
#:slot-value-using-class
#:specializer-direct-generic-functions
#:specializer-direct-methods
#:standard-instance-access
#:subtypep
#:typep
#:update-dependent
#:validate-superclass
#:writer-method-class
#:warn-on-defmethod-without-generic-function
))
| 6,252 | Common Lisp | .lisp | 120 | 24.641667 | 73 | 0.399739 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | dc96fec1f44b3d550964b1aaca75c4063927c7734b5056480e8d2b6cf214c0d3 | 13,166 | [
-1
] |
13,167 | network-tree.lisp | nixeagle_nisp/network-tree/network-tree.lisp | (in-package :nisp.network-tree)
(defun parse-method-lambda-expression-body (lambda-form)
"Try to find the body of LAMBDA-FORM.
Returns the body as the first value and the stuff before the body as the
second value."
(let ((lambda-args (second lambda-form))
declare-forms)
(labels ((parse (body &optional docstringp)
(if (or (and (consp (car body))
(eq 'declare (caar body)))
(and (stringp (car body)) (cdr body)))
(progn
(push (car body) declare-forms)
(parse (cdr body) (or docstringp (stringp (car body)))))
body)))
(values (parse (cddr lambda-form)) lambda-args (reverse declare-forms)))))
(defun pretend-splits (string)
(iter (repeat 1)
(for (values res next-start)
initially (test-first-command-word string)
then (test-first-command-word string next-start))
(collect res)
(while next-start)
))
(defun pretend-splits/2 (string)
(declare (optimize (speed 3) (debug 1) (safety 0)))
(iter (for (values new rest)
initially (first-command-word string)
then (first-command-word rest))
(repeat 3)
(until (string= rest ""))))
(declaim (inline test-first-command-word))
(defun test-first-command-word (command-string &optional (start-index 0) (seperater #\Space))
"Extract the first segment in COMMAND-STRING before SEPERATER.
Second return value is what is left after removing the segment."
(declare (simple-string command-string)
(character seperater)
(optimize (speed 3) (safety 0) (debug 1)))
(let ((space-index (position seperater command-string :start start-index)))
(declare (type (or null non-negative-fixnum) space-index))
(if space-index
(values (subseq command-string start-index space-index)
(1+ space-index))
(values (if (zerop start-index)
command-string
(subseq command-string start-index))
nil))))
(defun first-command-word (command-string &optional (seperater #\Space)
(start-index 0))
"Extract the first segment in COMMAND-STRING before SEPERATER.
Second return value is what is left after removing the segment."
(declare (type simple-string command-string)
(type character seperater)
(optimize (speed 3) (safety 0) (debug 1)))
(let ((space-index (position seperater command-string :start start-index)))
(declare (type (or null non-negative-fixnum) space-index))
(if space-index
(values
(subseq command-string start-index space-index)
(subseq command-string (the non-negative-fixnum (1+ space-index))))
(values command-string ""))))
(defun network-node-string-p (string)
"True if STRING can represent a valid tree-symbol.
A valid tree-symbol is defined as anything that does not contain a space."
(when (stringp string)
(not (find #\Space string))))
(deftype network-node-string ()
"String with no spaces."
'(and string (satisfies network-node-string-p)))
;;;{{{ ensure-network-node-symbol(s)
(defparameter +network-tree-symbols-package+ (find-package :keyword)
"Package that all tree symbols should get interned into.")
#+ ()
(defgeneric ensure-network-node-symbol (symbol)
(:documentation "Make sure SYMBOL exists in `+network-tree-symbols-package+'."))
(defun ensure-network-node-symbol (arg)
(if (stringp arg)
arg
(princ-to-string arg)))
#+ ()
(defmethod ensure-network-node-symbol (arg)
"Make a symbol out of ARG by `format-symbol'."
(string-upcase (format "~A" arg)))
#+ ()
(defmethod ensure-network-node-symbol ((symbol symbol))
"Make SYMBOL a list and recall."
(call-next-method))
#+ ()
(defmethod ensure-network-node-symbol ((symbol-as-string string))
"Split by spaces, then intern SYMBOLS as normal."
(declare (type network-node-string symbol-as-string))
(string-upcase symbol-as-string))
(defgeneric ensure-network-node-symbols (symbols)
(:documentation "Return a list of symbols instead of just one."))
(defmethod ensure-network-node-symbols ((args list))
(mapcar #'ensure-network-node-symbol args))
(defmethod ensure-network-node-symbols ((args symbol))
(ensure-network-node-symbols (ensure-list args)))
(defmethod ensure-network-node-symbols ((symbols-as-string string))
(split-sequence #\Space
(string-upcase symbols-as-string)
:remove-empty-subseqs t))
;;;}}}
;;;{{{ Tree classes
(defclass network-tree-parent ()
(#+ () (parent :initarg :parent
:reader network-tree-parent))
#+ () (:default-initargs :parent nil))
(locally (declare (optimize (speed 3) (safety 0) (debug 0)))
(defstruct (tree-generic-direct-nodes
(:conc-name))
(tree-generic-direct-nodes (make-hash-table :test 'equalp
#+sbcl :weakness
#+ccl :weak
#+ (or sbcl ccl) :value)
)))
(declaim (inline tree-generic-direct-node))
(defun tree-generic-direct-node (tree arg)
(declare (type simple-string arg)
(type tree-generic-direct-nodes tree)
(optimize (speed 3) (safety 0) (debug 0)))
(gethash arg (tree-generic-direct-nodes tree)))
(defclass network-tree-generic-function
(#+sbcl
cl:standard-generic-function
#-sbcl standard-generic-function)
()
(:metaclass closer-mop:funcallable-standard-class)
(:default-initargs :method-class (find-class 'tree-method)))
(defstruct (network-tree-node (:include tree-generic-direct-nodes)
(:conc-name))
)
(defclass network-tree-method (standard-method network-tree-parent)
((methods :type list :reader network-tree-method-methods
:initform ()))
#+ccl (:default-initargs :closer-patch t))
(defclass tree-method (network-tree-method)
())
#+ () (defmethod print-object ((obj network-tree-node) stream)
(print-unreadable-object (obj stream :type t :identity t)
(princ (network-tree-node-object obj) stream)))
;;;}}}
;;;{{{ Interning network-tree nodes
(defvar *network-tree-nodes* (make-instance 'tree-generic-direct-nodes))
(defun %intern-network-tree-node (node symbols)
(declare (type tree-generic-direct-nodes node)
(type list symbols)
;; We need tail recursion
(optimize (speed 3) (safety 0) (debug 1)))
(the network-tree-node
(if symbols
(%intern-network-tree-node
(or (gethash (car symbols) (tree-generic-direct-nodes node))
(setf (gethash (car symbols) (tree-generic-direct-nodes node))
(make-network-tree-node)
))
(cdr symbols))
node)))
(defun intern-network-tree-node (symbols)
"Intern a unique specializer for TREE for SYMBOLS.
SYMBOLS represents a path starting at the root of TREE and going down one
symbol at a time through repeated hash-tables until the last of SYMBOLS is
reached.
SYMBOLS may be a list of symbols, a string of space seperated words that
is translated into a list of symbols."
(declare (type string symbols))
(%intern-network-tree-node *network-tree-nodes* (ensure-network-node-symbols symbols)))
(defun find-network-tree-node (name &key (nodes *network-tree-nodes*))
"Find a node called NAME."
(loop for node-name in (ensure-network-node-symbols name)
for current-node = nodes then next-node
for next-node = (gethash node-name (tree-generic-direct-nodes current-node))
finally (return next-node)))
(defun network-tree-node-keys (node)
"Finds the keys required to get NODE."
(let (result foundp)
(labels ((next-node (current-node &optional so-far)
(loop for name being the hash-keys in (tree-generic-direct-nodes current-node) using (hash-value sub-node)
when (eq node sub-node) do
(setq result (reverse (cons name so-far))
foundp t)
unless foundp
do (next-node sub-node (cons name so-far)))))
(next-node *network-tree-nodes*))
result))
(defun maybe-make-tree-specializer-form (specializer-name)
;; We don't actually check right now, instead just making the correct
;; form.
;;
;; This _must_ return a form that creates the specializer, never the
;; specializer itself. This solves a bug related to SB-PCL::LOAD-DEFMETHOD.
;;
;; We must sharpsign quote the generic-function name, otherwise the fasl
;; cannot be loaded.
`(eql (intern-network-tree-node ,@(cdr specializer-name))))
;;; Now we need to make a specializer class. Most of this is from sbcl's
;;; boot.lisp `real-make-method-specializers-form'.
#+sbcl
(defmethod sb-pcl:make-method-specializers-form
((generic-function network-tree-generic-function)
method specializer-names environment)
;; If it is a list, we assume it is a tree specializer.
(if (listp (car specializer-names))
(call-next-method generic-function method
(cons (maybe-make-tree-specializer-form (car specializer-names))
(cdr specializer-names))
environment)
(call-next-method)))
(defparameter *args* nil)
(let ((*network-tree-remaining* nil))
(declare (special *network-tree-remaining*))
(defmethod compute-discriminating-function
((generic-function network-tree-generic-function))
(let ((it (call-next-method)))
(declare (type function it))
(lambda (&rest args)
(declare (dynamic-extent args))
(multiple-value-bind (command *network-tree-remaining*)
(first-command-word (car args))
(declare (special *network-tree-remaining*))
(apply it (the network-tree-node
(tree-generic-direct-node *network-tree-nodes* command))
(cdr args))))))
(defmethod make-method-lambda
((generic-function network-tree-generic-function) method expression environment)
(multiple-value-bind (body lambda-args declarations)
(parse-method-lambda-expression-body expression)
(let ((expression
`(lambda ,lambda-args ,@declarations
(labels ((test () 1)
(remaining-parameters ()
(declare (special *network-tree-remaining*))
(the string *network-tree-remaining*))
(next-node (&optional (remaining-parameters (remaining-parameters)))
(let ((*network-tree-nodes* ,(car lambda-args)))
(funcall #',(generic-function-name generic-function)
remaining-parameters
,@(cdr lambda-args)))))
(declare (ignorable (function test)
(function next-node)
(function remaining-parameters)))
,@body))))
(let ((lamb (call-next-method generic-function method expression environment)))
lamb)))))
(defmethod make-load-form ((self network-tree-node) &optional env)
(declare (ignore env))
(values `(intern-network-tree-node ,(network-tree-node-object self))
nil))
#+ ()
(defun maybe-intern-command-specializer (input)
(if (and (consp input) (eq (car input) 'command))
(intern-command-specializer (cdr input))
input))
#+ ()
(defun transform-method-specializers (input)
(mapcar #'maybe-intern-command-specializer input))
;;; Now we need to make a specializer class. Most of this is from sbcl's
;;; boot.lisp `real-make-method-specializers-form'.
#+ ()
(defmethod sb-pcl:make-method-specializers-form
((generic-function command-generic-function)
method specializer-names environment)
(let ((names (transform-method-specializers specializer-names)))
(call-next-method generic-function method names environment)))
;;; END
| 12,210 | Common Lisp | .lisp | 265 | 37.637736 | 121 | 0.641459 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 475fe996ee71170949f9863719174f4440c3a7823b32749724271491f08b7ebc | 13,167 | [
-1
] |
13,168 | network-tree-tests.lisp | nixeagle_nisp/network-tree/network-tree-tests.lisp | ;;; Tests for tree-funcallable-class
(in-package :nisp.network-tree)
#+ ()
(progn
(fmakunbound 'test-tree-generic-function)
(defgeneric test-tree-generic-function (tree arg1)
(:generic-function-class network-tree-generic-function))
(defmethod test-tree-generic-function ((tree (eql "hi")) arg1)
(list tree arg1 (next-node)))
(defmethod test-tree-generic-function ((tree (eql "hi there")) arg1)
(list tree (and (> arg1 1) (remaining-parameters))))
(defmethod test-tree-generic-function ((tree (eql "hi there")) (arg1 integer))
(list tree "ARG1 was an integer" (call-next-method)))
(defmethod test-tree-generic-function ((tree (eql "hi there")) (arg1 (eql 10)))
(list tree "ARG1 was = to 10" (call-next-method)))
(defmethod test-tree-generic-function :around ((tree (eql "hi there"))
arg1)
(list tree "around!" (call-next-method)))
(defmethod test-tree-generic-function ((tree (eql "hi there hi")) arg1)
(list tree (and (> arg1 2) (next-node))))
(defmethod test-tree-generic-function ((tree (eql "hi there hi how")) arg1)
(list tree (and (> arg1 3) (next-node))))
(defmethod test-tree-generic-function ((tree (eql "hi there hi how are")) arg1)
(list tree (and (> arg1 4) (next-node))))
(defmethod test-tree-generic-function ((tree (eql "hi there hi how are you")) arg1)
(list tree (and (> arg1 5) (next-node))))
(defmethod test-tree-generic-function ((tree (eql "hi there hi how are you doing")) arg1)
(list tree arg1 (remaining-parameters)))
(defmethod test-tree-generic-function :before ((tree (eql "hi there hi")) arg1)
1))
(progn
(fmakunbound 'test-tree-generic-function)
(fmakunbound 'call-test-tree-generic-function)
(defgeneric test-tree-generic-function (tree arg1)
(:generic-function-class network-tree-generic-function))
(defun call-test-tree-generic-function (tree arg1)
(declare (optimize (speed 3) (debug 0) (safety 0))
(simple-string tree))
(test-tree-generic-function (tree-generic-direct-node *network-tree-nodes* tree) arg1))
(defmethod test-tree-generic-function ((tree (eql "hi")) arg1)
arg1
"hi"
#+ () (remaining-parameters))
(defmethod test-tree-generic-function ((tree (eql "one")) arg1)
(next-node))
(defmethod test-tree-generic-function ((tree (eql "one two")) arg1)
(next-node))
(defmethod test-tree-generic-function ((tree (eql "one two three")) arg1)
arg1)
#+ () (defmethod test-tree-generic-function ((tree (eql (intern-network-tree-node "hi"))) arg1)
arg1
"hi"))
(def-suite root)
(test (first-command-word :suite root)
(is (string= "Hi" (first-command-word "Hi how are you?")))
(is (string= "Hi h" (first-command-word "Hi how are you?" #\o))
"Should be splitting on #\o.")
(is (string= "" (first-command-word ""))
"Empty string when no more words left."))
(test (network-node-string-p :suite root)
"Predicate returns false if a string has a space in it.
We assume input is a string."
(is (eq t (network-node-string-p "hi")))
(is (eq nil (network-node-string-p "hi there")))
(is (null (network-node-string-p " hi "))
"Leading or trailing spaces are _not_ ok if there is only one
\"word\" given as we should be able to parse out that and convert it
to a symbol."))
(test (ensure-network-node-symbol :suite root)
#+ ()
(with-fbound (ensure-network-node-symbol)
('it) (find-symbol "IT" +network-tree-symbols-package+)
('(it it2)) :signals error
("IT") (find-symbol "IT" +network-tree-symbols-package+)
"Lowercase input should result in an uppercase symbol."
("it") (find-symbol "IT" +network-tree-symbols-package+)
"Strings with spaces in them should error as it makes no sense to make
a single tree symbol out of what boils down to one symbol"
("it it2") :signals error))
(test (ensure-network-node-symbols :suite root
:depends-on ensure-network-node-symbol)
#+ ()
(with-fbound (ensure-network-node-symbols)
('(hi how)) '(:HI :HOW)
("hi how") '(:HI :HOW)
('hi) '(:HI)))
(test (intern-network-tree-node/typep :suite root)
"All that matters is we get a tree specializer"
(is (typep (intern-network-tree-node '("hi"))
'network-tree-node)))
(test (intern-network-tree-node/same/one-level
:suite root
:depends-on intern-network-tree-node/typep)
"The result from interning should always be the same object"
(let ((expected (intern-network-tree-node '(:HI))))
(is (eq expected (intern-network-tree-node '(:HI))))
(is (eq expected (intern-network-tree-node '("hi"))))
(is (eq expected (intern-network-tree-node "hi")))
(is (eq expected (intern-network-tree-node :hi)))))
(test (intern-network-tree-node/same/two-levels
:suite root
:depends-on intern-network-tree-node/same/one-level)
(let ((expected (intern-network-tree-node '(:TWO :LEVELS))))
(is (eq expected (intern-network-tree-node '(:TWO :LEVELS))))
(is (eq expected (intern-network-tree-node '("two" "levels"))))
(is (eq expected (intern-network-tree-node "two levels")))))
(test (test-tree-generic-function/complex-method-combination
:suite root
:depends-on intern-network-tree-node)
(finishes (test-tree-generic-function "hi2 there" 10)))
;;; END
| 5,362 | Common Lisp | .lisp | 111 | 43.387387 | 96 | 0.667686 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 3d94fd28bbc319191e0f1f358a5db6dbdc186432367dc6e3c3414e7059ebc58c | 13,168 | [
-1
] |
13,169 | package.lisp | nixeagle_nisp/irc-bot/package.lisp | (defpackage #:nisp.i
(:use :cl :iterate :nisp-core :nutils :eos
:closer-mop :nisp.network-tree)
(:import-from :cl-irc :user #:nickname #:username #:realname)
;; This whole shadowing import block is taken from
;; closer-mop-packages.lisp in order to correctly import the
;; closer-mop package.
(:shadowing-import-from :closer-mop
#:built-in-class
#:class
#:direct-slot-definition
#:effective-slot-definition
#:eql-specializer
#:forward-referenced-class
#:funcallable-standard-class
#:funcallable-standard-object
#:generic-function
#:metaobject
#:method
#:method-combination
#:slot-definition
#:standard-accessor-method
#:standard-class
#:standard-generic-function
#:standard-direct-slot-definition
#:standard-effective-slot-definition
#:standard-method
#:standard-object
#:standard-reader-method
#:standard-slot-definition
#:standard-writer-method
#:defclass
#:defgeneric
#:define-method-combination
#:defmethod
#:classp
#:ensure-finalized
#:ensure-method
#:fix-slot-initargs
#:required-args
#:subclassp
#:accessor-method-slot-definition
#:add-dependent
#:add-direct-method
#:add-direct-subclass
#:class-default-initargs
#:class-direct-default-initargs
#:class-direct-slots
#:class-direct-subclasses
#:class-direct-superclasses
#:class-finalized-p
#:class-precedence-list
#:class-prototype
#:class-slots
#:compute-applicable-methods-using-classes
#:compute-class-precedence-list
#:compute-default-initargs
#:compute-discriminating-function
#:compute-effective-method
#:compute-effective-method-function
#:compute-effective-slot-definition
#:compute-slots
#:direct-slot-definition-class
#:effective-slot-definition-class
#:ensure-class
#:ensure-class-using-class
#:ensure-generic-function
#:ensure-generic-function-using-class
#:eql-specializer-object
#:extract-lambda-list
#:extract-specializer-names
#:finalize-inheritance
#:find-method-combination
#:funcallable-standard-instance-access
#:generic-function-argument-precedence-order
#:generic-function-declarations
#:generic-function-lambda-list
#:generic-function-method-class
#:generic-function-method-combination
#:generic-function-methods
#:generic-function-name
#:intern-eql-specializer
#:make-method-lambda
#:map-dependents
#:method-function
#:method-generic-function
#:method-lambda-list
#:method-specializers
#:reader-method-class
#:remove-dependent
#:remove-direct-method
#:remove-direct-subclass
#:set-funcallable-instance-function
#:slot-boundp-using-class
#:slot-definition-allocation
#:slot-definition-initargs
#:slot-definition-initform
#:slot-definition-initfunction
#:slot-definition-location
#:slot-definition-name
#:slot-definition-readers
#:slot-definition-writers
#:slot-definition-type
#:slot-makunbound-using-class
#:slot-value-using-class
#:specializer-direct-generic-functions
#:specializer-direct-methods
#:standard-instance-access
#:subtypep
#:typep
#:update-dependent
#:validate-superclass
#:writer-method-class
#:warn-on-defmethod-without-generic-function
))
(defpackage #:nisp.i-zeta
(:use :cl :eos :iterate :alexandria)
(:shadowing-import-from :closer-mop
#:built-in-class
#:class
#:direct-slot-definition
#:effective-slot-definition
#:eql-specializer
#:forward-referenced-class
#:funcallable-standard-class
#:funcallable-standard-object
#:generic-function
#:metaobject
#:method
#:method-combination
#:slot-definition
#:specializer
#:standard-accessor-method
#:standard-class
#:standard-generic-function
#:standard-direct-slot-definition
#:standard-effective-slot-definition
#:standard-method
#:standard-object
#:standard-reader-method
#:standard-slot-definition
#:standard-writer-method
#:defclass
#:defgeneric
#:define-method-combination
#:defmethod
#:classp
#:ensure-finalized
#:ensure-method
#:fix-slot-initargs
#:required-args
#:subclassp
#:accessor-method-slot-definition
#:add-dependent
#:add-direct-method
#:add-direct-subclass
#:class-default-initargs
#:class-direct-default-initargs
#:class-direct-slots
#:class-direct-subclasses
#:class-direct-superclasses
#:class-finalized-p
#:class-precedence-list
#:class-prototype
#:class-slots
#:compute-applicable-methods-using-classes
#:compute-class-precedence-list
#:compute-default-initargs
#:compute-discriminating-function
#:compute-effective-method
#:compute-effective-method-function
#:compute-effective-slot-definition
#:compute-slots
#:direct-slot-definition-class
#:effective-slot-definition-class
#:ensure-class
#:ensure-class-using-class
#:ensure-generic-function
#:ensure-generic-function-using-class
#:eql-specializer-object
#:extract-lambda-list
#:extract-specializer-names
#:finalize-inheritance
#:find-method-combination
#:funcallable-standard-instance-access
#:generic-function-argument-precedence-order
#:generic-function-declarations
#:generic-function-lambda-list
#:generic-function-method-class
#:generic-function-method-combination
#:generic-function-methods
#:generic-function-name
#:intern-eql-specializer
#:make-method-lambda
#:map-dependents
#:method-function
#:method-generic-function
#:method-lambda-list
#:method-specializers
#:reader-method-class
#:remove-dependent
#:remove-direct-method
#:remove-direct-subclass
#:set-funcallable-instance-function
#:slot-boundp-using-class
#:slot-definition-allocation
#:slot-definition-initargs
#:slot-definition-initform
#:slot-definition-initfunction
#:slot-definition-location
#:slot-definition-name
#:slot-definition-readers
#:slot-definition-writers
#:slot-definition-type
#:slot-makunbound-using-class
#:slot-value-using-class
#:specializer-direct-generic-functions
#:specializer-direct-methods
#:standard-instance-access
#:subtypep
#:typep
#:update-dependent
#:validate-superclass
#:writer-method-class
#:warn-on-defmethod-without-generic-function
))
(in-package :nisp.i)
;;; DEBUG KLUDGE for now
(defvar *format-and-send-to-irc-function* nil
"Temporary hack for sending some debug info to an irc channel as a sideband.")
(defun d/i (formatspec &rest args)
(funcall *format-and-send-to-irc-function*
(substitute #\Space #\Newline (apply #'format nil formatspec args))))
| 12,262 | Common Lisp | .lisp | 233 | 24.660944 | 80 | 0.394325 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 32352c550aad68a905a679c223b404119a819861f41076ed638efe2883c55709 | 13,169 | [
-1
] |
13,170 | core-package.lisp | nixeagle_nisp/irc-bot/core-package.lisp | (cl:defpackage #:nixeagle.nisp.core
(:nicknames :nisp-core :nisp.core)
(:use :cl :closer-mop :nisp.network-tree)
(:shadowing-import-from :closer-mop
#:built-in-class
#:class
#:direct-slot-definition
#:effective-slot-definition
#:eql-specializer
#:forward-referenced-class
#:funcallable-standard-class
#:funcallable-standard-object
#:generic-function
#:metaobject
#:method
#:method-combination
#:slot-definition
#:standard-accessor-method
#:standard-class
#:standard-generic-function
#:standard-direct-slot-definition
#:standard-effective-slot-definition
#:standard-method
#:standard-object
#:standard-reader-method
#:standard-slot-definition
#:standard-writer-method
#:defclass
#:defgeneric
#:define-method-combination
#:defmethod
#:classp
#:ensure-finalized
#:ensure-method
#:fix-slot-initargs
#:required-args
#:subclassp
#:accessor-method-slot-definition
#:add-dependent
#:add-direct-method
#:add-direct-subclass
#:class-default-initargs
#:class-direct-default-initargs
#:class-direct-slots
#:class-direct-subclasses
#:class-direct-superclasses
#:class-finalized-p
#:class-precedence-list
#:class-prototype
#:class-slots
#:compute-applicable-methods-using-classes
#:compute-class-precedence-list
#:compute-default-initargs
#:compute-discriminating-function
#:compute-effective-method
#:compute-effective-method-function
#:compute-effective-slot-definition
#:compute-slots
#:direct-slot-definition-class
#:effective-slot-definition-class
#:ensure-class
#:ensure-class-using-class
#:ensure-generic-function
#:ensure-generic-function-using-class
#:eql-specializer-object
#:extract-lambda-list
#:extract-specializer-names
#:finalize-inheritance
#:find-method-combination
#:funcallable-standard-instance-access
#:generic-function-argument-precedence-order
#:generic-function-declarations
#:generic-function-lambda-list
#:generic-function-method-class
#:generic-function-method-combination
#:generic-function-methods
#:generic-function-name
#:intern-eql-specializer
#:make-method-lambda
#:map-dependents
#:method-function
#:method-generic-function
#:method-lambda-list
#:method-specializers
#:reader-method-class
#:remove-dependent
#:remove-direct-method
#:remove-direct-subclass
#:set-funcallable-instance-function
#:slot-boundp-using-class
#:slot-definition-allocation
#:slot-definition-initargs
#:slot-definition-initform
#:slot-definition-initfunction
#:slot-definition-location
#:slot-definition-name
#:slot-definition-readers
#:slot-definition-writers
#:slot-definition-type
#:slot-makunbound-using-class
#:slot-value-using-class
#:specializer-direct-generic-functions
#:specializer-direct-methods
#:standard-instance-access
#:subtypep
#:typep
#:update-dependent
#:validate-superclass
#:writer-method-class
#:warn-on-defmethod-without-generic-function)
(:export #:abstract-identity
#:abstract-connection
#:abstract-action
#:abstract-message-content
#:full-message
#:message
#:remaining-message
#:commandp
#:abstract-text-message-content
#:message-text
#:send
#:privmsg
#:connectedp
#:nisp-command-network-tree-generic-function
#:handle-command-method
#:handle-command-method-call-count
#:route-command
#:handle-command
#:define-simple-command
#:abstract-name
#:name
#:abstract-user
#:abstract-address
#:address
#:abstract-party
#:abstract-from
#:abstract-to
#:abstract-target
#:abstract-protocol
#:abstract-provider
#:abstract-medium
#:abstract-data-source
#:abstract-data-sink
#:abstract-action
#:abstract-message-content
#:reply
#:defcommand))
| 6,930 | Common Lisp | .lisp | 147 | 22.462585 | 74 | 0.403097 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 1b5481e56941cf6fbc84296ffc87f7c6b5c42263199bec363ebccbb8820e5815 | 13,170 | [
-1
] |
13,171 | comchar.lisp | nixeagle_nisp/irc-bot/comchar.lisp | (in-package :nisp.i)
(deftype valid-comchar ()
"Usable characters for irc comchars.
Most anything else in the ASCII set can't be used as they occur as part
of normal conversation and an IRC bot that interferes with that is not
a very friendly bot."
'(member #\! #\% #\) #\+ #\, #\- #\. #\<
#\@ #\\ #\] #\_ #\` #\{ #\| #\} #\~))
(defun valid-comchar-string-p (string)
(and (typep string '(and (string 1)))
(typep (character string) 'valid-comchar)))
(deftype valid-comchar-string ()
'(satisfies valid-comchar-string-p))
(defclass comchar ()
((comchar :type valid-comchar
:accessor comchar
:documentation "Single character that the program responds to.
Saying :comchar \"!\" or similar will work thanks to the shared-initialize."))
(:documentation "Represents an irc bot comchar.
This is a single character, usually a symbol that the bot responds
to. This class will signal an error if a comchar is not of the type
valid-comchar.")
(:default-initargs :comchar "\,"))
(defmethod (setf comchar) ((char string) (object comchar))
"Set CHAR, a string of length 1 as the comchar."
(declare (type (string 1) char))
(setf (slot-value object 'comchar)
(character char)))
(defmethod shared-initialize :after ((char comchar) slot-names &key comchar)
"Make sure that :COMCHAR is a char before storing."
(when comchar
(setf (comchar char) comchar)))
| 1,415 | Common Lisp | .lisp | 32 | 40.71875 | 78 | 0.690684 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | d60ef19b5616103c04fbb23bc440d07c903493e9b5c6fd20ef893288c5b093fd | 13,171 | [
-1
] |
13,172 | superclass-helpers.lisp | nixeagle_nisp/irc-bot/superclass-helpers.lisp | (in-package :nisp.i)
(defun add-superclass (instance new-superclass)
"Add NEW-SUPERCLASS to INSTANCE's superclass list."
(reinitialize-instance (class-of instance) :direct-superclasses
(adjoin (find-class new-superclass)
(class-direct-superclasses
(class-of instance)))))
(defun delete-superclass-of (instance superclass)
"Delete SUPERCLASS from INSTANCE's superclass list."
(reinitialize-instance (class-of instance) :direct-superclasses
(remove (find-class superclass)
(class-direct-superclasses
(class-of instance)))))
;;; END
| 727 | Common Lisp | .lisp | 14 | 36.857143 | 65 | 0.585915 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | c90e31dc9f25214a51438b3b160098a98347e3e2130ae8c270ff460bf3709e52 | 13,172 | [
-1
] |
13,173 | config-dist.lisp | nixeagle_nisp/irc-bot/config-dist.lisp | (in-package :nisp.i)
;;; Connection details here.
(defclass main-irc-bot (bot-connection
connect-with-background-handler-mixin)
()
(:default-initargs :server-name "irc.ninthbit.net"
:comchar #\!
:nickname "nisp-dist")
(:documentation "Demonstration class
Shows how to setup a connection to ninthbit.net using a comchar of !."))
;;; Tell the bot what to do after it connects. For now this includes
;;; channel joins and talking to nickserv.
(defmethod connect :after ((irc main-irc-bot) &key)
(irc:join irc "#bots")
(irc:privmsg irc "#bots" "hi all!"))
(defvar *main-irc-bot* (make-instance 'main-irc-bot))
(unless (connectedp *main-irc-bot*) (connect *main-irc-bot*))
| 723 | Common Lisp | .lisp | 17 | 38.294118 | 72 | 0.69 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 14f249ff14aebf0b4330bbf8a7d0fac45cf357fe0e91f9d3fcd6f57d9847cb91 | 13,173 | [
-1
] |
13,174 | user-init.lisp | nixeagle_nisp/irc-bot/user-init.lisp | ;;; Hackity hack to load configuration file _last_.
(in-package :nisp.i)
(load (merge-pathnames "config.lisp" +root-directory+)
:if-does-not-exist nil) | 159 | Common Lisp | .lisp | 4 | 37 | 54 | 0.714286 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 2f9e4879611c0404dfda20529a4260bcd658347850280d197d43df818ad82242 | 13,174 | [
-1
] |
13,175 | mixin.lisp | nixeagle_nisp/irc-bot/mixin.lisp | ;;; General mixins
(in-package :nisp.core)
(defclass abstract-identity () ()
(:documentation "Direct mapping to person's identity.
This is different then any handle/nick/username/email. A person's
identity should be the same across whatever protocols we operate
over."))
(defclass abstract-connection () ()
(:documentation "Protocol agnostic interface specification.
In principle any connection class derived from usocket that implements all
methods specialized on this object is a complient interface."))
;;; Not well specified atm, will be working on this
;;; soon. 01-03-2010
(defclass abstract-name () ())
(defgeneric name (object)
(:documentation "Must return a 'person/thing name'.
This is something to address someone by."))
(defmethod name ((object abstract-name))
(error "Must be implemented by child classes"))
(defclass abstract-user (abstract-name) ())
(defclass abstract-address () ())
(defgeneric address (object)
(:documentation "Must return a place or location."))
(defmethod address ((object abstract-address))
(error "Must be implemented by child classes"))
(defclass abstract-party (abstract-user abstract-address) ()
(:documentation "Participant in an exchange."))
(defclass abstract-from (abstract-party) ()
(:documentation "Generic information about a sender."))
(defclass abstract-to (abstract-party) ()
(:documentation "Generic information about a recipient/target/channel"))
(defclass abstract-target (abstract-from abstract-to) ())
(defclass abstract-protocol () ()
(:documentation "Transfer encodings.
This covers the spectrum from json, http, jabber, irc, and whatever else
you can think of. If you can encode data with it, this protocol interface
specification can cover it. This assumes proper CLOS superclassing."))
(defclass abstract-provider () ()
(:documentation "Particular domain/service.
This is not restricted to just one domain, but covers classes of services
from different providers depending on how classes that superclass this one
are structured."))
(defclass abstract-medium (abstract-protocol abstract-provider) ()
(:documentation "Protocol/service information."))
(defclass abstract-data-source (abstract-medium) ()
(:documentation "Generic information on the _source_ of a message.
This is different from `abstract-from' in that here we care about how we
got the message, not who or what sent it."))
(defclass abstract-data-sink (abstract-medium) ()
(:documentation "Generic information about destination protocol/service.
This is different from `abstract-to' in that here we care about where a
message is routed to, as opposed to who or what is to eventually receive
the message. The term 'sink' means what medium a message will be
convoyed over to reach its destination as specified by `abstract-to'."))
(defclass abstract-action () ()
(:documentation "Generic information about intended actions.
This will vary widely depending on source/sink combinations, but we need
this for generic function/default method definitions as well as interface
specification."))
(defclass abstract-message-content () ()
(:documentation "Message contents/information"))
(defgeneric full-message (object))
(defgeneric message (object))
(defgeneric remaining-message (object))
(defgeneric commandp (object))
(defclass abstract-text-message-content (abstract-message-content)
((full-message :initarg :message :reader full-message :type string)
(message :reader message :type string)
(remaining-message :reader remaining-message :type string)))
;;; possibly include abstract-message as a composed class or somehow
;;; holding all these parts in one interface, which is why we rename
;;; abstract-message to abstract-message-content.
(defgeneric message-text (object))
(defgeneric send (action sink to content &rest additional-args))
(defgeneric privmsg (sink to content))
(defgeneric connectedp (connection-object)
(:documentation "Is CONNECTION-OBJECT currently connected?"))
;;; END
| 3,995 | Common Lisp | .lisp | 78 | 49.153846 | 74 | 0.783617 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | cb7ae33d3a6ceb051cc51b55ca21e7267443526bfb61c9b2c652f8fe034a5446 | 13,175 | [
-1
] |
13,176 | connect.lisp | nixeagle_nisp/irc-bot/irc/connect.lisp | (in-package :nisp.i)
(defclass bot-connection (connection comchar
abstract-data-source
abstract-data-sink) ()
(:default-initargs :username "lisp" :nickname "nisp"
:realname "Nixeagle's lisp experiments"
:server-port 6667
:comchar ","))
(defclass connect-with-background-handler-mixin () ()
(:documentation "Superclass this to connect directly to background on
methods that support this."))
(defmethod shared-initialize :after ((bot bot-connection) (slot-names t)
&key nickname username realname)
(when (and nickname username realname)
(setf (slot-value bot 'irc:user)
(make-instance 'bot-user
:nickname nickname
:username username
:realname realname))))
(defgeneric connect (connection &key &allow-other-keys))
(defmethod connect :around ((bot connection) &key (first-connect-p t)
always-connect)
(declare (boolean first-connect-p always-connect))
(if (and first-connect-p (not (connectedp bot)))
(call-next-method)
(when always-connect
(call-next-method))))
(defmethod connect :before ((bot bot-connection) &key ssl)
(setf (slot-value bot 'irc::socket)
(usocket:socket-connect (irc:server-name bot)
(irc:server-port bot)
:element-type 'flexi-streams:octet))
(setf (irc:network-stream bot) (if ssl
(funcall #'cl+ssl:make-ssl-client-stream
(usocket:socket-stream
(irc::socket bot)))
(usocket:socket-stream
(irc::socket bot))))
(setf (irc:output-stream bot) (flexi-streams:make-flexi-stream
(irc:network-stream bot)
:element-type 'character
:external-format :UTF8)))
(defmethod connect ((bot connection) &key mode)
(when (irc:password bot)
(irc:pass bot (irc:password bot)))
(irc:nick bot (nickname bot))
(irc:user- bot (or (username bot) (nickname bot))
(or mode 0) (or (realname bot) (nickname bot)))
bot)
(defmethod connect :after ((bot connection) &key)
(irc:add-default-hooks bot))
(defmethod compute-connection-id ((irc connection))
"Uniquely identify IRC connections by `nickname'@`server-name'."
(concatenate 'string (irc:nickname irc) "@" (irc:server-name irc)))
(defun nisp-start-read-loop (irc)
(describe irc)
(irc:read-message-loop irc))
(defmethod connect :after ((irc connect-with-background-handler-mixin) &key)
"Start IRC's command loop in a different thread."
(bordeaux-threads:make-thread (lambda ()
(nisp-start-read-loop irc))
:name (compute-connection-id irc)))
(defmethod connect :after ((irc bot-connection) &key)
"Make sure IRC's hook is setup."
(irc:add-hook irc 'irc:irc-privmsg-message 'irc-handle-privmsg)
(sleep 2))
| 3,267 | Common Lisp | .lisp | 66 | 36 | 77 | 0.570533 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 9c94f9ca02ae2fc235a0795b5af248434787c0b17c7c4d02a9b70095b5f4175c | 13,176 | [
-1
] |
13,177 | ai-demo.lisp | nixeagle_nisp/irc-bot/commands/ai-demo.lisp | ;;; Temp location for ai related code until command definitions get a bit
;;; less internal to nisp and more external.
;;;
;;; This stuff will not be loaded into the running nisp for the time
;;; being.
(in-package :nisp.i)
(defun random-up-or-down (&optional (magnitude 1))
(if (zerop (random 2))
(- magnitude)
magnitude))
(defun generate-markov-sequence (&key (initial 0) (range 10))
"Demo markov to get the idea of it."
(iter (for up-or-down = (random-up-or-down))
(for n initially initial then (+ n up-or-down))
(until (or (> n (+ initial range)) (< n (+ initial (- range)))))
(collect (list n up-or-down))))
(define-simple-command markov
(reply (remove #\Newline
(format nil "~A" (generate-markov-sequence
:initial 0 :range 3)))))
(defvar *states* (list :positive-even :positive-odd :negative-odd :negative-even :zero))
;;=> *STATES*
(defvar *learning-rate* 1/10
"Rate that we adjust things based on a reward.")
(defvar *actions* (list (constantly "Probably")
(constantly "Bye")
(constantly "Hi")
(constantly "Interesting")
(constantly "ZzzZzzZzzZzz")))
(flet ((generate-action-list (&optional (initial-score 5) (action-set *actions*))
(mapcar (lambda (x) (cons x initial-score)) action-set)))
(defparameter *lookup-table* (alist-hash-table
`((:positive-even . ,(generate-action-list))
(:positive-odd . ,(generate-action-list))
(:zero . ,(generate-action-list))
(:negative-even . ,(generate-action-list))
(:negative-odd . ,(generate-action-list))))
"We default the score for every entry to 5. This is chosen by the
programmer. We have to start with some default. Our default is flat
between the range 0 and 10. These are arbitrary values"))
(defun state-action-score (state action)
"Scoring for a particular state/action pair."
(cdr (assoc action (gethash state *lookup-table*))))
(defun (setf state-action-score) (score state action)
(setf (cdr (assoc action (gethash state *lookup-table*)))
score))
(defun state-learning-rate (state action)
*learning-rate*)
(defun state-action-max-score (state action)
10)
(defun compute-new-score (state action reward)
(+ (state-action-score state action)
(* (state-learning-rate state action)
(+ reward
(- (state-action-score state action))))))
(defun compute-state (number-input)
(let ((number-input (if (stringp number-input)
(parse-integer number-input)
number-input)))
(cond
((zerop number-input) :zero)
((and (> 0 number-input) (evenp number-input)) :negative-even)
((and (> 0 number-input) (oddp number-input)) :negative-odd)
((evenp number-input) :positive-even)
(t :positive-odd))))
(defun flux (normal-score)
(+ normal-score (/ (random 150) 100)))
(defun compute-possible-actions (string-integer)
(aif (parse-integer string-integer :junk-allowed t)
(mapcar (lambda (action)
(cons (state-action-score
(compute-state it) action) action)) *actions*)
"I expect integers only! Your brainzzzzzzzz plox!"))
(defun add-flux (action-list)
(mapcar (lambda (action-score-pair)
(cons (flux (car action-score-pair))
(cdr action-score-pair)))
action-list))
(defun compute-best-action (action-list)
(sort action-list #'> :key #'car))
(defun handle-ai (string-integer)
(aif (string-integer-p string-integer)
(car (compute-best-action (add-flux (compute-possible-actions string-integer))))
"I expect integers only!"))
(let ((input "")
(last-score 0)
(last-action nil)
(last-state nil))
(define-simple-command ai
(if (string-integer-p (remaining-parameters))
(progn
(setq input (remaining-parameters))
(destructuring-bind (score . action) (handle-ai (remaining-parameters))
(setq last-action action
last-score score
last-state (compute-state (parse-integer (remaining-parameters))))
(reply (remove #\Newline
(funcall action)))))
(network-tree::next-node)))
(define-simple-command ai-test-state
(reply (princ-to-string (compute-state (parse-integer (remaining-parameters))))))
(define-simple-command ai-previnfo
(reply (list input last-score last-action)))
(define-simple-command ai-test
(network-tree::next-node))
(define-simple-command ai-test-reward
(if (string-integer-p (remaining-parameters))
(reply "New score for state ~A and action ~A would be ~A."
last-state
(funcall last-action)
(float (compute-new-score last-state last-action (parse-integer (remaining-parameters)))))
(reply "Come on! Integers rock!")))
(flet ((format-reward-reply (score)
(format nil "Score for state ~A saying ~A is now ~A."
last-state
(funcall last-action)
(float (reward-ai last-state last-action score)))))
(define-simple-command ai-trout
(reply (format-reward-reply 0)))
(define-simple-command ai-cookie
(reply (format-reward-reply 10)))))
(defun reward-ai (state action amount)
(setf (state-action-score state action)
(compute-new-score state action amount)))
(define-simple-command test
(network-tree::next-node))
(define-simple-command test-action
(reply (funcall (nth (random 5) *actions*))))
(define-simple-command test-tokenize
(network-tree::next-node))
#+ () (define-simple-command test-tokenize-word
(with-input-from-string (s (remaining-parameters))
(reply (nisp.tokenize::parse-word s))))
(define-simple-command tokenize
(reply "~S" (nisp.tokenize:tokenize-string (remaining-parameters))))
(define-simple-command test-wordinfo
(aif (gethash (remaining-parameters) wiktionary::*dictionary*)
(reply "~A types: ~A"
(wiktionary::word-name it)
(wiktionary::word-pos it))
(reply "I don't know!")))
(define-simple-command word
(network-tree::next-node))
(define-simple-command word-pos
(multiple-value-bind (pos-list found?)
(wiktionary:lookup-pos (remaining-parameters))
(if found?
(reply "~A" pos-list)
(reply "I can't find that word!"))))
| 6,657 | Common Lisp | .lisp | 149 | 36.355705 | 105 | 0.624652 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 85693d2f21b4b362106e58cac058b744bc19284c7a16ee0908705cf7beeb13b9 | 13,177 | [
-1
] |
13,178 | wikihow.lisp | nixeagle_nisp/irc-bot/commands/wikihow.lisp | (defpackage #:wikihow
(:use :cl :drakma :split-sequence :anaphora :alexandria :iterate
:trivial-timers)
(:export #:wikihow-rc-status))
(in-package :wikihow)
(defparameter +wikihow-rc-status-uri+
"http://~A.wikihow.com/Special:RCBuddy?justcount=1")
(defun get-cxml-element-contents (source element)
(klacks:find-element source element)
(if (eql :characters (klacks:peek-next source))
(with-output-to-string (*standard-output*)
(iter
(princ (klacks:current-characters source))
(while (eql :characters (klacks:peek-next source)))))
"")
#+ () (lastcar (klacks:serialize-element source (cxml-xmls:make-xmls-builder))))
(defun process-wikihow-status (status-string)
(mapcar (lambda (pair)
(let ((split-pair (split-sequence #\= pair)))
(cons (car split-pair) (ensure-car (cdr split-pair)))))
(subseq (split-sequence #\Newline status-string) 2)))
(defun wikihow-rc-status (&optional (lang "en"))
(process-wikihow-status (http-request (format nil +wikihow-rc-status-uri+ lang))))
(defun page-content (name)
(let ((source (cxml:make-source (http-request (format nil "http://www.wikihow.com/api.php?action=query&prop=revisions&titles=~A&rvprop=content&format=xml"
name)))))
(get-cxml-element-contents source "rev")))
(defun site-single-statistic (domain stat-property)
(let ((source (cxml:make-source (http-request (format nil "http://~A/api.php?action=query&meta=siteinfo&siprop=statistics&format=xml" domain)))))
(klacks:find-element source "statistics")
(klacks:get-attribute source stat-property)))
(defun parse-mediawiki-list (start-char text)
(cl-ppcre:all-matches-as-strings
(format nil "\\~A.+\\\n" start-char)
text))
(iter (for (lang . settings) in (cdr (read-from-string (page-content "wikiHow:Whbot/config"))))
(cl-l10n:with-locale lang
(let ((cl-l10n::*locale* (car cl-l10n::*locale*)))
(collect (iter (for (key translation) in settings)
(setf (cl-l10n:lookup-resource key)
translation))))))
(defvar *rc-quotes* ())
(defparameter +rc-feed-url+ "http://tinyurl.com/2nado7")
(defun format-quote (quote &key count)
(setq quote (cl-ppcre:regex-replace-all "^\\\*\\\s*|\\\n" quote ""))
(setq quote (cl-ppcre:regex-replace-all "<<URL>>" quote +rc-feed-url+))
(cl-ppcre:regex-replace-all "<<COUNT>>" quote (princ-to-string count)))
(defun update-quotes! ()
(length
(setq *rc-quotes*
(wikihow::parse-mediawiki-list "*" (wikihow::page-content "User:Caidoz/whbot")))))
(in-package :nisp.i)
(defun gettext-function (key &rest args)
(cl-l10n:lookup-resource key :arguments args))
(defmacro gettext (key &rest args)
`(gettext-function ,(if (symbolp key)
`',key
key)
,@args))
(defvar *rc-monitor-timer*
(trivial-timers:make-timer 'check-rc-status :name "Wikihow RC monitor"
:thread t))
#+ () (trivial-timers:schedule-timer *rc-monitor-timer* 1
:repeat-interval 60)
(let ((total-checks 7)
(wait-time 5))
(defun check-rc-status ()
(let ((total-unpatrolled (assoc-value (wikihow:wikihow-rc-status) "unpatrolled_fa" :test #'equal)))
(if (zerop (parse-integer total-unpatrolled))
(setq total-checks 0
wait-time 5)
(progn
(incf total-checks)
(when (<= wait-time total-checks)
(setq total-checks 0)
(incf wait-time)
(irc:privmsg *whbot* "#wikihow"
(wikihow::format-quote (random-elt wikihow::*rc-quotes*) :count
total-unpatrolled))))))))
(defmacro define-wikihow-command (name &body body)
`(defmethod handle-command
((tree (eql #-sbcl(network-tree::intern-network-tree-node
,(substitute #\Space #\- (symbol-name name)))
#+sbcl ,(substitute #\Space #\- (symbol-name name))))
(source whbot-bot-connection)
(user abstract-user)
(address abstract-target)
(identity abstract-identity)
(action abstract-action)
(content abstract-text-message-content))
,@body))
(defmacro define-wikihow-es-command (name &body body)
`(defmethod handle-command
((tree (eql #-sbcl(network-tree::intern-network-tree-node
,(substitute #\Space #\- (symbol-name name)))
#+sbcl ,(substitute #\Space #\- (symbol-name name))))
(source whbot-bot-connection)
(user abstract-user)
(address (eql (irc:find-channel *whbot* "#wikihow-es")))
(identity abstract-identity)
(action abstract-action)
(content abstract-text-message-content))
,@body))
#+ ()
(defmethod handle-command :around
(tree
(source whbot-bot-connection)
(user abstract-user)
(address (eql (irc:find-channel *whbot* "#wikihow-es")))
(identity abstract-identity)
(action abstract-action)
(content abstract-text-message-content))
(reply (princ-to-string (remaining-parameters)))
(cl-l10n:with-locale "es"
(call-next-method)) )
(defmethod route-command :around
((source whbot-bot-connection)
(from irc-user)
(content irc-message-content)
(to (eql (irc:find-channel *whbot* "#wikihow-es")))
(sink whbot-bot-connection))
(cl-l10n:with-locale "es"
(call-next-method)))
(define-wikihow-es-command link-nil
(reply (format-link-wikihow (remaining-parameters) "es")))
(define-wikihow-command stats
(network-tree::next-node))
(define-wikihow-command stats-article
(network-tree::next-node))
(define-wikihow-command stats-article-count
(reply (wikihow::site-single-statistic "en.wikihow.com" "articles")))
(define-wikihow-command link-g
(reply (format nil "Google: http://google.com/search?q=~A"
(substitute #\+ #\Space (remaining-parameters)))))
(define-wikihow-command link-forum
(let ((post-id (split-sequence #\| (remaining-parameters))))
(if (every #'string-integer-p post-id)
(reply (gettext wikihow-bot-cmd-forum (car post-id)
(shorturl-is.gd
(format nil "http://www.wikihow.com/forum/viewtopic.php?t=~A"
(if (length= 2 post-id)
(format nil "~A#~A" (car post-id) (second post-id))
(car post-id))))))
(reply (gettext wikihow-bot-cmd-forum-error)))))
(define-wikihow-command help
(reply (gettext wikihow-bot-cmd-help)))
(define-wikihow-command version
(reply (gettext wikihow-bot-cmd-version "0.1")))
(define-wikihow-command age
(reply (gettext wikihow-bot-cmd-age)))
(define-wikihow-command location
(reply (gettext wikihow-bot-cmd-location "#wikihow-bot")))
(define-wikihow-command quote
(network-tree::next-node))
(define-wikihow-command quote-update
(reply (gettext wikihow-bot-fa-rc-quotes (wikihow::update-quotes!))))
(define-wikihow-command quote-test
(reply (wikihow::format-quote (random-elt wikihow::*rc-quotes*) :count 123456789)))
(define-wikihow-command quote-number
(reply (wikihow::format-quote (nth (1- (parse-integer (remaining-parameters))) wikihow::*rc-quotes*)
:count 123456789)))
(defun format-wikihow-rc-stats (status)
(gettext wikihow-bot-cmd-rcstats
(assoc-value status "unpatrolled_total" :test #'equal)
(assoc-value status "unpatrolled_fa" :test #'equal)
(assoc-value status "users_editing" :test #'equal)))
(define-wikihow-command rcstats
(reply (format-wikihow-rc-stats (wikihow:wikihow-rc-status))))
(define-wikihow-es-command rcstats
(reply (format-wikihow-rc-stats (wikihow:wikihow-rc-status "es"))))
(define-wikihow-command gender
(reply (random-elt '("I'm a male" "I'm a female"
"I'm an alien" "I'm an it"
"I'm confused" "I'm Vulcan"
"I'm HAL9000"))))
(define-wikihow-command link-nil
(reply (format-link-wikihow (remaining-parameters))))
(macrolet ((links (&rest langs)
`(progn
,@(mapcar (lambda (lang)
`(define-wikihow-command ,(format-symbol t "link-~A" lang)
(reply (format-link-wikihow (remaining-parameters) ,lang))))
langs))))
(links "af" "sq" "am" "ar" "hy" "az" "eu" "be" "bn" "bh" "bg" "my" "ca" "chr"
"zh" "zh-CN" "zh-TW" "hr" "cs" "da" "dv" "nl" "en" "eo" "et" "tl" "fi"
"fr" "gl" "ka" "de" "el" "gn" "gu" "iw" "hi" "hu" "is" "id" "iu" "it"
"ja" "kn" "kk" "km" "ko" "ku" "ky" "lo" "lv" "lt" "mk" "ms" "ml" "mt"
"mr" "mn" "ne" "no" "or" "ps" "fa" "pl" "pt-PT" "pa" "ro" "ru" "sa" "sr"
"sd" "si" "sk" "sl" "es" "sw" "sv" "tg" "ta" "tl" "te" "th" "bo" "tr"
"uk" "ur" "uz" "ug" "vi"))
(define-wikihow-command emacs)
(define-wikihow-command markov)
| 9,184 | Common Lisp | .lisp | 192 | 39.046875 | 156 | 0.609279 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 168b9fea75865a0523d0ca8a8f69dd78817766dc623f13b90e9bc00657fb0b65 | 13,178 | [
-1
] |
13,179 | links.lisp | nixeagle_nisp/irc-bot/commands/links.lisp | (in-package :nisp.i)
(define-simple-command link
(handler-case (network-tree::next-node)
(error (condition)
(network-tree::next-node
(apply #'format nil "nil ~A:~A"
(multiple-value-list (network-tree::first-command-word (remaining-parameters))))))))
(defmethod handle-command
((tree (eql "link")) (source connection) (user abstract-user)
(address bot-channel) (identity abstract-identity)
(action abstract-action) (content abstract-text-message-content))
(unless #+nisp-vps (or (gethash "whbot-dev" (irc:users address) nil)
(gethash "nisp-devel" (irc:users address) nil)
(gethash "nisp-dev" (irc:users address) nil)
#+nisp-vps
(and (gethash "nisp" (irc:users address) nil)
(string= (irc:nickname source)
"nisp-stable")))
#-nisp-vps nil
(handler-case (nisp.network-tree::next-node)
(error (condition)
(declare (ignore condition))
(nisp.network-tree::next-node
(apply #'format nil "nil ~A:~A"
(multiple-value-list
(nisp.network-tree::first-command-word
(remaining-parameters)))))))))
(defun format-euler-problem-url-text (id)
(let ((url (format nil "http://projecteuler.net/index.php?section=problems&id=~A" id)))
(let ((it (dom:get-elements-by-tag-name (chtml:parse (drakma:http-request url) (rune-dom:make-dom-builder)) "p")))
(format nil "Project Euler problem #~A: ~A <~A>"
id
(dom:data (dom:first-child (aref it (1- (fill-pointer it)))))
(shorturl-is.gd url)))))
(define-simple-command link-euler
(if (string-integer-p (remaining-parameters))
(reply (format-euler-problem-url-text (remaining-parameters)))
(reply "Project Euler profile for ~A: ~A" (remaining-parameters)
(shorturl-is.gd (format nil "http://projecteuler.net/index.php?section=profile&profile=~A" (remaining-parameters))))))
(defun format-link-wikipedia (params)
(format nil "Wikipedia article ~A: ~A" params
(format nil "http://en.wikipedia.org/wiki/~A"
(substitute #\_ #\Space params))))
(define-simple-command link-wikipedia
(reply (format-link-wikipedia (remaining-parameters))))
(define-simple-command link-wiki
(reply (format-link-wikipedia (remaining-parameters))))
(define-simple-command link-nil
(reply (format-link-wikipedia (remaining-parameters))))
(iter (for x in-vector (dom:get-elements-by-tag-name
(chtml:parse (drakma:http-request "http://www.itl.nist.gov/div897/sqg/dads/ui.html")
(rune-dom:make-dom-builder)) "a"))
(when (search "HTML/" (dom:get-attribute x "href") :end2 5)
(when (dom:text-node-p (dom:first-child x))
(setf (gethash (dom:data (dom:first-child x)) *nist-compsci-dictionary*)
(concatenate 'string "http://www.itl.nist.gov/div897/sqg/dads/"
(dom:get-attribute x "href"))))))
(define-simple-command link-nist
(reply (gethash (remaining-parameters) *nist-compsci-dictionary*
(format nil "Requested page ~A does not exist in my index."
(remaining-parameters)))))
(define-simple-command link-cpan
(reply "CPAN: http://search.cpan.org/search?mode=all&query=~A" (remaining-parameters)))
(define-simple-command link-emacs
(reply "Emacwiki: ~A"
(shorturl-is.gd (format nil "http://www.google.com/cse?cx=004774160799092323420%3A6-ff2s0o6yi&q=~A&sa=Search" (substitute #\+ #\Space (remaining-parameters))))))
(define-simple-command link-wk
(reply "wiktionary: http://en.wiktionary.org/wiki/~A" (remaining-parameters)))
(defun format-link-wikihow (params &optional lang)
(let ((article (substitute #\- #\Space params)))
(format nil "wikiHow page ~A: ~A"
(substitute #\Space #\- article)
(if lang
(format nil "http://~A.wikihow.com/~A"
lang article)
(format nil "http://wikihow.com/~A"
article)))))
(define-simple-command link-wikihow
(reply (format-link-wikihow (remaining-parameters))))
(define-simple-command link-google
(reply "Google: http://google.com/search?q=~A"
(substitute #\+ #\Space (remaining-parameters))))
(define-simple-command link-debpackage
(reply "http://packages.debian.org/~A" (remaining-parameters)))
(define-simple-command link-rfc
(if (string-integer-p (remaining-parameters))
(reply "RFC: http://www.ietf.org/rfc/rfc~A" (remaining-parameters))
(reply "RFCs are referred to by number")))
(define-simple-command link-g
(reply (format nil "Google: http://google.com/search?q=~A"
(substitute #\+ #\Space (remaining-parameters)))))
;;; END
| 5,003 | Common Lisp | .lisp | 92 | 44.130435 | 171 | 0.617791 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 98d62841bd8a60f8fc48c809f8e78183197eca08bc3b1362bc10c8656656b174 | 13,179 | [
-1
] |
13,180 | chemical-elements.lisp | nixeagle_nisp/irc-bot/commands/chemical-elements.lisp | (defpackage #:nisp.plugin.chemical-elements
(:use :cl :alexandria :nisp-core))
(in-package :nisp.plugin.chemical-elements)
(defparameter *elements* (alist-hash-table
'(("H" . "Hydrogen")
("He" . "Helium")
("Li" . "Lithium")
("Be" . "Beryllium")
("B" . "Boron")
("C" . "Carbon")
("N" . "Nitrogen")
("O" . "Oxygen")
("F" . "Fluorine")
("Ne" . "Neon")
("Na" . "Sodium")
("Mg" . "Magnesium")
("Al" . "Aluminum")
("Si" . "Silicon")
("P" . "Phosphorus")
("S" . "Sulfur")
("Cl" . "Chlorine")
("Ar" . "Argon")
("K" . "Potassium")
("Ca" . "Calcium")
("Sc" . "Scandium")
("Ti" . "Titanium")
("V" . "Vanadium")
("Cr" . "Chromium")
("Mn" . "Manganese")
("Fe" . "Iron")
("Co" . "Cobalt")
("Ni" . "Nickel")
("Cu" . "Copper")
("Zn" . "Zinc")
("Ga" . "Gallium")
("Ge" . "Germanium")
("As" . "Arsenic")
("Se" . "Selenium")
("Br" . "Bromine")
("Kr" . "Krypton")
("Rb" . "Rubidium")
("Sr" . "Strontium")
("Y" . "Yttrium")
("Zr" . "Zirconium")
("Nb" . "Niobium")
("Mo" . "Molybdenum")
("Tc" . "Technetium")
("Ru" . "Ruthenium")
("Rh" . "Rhodium")
("Pd" . "Palladium")
("Ag" . "Silver")
("Cd" . "Cadmium")
("In" . "Indium")
("Sn" . "Tin")
("Sb" . "Antimony")
("Te" . "Tellurium")
("I" . "Iodine")
("Xe" . "Xenon")
("Cs" . "Cesium")
("Ba" . "Barium")
("La" . "Lanthanum")
("Ce" . "Cerium")
("Pr" . "Praseodymium")
("Nd" . "Neodymium")
("Pm" . "Promethium")
("Sm" . "Samarium")
("Eu" . "Europium")
("Gd" . "Gadolinium")
("Tb" . "Terbium")
("Dy" . "Dysprosium")
("Ho" . "Holmium")
("Er" . "Erbium")
("Tm" . "Thulium")
("Yb" . "Ytterbium")
("Lu" . "Lutetium")
("Hf" . "Hafnium")
("Ta" . "Tantalum")
("W" . "Wolfram")
("Re" . "Rhenium")
("Os" . "Osmium")
("Ir" . "Iridium")
("Pt" . "Platinum")
("Au" . "Gold")
("Hg" . "Mercury")
("Tl" . "Thallium")
("Pb" . "Lead")
("Bi" . "Bismuth")
("Po" . "Polonium")
("At" . "Astatine")
("Rn" . "Radon")
("Fr" . "Francium")
("Ra" . "Radium")
("Ac" . "Actinium")
("Th" . "Thorium")
("Pa" . "Protactinium")
("U" . "Uranium")
("Np" . "Neptunium")
("Pu" . "Plutonium")
("Am" . "Americium")
("Cm" . "Curium")
("Bk" . "Berkelium")
("Cf" . "Californium")
("Es" . "Einsteinium")
("Fm" . "Fermium")
("Md" . "Mendelevium")
("No" . "Nobelium")
("Lr" . "Lawrencium")
("Rf" . "Rutherfordium")
("Db" . "Dubnium")
("Sg" . "Seaborgium")
("Bh" . "Bohrium")
("Hs" . "Hassium")
("Mt" . "Meitnerium")
("Ds" . "Darmstadtium")
("Rg" . "Roentgenium")
("Cn" . "Copernicium")
("Uut" . "Ununtrium")
("Uuq" . "Ununquadium")
("Uup" . "Ununpentium")
("Uuh" . "Ununhexium")
("Uus" . "Ununseptium")
("Uuo" . "Ununoctium")
("Hydrogen" . "H")
("Helium" . "He")
("Lithium" . "Li")
("Beryllium" . "Be")
("Boron" . "B")
("Carbon" . "C")
("Nitrogen" . "N")
("Oxygen" . "O")
("Fluorine" . "F")
("Neon" . "Ne")
("Sodium" . "Na")
("Magnesium" . "Mg")
("Aluminum" . "Al")
("Silicon" . "Si")
("Phosphorus" . "P")
("Sulfur" . "S")
("Chlorine" . "Cl")
("Argon" . "Ar")
("Potassium" . "K")
("Calcium" . "Ca")
("Scandium" . "Sc")
("Titanium" . "Ti")
("Vanadium" . "V")
("Chromium" . "Cr")
("Manganese" . "Mn")
("Iron" . "Fe")
("Cobalt" . "Co")
("Nickel" . "Ni")
("Copper" . "Cu")
("Zinc" . "Zn")
("Gallium" . "Ga")
("Germanium" . "Ge")
("Arsenic" . "As")
("Selenium" . "Se")
("Bromine" . "Br")
("Krypton" . "Kr")
("Rubidium" . "Rb")
("Strontium" . "Sr")
("Yttrium" . "Y")
("Zirconium" . "Zr")
("Niobium" . "Nb")
("Molybdenum" . "Mo")
("Technetium" . "Tc")
("Ruthenium" . "Ru")
("Rhodium" . "Rh")
("Palladium" . "Pd")
("Silver" . "Ag")
("Cadmium" . "Cd")
("Indium" . "In")
("Tin" . "Sn")
("Antimony" . "Sb")
("Tellurium" . "Te")
("Iodine" . "I")
("Xenon" . "Xe")
("Cesium" . "Cs")
("Barium" . "Ba")
("Lanthanum" . "La")
("Cerium" . "Ce")
("Praseodymium" . "Pr")
("Neodymium" . "Nd")
("Promethium" . "Pm")
("Samarium" . "Sm")
("Europium" . "Eu")
("Gadolinium" . "Gd")
("Terbium" . "Tb")
("Dysprosium" . "Dy")
("Holmium" . "Ho")
("Erbium" . "Er")
("Thulium" . "Tm")
("Ytterbium" . "Yb")
("Lutetium" . "Lu")
("Hafnium" . "Hf")
("Tantalum" . "Ta")
("Wolfram" . "W")
("Rhenium" . "Re")
("Osmium" . "Os")
("Iridium" . "Ir")
("Platinum" . "Pt")
("Gold" . "Au")
("Mercury" . "Hg")
("Thallium" . "Tl")
("Lead" . "Pb")
("Bismuth" . "Bi")
("Polonium" . "Po")
("Astatine" . "At")
("Radon" . "Rn")
("Francium" . "Fr")
("Radium" . "Ra")
("Actinium" . "Ac")
("Thorium" . "Th")
("Protactinium" . "Pa")
("Uranium" . "U")
("Neptunium" . "Np")
("Plutonium" . "Pu")
("Americium" . "Am")
("Curium" . "Cm")
("Berkelium" . "Bk")
("Californium" . "Cf")
("Einsteinium" . "Es")
("Fermium" . "Fm")
("Mendelevium" . "Md")
("Nobelium" . "No")
("Lawrencium" . "Lr")
("Rutherfordium" . "Rf")
("Dubnium" . "Db")
("Seaborgium" . "Sg")
("Bohrium" . "Bh")
("Hassium" . "Hs")
("Meitnerium" . "Mt")
("Darmstadtium" . "Ds")
("Roentgenium" . "Rg")
("Copernicium" . "Cn")
("Ununtrium" . "Uut")
("Ununquadium" . "Uuq")
("Ununpentium" . "Uup")
("Ununhexium" . "Uuh")
("Ununseptium" . "Uus")
("Ununoctium" . "Uuo"))
:test #'equalp))
(defcommand element ()
(reply (gethash (network-tree::remaining-parameters) *elements*)))
| 10,161 | Common Lisp | .lisp | 243 | 19.345679 | 68 | 0.253454 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | dd283b5aa5209093436f0e20034adc220c27b33ce4a2a00b42421ef260358d82 | 13,180 | [
-1
] |
13,181 | system-keyword.lisp | nixeagle_nisp/global/system-keyword.lisp | (in-package :%global)
(defparameter +systems+
'(("lappy" . :nisp-devel)
("box" . :nisp-vps))
"Alist of common systems that nixeagle runs nisp on. These are lookups
to get to a standardized keyword in some cases where these are
required.")
(pushnew (cdr (assoc (machine-instance) +systems+ :test #'string=))
*features*)
(defun system-keyword ()
"Return a keyword depending on where we are running. If the system is
unknown, we return nil."
(cdr (assoc (machine-instance) +systems+ :test #'string=))) | 526 | Common Lisp | .lisp | 13 | 37.384615 | 72 | 0.704501 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | e376c99ffb40761afa112cbc67aaf96c605513397c41e7e239839430b3c69ddb | 13,181 | [
-1
] |
13,182 | alerts.lisp | nixeagle_nisp/3rd-party/alerts.lisp | ;;; Wed Mar 20 17:24:00 1991 by Mark Kantrowitz <[email protected]>
;;; alerts.lisp
;;; ****************************************************************
;;; Alerts: A Convenient Debugging Status Indicator ****************
;;; ****************************************************************
;;;
;;; Written by Kenneth J Meltsner <[email protected]>
;;;
;;; From http://www-cgi.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/ext/alerts/alerts.cl
;;;
;;; Copying/distribution/modification are all allowed by original author.
;;; See: http://www-cgi.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/ext/alerts/0.html
;;;
;;; Modifications made to make this compile on sbcl by James S.
;;; Copyright (C) 2010, released under the same terms as original author.
(in-package :cl-user)
(defpackage #:alerts
(:use :common-lisp)
(:export :set-alert-level :set-alert-stream :alert :query-user))
(in-package :alerts)
;;; ********************************
;;; Alert Functions ****************
;;; ********************************
;;; Alert functions
(defvar *alert-level* 0
"If alert-level is nil, then expressions within an alert are not defined or
invoked. Use (set-alert-level nil) before functions are loaded or defined
to do this. If it is done afterwards, they will not be invoked, but
their code will still exist.")
(defun set-alert-level (&optional (x 0))
(when (numberp x) (setq *alert-level* x)))
(defvar *alert-stream* *standard-output*
"*standard-output* is redirected to *alert-stream* for all alert output.
If nil, output is sent to *standard-output*.")
(defun set-alert-stream (&optional x)
(cond ((output-stream-p x) (setq *alert-stream* x))
((null x) (setq *alert-stream* *error-output*))))
(defmacro alert (level &rest ops)
"Alert user macro -- (alert level (operation1) (operation2)...)
When *alert-level* is less than or equal to level, perform the specified
operations. If LEVEL is t, always perform them (equivalent to progn) and
ignore the alert-level setting.
Typically:
level = 0 interesting comments of no real importance
level = 1 minor status notes
level = 2 major status notes
level = 3 warnings
level = 4 real problems
level = t fatal errors
If the first argument after the level is a string, there is an implicit
format command. (alert 4 \"~%Alert! ~A is bad\" arg) =
(alert 4 (format t \"~%Alert! ~A is bad\" arg))"
(when (stringp (car ops))
(setq ops `((format t ,@ops))))
(when (or (eq level t) (numberp *alert-level*))
`(when ,(if (numberp level)
`(and (numberp *alert-level*)
(>= ,level *alert-level*))
level)
(let ((*standard-output* (or *alert-stream* *standard-output*)))
(fresh-line *standard-output*)
,@ops
(force-output *standard-output*)))))
(defmacro query-user (&rest ops)
"Query user macro -- (query (operation1) (operation2)...)
If the first argument after the level is a string, there is an implicit
format command. (alert 4 \"~%Alert! ~A is bad\" arg) =
(alert 4 (format t \"~%Alert! ~A is bad\" arg))"
(when (stringp (car ops))
(setq ops `((format t ,@ops))))
`(progn ,@ops
(force-output)
(read)))
;;; *EOF*
| 3,343 | Common Lisp | .lisp | 74 | 41.054054 | 102 | 0.616897 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 1b1d5272ac48d97093bcf8de180628aa093cdd0149c64b734db3deed9fa49893 | 13,182 | [
-1
] |
13,183 | save-object.lisp | nixeagle_nisp/3rd-party/save-object.lisp | ;;; -*- Base: 10; Mode: LISP; Package: (DATABASE :USE LISP); Syntax: Common-Lisp -*-
;;; SAVE-OBJECT, Version 10.2 Effective Date: June 2001 Copyright (C)
;;; Kerry V. Koitzsch, 1992,1993,1994,1995. [email protected] New work and
;;; beautification by Kevin Thompson, NASA Ames Research Center.
;;; [email protected] Additional fixes, and porting to
;;; modern CMUCL and SBCL by kr (Markus Krummenacker [email protected])
;;; More fixes by Nixeagle (C) 2010. Fixes released under same license
;;; as original source.
;;; the version info is stored in db:*save-object-system-date*
;;; (load "/lisp/kb/save-object/save-object-10.2.lisp")
;;; (compile-file "/lisp/kb/save-object/save-object")
#|
The views, opinions, and/or findings contained in this document are those
of the author, and should not be construed as an official position, policy,
or decision of any company or other individual, unless designated by other
documentation.
Permission is granted to any individual or institution to use, copy,
modify and distribute this document, provided the copyright and permission
notice is maintained, intact, in all copies and supporting documentation.
The author makes no representations about the suitability of the software
described herein for any purpose. It is provided "as is" without express
or implied warranty.
Suggestions, bugs, criticism and questions to [email protected].
Description of SAVE OBJECT:
----------- -- ---- -------
SAVE-OBJECT is a recursive function which writes an ASCII representation
of a LISP object to a designated file.
kr010622: in other words, it serializes arbitrary LISP data
structures, very similar to what the "pickle" operation does in the
scripting language python.
NOTE: SAVE-OBJECT doesnt need a special LOAD function!
You can load files created by SAVE-OBJECT with the
standard LOAD function
To save:
(SAVE-OBJECT (list 10 20 30) "myfile.lisp") ,
To restore the data in the saved list:
(LOAD "myfile.lisp")
Where the newly restored data ends up:
db:*db-input* == (LIST 10 20 30)
Objects which may be saved include:
--- symbols, keywords, characters, strings, and pathnames.
--- numbers, including integer, rational, complex, and floating point.
--- vectors and multi-dimensional arrays.
--- objects produced by DEFSTRUCT.
--- CLOS (PCL) instances, and CLOS(PCL) classes.
--- hash tables.
--- compiled functions, represented as (FUNCTION <function name>),
internally.
--- generic functions, method objects, and class objects.
--- conses and lists.
--- circular conses and lists (new)
--- user defined methods may be defined for arbitrary objects, such
as images.
--- readtables (a kludge for now)
--- CLIM objects (saved as ordinary CLOS instances)
Calling sequence for INSTANCE-DUMP-FORM:
------- -------- --- ------------------
class-slots ==> all-slotnames ==> all-slots-and-values ==>
map-instance ==> get-slot-values ==> get-ordered-slot-values ==>
instance-dump-form.
========================= D I R E C T I O N S ============================
(1) Redefine the IN-PACKAGEs below to suit: they should USE CLOS or PCL,
though.
In version 5a, the attribute line should be correct to 'just load' the
file, even if the package database does not exist.
Or, try this:
(make-package 'DATABASE :nicknames '(db) :use '(common-lisp))
(in-package 'database)
(shadowing-import '(setf documentation) 'database)
(use-package 'clos)
If at any point an error occurs about conflicting symbols, select the
proceed option which prefers the symbols in the common lisp package.
(2) After defining an appropriate package, load the file,
save-object.lisp, or its compiled version.
(3) Enter package DATABASE with (in-package 'DATABASE) or
(in-package "database"). You are now ready to save objects!
(4) To save an object to a file, invoke the SAVE-OBJECT function:
(in-package 'database) or (in-package "database") if in 8.1.1.
(save-object (list 20 30 19.6) "my-simple-filename.lisp")
to reload the saved-object file:
(load "my-simple-filename.lisp")
The result of the load is stored in the global variable *db-input*,
in the DATABASE package.
(in-package 'db)
*db-input* ====> (20 30 19.6)
(5) To save MULTIPLE OBJECTS to a file, use the macro WITH-SAVED-
OBJECTS:
(with-saved-objects (x "my-multiple-save-file.lisp")
(make-whiz) ;; a defstruct
(make-instance 'my-class) ;; a clos/pcl instance...
PI ;; whatever you want....
#c(0 1)
)
To re-load a multiple-object data-file, simply use LOAD:
(load "my-multiple-save-file.lisp")
Results end up in the global variable *storage-vector*:
(aref *storage-vector* 0) ====> a whiz instance
1 ====> clos pcl instance
2 ====> pi
3 ====> a complex number...
Since save-object uses vector-push-extend on *storage-vector*,
no allocation or manipulation of *storage-vector* is necessary.
To forget and reset *storage-vector*, simply do
(defvar *storage-vector*) or (mkunbound '*storage-vector*).
=========
PLATFORMS this was tested on:
========= ------ --
Machines: Sun-4,
Symbolics 3670,
Mac IIfx and Mac Quadra, Mac Classic II with MCL 2.0.1.
Allegro\PC Version 1.0 on an IBM-PC with 16 meg, Windows 3.1,
MSDOS 5.0.
Versions of Symbolics Common Lisp: Genera 8.1, Genera 7.2 w/rev 4b PCL.
Versions of PCL/CLOS: AAAI PCL, Victoria Day PCL, REV 4b PCL, Lucid 4.0
CLOS, Lucid 4.1 CLOS.
Versions of CMU Common Lisp: 16c, SunOS 4.1, Sun 4, and:
17b, SunOS 4.1, Sun 4 with PCL Sept. 1992 (f).
18c, RedHat Linux-6.2 on Intel, kr010612
(probably won't run on the really old pre-18 versions anymore)
Versions of SBCL Common Lisp: 0.6.6, RedHat Linux-6.2 on Intel, kr010612
Versions of MCL: 2.0b3, Version 2.0.1.
Versions of Allegro Common Lisp: 4.0, 4.1, 4.2b.
Note: ALLEGRO 4.0 users (SUNS): the patch which fixes the defstruct slot-
value problem must be installed in your 4.0 image for this code to
work properly! Franz internal problem number: spr4914, patch25.fasl.
See your Franz dealer to get a copy.
Versions of Lucid (Sun) Common Lisp: 4.0, LCL 4.1.
=======================================================================
Changes in Version 10:
=======================================================================
;;;kr010608: declared new version-10.2
;;; - applied patch that contains the diff of v.9X.2 versus v.10A
;;; found v.10A at: ftp://ftp.digitool.com/pub/mcl/contrib/save-object.lisp
;;; first had to convert Macintosh-CR to Unix-LF of that file
;;; - kr010611: in a few places, used (delete ) instead of (remove ) to reduce cons'ing
;;; - kr010619: had to fight it out quite bit with the dotted lists, to get
;;; (TEST-CONS-SAVE) to not bomb out right away, and subsequently with
;;; circular lists, because of a code circularity that entered an infinite loop.
;;; to me, this seemd like quite mess, and i tried to clean it up and stream-line
;;; a bit. (dotted-list-p ) now does not check for circularity, which needs to be
;;; done beforehand. reworked (%list-length ) , which now works correctly and
;;; probably a lot more efficiently too.
;;; - kr010620: no doubt a ton of additional clean-up work is really needed. a lot of
;;; the code looks messy and duplicative, but given that i do not feel responsible for it,
;;; i won't find time to clean it up right now.
=======================================================================
Changes in Version 9X:
=======================================================================
;;;kr0103??: made a version-9x.3 to contain a bunch of changes,
;;; such as trying to get it to run on SBCL and CMUCL-18c.
;;;kr010601: in the pcl-related versions of (%ALLOCATE-INSTANCE ) , i had to make sure that
;;; (sb-pcl::find-class ) was used instead of just (find-class ) !!!! this got dumping
;;; of clos objects to work (at least for the instances).
- Fixed definition of CIRCULAR-LIST-P for MCL.
Notes on version 9
===== == ======= =
In MCL 2.0.1, the slot-definition-... access functions remain undefined.
This means some components of the generated DEFCLASS DUMP FORM may be
unpredictable; this will be fixed when MCL has all the appropriate access
functions available.kvk
Changes in Version 9
(Changes by KOT == Kevin Thompson, [email protected])
Tried to make indentation relatively uniform (only top-level forms in
col 1, and only use 3 ;;;'s if in column 1). This makes most GNU Emacs
Lisp modes work better (since begin-of-defun looks for lparen in col 1),
but makes etags fail ...
Tried to make it all fit in 80 columns, since 90% of it did already.
Various fixes for Allegro 4.2 (mostly just change #+)
Wrapped several top-level (def***) and (setf) forms in eval-when.
My understanding of CL fails here; but one way or another previously one
had to load this first to get it to compile in Allegro, and now that's
unnecessary.
Many declare's etc, in an anal attempt to remove most compiler warnings.
Fixed get-defstruct-constructor when defstruct has a :constructor option.
Other misc bug fixes -- search for 'KOT' below.
=======================================================================
Changes in Version 7:
=======================================================================
1. Support for the newer PCL versions: March, June and August PCLs.
2. Support for CMU Common Lisp.
3. Support for Austin Kyoto Common Lisp.
4. Support for the saving of multiple objects to one file with the
macro WITH-SAVED-OBJECTS.
5. The ability to save defstruct 'classes' to file, as well as
defstruct instances.
6. A complete re-write of defstruct accessors: most of these functions
are generated automatically by the function CREATE-DEFSTRUCT-ACCESS-
FUNCTIONS.
7. Support for Symbolics Genera 8.1.1.
8. Improved array and vector functions: added MAP-INTO if needed.
9. The ability to save GENSYMed symbols, circular CONSes, and
symbol property lists (if the global variable flag is set).
10. Numerous bug fixes and documentation changes.
11. Added DOTTED-LIST-P, DOTTED-LIST-DUMP-FORM, modified
GET-DUMP-FORM, added %EVERY, %SOME:
changed all occurences of EVERY and SOME to
%EVERY and %SOME (predicates which dont barf on dotted lists)
This means (SAVE-OBJECT (LIST* 1 2 3 4 5) "my-dotted-list.lisp")
should work.
=======================================================================
Changes from Version 4A;
------------------------
--- Attribute line is fixed for Symbolics users.
--- the ability to save CLOS instances with unbound slots: fixed the
bug where nil was installed as the slot value. (see TEST-UNBOUND-
SLOT-SAVE function)
--- the ability to save out CONSes (vs LISTS) in the appropriate
format: required modification to predicate CONS-P and %TYPE-OF.
(see TEST-CONS-SAVE function)
--- predicate %CONS-P is the internal cons predicate: EXCL uses an
internal function: the non-EXCL version uses a Common Lisp
version. Ideally one would use (LAST X 0) as in CLtl2 pg. 416,
but here i use (CDR (LAST X)).
--- Unsaveable slot bug, which screwed up slots and values returned,
is now fixed in the new mechanism using INSTANCE-SLOTNAMES.
=======================================================================
Changes to newest version:
*save-symbol-plist* ==> *save-symbol-plists* global variable.
=======================================================================
Defstruct functions used by SAVE-OBJECT:
--------- --------- ---- -- -----------
STRUCTURE-P (x) [Function] :
Predicate, returns T if X is a structure instance.
GET-DEFSTRUCT-LENGTH (s) [Function] :
Returns the number of slots in a structure instance S.
GET-DEFSTRUCT-DESCRIPTOR (symbol) [Function] :
Given a symbol, returns a standard defstruct spec if
SYMBOL is the name of a defined defstruct class:
NIL otherwise.
ALLOCATE-STRUCT (type) [Function] :
Given a symbol TYPE which is the name of a defined defstruct
class, make a default instance of that class.
FILL-STRUCT (struct vals) [Function] :
Fills the structure instance struct with the values vals.
GET-DEFSTRUCT-CONSTRUCTOR (s) [Function] :
Given a symbol or structure instance, return the
name of the function that can construct an instance
of the same type as S.
GET-DEFSTRUCT-NAME (s) [Function] :
Given a structure instance S, return the name of
that instances class.
GET-DEFSTRUCT-TYPE (s) [Function] :
Given a symbol or structure instance <s>, return the
type of that structure class.
SET-DEFSTRUCT-SLOT-VALUE (s slotname new-value) [Function] :
Sets the defstruct instance <s> slot named <slotname>
with the new value <newval>.
GET-DEFSTRUCT-SLOT-VALUE (s slotname) [Function]:
Given the defstruct instance <s> and the slot name <slotname>,
return the value of <slotname> in <s>.
GET-DEFSTRUCT-SLOT-NAMES (s) [Function] :
Given a structure instance S, return a list of the
names of that instances slots, in no particular order.
COPY-STRUCTURE (s &key (mode :shallow)) [Function] :
Analogous to the COPY-INSTANCE method. Mode may be :SHALLOW or
:DEEP : make a copy of the structure instance S.
GET-DEFSTRUCT-SLOTS-AND-VALS (s) [Function] :
MAKE-STRUCTURE (struct-type &rest kwd-val-pairs) [Macro] :
Analogous to MAKE-INSTANCE.
GET-DEFSTRUCT-VALUES (s) [Function] :
Return the values of all the slots in structure instance S,
in the same order that the slot names are returned from
GET-DEFSTRUCT-SLOT-NAMES.
GET-DEFSTRUCT-DOCUMENTATION:
GET-DEFSTRUCT-PREDICATE:
GET-DEFSTRUCT-PRINT-FUNCTION:
GET-DEFSTRUCT-INCLUDE:
GET-DEFSTRUCT-CONC-NAME:
Slot operations:
==== ===========
GET-DEFSTRUCT-SLOT-READ-STATUS (sd) [Function]:
GET-DEFSTRUCT-SLOT-ACCESSOR (sd): [Function]:
GET-DEFSTRUCT-SLOT-NAME (sd) [Function]:
GET-DEFSTRUCT-SLOT-TYPE (sd) [Function]:
GET-DEFSTRUCT-SLOT-READER (sd) [Function]:
GET-DEFSTRUCT-SLOT-WRITER (sd) [Function]:
GET-DEFSTRUCT-SLOT-DESCRIPTOR (sd) [Function]:
NEW MACINTOSH CHANGES:
=== ========= =======
#+:mcl changed to #+mcl. (12-19-93)
|#
;;; Package engineering....
#+akcl
(eval-when (load eval compile)
(in-package 'DATABASE :nicknames '(DB) :use '(LISP))
)
#+lucid
(in-package 'DATABASE :nicknames '(DB) :use '(CLOS LISP))
#+mcl
(eval-when (load eval compile)
(ccl::old-in-package :COMMON-LISP :nicknames '(LISP))
(ccl::old-in-package :COMMON-LISP-USER :nicknames '(USER)) ;;; added this for version X.
(unless (find-package 'database)
(make-package 'database :nicknames '(db) :use '(common-lisp)))
(in-package DATABASE) ;; ANSI definition of IN-PACKAGE
;; Uncomment the following line if using mcl....
;;(PUSHNEW :mcl *features*)
(pushnew :clos *features*) ;; MCL has clos, but it isnt in the features list.
(unless (find-package 'clos)
(make-package 'clos :use '(ccl common-lisp))) ;;hence no cl package, either
(when (equal (machine-instance) "Quadra")
(pushnew :quadra *features*) ;; note that its a 68040 on features....
)
(when (equal (machine-type) "Macintosh IIfx")
(pushnew :fx *features*) ;; note that its an fx on features....
)
) ;; end of MCL eval-when...
#+lispm
(eval-when (load eval compile)
;; NEW: added 1.1 to the minor release list below....
(multiple-value-bind (major minor status)
(sct:get-release-version)
(cond ((and (equal major 7)(equal minor "2"))(pushnew :rel-7-2 *features*))
((and (equal major 8)(member minor '("0" "1" "1.1") :test #'equal))
(pushnew :rel8 *features*)
(if (equal minor "0")(pushnew :rel-8-0 *features*)
(pushnew :rel-8-1 *features*)))
(T (error "Can't deal with major release ~a, minor release ~a!"
major minor))))
(when (find-package 'clos)
(pushnew :clos *features*))
(unless (find-package 'database)
(make-package 'database :nicknames '(db) :use '(clos)))
(shadowing-import '(setf documentation) 'database)
(unless (find-package 'clos)
(format t "Couldnt find the CLOS package, trying to continue.~%"))
#-rel-8-1(in-package 'database :use '(LISP))
#+rel-8-1(in-package "database" :use '(LISP))
(defun UNLOCK-PKG (packagename)
"Changes read-only package status to read+write, if package exists."
(when (find-package packagename)
(setf (si:pkg-locked (find-package packagename)) NIL)))
) ;; end of Symbolics eval-when. Worry about TI much later.
;;; Initial package-building eval-when for allegro on suns.
#+excl
(eval-when (load eval compile)
(setf excl:*cltl1-in-package-compatibility-p* T)
(in-package :Common-lisp-user)
(defpackage "database" (:nicknames "dbs")
(:use :clos :excl :common-lisp-user))
(in-package DATABASE)
(in-package 'DATABASE)
#+(or allegro-v4.1 allegro-v4.2)
(defun UNLOCK-pKG (packagename)
(setf (excl:package-definition-lock (find-package packagename)) nil))
#+(or allegro-v4.1 allegro-v4.2)
(unlock-pkg 'common-lisp)
#|
#+(or allegro-v4.1 allegro-v4.2)
(defun UNLOCK-PKG (packagename)
"Changes read-only package status to read+write, if package exists."
(when (find-package packagename)
(setf (excl::package-lock-fdefinitions
(find-package packagename)) NIL)))
#+(or allegro-v4.1 allegro-v4.2)
(unlock-pkg 'common-lisp)
|#
) ;; end of excl eval-when...
;;; Set up correct Lucid hash-table accessors....
#+lucid
(shadowing-import '(lcl::hash-table-rehash-size
lcl::hash-table-size
lcl::hash-table-test
lcl::hash-table-rehash-threshold
lcl::ignore-errors
) 'database)
;;; Set up correct ACL\PC hash-table accessors....
#+aclpc
(eval-when (:compile-toplevel :load-toplevel :execute)
(in-package 'DATABASE :nicknames '(DB) :use '(LISP))
(shadowing-import '(acl::hash-table-rehash-size
acl::hash-table-size
acl::hash-table-test
acl::hash-table-rehash-threshold
) 'database)
) ;; end aclpc eval-when...
#+cmu
(eval-when (:compile-toplevel :load-toplevel :execute)
;;kr010205: replaced the following (in-package ) with a (defpackage ) :
;;(in-package 'database :nicknames '(db) :use '(PCL LISP))
(defpackage "DATABASE"
(:nicknames "DB")
(:use "COMMON-LISP")
)
(in-package "DATABASE")
(shadowing-import '(;;common-lisp::hash-table-rehash-size
;;common-lisp::hash-table-rehash-threshold
;;kr010210:
PCL:METHOD-SPECIALIZERS
PCL:METHOD-GENERIC-FUNCTION
PCL:GENERIC-FUNCTION-NAME
PCL:GENERIC-FUNCTION-LAMBDA-LIST
;;PCL::FIND-CLASS
) 'database)
#|;;kr010602: what weird old stuff is this ??? : commented out !
(setf (symbol-function 'hash-table-rehash-size)
#'common-lisp::hash-table-rehash-size)
(setf (symbol-function 'hash-table-rehash-threshold)
#'common-lisp::hash-table-rehash-threshold)
|#
) ;; end of cmu evalwhen....
;;;kr010120: added SBCL support
#+:sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(defpackage "DATABASE"
(:nicknames "DB")
(:use "COMMON-LISP")
)
(in-package "DATABASE")
(shadowing-import '(;;common-lisp::hash-table-rehash-size
;;common-lisp::hash-table-rehash-threshold
;;kr010210:
SB-PCL:METHOD-SPECIALIZERS
SB-PCL:METHOD-GENERIC-FUNCTION
SB-PCL:GENERIC-FUNCTION-NAME
SB-PCL:GENERIC-FUNCTION-LAMBDA-LIST
#|;;kr010313: needed to comment out, after having added the SBCL PCL stuff further below.
;; otherwise, bad hang when file load...
SB-PCL::CLASS-NAME
SB-PCL::CLASS-SLOTS
SB-PCL::CLASS-OF
SB-PCL::CLASSP
SB-PCL::FIND-CLASS
|#
) :database)
#|;;kr010605: what weird old stuff is this ??? : commented out !
(setf (symbol-function 'hash-table-rehash-size)
#'common-lisp::hash-table-rehash-size)
(setf (symbol-function 'hash-table-rehash-threshold)
#'common-lisp::hash-table-rehash-threshold)
|#
) ;; end of sbcl evalwhen....
#+lucid
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'hash-table-rehash-size)
#'lcl::hash-table-rehash-size)
(setf (symbol-function 'hash-table-size) #'lcl::hash-table-size)
(setf (symbol-function 'hash-table-test) #'lcl::hash-table-test)
(setf (symbol-function 'hash-table-rehash-threshold)
#'lcl::hash-table-rehash-threshold)
) ;; end lucid eval-when
;;; NOTE: Change the package def below if it does not suit you:
;;; make sure you USE-PACKAGE your favorite brand of CLOS or PCL, though.
#+lispm
(in-package 'DATABASE :nicknames '(DB) :use '(CLOS LISP))
#+pcl
;;;kr010207: had to introduce the (unless ) clause for :CMU
(unless (find-package "DATABASE")
(in-package "DATABASE" :nicknames '(DB) :use '(PCL LISP)))
#+pcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (equal pcl::*pcl-system-date* "July 92 PCL (beta)")
(pushnew :july-pcl *features*))
(when (equal pcl::*pcl-system-date* "March 92 PCL (3a)")
(pushnew :march-pcl *features*))
(when (equal pcl::*pcl-system-date* "Aug 92 PCL (a)")
(pushnew :aug-pcl *features*))
(when (equal pcl::*pcl-system-date* "September 16 92 PCL (f)")
(pushnew :sept-pcl *features*))
(when (or (member :march-pcl *features*)
(member :july-pcl *features*)
(member :aug-pcl *features*)
(member :sept-pcl *features*))
(pushnew :new-pcl *features*))
)
;;; KOT added this, made some directives simpler below.
#+(or allegro-v4.0 allegro-v4.1 allegro-v4.2)
(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew :allegro-v4 *features*))
;;; KOT first cut, this might not be portable but should work. See if
;;; function-lambda-expression is defined, and if so can use it below.
(eval-when (:compile-toplevel :load-toplevel :execute)
(let ((apropos (apropos-list "FUNCTION-LAMBDA-EXPRESSION"
(find-package :user))))
(when (some #'fboundp apropos)
(pushnew :function-lambda-expression *features*))))
#+lucid
(in-package :DATABASE :nicknames '(DB) :use '(LISP))
;;; ========= end of package engineering .... ===========
;;; Tracing defun eval-when follows....
#+ignore
(eval-when (:compile-toplevel :load-toplevel :execute)
(shadow '(defun))
(in-package :DATABASE :nicknames '(DB) :use '(LISP))
(defmacro DEFUN (name &rest args)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(when (fboundp ',name)
(format t "Warning: ~s was already defined!~%" ',name))
(format t "now compiling: ~a.~%" ',name)
(lisp:defun ,name ,@args)))
#+ignore
(defmacro DEFMETHOD (name &rest args)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(when (fboundp ',name)
(format t "Warning: METHOD ~s was already defined!~%" ',name))
(format t "now compiling method: ~a.~%" ',name)
(pcl::defmethod ,name ,@args)))
) ;; end of tracing defun eval-when.....
;; Exports.
(export '(save-object
with-saved-objects
makesyms
*save-object-system-date*
*db-input*
*storage-vector*
get-slot-values))
;;; Global variables.
(defvar *db-input* nil "where the loaded data file deposits
the saved object on reload.")
(defvar *list-hash-table* nil "Gets initialized by function INIT-LIST-HTAB.")
#-akcl ;;; new, AKCL (PCL defclass) doesnt like this one!
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *print-circle* t)
)
#+lucid
(defvar *lucid-structure-types*
'(package hash-table defstruct system::process
lucid:arrayheader lucid:%pathname
lucid::area lucid::region lucid::stack-group
lucid::defstruct-slot lucid::%fs-slot
lucid::%fsft-pointer lucid::%fsft-structure
lucid::%fsft-field lucid::%fsft-array
lucid::%fsft-primitive lucid::%fsft-set
lucid::%fsft-enumerate lucid::%foreign-type
#+LCL4.l lucid::fsft
))
(defvar *storage-list* nil)
;;; KOT wrapped eval-when around this, in Allegro-V4 allows better compilation
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (compile load eval)
(defvar *storage-hash-table* (make-hash-table)
"Used by with-saved-objects : NEW.")
) ;; end of eval-when
(defvar *use-file-encoded-format* nil "NEW:")
(defvar *use-symbol-long-form* nil
"if t, use a make-symbol form instead of quote+letter.")
(defvar *minimum-storage-vector-length* 5
"default length of *storage-vector*")
(defvar *save-symbol-plists* nil
"Used in long-symbol-dump-form. if t, the symbols property
list is saved with the occurrence of the symbol.")
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
;; KOT -- older version of this had the defvar at top level, and the (if)
;; form in the eval-when. Allegro V4 (at least) bombed on this, saying
;; *allow-defstruct-save* didn't yet exist in this case. This fixes it,
;; though I'm not clear why.
(defvar *allow-defstruct-save* t
"when t, allow the saving of defstruct 'classes', e.g. the thing
defined by DEFSTRUCT.")
(if *allow-defstruct-save* (pushnew :allow-defstruct-save *features*))
)
(defvar *debug-instance-storage* nil
"when this one is T, status messages are printed by the CLOS instance saver
to aid diagnosis of problems.")
(defvar *debug-local-bindings* nil
"set this var to t to see a printout of the constructed lexical bindings as
they are created.")
(defvar *supress-standard-object* T "")
(defvar *save-contents-of-class-allocated-classes* T
"This one, if true, includes the slot contents of slots with :allocation
:class.")
(defvar *make-list-length-threshold* 10
"any list longer than this, which has the same element throughout,
is constructed with MAKE-LIST instead of (list el el el el el el....)."
)
(defvar *load-object-hash-table* (make-hash-table :size 50 :test #'eql)
"A hash table which is filled at load time with objects restored from a
file.")
(defvar *save-object-hash-table* (make-hash-table :size 50 :test #'eql)
"A hash table which is filled at save time by the invokation of the
save object function.")
(defvar *mode-for-set-object-var* nil
"Either :load or :save, depending on the context. Used by SET-OBJECT-VAR.")
(defvar *mode-for-object-var* :save)
(defvar *global-unsaveable-slotnames* nil "")
(defvar *save-object-system-date*
"save-object-10.2 of June 2001")
(defvar *unbound-slot-token* '%%.us.%)
(defvar *debug-htab-load* t)
(defvar *debug-struct-save* nil)
(defvar *classes-seen* nil)
(defvar *class-vars* nil)
(defvar *seen* nil "when using linear search, where the CLOS instances go.")
(defvar *vars* nil)
(defvar *structs-seen* nil)
(defvar *struct-vars* nil)
(defvar *htabs-seen* nil)
(defvar *htab-vars* nil)
(defvar *arrays-seen* nil)
(defvar *array-vars* nil)
(defvar *vectors-seen* nil)
(defvar *vector-vars* nil)
(defvar *current-htab-size* 5000)
(defvar *class-safety-p* T "When t, use safe-class-dump-form, not class-dump-form.")
(defvar *current-htab-rehash-threshold* #-akcl 65
#+akcl 0.6
)
(defvar *current-htab-rehash-size* 39)
(defvar *current-htab-test* #'eql)
(defvar *pco-types* '(structure hash-table array-type-t
class instance circular-list)
"A list of the type names returned by function %type-of, that
are potentially circular objects (PCOs).")
(setf *pco-types* '(structure hash-table array-type-t
class instance circular-list))
#+lucid
(setf lcl::*print-structure* T) ;; "Prints the #S form of a defstruct when t."
(defvar *global-instance-count* 0)
(defvar *global-object-count* 0
"count of varnames made for object hashtable objects, by makevar in
cache-object invokations.")
(defvar *use-default-class-initargs* nil)
(defvar *unsaveable-slot-token* '%.uns.%)
(defvar *unsaveable-slotname-hash-table* (make-hash-table))
;;; Used by WITH-SAVED-OBJECTS to store more than one result...
(defvar *storage-vector*)
(defvar *save-defstruct-includes* nil "")
(defvar *construct-pkg-if-not-found* nil "")
#|
Vendor Dependent Defstruct Internal Structure Access Control Variables:
=======================================================================
Vendor dependent defstruct access info is encoded in the following
global lists:
*vendor-set-slot-function*:
*vendor-defstruct-type-function*:
*vendor-defstruct-name-function*:
*vendor-defstruct-descriptor-function*:
*vendor-defstruct-slot-descriptors-function*:
|#
;;;; Vendor dependent defstruct access data.
(defvar *vendor-set-slot-function*)
(setf *vendor-set-slot-function*
#+symbolics #'(lambda (struct slotname newval)
(setf (slot-value struct slotname) newval))
#+lucid #'(lambda (struct slotname newval)
(eval `(SETF (,(get-defstruct-slot-accessor struct slotname)
,struct)
,newval)))
#+excl #'(lambda (struct slotname newval)
(setf (slot-value struct slotname) newval))
#+akcl #'(lambda (struct slotname newval)
(let ((offset (get-defstruct-slot-offset struct slotname))
(type (get-defstruct-type struct)))
(si:structure-set struct type offset newval)))
#+cmu #'(lambda (struct slotname newval)
(let ((offset (%get-defstruct-slot-offset struct slotname)))
#+(and :cmu (not :cmu18)) (kernel::structure-set struct offset newval)
;;kr010602: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) (kernel::%instance-set struct offset newval)
))
;;kr010120: added SBCL support
#+sbcl #'(lambda (struct slotname newval)
(let ((offset (%get-defstruct-slot-offset struct slotname)))
(sb-kernel::%instance-set struct offset newval)))
#+mcl #'(lambda (struct slotname newval)
(let ((offset (get-defstruct-slot-offset struct slotname)))
(ccl::struct-set struct offset newval))) ;;; corrected this typo
#+xerox #'(lambda (struct slotname newval)
)
#+aclpc #'(lambda (struct slotname newval)
(eval `(SETF (,(get-defstruct-slot-accessor struct slotname)
,struct)
,newval)))
)
;;;kr010602: enabled this also for SBCL
#+(or :cmu :sbcl)
(defun %GET-DEFSTRUCT-SLOT-OFFSET (struct slotname)
(let ((sd (get-sd-named struct slotname)))
(when sd (#+:old-cmu c::dsd-index
;;kr010602: this is now in the kernel package
#+:cmu18 kernel::dsd-index
#+:sbcl sb-kernel::dsd-index
sd))))
(defvar *vendor-defstruct-type-function*)
(defvar *vendor-dependent-special-predicate*)
(defvar *save-symbol-constants-by-name* nil)
(defvar *save-symbol-constants-by-value* T "The default.")
(setf *vendor-dependent-special-predicate*
#+Symbolics 'si:special-variable-p
#+Lucid 'lucid::proclaimed-special-p
#+KCL 'si:specialp
#+excl #'(lambda (symbol)
(get symbol 'excl::.globally-special))
#+:CMU #'(lambda (symbol)
(or (get symbol 'lisp::globally-special)
;;kr010612: commented out the following. the package clc doesn't even exist...
;;(get symbol 'clc::globally-special-in-compiler)
))
;;kr010609: attempt to add the SBCL version too. hope this is right.
#+:SBCL #'sb-walker:variable-globally-special-p
#+MCL #'(lambda (symbol)
(or (ccl::symbol-special-p symbol)
(ccl::constant-symbol-p symbol)))
)
(defun SYMBOL-SPECIAL-P (symbol)
"Predicate, returns T if <symbol> is a symbol, and if it is a constant or declared
special. "
(and (symbolp symbol)
(funcall *vendor-dependent-special-predicate* symbol)))
(setf *vendor-defstruct-type-function*
#+akcl #'(lambda(desc)(si::s-data-type desc))
#+excl #'(lambda(desc)(slot-value desc 'excl::type))
#+lucid #'(lambda(desc)(system::structure-ref desc 1 'lucid::defstruct))
#+lispm #'(lambda(desc)(si:defstruct-description-type desc))
;;#+mcl #'(lambda(desc)(car (ccl::struct-ref desc 0))) ;;kr010608: the path to 10A replaced this. hope this is right.
#+mcl #'(lambda (desc i)(elt desc i)) ;;; This is correct for MCL 2.0.1.
#+(and :cmu (not :cmu18)) #'(lambda(desc)(kernel::structure-ref struct 1)) ;; ???
;;kr010601: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) #'(lambda(desc)(pcl::%instance-ref desc 1))
;;kr010120: added SBCL support
#+sbcl #'(lambda(desc)(sb-kernel::%instance-ref desc 1))
#+xerox #'(lambda(desc))
#+aclpc #'(lambda (desc) (first (aref desc 0)))
)
(defvar *vendor-defstruct-name-function*)
;;; Added for 9X.
#+lucid
(proclaim '(special lucid::*defstructs*))
(setf *vendor-defstruct-name-function*
#+akcl #'(lambda(desc)(si::s-data-name desc))
#+excl #'(lambda(desc)(slot-value desc 'excl::name))
#+lucid #'(lambda(desc)(system::structure-ref desc 0 'lucid::defstruct))
#+lispm #'(lambda(desc)(si:defstruct-description-name desc))
#+mcl #'(lambda(desc)(class-name (class-of desc)))
#+(and :cmu (not :cmu18)) #'(lambda(desc)(kernel::structure-ref struct 0)) ;; ???
;;kr010601: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) #'(lambda(desc)(pcl::%instance-ref desc 0))
;;kr010120: added SBCL support
#+sbcl #'(lambda(desc)(sb-kernel::%instance-ref desc 0))
#+xerox #'(lambda(desc))
#+aclpc #'(lambda (desc) desc)
)
(defvar *vendor-defstruct-descriptor-function* nil
"from symbol name of defstruct get the defstruct descriptor.")
(setf *vendor-defstruct-descriptor-function*
#+symbolics #'(lambda(name)(si:get name 'si:defstruct-description))
#+lucid #'(lambda(name)(gethash name lucid::*defstructs*))
#+excl #'(lambda(name)(get name 'excl::%structure-definition))
#+akcl #'(lambda (name)(get name 'si::s-data))
#+old-cmu #'(lambda (name)(ext:info c::type c::defined-structure-info name))
#+(and :cmu (not :cmu18)) #'(lambda (name)(ext:info c::type c::defined-structure-info name))
;;kr010601: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) #'(lambda (name)(KERNEL:LAYOUT-INFO (ext:info :type :compiler-layout name)))
;;kr010120: added SBCL support. needed some major hunting around.
#+:sbcl #'(lambda (name)(SB-KERNEL:LAYOUT-INFO (sb-int:info :type :compiler-layout name)))
#+mcl #'(lambda (name)(gethash name ccl::%defstructs%))
#+xerox #'(lambda(name))
#+aclpc #'(lambda (name)(acl::structure-name-p name))
)
(defvar *vendor-defstruct-slot-descriptors-function* nil
"from name of defstruct get list of the defstruct slot descriptors.")
;;; KOT wrapped eval-when around -- think it makes later compilation cleaner
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(setf *vendor-defstruct-slot-descriptors-function*
#+symbolics #'(lambda(name)
(let ((desc (get-defstruct-descriptor name)))
(FOURTH DESC)))
#+lucid #'(lambda(name)
(let ((desc (get-defstruct-descriptor name)))
(coerce (system:structure-ref desc 7 'lucid::defstruct)
'list)))
#+excl #'(lambda(name)
(let ((desc (get-defstruct-descriptor name)))
(slot-value desc 'excl::slots)))
#+akcl #'(lambda (name)
(let ((desc (get-defstruct-descriptor name)))
(si::s-data-slot-descriptions desc)))
#+cmu #'(lambda (name)
(let ((desc (get-defstruct-descriptor name)))
;;kr010602: moved from c to kernel package
(kernel::dd-slots desc)))
;;kr010120: added SBCL support
#+sbcl #'(lambda (name)
(let ((desc (get-defstruct-descriptor name)))
(sb-kernel::dd-slots desc)))
#+mcl #'(lambda (name)
(let ((desc (gethash name ccl::%defstructs%)))
(mapcar #'(lambda (cell)(list (first cell)(second cell)))
(REST (elt desc 1)))))
#+xerox #'(lambda (name)
)
#+aclpc #'(lambda (name)
(let ((desc (get-defstruct-descriptor name)))
(when desc (rest (aref desc 1)))))))
(defvar *vendor-defstruct-predicate-function*)
;;; KOT wrapped eval-when around -- think it makes later compilation cleaner
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(setf *vendor-defstruct-predicate-function*
#+aclpc #'(lambda (x)(and (not (hash-table-p x))
(typep x 'structure-object)))
#+symbolics #'cli::structurep
#+lucid #'(lambda (x)
(and (system:structurep x)
(let ((type (system:structure-type x)))
(and (not (lucid::memq type *lucid-structure-types*))
(not #+LCL4.1
(lucid::memq type lucid::*stream-type-names*)
#-LCL4.1
(streamp x))
(not (typep x 'standard-object))))))
#+excl #'excl::structurep
;;; #+akcl #'(lambda (x)(and (system::structurep x)
;;; (not (hash-table-p x))))
#+akcl #'(lambda (x)(and (not (classp x))
(not (hash-table-p x))
(not (instance-p x))
(sys:structurep x)))
#+old-cmu #'(lambda (x)
(and (system::structurep x)
(not (hash-table-p x))
(not (instance-p x))))
#|;;kr010602: let's rather try the thing below.
#+cmu #'(lambda (instance)
(equal (class-name (class-of (find-class (type-of instance))))
'structure-class))
|#
;;kr010614: noticed the bizarre fact that apparently, (pcl::structurep ) will
;; return t on hash-tables too. so we need to filter against them after all.
#+:CMU #'(lambda (instance)
(and (pcl::structurep instance)
;; hash-table exclusion was essential
(not (hash-table-p instance))
) )
;;kr010120: added SBCL support
#|;;kr010212: let's rather try the thing below.
#+sbcl #'(lambda (instance)
(equal (class-name (class-of (find-class (type-of instance))))
'structure-class))
|#
;;kr010614: noticed the bizarre fact that apparently, (sb-pcl::structurep ) will
;; return t on hash-tables too. so we need to filter against them after all.
#+:SBCL #'(lambda (instance)
(and (sb-pcl::structurep instance)
;; hash-table exclusion was essential
(not (hash-table-p instance))
) )
#+mcl
#'(lambda (x) (ccl::structurep x))
;;;; old def: (equal (class-of x) 'structure-class))
#+xerox #'(lambda (x))
))
(defvar *vendor-data-table-access-function* nil
"This function accesses a particular column of the data tables,
dependent upon which vendor it is. ")
(setf *vendor-data-table-access-function*
#+symbolics #'first
#+lucid #'second
#+excl #'third
#+akcl #'fourth
#+cmu #'fifth
#+mcl #'sixth
#+xerox #'seventh
#+aclpc #'eighth
;;kr010120: added SBCL support
#+sbcl #'ninth
)
(defvar *vendor-defstruct-slot-desc-access-function* nil
"given a slot description and an index, return the contents of index.")
(setf *vendor-defstruct-slot-desc-access-function*
#+symbolics #'(lambda (desc i)(elt desc i))
#+lucid #'(lambda(desc i)
(system::structure-ref desc i 'lucid::defstruct-slot))
#+excl #'(lambda(desc i)(excl::structure-ref desc i))
#+akcl #'(lambda (desc i)(elt desc i))
#+(and :cmu (not :cmu18)) #'(lambda(desc i)(kernel::structure-ref desc i))
;;kr010601: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) #'(lambda(desc i)(pcl::%instance-ref desc i))
;;kr010120: added SBCL support
#+sbcl #'(lambda(desc i)(sb-kernel::%instance-ref desc i))
#+mcl #'(lambda(desc i)(ccl::struct-ref desc i))
#+xerox #'(lambda(desc i))
#+aclpc #'(lambda(desc i))
)
(defvar *vendor-defstruct-desc-access-function* nil
"given a description and an index, return the contents of index."
)
(setf *vendor-defstruct-desc-access-function*
#+symbolics #'(lambda(desc i)(nth i desc))
#+lucid #'(lambda(desc i)(system::structure-ref desc i 'lucid::defstruct))
#+excl #'(lambda(desc i)(excl::structure-ref desc i))
#+akcl #'(lambda (desc i)(system::structure-ref desc i))
#+(and :cmu (not :cmu18)) #'(lambda(desc i)(kernel::structure-ref desc i))
;;kr010601: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) #'(lambda(desc i)(pcl::%instance-ref desc i))
;;kr010120: added SBCL support
#+sbcl #'(lambda(desc i)(sb-kernel::%instance-ref desc i))
#+mcl #'(lambda(desc i)(ccl::struct-ref desc i))
#+xerox #'(lambda(desc i))
#+aclpc #'(lambda(desc i))
)
(defvar *vendor-defstruct-slot-desc-index-table* nil
"values in this table are either nil, a number, or a symbol.
if nil, funcall desc index function on slot desc only.
if a number, funcall desc index function on slot desc, index.
if a symbol, the symbol represents a slot name. call slot-value
on desc (which is presumed to be a CLOS instance) and the slot name.
If t, we dont know what it is: return the result of a default function."
)
(setf *vendor-defstruct-slot-desc-index-table*
;;"SYMBOLICS LUCID EXCL AKCL CMU MCL XEROX ACLPC SBCL"
'((:name 0
0
#+excl excl::name #-excl nil
#+akcl 0 #-akcl nil
#+cmu #'c::dsd-name #-cmu nil
#+mcl #'first #-mcl nil
#+xerox t #-xerox nil
0 ;; aclpc
;;kr010212: added sbcl support
#+:SBCL #'sb-kernel:dsd-name #-:SBCL nil
)
(:type 4
3
#+excl excl::type #-excl nil
#+akcl 2 #-akcl nil
#+cmu #'c::dsd-type #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
3 ;; aclpc
#+:SBCL #'sb-kernel:dsd-type #-:SBCL nil
)
(:read-status 0
5
#+excl excl::read-only #-excl nil
#+akcl 3 #-akcl nil
#+cmu #'c::dsd-read-only #-cmu nil
#+mcl t #-mcl nil
#+xerox t #+xerox nil
4 ;; aclpc
#+:SBCL #'sb-kernel:dsd-read-only #-:SBCL nil
)
(:position 1
1
#+excl excl::index #-excl nil
#+akcl 4 #-akcl nil
#+cmu #'c::dsd-index #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
#+aclpc t #-aclpc nil
#+:SBCL #'sb-kernel::dsd-index #-:SBCL nil
)
(:default-value 3
4
#+excl excl::default #-excl nil
#+akcl 1 #-akcl nil
;;kr010602: moved from c to kernel package
#+cmu #'kernel::dsd-default #-cmu nil
#+mcl #'second #-mcl nil
#+xerox t #-xerox nil
2 ;; aclpc
#+:SBCL #'sb-kernel::dsd-default #-:SBCL nil
)
(:accessor 6
2
#+excl excl::accessor #-excl nil
#+akcl t #-akcl nil
#+cmu #'c::dsd-accessor #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
1 ;; aclpc
#+:SBCL #'sb-kernel:dsd-accessor #-:SBCL nil
)
))
(defvar *vendor-dependent-defstruct-symbol-function* nil
"Given a name of a defstruct as a symbol, return the defstruct descriptor
data structure for that defstruct."
)
(setf *vendor-dependent-defstruct-symbol-function*
#+symbolics #'(lambda(name)(si:get name 'si:defstruct-description))
#+lucid #'(lambda(name)(gethash name lucid::*defstructs*))
#+excl #'(lambda(name)(get name 'excl::%structure-definition))
#+akcl #'(lambda (name)(get name 'si::s-data))
#+(and :cmu (not :cmu18)) #'(lambda (name)(ext:info c::type c::defined-structure-info name))
;;kr010601: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) #'(lambda (name)(KERNEL:LAYOUT-INFO (ext:info :type :compiler-layout name)))
;;kr010120: added SBCL support
;;#+sbcl #'(lambda (name)(sb-int:info sb-c::type sb-c::defined-structure-info name))
#+:sbcl #'(lambda (name)(SB-KERNEL:LAYOUT-INFO (sb-int:info :type :compiler-layout name)))
#+mcl #'(lambda (name)(gethash name ccl::%defstructs%))
#+xerox #'(lambda(name))
#+aclpc #'(lambda(name)(acl::structure-name-p name))
)
;;;kr010605: this is just used in the table below. made this low-level extractor work
;;; in modern cmu-derived lisps. using a separate fn allows this often used code to be compiled.
;;;
#+(or :sbcl (and :cmu :cmu18))
(defun cmu-and-sbcl-defstruct-constructor-extractor (defstruct-description)
;;kr010601: for cmu18c, changed package from c to kernel
(let ((them (#+:cmu kernel::dd-constructors
#+:sbcl sb-kernel::dd-constructors
defstruct-description)))
(if (consp them)
(first them)
;;kr010604: well, guess what, in cmucl-18c, this defstruct slot is empty !
;; and we need to get the following:
(#+:cmu kernel::dd-default-constructor
#+:sbcl sb-kernel::dd-default-constructor
defstruct-description))))
(defvar *vendor-defstruct-desc-index-table* nil
"values in this table are either nil, a number, or a symbol.
if nil, funcall desc index function on desc only.
if a number, funcall desc index function on desc, index.
if a symbol, the symbol represents a slot name. call slot-value
on desc (which is presumed to be a CLOS instance) and the slot name.")
(setf *vendor-defstruct-desc-index-table*
;;"SYMBOLICS LUCID EXCL AKCL CMU MCL XEROX ACLPC SBCL"
'((:NAME #+lispm #'si:defstruct-description-name #-lispm nil
0
#+excl excl::name #-excl nil
#+akcl #'si::s-data-conc-name #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-name #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
#+aclpc t #-aclpc nil
;;kr010213: added sbcl support
#+:SBCL #'sb-kernel:dd-name #-:SBCL nil
)
(:PRINT-FUNCTION #+lispm #'si:defstruct-description-print-function #-lispm nil
6
#+excl excl::print-function #-excl nil
#+akcl #'si::s-data-print-function #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-print-function #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
#+aclpc t #-aclpc nil
#+:SBCL #'sb-kernel::dd-print-function #-:SBCL nil
)
(:TYPE #+lispm #'si:defstruct-description-type #-lispm nil
1
#+excl excl::type #-excl nil
#+akcl #'si::s-data-type #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-type #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
0 ;; aclpc
#+:SBCL #'sb-kernel:dd-type #-:SBCL nil
)
(:PREDICATE #+lispm #'si:defstruct-description-predicate #-lispm nil
5
#+excl excl::predicate #-excl nil
#+akcl t #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-predicate #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
4 ;; aclpc
#+:SBCL #'sb-kernel:dd-predicate #-:SBCL nil
)
(:COPIER #+lispm #'si:defstruct-description-copier #-lispm nil
4
#+excl excl::copier #-excl nil
#+akcl t #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-copier #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
5 ;; aclpc
#+:SBCL #'sb-kernel:dd-copier #-:SBCL nil
)
(:DOCUMENTATION #+lispm #'si:defstruct-description-documentation #-lispm nil
t #+excl excl::doc #-excl nil
#+akcl #'si::s-data-documentation #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-doc #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
#+aclpc t #-aclpc nil
#+:SBCL #'sb-kernel::dd-doc #-:SBCL nil
)
(:CONC-NAME #+lispm #'si::defstruct-description-conc-name #-lispm nil
2
#+excl excl::conc-name #-excl nil
#+akcl #'si::s-data-conc-name #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-conc-name #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
#+aclpc t #-aclpc nil
#+:SBCL #'sb-kernel::dd-conc-name #-:SBCL nil
)
(:INCLUDE #+lispm #'si:defstruct-description-include #-lispm nil
0
#+excl excl::include #-excl nil
#+akcl #'si::s-data-include #-akcl nil
;;kr010601: for cmu18c, changed package from c to kernel
#+cmu #'kernel::dd-include #-cmu nil
#+mcl t #-mcl nil
#+xerox t #-xerox nil
3 ;; aclpc
#+:SBCL #'sb-kernel::dd-include #-:SBCL nil
)
(:CONSTRUCTOR #+lispm #'si::defstruct-description-constructor #-lispm nil
3
#+excl excl::constructor #-excl nil
#+akcl #'(lambda (x)
(let ((them (si::s-data-constructors x)))
(if (listp them)(first them) them)))
#-akcl nil
#+(and :cmu (not :cmu18)) #'(lambda (x)
(let ((them (kernel::dd-constructors x)))
(if (listp them)(first them) them)))
#+(and :cmu :cmu18) #'cmu-and-sbcl-defstruct-constructor-extractor
#-cmu nil
;; #+mcl t #-mcl nil
4 ;;;; fifth thing in the descriptor in mcl 2.0.1
#+xerox t #-xerox nil
2 ;; aclpc
#+:SBCL #'cmu-and-sbcl-defstruct-constructor-extractor #-:SBCL nil
)
))
(defvar *cons-hash-table* nil
"cache for conses: initialized in INIT-LIST-HTABS, used in INDEX-LIST.")
(defvar *dl-hash-table* nil
"cache for dotted lists: initialized in INIT-LIST-HTABS, used in INDEX-LIST.")
(defvar *list-hash-table* nil
"cache for ordinary lists: initialized in INIT-LIST-HTABS, used in INDEX-LIST.")
(defvar *use-default-defstruct-options-in-save* nil "")
(defvar *test-for-circularities* T "This should normally be t.")
(setf *test-for-circularities* T)
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(when *test-for-circularities* (pushnew :CIRCULAR-TESTS *FEATURES*)))
;;;======================================================================
#+akcl
(eval-when (:compile-toplevel :load-toplevel :execute)
;; HASH-TABLE-SIZE does not seem to exist in AKCL!
(when (not (fboundp 'hash-table-size))
(defun HASH-TABLE-SIZE (htab)
39)
)
(defun INSTANCE-P (X) (typep x 'pcl::standard-object))
(defun %CLASSP (X) (pcl::classp x))
) ;; end of akcl eval-when....
;;; ROW MAJOR AREF --- ACL doesnt have it, Genera has it in package FCL....
;;; lucid has row-major-aref, no problem.
#+(or rel-8-0 rel-8-1)
(shadowing-import '(future-common-lisp:row-major-aref) 'database)
#+cmu
(shadowing-import '(user::row-major-aref) 'database)
;;; KOT I think don't need this in Allegro 4.2 (Sun); it's defined in CL
;;; package but I don't know how to test whether it works as I don't use
;;; arrays in my test cases.
#-(or lispm rel-8-0 rel-8-1 lucid cmu aclpc)
(when (not (fboundp 'row-major-aref))
(pushnew :need-row-major-aref *features*))
;;; lispm has it, CMU has it.
#-(or cmu lispm aclpc)
(eval-when (:compile-toplevel :load-toplevel :execute)
#+need-row-major-aref
(defun ROW-MAJOR-AREF (array index)
"We have to define this, as Franz does not implement RMA pg. 450 CLtL2.
NOTE: Neither does Symbolics."
(aref (make-array (array-total-size array)
:displaced-to array
:element-type (array-element-type array))
index))
#+need-row-major-aref
(defun ROW-MAJOR-SETA (array index newval)
"so we can defsetf row-major-aref!"
(setf (aref (make-array (array-total-size array)
:displaced-to array
:element-type (array-element-type array))
index) newval))
#+need-row-major-aref
(defsetf row-major-aref row-major-seta)
) ;; row-major-aref eval-when....
(defun %FILL-INSTANCE (i ordered-slot-values)
"Modified by KJ for MCL: Fills in the slots alphabetically.
Assumes the slot values come into the function
alphabetically ordered already: Returns the instance object.
NOTE: modification to deal with unbound slots is included!"
(if (null ordered-slot-values) i
(let ((osv (copy-list ordered-slot-values))
(unbound-slot nil)
(default-slot nil)
(names (get-ordered-slot-names i))
(thang nil)
(name nil))
(IF (NULL NAMES) I
(loop (setf name (pop names))
(setf thang (pop osv))
(cond ((unbound-slot-token-p thang)
(setf unbound-slot T)
(setf default-slot NIL))
((unsaveable-slot-token-p thang)
(setf default-slot T))
((and thang (symbolp thang))
;; mod by KJ to get rid of annoying quotes that
;; don't belong (I think this is because
;; initialize-instance is no longer getting
;; called so the quotes aren't needed.)
;(setf thang `(quote ,thang))
(setf unbound-slot NIL)
(setf default-slot NIL))
(T (setf unbound-slot NIL)
(setf default-slot NIL)))
;; if this slot was marked as unsaveable,
;; let the value be whatever allocate-instace willed it to be.
;; if it was unbound when saved, make the new instace slot
;; unbound, too. if neither, put the supplied slot value from
;; the file in the slot.
(if default-slot NIL ;; do nothing.
(if (not unbound-slot)
(cond ((instance-p i)
(setf (slot-value i name) thang)) ;; put the value in.
((structure-p i)(set-defstruct-slot-value i name thang)))
(slot-makunbound i name))) ;; make the slot unbound.
(when (and (null names)(null osv))(return i)))))))
(defmacro ASV (new-element)
"Add to storage vector, create, or vector push extend if necessary."
`(progn (when (not (boundp '*storage-vector*))
(setf *storage-vector*
(make-array *minimum-storage-vector-length*
:adjustable t :fill-pointer 0)))
(vector-push-extend (EVAL ',new-element) *storage-vector*)))
(defun WRITE-ASV-FORM (stream instance)
"Write the dump form of the instance for appending to the storage vector.
make sure that print-pretty is turned off to save room."
(let* ((*print-pretty* nil))
(format stream "~s~%" `(ASV ,(get-dump-form instance))))
)
(defun %WRITE-ASV-FORM (stream instance)
"Write the dump form of the instance for appending to the storage vector.
make sure that print-pretty is turned off to save room."
(let* ((*print-pretty* nil))
(format stream "~s~%" `(ASV ,(make-dumpable-form instance))))
)
(defun WRITE-ASV-FORMS (stream)
""
(maphash #'(lambda (key val)
(declare (ignore key))
(format stream "~s~%" `(ASV ,val)))
*storage-hash-table*))
#+ignore
(defmacro WITH-SAVED-OBJECTS-INTERNAL ((so-var construction-form) &rest body)
"Internal workhorse macro for WITH-SAVED-OBJECTS... derived from WITH-OPEN-
FILE...."
(declare (special so-var)) ;;; new!
`(let ((.stream-abort-flag. :ABORT))
(unwind-protect
(multiple-value-prog1
(progn (set ',so-var ,construction-form)
(write-attribute-line ,so-var)
(write-package-info ,so-var)
(dolist (form ',body)
;;(let ((result (eval form)))
;;(if (not (pco-p result))
;;(write-asv-form ,so-var result)
;;(get-dump-form result)
;;))
(%write-asv-form ,so-var (eval form))
)
;;(write-lex-env-prelude ,so-var)
;;(write-asv-forms ,so-var)
;;(write-lex-env-apotheosis ,so-var)
(setf .stream-abort-flag. nil))
(when ,so-var (close ,so-var :abort .stream-abort-flag.))))))
(defmacro WITH-SAVED-OBJECTS-INTERNAL ((so-var construction-form) &rest body)
"Internal workhorse macro for WITH-SAVED-OBJECTS... derived from WITH-OPEN-
FILE...."
(declare (special so-var))
`(let ((.stream-abort-flag. :ABORT))
(unwind-protect
(multiple-value-prog1
(progn (set ',so-var ,construction-form)
(write-attribute-line ,so-var)
(write-package-info ,so-var)
(dolist (form ',body)
(%write-asv-form ,so-var (eval form))
)
(setf .stream-abort-flag. nil))
(when ,so-var (close ,so-var :abort .stream-abort-flag.))))))
(defun WRITE-LEX-ENV-PRELUDE (stream)
(format stream "(LET* ( ")
(maphash #'(lambda (key value)
(format stream "(~A ~A)"
key value))
*storage-hash-table*)
(format stream ")"))
(defun WRITE-LEX-ENV-APOTHEOSIS (stream)
""
(format stream ")~%"))
(defmacro WITH-SAVED-OBJECTS ((svar sspec . options) &body body)
"Macro which evaluates, then dumps, as many forms as you want to
the specified file. If you do not specify file attributes, a reasonable
set (such as :direction :output, if does not exist :create) is assumed.
NOTE: This macro now returns the filename where the data is stored."
(declare (special svar))
(clrhash *storage-hash-table*)
;;kr010612: what is this good for ? commented out.
;;(setf (get 'already-exists 'file)(probe-file sspec))
(when (null options)(setf options (list :direction :output
:if-exists :append
:if-does-not-exist :create)))
`(progn (with-saved-objects-internal (,svar (open ,sspec . ,options))
. ,body)
,sspec))
;;; Dump forms.
#|
Dump forms include:
constant
complex
quoted-symbol
simple-list
defstruct-instance
defstruct-class
|#
(defun STREAM-DUMP-FORM (instance)
"Very machine dependent! for now, just recognize we got one, return NIL as
DUMP FORM."
(format t "Recognized a stream in save object: ~a.~%" instance)
NIL)
(defun CONSTANT-DUMP-FORM (instance)
"Anything which evals to itself (aside from structured objects),
can be written as is."
instance)
(defun COMPLEX-DUMP-FORM (instance)
"Dumps anything which is a complex number."
`(COMPLEX ,(get-dump-form (REALPART instance))
,(get-dump-form (IMAGPART instance))))
(defun QUOTED-SYMBOL-DUMP-FORM (instance)
"PATCHED: ADDED SECOND QUOTE FOR 9X: Dump form for a quoted symbol."
`(QUOTE (QUOTE ,(second instance))))
#+ignore
(defun SIMPLE-LEX-DUMP-FORM (lst)
`(QUOTE (LIST ,@lst)))
(defun SIMPLE-LEX-DUMP-FORM (lst)
`(LIST ,@lst))
(defun SIMPLE-LIST-DUMP-FORM (instance)
"Dump form for lists of admissible cnstants."
#-cmu `(LIST ,@instance)
#+cmu `(LIST ',@instance)
)
(defun DOTTED-LIST-DUMP-FORM (instance)
"Dump form whose last element is a dotted air, e.g. returned by LIST*."
`(LIST* ,(get-dump-form (first instance))
,(get-dump-form (rest instance))))
(defun DEFSTRUCT-INSTANCE-DUMP-FORM (instance)
"Vendor independent!"
`(fill-struct ,(get-instance-label instance)
;; ',(get-defstruct-values instance)
(LIST ,@(get-defstruct-values instance))))
(defun REGULAR-FUNCTION-DUMP-FORM (instance)
""
`(FUNCTION ,instance))
;;; Lucid is the only one that has a list length limit.
#-lucid
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun LONG-LIST-DUMP-FORM (instance)
""
(list-dump-form instance))
) ;; long-list eval-when.
(defun LIST-DUMP-FORM (instance)
""
`(LIST ,@(mapcar #'(lambda (thing)
(get-dump-form thing))
instance)))
#+ignore
(defun NEW-CACHE-OBJECT (object object-list var-list1 var-list2
dump-form)
"Fixed bug in position call this time."
(if (member object object-list :test #'equal)
(symbol-dump-form (nth (position OBJECT object-list :test #'equal)
var-list1))
(progn (push object object-list)
(setq var-list2 (pushsym var-list1))
(funcall dump-form object))))
;;; KOT added this; though not clearly how to completely add it in.
(defun CLOSUREP (x)
"This machine dependent predicate returns t if the object <x> is
a lexical closure, ie. either a (function (lambda .... thing, or
a hash-mark quote thing,"
#+lucid (and (not (typep x 'compiled-function))
(typep x 'system:procedure))
#+allegro-v4 (typep x 'excl::closure)
#-(or lucid allegro-v4)(progn x nil)
)
(defun CLOSURE-DUMP-FORM (closure)
#-:function-lambda-expression (declare (ignore closure))
#+:function-lambda-expression
(multiple-value-bind (lambda-expression closure-p name)
(function-lambda-expression closure)
;; KOT's reading of ANSI Draft 12.24, page 5-26, is that only the primary
;; value is something that potentially could be readable.
(declare (ignore closure-p name))
lambda-expression)
#-:function-lambda-expression nil
)
;;; KOT put this in here to look at, but it doesn't write anything useful
;;; in Allegro-V4
#+:ignore
(defun CLOSURE-DUMP-FORM-V70 (closure)
(let ((ans nil)
(strname ""))
(setq *readtable* (copy-readtable))
(set-dispatch-macro-character #\# #\' (function pseudo-quote-reader))
(set-dispatch-macro-character #\# #\< (function pseudo-quote-reader))
(setf strname (format nil "~S" closure))
(setq ans (read-from-string (SUBSEQ strname 0 (length strname))))
(setq *readtable* (copy-readtable nil))
`(FUNCTION ,ans)))
(defun STRUCTURED-OBJECT-DUMP-FORM (object)
"Routine which deals with any potentially circular objects (PCOS).
NEW: Adds the local variable and the dump form to the *Storage-hash-table*
so that with-saved-objects need to only do one set of local bindings for
structure-sharing. need to complete arrayp, hash-table-p clauses, test."
(cond ((null object) NIL)
((%classp object)
(if (member object *classes-seen* :test #'equal)
(symbol-dump-form
(nth (position object *classes-seen* :test #'equal)
*class-vars*))
(let ((df nil))
(push object *classes-seen*)
(setq *vars* (pushsym *class-vars*))
(setf df (if *class-safety-p* (safe-class-dump-form object)
(class-dump-form object)))
(push (list (first *vars*) df) *storage-list*)
(setf (gethash (first *vars*) *storage-hash-table*)
df)
df)))
((instance-p object)
(if (member object *seen* :test #'equal)
(symbol-dump-form
(nth (position object *seen* :test #'equal) *vars*))
(let ((df nil))
(push object *seen*)
(setq *vars* (pushsym *vars*))
(setf df (instance-dump-form object))
(push (list (first *vars*) df) *storage-list*)
(setf (gethash (first *vars*) *storage-hash-table*)
df)
df)))
((structure-p object)
(if (member object *structs-seen* :test #'equal)
(symbol-dump-form (nth (position object *structs-seen*
:test #'equal)
*struct-vars*))
(let* ((df nil))
(push object *structs-seen*)
(setf *struct-vars* (pushsym *struct-vars*))
(setf df (structure-dump-form object))
(push (list (first *struct-vars*) df) *storage-list*)
(setf (gethash (first *struct-vars*) *storage-hash-table*)
df)
df)))
((vectorp object)
(if (member object *vectors-seen* :test #'equal)
(progn (symbol-dump-form (nth (position object *vectors-seen*
:test #'equal)
*vector-vars*)))
(let ((df nil))
(push object *vectors-seen*)
(setf *vector-vars* (pushsym *vector-vars*))
(setf df (vector-dump-form object))
(push (list (first *vector-vars*) df) *storage-list*)
(setf (gethash (first *vector-vars*) *storage-hash-table*)
df)
df)))
((arrayp object)
(if (member object *arrays-seen* :test #'equal)
(progn (symbol-dump-form (nth (position object *arrays-seen*
:test #'equal)
*array-vars*)))
(let ((df nil))
(push object *arrays-seen*)
(setf *array-vars* (pushsym *array-vars*))
(setf df (array-dump-form object))
(push (list (first *array-vars*) df) *storage-list*)
(setf (gethash (first *array-vars*) *storage-hash-table*)
df)
df)))
((hash-table-p object)
(if (member object *htabs-seen* :test #'equal)
(symbol-dump-form (nth (position object *htabs-seen*
:test #'equal) *htab-vars*))
(let* ((df nil))
(push object *htabs-seen*)
(setf *htab-vars* (pushsym *htab-vars*))
(setf *current-htab-size* (or (hash-table-size object) 5000))
(setf *current-htab-rehash-threshold*
(or (hash-table-rehash-threshold object) 20))
(setf *current-htab-test* (hash-table-test object))
(setf *current-htab-rehash-size*
(or (hash-table-rehash-size object) 67))
(setf df (htab-dump-form object))
(push (list (first *htab-vars*) df) *storage-list*)
(setf (gethash (first *htab-vars*) *storage-hash-table*)
df)
df)))
#+CIRCULAR-TESTS ((circular-list-p object)(circular-list-dump-form object))
(T (error "couldnt parse ~a as a structured object!" object))))
(defun DEFSTRUCT-OBJECT-P (obj)
"Predicate for testing whether something is a defstruct descriptor."
(typep obj #+lispm 'si::defstruct-description
#+allegro 'excl::defstruct-description
#+lucid 'defstruct
#+akcl 'system::s-data
#+(and :cmu (not :cmu18)) 'c::defstruct-descriptor
;;kr010602: it seems to be necessary to distinguish between yet another newer cmucl version:
#+(and :cmu :cmu18) 'kernel::defstruct-description
;;kr010210: added support for SBCL
#+:SBCL 'sb-kernel::defstruct-description
#+mcl 'vector
#+aclpc 'vector ;; the descriptor as a whole is a simple vector.
)
)
#|
(defun STRUCTURED-OBJECT-DUMP-FORM (object)
"Routine which deals with any potentially circular objects (PCOS)."
(cond ((null object) NIL)
((defstruct-object-p object)
(defstruct-object-dump-form object))
((%classp object)
(new-cache-object object *classes-seen* *class-vars* *vars*
#'class-dump-form))
((instance-p object)
(new-cache-object object *seen* *vars* *vars*
#'instance-dump-form))
((structure-p object)
(new-cache-object object *structs-seen* *struct-vars*
*struct-vars*
#'defstruct-instance-dump-form))
((vectorp object)
(new-cache-object object *vectors-seen* *vector-vars*
*vector-vars*
#'vector-dump-form))
((arrayp object)
(new-cache-object object *arrays-seen* *array-vars*
*array-vars*
#'array-dump-form))
((hash-table-p object)
(if (member object *htabs-seen* :test #'equal)
(symbol-dump-form
(nth (position object *htabs-seen* :test #'equal) *htab-vars*))
(progn (push object *htabs-seen*)
(setf *htab-vars* (pushsym *htab-vars*))
(setf *current-htab-size* (or (hash-table-size object) 5000))
(setf *current-htab-rehash-threshold*
(or (hash-table-rehash-threshold object) 20))
(setf *current-htab-test* (hash-table-test object))
(setf *current-htab-rehash-size*
(or (hash-table-rehash-size object) 67))
(htab-dump-form object))))
((circular-list-p object)(circular-list-dump-form object))
(T (error "couldnt parse ~a as a structured object!" object))))
|#
(defun HTAB-DUMP-FORM (htab)
"Dump for for hash tables.... "
`(makehash ,(get-instance-label htab)
:test ,(get-dump-form (hash-table-test htab))
:size ,(get-dump-form (hash-table-size htab))
:rehash-size ,(get-dump-form (hash-table-rehash-size htab))
:rehash-threshold ,(get-dump-form
(hash-table-rehash-threshold htab))
:values (LIST ,@(get-htab-values htab))))
(defun PACKAGE-DUMP-FORM (package)
"assume its there in the environment, somewhere."
(let ((pn (get-dump-form (package-name package))))
`(FIND-PACKAGE ,pn)))
(defun REPEATING-ELEMENT-LIST-DUMP-FORM (instance)
"A dump form for a list which has a repeating element."
(let ((length (length instance))
(form (get-dump-form (first instance))))
`(MAKE-LIST ,length :initial-element ,form)))
(defun REC-LIST-DUMP-FORM (l)
`(LIST ,@(%rec-list-dump-form l)))
(defun %REC-LIST-DUMP-FORM (l)
""
(cond ((null l) nil)
((not (listp (first l)))
(cons (get-dump-form (first l))
(%rec-list-dump-form (rest l))))
(T (cons (%rec-list-dump-form (first l))
(%rec-list-dump-form (rest l))))))
(defun CONS-DUMP-FORM (item)
`(CONS ,(get-dump-form (first item))
,(get-dump-form (rest item))))
(defun PRINT-SLOTS (instance)
"Utility function to print the slots in the instance, ala describe."
(mapcar #'(lambda (s)(format t "Name:~a, Value:~a~%" s
(if (slot-boundp instance s)(slot-value instance s) :UNBOUND)))
(all-slotnames instance)))
(defun ARRAY-DUMP-FORM (array)
"this function return a make-array form."
(setf *print-array* T)
(let ((vals (%list-array array)))
`(let ((tmp (allocate-array ,(get-dump-form (array-dimensions array))
:element-type ',(array-element-type array)
:adjustable ,(adjustable-array-p array)
:initial-contents ,(get-dump-form vals)
)))
TMP)))
(defun SIMPLE-ARRAY-DUMP-FORM (array)
"Numerical arrays are stored using this routine...."
(let ((vals (%list-array array)))
`(allocate-array ,(get-dump-form (array-dimensions array))
:element-type ',(array-element-type array)
:initial-contents ,(get-dump-form vals)
)))
(defun VECTOR-DUMP-FORM (array)
"this function return a make-array form."
(setf *print-array* T)
(let ((vals (%list-array array)))
`(let ((tmp (allocate-array ,(get-dump-form (array-dimensions array))
:element-type ',(array-element-type array)
:adjustable ,(adjustable-array-p array)
:initial-contents ,(get-dump-form vals))))
TMP)))
(defun READTABLE-DUMP-FORM (i)
"Doesnt seem to be a good way to probe the internals of readtables, even
machine specific ways!!!!"
(declare (ignore i))
`(copy-readtable *readtable*))
(defun GENERIC-FUNCTION-DUMP-FORM (instance)
"Dump Form for saving out generic functions..."
(let ((name (generic-function-name instance))
(arglist (generic-function-lambda-list instance))
(documentation (%generic-function-documentation instance)))
`(OR (FIND-GENERIC-FUNCTION ',name)
(DEFGENERIC ,name ,arglist (:DOCUMENTATION ,(or documentation ""))))))
(defun METHOD-DUMP-FORM (instance)
"dump form for saving out method objects."
(LET* ((name (generic-function-name (method-generic-function instance)))
(qualifiers (method-qualifiers instance))
(specializers (method-specializers instance)))
`(FIND-METHOD (FUNCTION ,name)
(LIST ,@qualifiers)
(LIST ,@(DO-SPECIALIZERS specializers))
NIL)))
;;; PCL/CLOS classes and instances:
;;; NOTE: CLASS DEFINITIONS, WHEN READ IN, WILL OVERWRITE THE CLASS
;;; DEFINITION PREVIOUSLY IN MEMORY. IF YOU DO NOT WANT THIS TO HAPPEN,
;;; REPLACE 'DEFCLASS' BELOW WITH 'FIND CLASS' + the APPROPRIATE ARGUMENTS!
(defun SAFE-CLASS-DUMP-FORM (instance)
"MODIFIED: does not do the let unless the class is not found...
his version of the class-dump-form function WILL NOT overwrite
current class definitions with the same name. It is the one invoked
by GET-DUMP-FORM and SAVE-OBJECT."
(let* ((name (%class-name instance)))
`(FIND-CLASS ',name)))
#|
`(OR (FIND-CLASS ',name)
(let* ((supertypes (get-class-superclasses ,instance))
(slots (generate-class-slot-forms ,instance))
(options (generate-class-options-form ,instance)))
`(DEFCLASS ,name ,supertypes ,slots ,@options)))))
|#
(defun CLASS-DUMP-FORM (instance)
"This version of the class-dump-form function WILL OVERWRITE
CURRENT CLASS DEFINITIONS WITH THE SAME NAME. Sunstitute a call to
this one in GET-DUMP-FORM and SAVE-OBJECT."
(let* ((name (%class-name instance))
(supertypes (get-class-superclasses instance))
(slots (generate-class-slot-forms instance))
(options (generate-class-options-form instance)))
(if (builtin-class-p instance) `(FIND-CLASS ',name)
`(DEFCLASS ,name ,supertypes ,slots ,@options))))
(defun INSTANCE-DUMP-FORM (instance)
"Basic dump form for clos/pcl instances. checks if the instance has a custom
dump form, binds it to a generated symbol name, recursively expands the
instances contents."
(declare (special tmp))
(if (has-dump-form-p (instance-name instance))
`(setq ,(get-instance-label instance) ,(funcall #'(lambda (x)
(get-dump-form x))
instance))
`(fill-instance ,(get-instance-label instance)
(LIST ,@(get-ordered-slot-values instance)))))
(defun LONG-SYMBOL-DUMP-FORM (instance &optional (package *package*))
"Uses a MAKE-SYMBOL form to re-create the symbol:
saves the property list of the symbol if the global flag *save-symbol-plists* is T."
(if *save-symbol-plists*
`(let ((sym (intern ,(symbol-name instance) (find-package ,(package-name package)))))
(setf (symbol-plist sym) ,(get-dump-form (symbol-plist instance))))
`(intern ,(symbol-name instance) (find-package ,(package-name package)))))
(defun SYMBOL-DUMP-FORM (instance)
"Better bolder symbol saving formula which includes the package data
implicitly: if package cell is NULL (as returned by GENSYM),
default *package* is used."
(let ((package-name nil)
(the-package (symbol-package instance)))
(if (null the-package)(setf package-name (package-name *package*))
(setf package-name (package-name the-package)))
(if (null instance) NIL
(if (special-marker-p instance) instance
(if *use-symbol-long-form*
(long-symbol-dump-form instance)
(read-from-string (format nil "~a"
(concatenate 'string "'"
package-name "::"
(symbol-name instance)))))))))
(defun SIMPLE-QUOTED-LIST-DUMP-FORM (x)
(let ((it (quoteit x)))
`(QUOTE (,@it))))
#|
(defun SIMPLE-QUOTED-LIST-DUMP-FORM (x)
"If the list contains no sublists, and the elements are admissible
constants, use this dump form."
`(QUOTE (,@x)))
|#
(defun ALL-NUMBERS-LIST-DUMP-FORM (instance)
`(LIST ,@instance))
(defun QUOTED-LIST-DUMP-FORM (instance)
"If something is a quoted list (may contain sublists),
put the quote at the right place."
`(QUOTE ,instance)
)
(defun COMPILED-FUNCTION-DUMP-FORM (X)
"dump form for hashmark-quote e.g. (FUNCTION name) forms."
#+lispm (if (si:lexical-closure-p x) nil)
`(function ,(get-compiled-function-name x)))
;;; *** beginning of MCL common lisp definitions...***
;;; NOTE: mst of the slot definition access functions remain undefined in
;;; MCL 2.0.1 --- see introspective-mop.txt for details! kvk
#+mcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun CLASS-SLOTNAMES (class-object)
"Calls the clos internal function to compute class slot names."
(lisp:remove nil (mapcar #'first (class-slots class-object))))
(defun CLASS-SLOTS (class)
"MODIFIED: Given a class object, return all the slot objects."
;#+quadra(ccl::class-instance-slots class)
;#+fx (ccl::class-slots class)
;#+mcl(class-direct-slots class)
;; modified by KJ
#+mcl(ccl::class-instance-slots class)
)
;; ---- new experimental routines for Mcl ------
#-ccl-2
(defun CLASS-DIRECT-SLOTS (class)
"Given a class object return the slot objects."
(ccl::class-direct-slots class))
#+ccl-2
(defun CLASS-DIRECT-SLOTS (class)
"Given a class object return the slot objects."
(ccl::class-direct-class-slots class))
(defun INSTANCE-P (X)
"Predicate to determine whether something is an INSTANCE."
(and (not (%classp x))(typep x 'standard-object)))
(defun GET-CLASS-DEFAULT-INITARGS (class)
"Gets the default-initargs out of the class object."
class
nil)
(defun %CLASSP (X)
"predicate to tell if something is a class object."
(typep x 'ccl::standard-class))
(defun %GENERIC-FUNCTION-DOCUMENTATION (f)
""
(or (documentation f) ""))
(defun GET-SLOT-TYPE (S)
""
#+mcl-3
(progn
(if (dotted-list-p s)(rest (%last s)) ;;; this line is new, kvk.
nil))
#-mcl-3
(progn
(if (dotted-list-p s)(rest (%last s)) ;;; this line is new, kvk.
nil))
)
#+ignore
(defun GET-SLOT-TYPE (S)
""
(if (dotted-list-p s)(rest (%last s)) ;;; this line is new, kvk.
(first (reverse s))))
(defun GET-DIRECT-SLOTS (class-object)
"Gets the immediately available 'new' non inheried slot OBJECTS."
(class-direct-slots class-object))
(defun GET-SLOT-DOCUMENTATION (s)
""
(if (listp s) ""
(or (documentation s) "")))
(defun GET-SLOT-NAME (S)
"Method to get the name from a standard slot."
(clos::slot-definition-name s))
(defun SLOT-HAS-AN-INITFORM-P (slot-object)
"Predicate for ccl (where slots are represented as lists) to determine
whether a slot object has an initform component."
(second slot-object))
(defun GET-SLOT-READERS (s)
""
s
nil)
(defun GET-SLOT-WRITERS (s)
""
s
nil)
(defun %SLOT-DEFINITION-ALLOCATION (S)
""
s
NIL)
(defun GET-SLOT-NAMED (instance name)
""
(find-if #'(lambda (slot)
(equal (get-slot-name slot) name))
(all-slots instance)))
(defun GET-SLOT-ALLOCATION (S)
"Method to get the type of allocation from a standard slot: oneof
:CLASS or :INSTANCE."
(let ((alloc (%slot-definition-allocation s)))
(cond ((%classp alloc) :CLASS)
((member alloc '(:INSTANCE :CLASS)) alloc)
(T :INSTANCE))))
(defun GET-SLOT-INITFORM (s)
"For ccl:returns the initform of a slot object."
(when (slot-has-an-initform-p s)
(first (second s))))
(defun GET-SLOT-INITARGS (s)
""
(format t "s == ~a~%" s)
(if (listp s)(list (second s))
(ccl::class-slot-initargs s)))
(defun GET-SLOT-INITARG (s)
""
(format t "s <==> ~a~%" s)
(if (listp s)(second s)
(first (ccl::class-slot-initargs s))))
(defmethod ALL-SLOTNAMES ((instance T) &optional (all-allocations T))
"returns the names of the slots in instance, uses what MOP stuff is
available."
(declare (ignore all-allocations))
(lisp:REMOVE NIL (mapcar #'clos::slot-definition-name
(class-slots (clos::class-of instance)))))
;; Hohmann patch...
(setf (symbol-function 'classp) #'ccl::classp) ;; FIXED!!!!
(defun ALL-SLOTS (instance)
"Gets all the slots from the instances class, whether inherited or not."
(class-slots (clos::class-of instance)))
(defun GET-SUPERCLASS-NAMES (class)
""
(mapcar #'clos::class-name (clos::class-direct-superclasses class)))
) ;; *END OF MCL CCL CLOS eval-when! ****
;;; A CLOS eval-when for Allegro PC:
#+clos
(eval-when (:compile-toplevel :load-toplevel :execute)
#-aclpc
(defun %CLASS-NAME (x)
"If instance, gets the name of the class of the instance."
(if (instance-p x)(clos::class-name (clos::class-of x))
(clos::class-name x)))
#+aclpc
(defun %CLASS-NAME (x)
"If instance, gets the name of the class of the instance."
(if (instance-p x)(class-name (class-of x))
(class-name x)))
#+aclpc
(defun ACLPC-GET-DEFSTRUCT-CONSTRUCTOR (symbol)
(read-from-string (concatenate 'string "MAKE-" (format nil "~A" symbol))))
#+aclpc
(defmethod ALLOCATE-INSTANCE ((class structure-class) &rest initargs)
""
(apply (aclpc-get-defstruct-constructor (class-name class)) nil))
) ;; end of eval-when....
;;; HASH TABLES...
;;; PCL Dependent functions & methods,,,
#+pcl
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defvar *the-pcl-standard-class-name* 'pcl::standard-class)
(defun BUILTIN-CLASS-P (X)
;;kr010602: wow! this seems idiotically inefficient for such a predicate that is used quite a bit.
;; (mapcar ) always conses up a new list !!
;;(member (type-of x) (mapcar #'first pcl::*built-in-classes*))
;;kr010602: do this instead:
(find (type-of x) pcl::*built-in-classes* :key #'first)
)
(defun GET-SLOT-READERS (slot-object)
#-new-pcl(pcl::slotd-readers slot-object)
#+new-pcl(pcl::slot-definition-readers slot-object)
)
(defun GET-SLOT-WRITERS (slot-object)
#-new-pcl(pcl::slotd-writers slot-object)
#+new-pcl(pcl::slot-definition-writers slot-object)
)
(defun %GET-SLOT-ALLOCATION (s)
#-new-pcl(pcl::slotd-allocation s)
#+new-pcl(pcl::slot-definition-allocation s)
)
(defun GET-SLOT-ALLOCATION (S)
"Method to get the type of allocation from a standard slot: oneof
:CLASS or :INSTANCE."
(let ((alloc (%get-slot-allocation s)))
(cond ((%classp alloc) :CLASS)
((member alloc '(:INSTANCE :CLASS)) alloc)
(T :INSTANCE))))
(defun GET-SLOT-NAME (S)
"Method to get the name from a standard slot."
#-new-pcl(pcl::slotd-name s)
#+new-pcl(pcl::slot-definition-name s)
)
(defun %CLASS-NAME (class)
""
(pcl::class-name class))
(defmethod GET-SLOT-INITFORM (s)
""
(when (slot-has-an-initform-p s)
#-new-pcl(pcl::slotd-initform s)
#+new-pcl(pcl::slot-definition-initform s)
))
(defun SLOT-HAS-AN-INITFORM-P (s)
""
(slot-boundp s 'pcl::initform))
(defun GET-SLOT-INITARGS (s)
""
#-new-pcl(pcl::slotd-initargs s)
#+new-pcl(pcl::slot-definition-initargs s)
)
(defun GET-SLOT-INITARG (s)
""
#-new-pcl(first (pcl::slotd-initargs s))
#+new-pcl(first (pcl::slot-definition-initargs s))
)
#-akcl
(defun CLASS-SLOTS (class-object)
"Calls the clos internal function to compute class slot objects:
used in CMUCL, too!"
(pcl::slots-to-inspect (class-of class-object) class-object))
(defun %ALLOCATE-INSTANCE (class-object &rest htab-plist)
(cond
((equal class-object 'HASH-TABLE)
(allocate-htab class-object
:size (getf htab-plist :size 5000)
:rehash-size (getf htab-plist :rehash-size 67)
:rehash-threshold (getf htab-plist :rehash-threshold 0.67)
:test (getf htab-plist :test #'eql)))
((get-symbol-defstruct-spec class-object)
(allocate-struct class-object))
((structure-p class-object)(allocate-struct class-object))
((symbolp class-object)
;;kr010601: use (pcl::find-class ) here, certainly for cmu18c
(pcl::allocate-instance (pcl::find-class class-object nil)))
((%classp class-object)(pcl::allocate-instance class-object))
((instance-p class-object) class-object)
(T (format T "Warning: couldnt allocate instance for object: ~A!" class-object) NIL)))
;; CLASSP is not exported from PCL, the next two are substitutes.
(defun CLASSP (x)
"Predicate, determines whether the object x is a class object."
(pcl::classp x))
(defun %CLASSP (x)
"Predicate, determines whether the object x is a class object."
(classp x))
(defun INSTANCE-NAME (instance)
"returns the symbol naming the given class object."
(cond ((hash-table-p instance) 'hash-table)
((structure-p instance)(get-defstruct-name instance))
((instance-p instance)(pcl::class-name (pcl::class-of instance)))
(T NIL)))
(defun ALL-SLOTNAMES (instance &optional (all-allocations T))
"returns the names of the slots in instance."
(let ((them (mapcar #'(lambda (slot)
(pcl::slot-value slot 'pcl::name))
(pcl::slots-to-inspect (pcl::class-of instance)
instance))))
(if all-allocations them
(remove-if-not #'(lambda (slot)
(equal (%get-slot-allocation slot) :instance))
them))))
(defun ALL-SLOTS (instance &optional (all-allocations T))
"returns the names of the slots in instance."
(let ((them (pcl::slots-to-inspect (pcl::class-of instance)
instance)))
(if all-allocations them
(remove-if-not #'(lambda (slot)
(equal (%get-slot-allocation slot) :instance))
them))))
(defun %GENERIC-FUNCTION-P (X)
""
(pcl::generic-function-p x))
(defun GET-SLOT-DOCUMENTATION (slot)
""
(or (documentation slot (type-of slot)) ""))
(defun GET-SLOT-TYPE (slot)
""
#-new-pcl(pcl::slotd-type slot)
#+new-pcl(pcl::slot-definition-type slot)
)
(defun GET-SUPERCLASS-NAMES (class)
""
(mapcar #'%class-name (pcl::class-direct-superclasses class)))
(defun GET-CLASS-DEFAULT-INITARGS (class)
""
(pcl::class-default-initargs class))
(defun GET-CLASS-METACLASS (class-object)
"Given a class object, returns the metaclass name to help build
CLASS-DUMP-FORM: (NEW)."
(when (%classp class-object)
(let ((meta (%class-name (class-of (class-of class-object)))))
(if (not (equal meta *the-pcl-standard-class-name*)) ;; the default...
(list (list :metaclass meta))))))
#+cmu
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun INSTANCE-P (x)
"Predicate for CMU Common Lisp: detects instances."
;; used to be std-instance.
(and (not (%classp x))(typep x 'pcl::standard-object)))
) ;; end of CMU CL eval-when for PCL.....
(defun GET-DOCUMENTATION (object)
""
(let ((answers nil))
(dolist (current-type (get-available-types object)(nreverse answers))
(push (documentation object current-type) answers))))
) ;; *** END PCL EVAL-WHEN.... ***
;;;kr010301: copied the above pcl block, and modified for SBCL
;;;
#+SBCL
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *the-pcl-standard-class-name* 'sb-pcl::standard-class)
(defun BUILTIN-CLASS-P (X)
;;kr010602: less wasteful than what was here before:
(find (type-of x) sb-pcl::*built-in-classes* :key #'first)
)
(defun GET-SLOT-READERS (slot-object)
(sb-pcl::slot-definition-readers slot-object)
)
(defun GET-SLOT-WRITERS (slot-object)
(sb-pcl::slot-definition-writers slot-object)
)
(defun %GET-SLOT-ALLOCATION (s)
(sb-pcl::slot-definition-allocation s)
)
(defun GET-SLOT-ALLOCATION (S)
"Method to get the type of allocation from a standard slot: oneof
:CLASS or :INSTANCE."
(let ((alloc (%get-slot-allocation s)))
(cond ((%classp alloc) :CLASS)
((member alloc '(:INSTANCE :CLASS)) alloc)
(T :INSTANCE))))
(defun GET-SLOT-NAME (S)
"Method to get the name from a standard slot."
(sb-pcl::slot-definition-name s)
)
(defun %CLASS-NAME (class)
""
(sb-pcl::class-name class))
(defmethod GET-SLOT-INITFORM (s)
""
(when (slot-has-an-initform-p s)
(sb-pcl::slot-definition-initform s)
))
(defun SLOT-HAS-AN-INITFORM-P (s)
""
(slot-boundp s 'sb-pcl::initform))
(defun GET-SLOT-INITARGS (s)
""
(sb-pcl::slot-definition-initargs s)
)
(defun GET-SLOT-INITARG (s)
""
(first (sb-pcl::slot-definition-initargs s))
)
(defun CLASS-SLOTS (class-object)
"Calls the clos internal function to compute class slot objects:
used in CMUCL, too!"
(sb-pcl::slots-to-inspect (class-of class-object) class-object))
(defun %ALLOCATE-INSTANCE (class-object &rest htab-plist)
(cond
((equal class-object 'HASH-TABLE)
(allocate-htab class-object
:size (getf htab-plist :size 5000)
:rehash-size (getf htab-plist :rehash-size 67)
:rehash-threshold (getf htab-plist :rehash-threshold 0.67)
:test (getf htab-plist :test #'eql)))
((get-symbol-defstruct-spec class-object)
(allocate-struct class-object))
((structure-p class-object)(allocate-struct class-object))
((symbolp class-object)
;;kr010601: use (sb-pcl::find-class ) here, certainly for early sbcl-0.6.x
(sb-pcl::allocate-instance (sb-pcl::find-class class-object nil)))
((%classp class-object)(sb-pcl::allocate-instance class-object))
((instance-p class-object) class-object)
(T (format T "Warning: couldnt allocate instance for object: ~A!" class-object) NIL)))
;; CLASSP is not exported from SB-PCL, the next two are substitutes.
(defun CLASSP (x)
"Predicate, determines whether the object x is a class object."
(sb-pcl::classp x))
(defun %CLASSP (x)
"Predicate, determines whether the object x is a class object."
(classp x))
(defun INSTANCE-NAME (instance)
"returns the symbol naming the given class object."
(cond ((hash-table-p instance) 'hash-table)
((structure-p instance)(get-defstruct-name instance))
((instance-p instance)(sb-pcl::class-name (sb-pcl::class-of instance)))
(T NIL)))
(defun ALL-SLOTNAMES (instance &optional (all-allocations T))
"returns the names of the slots in instance."
(let ((them (mapcar #'(lambda (slot)
(sb-pcl::slot-value slot 'sb-pcl::name))
(sb-pcl::slots-to-inspect (sb-pcl::class-of instance)
instance))))
(if all-allocations them
(remove-if-not #'(lambda (slot)
(equal (%get-slot-allocation slot) :instance))
them))))
(defun ALL-SLOTS (instance &optional (all-allocations T))
"returns the names of the slots in instance."
(let ((them (sb-pcl::slots-to-inspect (sb-pcl::class-of instance)
instance)))
(if all-allocations them
(remove-if-not #'(lambda (slot)
(equal (%get-slot-allocation slot) :instance))
them))))
(defun %GENERIC-FUNCTION-P (X)
""
(sb-pcl::generic-function-p x))
(defun GET-SLOT-DOCUMENTATION (slot)
""
(or (documentation slot (type-of slot)) ""))
(defun GET-SLOT-TYPE (slot)
""
(sb-pcl::slot-definition-type slot)
)
(defun GET-SUPERCLASS-NAMES (class)
""
(mapcar #'%class-name (sb-pcl::class-direct-superclasses class)))
(defun GET-CLASS-DEFAULT-INITARGS (class)
""
(sb-pcl::class-default-initargs class))
(defun GET-CLASS-METACLASS (class-object)
"Given a class object, returns the metaclass name to help build
CLASS-DUMP-FORM: (NEW)."
(when (%classp class-object)
(let ((meta (%class-name (class-of (class-of class-object)))))
(if (not (equal meta *the-pcl-standard-class-name*)) ;; the default...
(list (list :metaclass meta))))))
(defun INSTANCE-P (x)
"Predicate for CMU Common Lisp: detects instances."
;; used to be std-instance.
(and (not (%classp x))(typep x 'sb-pcl::standard-object)))
;;kr010120: added SBCL support
;; would this work too ? :
;; (defun INSTANCE-P (X) (typep x 'standard-object))
(defun GET-DOCUMENTATION (object)
""
(let ((answers nil))
(dolist (current-type (get-available-types object)(nreverse answers))
(push (documentation object current-type) answers))))
) ;; *** END SBCL PCL EVAL-WHEN.... ***
(defun GET-COMPILED-FUNCTION-NAME (fn)
"Given a function object <fn>, return the symbol name of the function."
#+lispm
(when (si:lexical-closure-p fn)
(return-from get-compiled-function-name nil))
(etypecase fn
(symbol fn)
(compiled-function #+old-cmu(kernel:%function-header-name fn)
#+cmu(kernel:%function-name fn)
#+mcl(ccl::function-name fn)
#+lispm(si:compiled-function-name fn)
#+akcl(system::compiled-function-name fn)
#+lucid
(when (sys:procedurep fn)
(sys:procedure-ref fn SYS:PROCEDURE-SYMBOL))
#+excl (xref::object-to-function-name fn)
)))
;;;(let ((ans nil)
;;; (strname ""))
;;;(setq *readtable* (copy-readtable))
;;;(set-dispatch-macro-character #\# #\' (function pseudo-quote-reader))
;;;(set-dispatch-macro-character #\# #\< (function pseudo-quote-reader))
;;;(setf strname (format nil "~S" fn))
;;;(setq ans (read-from-string (SUBSEQ strname 0 (length strname))))
;;;(setq *readtable* (copy-readtable nil))
;;;ans)
;;;)))
;;; Support functions for MAP-CLASS.
#+lucid
(defun ALL-SLOTS (class-object)
""
(class-slots class-object))
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun GET-SLOT-COMPONENT (key slot-object)
""
(let* ((keylist '((:all identity)
(:initform get-slot-initform)))
(applyfun (second (assoc key keylist :test #'equal))))
(when applyfun (funcall applyfun slot-object))))
(defun MAP-CLASS (function class-object &key (component :all)
(save T)
(plist T))
"Iterator for class objects. Applies a function to each (slot). "
(let ((slots (all-slots class-object))
(answer nil)
(current nil))
(dolist (slot slots answer)
(if plist
(setf current (list (make-keyword (get-slot-name slot))
(funcall function
(get-slot-component component slot))))
(setf current (funcall function
(get-slot-component component slot))))
(when (and save (not plist)) (push current answer))
(when (and save plist)(setf answer (append answer current))))
answer))
(defun MAP-CLASS-DUMP-FORM (class-object &key (component :all))
""
(get-dump-form
(map-class #'get-dump-form class-object :plist t
:component component :save t)))
) ;; non clos/pcl eval-when end.
(defun SIMPLE-ARRAY-P (instance)
""
;; KOT fixed typo here.
(and (arrayp instance)(not (pco-p instance))))
#+mcl
(defun MAC-HANDLE-DUMP-FORM (instance)
"STUB."
(declare (ignore instance))
nil)
(defun BUILTIN-INSTANCE-P (instance)
(and instance
(not (eq instance T))
(not (instance-p instance))
;;kr010602: from my reading of the code, (instance-p ) is only supposed to cover the CLOS instances,
;; and so we need to exclude structure instances as well (or this predicate will fire accidentally):
(not (structure-p instance))
(not (stringp instance))
(not (hash-table-p instance))
(not (pathnamep instance))
(not (numberp instance))
(not (keywordp instance))
(not (arrayp instance))
(not (consp instance))
;;kr010602: comment: the following fn call seems somewhat expensive. no wonder it comes last.
(builtin-class-p (type-of instance))))
(defun MAKE-BUILTIN-INSTANCE (instance)
"STUB!"
(declare (ignore instance))
:INSTANCE)
(defun BUILTIN-INSTANCE-DUMP-FORM (instance)
""
`(MAKE-BUILTIN-INSTANCE ',(instance-name instance)))
(defun INIT-LIST-HTABS (&optional (test #'equal))
"Initialize or clear the hash tables associated with list caching."
(if *cons-hash-table*
(progn
(clrhash *cons-hash-table*)
(clrhash *dl-hash-table*)
(clrhash *list-hash-table*))
(progn
(setf *cons-hash-table* (make-hash-table :test test))
(setf *dl-hash-table* (make-hash-table :test test))
(setf *list-hash-table* (make-hash-table :test test)))))
(defun LOOKUP-LIST (x)
"Returns a (possibly cached) dump form for list <x>."
(when (null x)(return-from lookup-list nil))
(when (eq x T)(return-from lookup-list T))
(cond ((or (cons-p x)(circular-cons-p x))(gethash x *cons-hash-table*))
((or (dotted-list-p x)(circular-dotted-list-p x))
(gethash x *dl-hash-table*))
((listp x)(gethash x *list-hash-table*))
(T NIL)))
(defun INDEX-LIST (x)
"When we index list forms, we cache them in one of three hash tables: conses, dotted lists,
and ordinary lists."
(cond ((cons-p x)
(unless *cons-hash-table* (setf *cons-hash-table* (make-hash-table)))
(unless (gethash x *cons-hash-table*)
(setf (gethash x *cons-hash-table*)
(%get-dump-form x))))
((dotted-list-p x)
(unless *dl-hash-table* (setf *dl-hash-table* (make-hash-table)))
(unless (gethash x *dl-hash-table*)
(setf (gethash x *dl-hash-table*)
(%get-dump-form x))))
((listp x)
(unless *list-hash-table* (setf *list-hash-table* (make-hash-table)))
(unless (gethash x *list-hash-table*)
(setf (gethash x *list-hash-table*)
(%get-dump-form x))))
(T NIL)))
(defun ANY-CONS-P (X)
"Either a cons, dotted list, or list. Any may be circular."
(and (not (null x))(not (eq x T))
(or (cons-p x)(listp x)(dotted-list-p x))))
(defun STANDARD-STREAM-DUMP-FORM (instance)
"In interface code, *standard-output*, etc. get dumped a lot.
This replaces them with their appropriate global variables."
(cond ((eq instance :STANDARD-OUTPUT) '*STANDARD-OUTPUT*)
((eq instance :TERMINAL-IO) '*TERMINAL-IO*)
((eq instance :STANDARD-INPUT) '*STANDARD-INPUT*)
((eq instance :ERROR-OUTPUT) '*ERROR-OUTPUT*)
(T (warn "Couldnt dump a supposed stream: ~a!" instance))))
(defun STANDARD-STREAM-P (instance)
"Predicate: returns t if instance is oneof STANDARD-OUTPUT,
standard-input, terminal-io, or error-output."
(if (not (streamp instance)) nil
(cond ((eq instance *standard-output*) :STANDARD-OUTPUT)
((eq instance *terminal-io*) :TERMINAL-IO)
((eq instance *standard-input*) :STANDARD-INPUT)
((eq instance *error-output*) :ERROR-OUTPUT)
(T NIL))))
(defun %GET-DUMP-FORM (instance)
"New incarnation of get-dump-form: if the instance is a structured
object, construct a representation for it anticipating that it might
be a PCO. NOTE: in MCL Common Lisp, note that STREAMS are implemented as
CLASSES! This makes it possible to SAVE-OBJECT things like *TERMINAL-IO*!"
(cond ((null instance) nil)
((equal instance T) T)
#+mcl ((ccl::handlep instance)(mac-handle-dump-form instance))
#+CIRCULAR-TESTS ((circular-cons-p instance)(circular-cons-dump-form instance))
#+CIRCULAR-TESTS ((circular-dotted-list-p instance)(circular-dotted-list-dump-form instance))
((numberp instance) instance)
((or (pathnamep instance)
(stringp instance)
(keywordp instance)
(special-marker-p instance)
(characterp instance)) instance)
((packagep instance)(package-dump-form instance))
((quoted-symbol-p instance)(quoted-symbol-dump-form instance))
((symbolp instance)(symbol-dump-form instance))
((vectorp instance)(vector-dump-form instance))
((cons-p instance)(cons-dump-form instance))
((BUILTIN-INSTANCE-P INSTANCE)
(format t "found builtin : ~a~%" instance)
(BUILTIN-INSTANCE-DUMP-FORM INSTANCE))
((standard-stream-p instance)(standard-stream-dump-form (standard-stream-p instance)))
((pco-p instance)(structured-object-dump-form instance))
((arrayp instance)(array-dump-form instance))
;; KOT put this in. Might be wrong for many people, but for my
;; application dumping closures just caused me to have unreadable
;; forms, so I've basically stubbed out closures (as nil) above.
;; I'm unconvinced these can be written portably, do with this what
;; you want.
((closurep instance) (closure-dump-form instance))
#-mcl ((functionp instance) (compiled-function-dump-form instance))
#+mcl ((functionp instance)
(if (ccl::function-name instance)
(compiled-function-dump-form instance)))
((stream-p instance)(stream-dump-form instance))
((readtablep instance)(readtable-dump-form instance))
((repeating-element-list-p instance)(repeating-element-list-dump-form instance))
((dotted-list-p instance)(dotted-list-dump-form instance))
((all-numbers-list-p instance)(all-numbers-list-dump-form instance))
((simple-lex-list-p instance)(simple-lex-dump-form instance))
#-mcl((listp instance)
`(LIST ,@(mapcar #'(lambda (thing)
(get-dump-form thing))
instance)))
#+mcl((listp instance)(list-dump-form instance))
(T (error "could not parse object ~a, of type ~a.~%"
instance (type-of instance)))))
(defun GET-DUMP-FORM (instance)
"New incarnation of get-dump-form: if the instance is a structured
object, construct a representation for it anticipating that it might
be a PCO. NOTE: in MCL Common Lisp, note that STREAMS are implemented as
CLASSES! This makes it possible to SAVE-OBJECT things like *TERMINAL-IO*!"
(when (any-cons-p instance)(index-list instance))
(cond ((null instance) nil)
((equal instance T) T)
#+mcl ((ccl::handlep instance)(mac-handle-dump-form instance))
#+CIRCULAR-TESTS ((circular-cons-p instance)
(or (lookup-list instance)
(circular-cons-dump-form instance)))
#+CIRCULAR-TESTS ((circular-dotted-list-p instance)
(or (lookup-list instance)
(circular-dotted-list-dump-form instance)))
((numberp instance) instance)
((or (pathnamep instance)
(stringp instance)
(keywordp instance)
(special-marker-p instance)
(characterp instance)) instance)
((packagep instance)(package-dump-form instance))
((quoted-symbol-p instance)(quoted-symbol-dump-form instance))
;;; ((quoted-form-p instance)(quoted-form-dump-form instance))
((symbolp instance)(symbol-dump-form instance))
;; ((simple-array-p instance)(simple-array-dump-form instance))
((vectorp instance)(vector-dump-form instance))
((cons-p instance)(cons-dump-form instance))
((BUILTIN-INSTANCE-P INSTANCE)
(format t "found builtin : ~a~%" instance)
(BUILTIN-INSTANCE-DUMP-FORM INSTANCE))
((standard-stream-p instance)(standard-stream-dump-form (standard-stream-p instance)))
((has-predicate-dump-form-p instance)(get-predicate-dump-form instance))
((pco-p instance)(structured-object-dump-form instance))
((arrayp instance)(array-dump-form instance))
;; KOT put this in. Might be wrong for many people, but for my
;; application dumping closures just caused me to have unreadable
;; forms, so I've basically stubbed out closures (as nil) above.
;; I'm unconvinced these can be written portably, do with this what
;; you want.
((closurep instance) (closure-dump-form instance))
#-mcl ((functionp instance) (compiled-function-dump-form instance))
#+mcl ((functionp instance)
(if (ccl::function-name instance)
(compiled-function-dump-form instance)))
((stream-p instance)(stream-dump-form instance))
((readtablep instance)(readtable-dump-form instance))
((repeating-element-list-p instance)
(or (lookup-list instance)
(repeating-element-list-dump-form instance)))
((dotted-list-p instance)
(or (lookup-list instance)(dotted-list-dump-form instance)))
((all-numbers-list-p instance)
(or (lookup-list instance)
(all-numbers-list-dump-form instance)))
((simple-lex-list-p instance)
(or (lookup-list instance)(simple-lex-dump-form instance)))
#-mcl((listp instance)
(or (lookup-list instance)
`(LIST ,@(mapcar #'(lambda (thing)
(get-dump-form thing))
instance))))
#+mcl((listp instance)
(or (lookup-list instance)(list-dump-form instance)))
(T (error "could not parse object ~a, of type ~a.~%"
instance (type-of instance)))))
(defun MAPAPPEND (fun &rest args)
"From the MOP book!"
(if (%some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args)))))
(defun QUOTEIT (l)
(cond ((null l) nil)
((null (first l))
(cons nil (quoteit (rest l))))
((equal (first l) T)
(cons t (quoteit (rest l))))
((not (listp (first l)))
(cons (get-dump-form (first l))(quoteit (rest l))))
((simple-quoted-list-p (first l))
(cons (simple-quoted-list-dump-form (first l))
(quoteit (rest l))))
(T (cons (quoted-list-dump-form (first l))
(quoteit (rest l))))))
(defun SAMESET (l1 l2 &key (test #'equal))
"predicate, returns t if the two sets contain the same elements."
(and (subsetp l1 l2 :test test)(subsetp l2 l1 :test test)))
(defun MAPPLIST (fun x)
"From the MOP book!"
(if (null x) nil (cons (funcall fun (first x)(second x))
(mapplist fun (cddr x)))))
(defun %TYPE-OF (x)
"Special type-of operator, returns more intelligent type for object caching:"
(cond ((%classp x) 'class)
((instance-p x) 'instance)
((structure-p x) 'structure)
((hash-table-p x) 'hash-table)
((typep x 'vector) 'vector)
((array-type-t-p x) 'array-type-t)
((arrayp x) 'array)
((cons-p x) 'cons)
((listp x)(if (circular-list-p x) 'circular-list 'list))
(T (type-of x))))
;;; NOTE: For the following two functions, NCONC should be used to
;;; construct the list ANSWER, not APPEND!
;;;kr010611: i am puzzled by this comment, because it is new in 10A, compared to 9X2.
;;; those functions always used (nconc ) , so what was the issue here ?
;;; but the two versions (%FLATTEN ) and (%FLATTEN1 ) are new, and they seem to use
;;; (append ) . is this necessary ???
(defun FLATTEN (l)
""
(if (circular-list-p l)(flatten (get-circular-list-elements l))
(let ((answers nil))
(dolist (cell l answers)
(setf answers (NCONC answers cell)))
answers)))
(defun FLATTEN1 (cells)
""
(if (circular-list-p l)(flatten1 (get-circular-list-elements l))
(let ((answer nil))
(dolist (cell cells answer)
(setf answer (NCONC answer cell)))
answer)))
(defun %FLATTEN (l)
""
(if (circular-list-p l)(flatten (get-circular-list-elements l))
(let ((answers nil))
(dolist (cell l answers)
(setf answers (APPEND answers cell))) ;;; was NCONC.
answers)))
(defun %FLATTEN1 (cells)
""
(if (circular-list-p l)(flatten1 (get-circular-list-elements l))
(let ((answer nil))
(dolist (cell cells answer)
(setf answer (APPEND answer cell))) ;;; was NCONC.
answer)))
(defun PAIR-UP (l)
""
(let ((answers nil))
(loop (push (list (pop l)(pop l)) answers)
(when (null l)
;;kr010607: used the non-consing (nreverse ) as answers is cons'd from scratch anyway
(return (nreverse answers))))))
(defun GET-ORDERED-SLOT-VALUES (i)
"Gets the dump forms out of the instance slot values, then alphabetizes them"
(cond ((instance-p i)(alphabetize-by-keyword (get-slot-values i)))
((structure-p i)(%%get-defstruct-values i))
(T (error "could not parse object ~a~%" i))))
(defmacro MAKE-KEYWORD (thing)
"Macro which makes a keyword out of a string or a non-string."
(if (keywordp thing) thing
(if (stringp thing)
`(intern ,thing (find-package :keyword))
`(intern (format nil "~A" ,thing) (find-package :keyword)))))
#+ignore
(defun MAKE-KEYWORD (x)
"Makes a keyword out of a symbol."
(if (keywordp x) x (intern (symbol-name x) 'keyword)))
(defun NEWSYM (symbol)
"Similar to GENSYM, but allows access to the gensym counter unlike pre-ANSI
GENSYM."
(if (null (get symbol 'namecounter))
(setf (get symbol 'namecounter) 0))
(read-from-string (concatenate 'string (string symbol)
(format nil "~S"
(incf (get symbol 'namecounter))))))
(defun PSEUDO-QUOTE-READER (stream subchar arg)
"Reader to convert a function spec into a more parsable format."
(declare (ignore subchar arg))
(eval
(list 'quote
(second (read-from-string
(nsubstitute #\space #\#
(concatenate 'string "("
(read-line stream t nil t) ")")
:test #'equal))))))
(defun INSURE-LIST (X)
"If <x> is not a list, it makes (list <x>) and returns it."
(if (listp x) x (list x)))
(defun NASSOC (key list &key (test #'equal))
"Given a key and a list, return the thing AFTER that key in the list.
Similar to GETF."
(let ((where (position key list :test test)))
(when where (nth (1+ where) list))))
(defun MAKEVAR (&optional (label '.%%SL%%.))
"makes a new variable for something in the global object hashtable."
(incf *global-object-count*)
(newsym label))
(defun PUSHSYM (list &optional (label '.%%SL%%.))
"label must match with special-marker-p, and must be upper-case."
(push (newsym label) list))
(defun MAKESYMS (symbol min max &optional (pkg *package*))
(let ((c min))
(progn
;; KOT *nowarn* isn't defined in 4.2, not sure why ...
#+(and excl (not :allegro-v4.2)) (setf excl::*nowarn* T)
#+symbolics (setf compiler::*suppress-compiler-warnings* T)
(dotimes (count max)
(incf c)
(eval `(defvar
,(read-from-string (concatenate 'string
(format nil "~A" symbol)
(format nil "~A" c))
pkg))))
#+(and excl (not :allegro-v4.2)) (setf excl::*nowarn* NIL)
#+symbolics (setf compiler::*suppress-compiler-warnings* NIL)
)))
(defun %INSURE-LIST (X)
"If a list retrns it, if not a list, makes it one."
(if (listp x) x
(list nil x)))
;;; Functions for allocating and maniulating arrays.
(defmacro ALLOCATE-ARRAY (dims &key (element-type t)
(adjustable nil)
(initial-contents nil))
"Function to allocate an array. No fill-pointer.
suggested by [email protected]."
`(make-array ,dims :element-type ,element-type
:initial-contents #-mcl ,initial-contents
#+mcl ,initial-contents
:adjustable ,adjustable))
(defmacro ALLOCATE-VECTOR (dims &key (element-type t)
(adjustable nil)
(fill-pointer nil))
"Function to allocate an array. suggested by [email protected]."
`(make-array ,dims :element-type ,element-type
:adjustable ,adjustable
:fill-pointer ,fill-pointer))
(defun LIST-ARRAY (array)
"Function for converting an n-dimensional array into the kind of list approp
riate for the initial-elements keyword of a make-array function: dump-form-on-p
means that the elements of the array are generated as dump forms, not just
the explict LISP values within the array!"
(list-array-aux array 0 nil :dump-form-on-p T))
(defun %LIST-ARRAY (array)
"Function for converting an n-dimensional array into the kind of list approp
riate for the initial-elements keyword of a make-array function.
DUMP-FORM-ON is NIL. The generated list contains the explicit values which
were in the array, NOT the dump forms! This is used in VECTOR-DUMP-FORM and
ARRAY-DUMP-FORM, among others."
(list-array-aux array 0 nil :dump-form-on-p nil))
#-(or mcl akcl allegro aclpc)
(defun LIST-ARRAY-AUX (array level subscript-list &key (dump-form-on-p T))
"Helper function for coercing an n-dimensional array into a list."
(let ((new-level (1+ level))
(dims (array-dimensions array)))
(loop for i from 0 to (1- (nth level dims))
collect
(cond ((equal level (1- (length dims)))
(let* ((aref-arg-list
(cons array (append subscript-list
(list i))))
(array-val (apply #'aref aref-arg-list)))
(if (numberp array-val) array-val
(if dump-form-on-p (get-dump-form array-val)
array-val))))
(T (list-array-aux array new-level
(append subscript-list (list i)))))
;; (append '(list) temp)
into temp finally (return temp))))
#+(or akcl mcl allegro aclpc)
(defun LIST-ARRAY-AUX (array level subscript-list &key (dump-form-on-p nil))
"Helper function for coercing an n-dimensional array into a list."
(let ((new-level (1+ level))
(dims (array-dimensions array))
(answers nil))
;; was 1- nth level-dims before.
(dotimes (i (nth level dims) answers)
(setf answers (append
answers
(list
(cond ((equal level (1- (length dims)))
(let* ((aref-arg-list
(cons array (append subscript-list
(list i))))
(array-val (apply #'aref aref-arg-list)))
(if (numberp array-val) array-val
(if dump-form-on-p (get-dump-form array-val)
array-val))))
(T (list-array-aux array new-level
(append subscript-list
(list i)))))))))
answers))
(defun CLEAR-GLOBAL-VARS-AND-HTABS ()
"Initializes the SAVE-OBJECT enviroment for recording graph cycles."
(setf *classes-seen* nil *class-vars* nil)
(setf *structs-seen* nil *struct-vars* nil)
(setf *vectors-seen* nil *vector-vars* nil)
(setf *arrays-seen* nil *array-vars* nil)
(setf *htabs-seen* nil *htab-vars* nil)
(setf *seen* nil *vars* nil)
(clrhash *save-object-hash-table*))
;;; Functions for manipulating hash tables....
(defun %LOAD-HTAB (htab &optional lst)
""
(loop
(when *debug-htab-load* (format t "setting slot ~a to ~a.~%"
(first lst)(second lst)))
(setf (gethash (pop lst) htab)(pop lst))
(when (null lst)(return htab))))
;;; Map lucid/allegro htab incompatibility of rehash threshold
;;; parameter into mutually acceptable values. (i.e. fix bug)
#+lucid
(defun SCALE-REHASH-THRESHOLD (num)
(if (> num 1)(float (/ num 100)) num))
#+allegro
(defun SCALE-REHASH-THRESHOLD (num)
(if (<= num 1)(* num 100) num))
#-(or allegro lucid)
(defun SCALE-REHASH-THRESHOLD (num)
num)
(defun MAKEHASH (h &key (test #'eql)
(size 5000)
(rehash-size 67)
(rehash-threshold 0.65)
values)
""
(let ((htab (or h
(make-hash-table
:test test
:size size
:rehash-size rehash-size
:rehash-threshold (scale-rehash-threshold rehash-threshold)
))))
(if (null values) htab
(progn (%load-htab htab values) htab))))
(defun GET-HTAB-VALUES (htab)
(let ((values nil))
(maphash #'(lambda (key val)
(push (get-dump-form val) values)
(push (get-dump-form key) values))
htab) values))
(defun PRINT-HTAB (htab)
(maphash #'(lambda (key val)
(format t "~%Key: ~a, value=~a.~%" key val))
htab))
;;; Now, the Symbolics....
#+lispm
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun HASH-TABLE-SIZE (x)
(scl:send x :size))
(defun HASH-TABLE-TEST (x)
(si:function-name (cli::test-function x)))
)
(defun CREATE-HASH-TABLE (&key (test #'eql)
(size 67)
(rehash-size nil)
(rehash-threshold nil))
(let ((args (delete ;;kr010611: to avoid cons'ing, use (delete ) here instead of (remove ). should be safe.
;;remove
nil
`(:size ,(get-dump-form size)
:test ,test
,@(when rehash-size
(list :rehash-size
(get-dump-form rehash-size)))
,@(when rehash-threshold
(list :rehash-threshold
(get-dump-form rehash-threshold)))))))
(cache-object (apply #'make-hash-table args) :mode :load)))
(defun LOAD-HTAB (values &key (test #'eql)
(size 67)
(rehash-size nil)
(rehash-threshold nil))
""
(let ((htab (create-hash-table :test test
:size size
:rehash-size rehash-size
:rehash-threshold rehash-threshold))
(key nil)(val nil))
(dolist (cell values)
(setf key (first cell))
(setf val (eval (second cell)))
(setf (gethash key htab) val))))
;;; Defstruct access functions.
(defun GET-DEFSTRUCT-TYPE (structname)
""
(if (structure-p structname)(type-of structname)
(let ((desc (get-defstruct-descriptor structname)))
(funcall *vendor-defstruct-type-function* desc))))
;;; KOT wrapped eval-when around this -- in Allegro-V4 at least, allowed the
;;; succeeding (setf (symbol-function 'structurep)) to compile (???).
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun STRUCTURE-P (X)
"Predicate: returns T if x is a structure instance!"
(funcall *vendor-defstruct-predicate-function* x)))
#-aclpc
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'structurep) #'structure-p)
) ;; end of eval-when....
(defun GET-DEFSTRUCT-DESCRIPTOR (structname)
""
(when (structure-p structname)
(setf structname (get-defstruct-name structname)))
(funcall *vendor-defstruct-descriptor-function* structname))
(defun GET-DEFSTRUCT-SLOT-DESCRIPTORS (structname)
""
(when (structure-p structname)
(setf structname (get-defstruct-name structname)))
(funcall *vendor-defstruct-slot-descriptors-function* structname))
(defun GET-DEFSTRUCT-SLOT-DESCRIPTOR (structname slotname)
""
(dolist (slot (get-defstruct-slot-descriptors structname))
(when (equal slotname (get-defstruct-slot-name slot))
(return slot))))
;;; KOT wrapped eval-when around this, in Allegro-V4 allows better compilation
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
;;kr010615: this fn is called quite a bit further below in this file.
;; generally, this all seems a bit cumbersome, as it is not immediately apparent
;; where those generated functions came from when debugging.
(defun MAKE-DEFSTRUCT-ACCESS-FUNCTIONS ()
"Automatically generates the functions we need to access the
components of the defstruct object and its instances."
(let* ((kwd-list '(:print-function :predicate :include
:constructor :copier :documentation :conc-name))
(kwd-slot-list '(:name :type :read-status :default-value :position))
(answers nil))
(dolist (kwd kwd-slot-list)
;;; This next EVAL seems to have problems in MCL 2.0.1:
(pushnew (EVAL `(defun
,(read-from-string (concatenate 'string
"GET-DEFSTRUCT-SLOT-"
(symbol-name kwd)))
(slotd)
(defstruct-slot-descriptor-ref slotd ,kwd)))
answers))
(dolist (kwd kwd-list)
(pushnew (EVAL `(defun
,(read-from-string (concatenate 'string
"GET-DEFSTRUCT-"
(symbol-name kwd)))
(struct)
(let ((desc (get-defstruct-descriptor struct)))
(when (null desc)
(format t "WARNING: desc was NULL!~%"))
(defstruct-descriptor-ref desc ,kwd))))
answers))
;;kr010615: from what i can tell, the above construction s ensure that the resulting
;; functions are only interpretated, which seems awfully slow, given this overall hack.
;; so, i am adding a compilation stage here, to at least make use of the otherwise pointless
;; collection of all these functions in the answers list.
(map nil #'compile answers)
answers
)))
(defun GET-INDEX-FOR-DD-KWD (kwd)
(funcall *vendor-data-table-access-function*
(cdr (assoc kwd *vendor-defstruct-desc-index-table*
:test #'equal))))
(defun GET-INDEX-FOR-SD-KWD (kwd)
(funcall *vendor-data-table-access-function*
(cdr (assoc kwd *vendor-defstruct-slot-desc-index-table*
:test #'equal))))
(defun SD-USE-DEFAULT (sd kwd &optional structname)
""
(let* ((sdname
(symbol-name (defstruct-slot-descriptor-ref sd :name))))
(cond ((equal kwd :accessor)
(return-from sd-use-default
(read-from-string
(concatenate 'string (symbol-name structname)
"-" sdname)))))))
(defun DD-USE-DEFAULT (dd kwd)
""
(let* ((name (defstruct-descriptor-ref dd :name))
(sname (symbol-name name))
(kwds '((:copier "COPY-")
(:constructor "MAKE-")))
(the-one (second (assoc kwd kwds :test #'equal))))
(when the-one (return-from dd-use-default
(read-from-string (concatenate 'string the-one sname))))))
(defun DEFSTRUCT-DESCRIPTOR-REF (desc kwd)
"Vendor independent function to extract defstruct info from a defstruct
descriptor."
(let ((i (get-index-for-dd-kwd kwd)))
(cond ((null i)
(funcall *vendor-defstruct-desc-access-function* desc))
((equal i T)(dd-use-default desc kwd))
((numberp i)(apply *vendor-defstruct-desc-access-function*
(list desc i)))
((compiled-function-p i)(funcall i desc))
((symbolp i)(slot-value desc i))
((and (listp i)(equal (first i) 'function))
(funcall (eval i) desc))
(T (error "not a valid index type: ~s~%" i)))))
(defun DEFSTRUCT-SLOT-DESCRIPTOR-REF (sd kwd &optional structname)
"Given a slot descriptor and a keyword, return the value for that
keyword. If the kewyord value is T, that means we dont really know
how to do it, and to use the default function for that keyword."
(let ((i (get-index-for-sd-kwd kwd)))
(cond ((null i)
;;kr010212: had to pass argument i as well. did anybody ever try this before ???
(funcall *vendor-defstruct-slot-desc-access-function* sd 0))
((equal i T)(sd-use-default sd kwd structname))
((numberp i)
(funcall *vendor-defstruct-slot-desc-access-function* sd i))
((compiled-function-p i)(funcall i sd))
((symbolp i)(slot-value sd i))
((and (listp i)(equal (first i) 'function))
(funcall (eval i) sd))
(T (error "not a valid index type: ~s~%" i)))))
#+aclpc
(defun GET-DEFSTRUCT-SLOT-NAMES (struct)
"Gets an unordered list of the structs slotnames."
(let* ((desc (get-defstruct-slot-descriptors (get-defstruct-name struct))))
(when desc (mapcar #'first desc))))
#-aclpc
(defun GET-DEFSTRUCT-SLOT-NAMES (struct)
"Gets an unordered list of the structs slotnames."
(let* ((slotds (get-defstruct-slot-descriptors (get-defstruct-name struct)))
(names (mapcar #'(lambda (slotd)
(get-defstruct-slot-name slotd))
slotds)))
names))
(defun FILL-STRUCT (struct vals)
"Fills the structure instance struct with the values vals."
(when (symbolp struct)(setf struct (allocate-struct struct)))
(dolist (slotname (get-defstruct-slot-names struct) struct)
;;;; (format t "Slot name:~s, Value: ~s~%" slotname (first vals))
(set-defstruct-slot-value struct slotname (pop vals)))
struct)
(defun ALLOCATE-STRUCT (name)
"Function to allocate the empty husk of a defstruct."
(apply (get-defstruct-constructor name) nil))
(defun FIND-STRUCTURE-OBJECT (name)
"Now its just get-defstruct-descriptor, but it might get mor elaborate."
(get-defstruct-descriptor name))
(defun GET-NAME-FROM-OPTION-LIST (option-list)
""
;; KOT put in declare, but what is the use of this??
(declare (ignore option-list))
)
(defun CONSTRUCT-DEFSTRUCT-OPTION-LIST (name)
"Given a defstruct descriptor, make an option list for that descriptor."
(cond ((structure-p name))
((symbolp name))
(T NIL)))
(defun CONSTRUCT-DEFSTRUCT-SLOT-LIST (name)
"Given a defstruct descriptor, make a slot list for that descriptor."
(let* ((slist (get-defstruct-slot-descriptors name))
(answers nil))
(dolist (slot slist (nreverse answers))
(let ((name (get-defstruct-slot-name slot))
(value (get-defstruct-slot-default-value slot))
(read-status (get-defstruct-slot-read-status slot))
(type (get-defstruct-slot-type slot)))
(push (make-canonical-defstruct-slot-form
name value read-status type)
answers)))))
(defun MAKE-CANONICAL-DEFSTRUCT-SLOT-FORM
(name value read-status type)
`( ,(get-dump-form name)
,(get-dump-form value)
:type ,(get-dump-form type)
:read-only ,(get-dump-form read-status)))
(defun NO-OPTION-BUT-NAME-p (option-list)
"Inline predicate: "
;; KOT put in declare, but what is the use of this??
(declare (ignore option-list)
(inline no-option-but-name-p))
)
(defun ENSURE-DEFSTRUCT-CLASS-OBJECT (option-list doc-string slots)
""
(when (null doc-string)(setf doc-string ""))
`(or (find-structure-object ,(get-name-from-option-list option-list))
(defstruct ,option-list ,doc-string ,@slots)))
;;; KOT couldn't the lambda-list here just be (name &allow-other-keywords)?
#+ignore
(defun MAKE-STRUCTURE-OBJECT (name
&key type
lisp-type
(copier nil)
(predicate nil)
(constructor nil)
slots
conc-name
named
include
(documentation ""))
""
`(defstruct ,(make-defstruct-option-list :name name)
,documentation ,@slots)
)
(defun MAKE-DEFSTRUCT-PRINT-FUNCTION (name)
""
(if *use-default-defstruct-options-in-save*
nil
(get-defstruct-print-function name)))
(defun MAKE-DEFSTRUCT-COPIER (name)
""
(if *use-default-defstruct-options-in-save*
(read-from-string (concatenate 'string "COPY-"
(format nil "~A" name)))
(get-defstruct-copier name)))
(defun MAKE-DEFSTRUCT-CONSTRUCTOR (name)
""
(if *use-default-defstruct-options-in-save*
(read-from-string (concatenate 'string "MAKE-"
(format nil "~A" name)))
(get-defstruct-constructor name)))
(defun MAKE-DEFSTRUCT-PREDICATE (name)
""
(if *use-default-defstruct-options-in-save*
(read-from-string (concatenate 'string
(format nil "~A" name) "-P" ))
(get-defstruct-predicate name)))
(defun MAKE-DEFSTRUCT-CONC-NAME (name)
""
(if *use-default-defstruct-options-in-save*
(read-from-string (concatenate 'string
(format nil "~A" name) "-" ))
(get-defstruct-conc-name name)))
;;; KOT couldn't the lambda-list here just be (name &allow-other-keywords)?
#+ignore
(defun MAKE-DEFSTRUCT-OPTION-LIST (&key name
(copier name)
(include name)
(predicate name)
(constructor name)
(conc-name name))
""
`(,name (:copier ,(make-defstruct-copier name))
(:include ,(make-defstruct-include name))
(:predicate ,(make-defstruct-predicate name))
(:constructor ,(make-defstruct-constructor name))
(:print-function ,(make-defstruct-print-function name))
(:conc-name ,(make-defstruct-conc-name name))))
(defun MAKE-FUNCTION-PLACEHOLDER (name)
""
(setf (symbol-function name)
#'(lambda (&rest ignore) (declare (ignore ignore)) nil)))
(defun STRUCTURE-DUMP-FORM (instance)
"Independent of vendor: make-defstruct-values was UNquoted."
`(fill-struct ,(get-instance-label instance)
(LIST ,@(get-defstruct-values instance))))
(defun DEFSTRUCT-OBJECT-DUMP-FORM (instance)
"The dump form for defstruct 'classes'."
(let* ((struct-name (get-defstruct-name instance))
(option-list (construct-defstruct-option-list struct-name))
(doc-string (get-defstruct-documentation struct-name))
(slot-def-list (construct-defstruct-slot-list instance)))
`(ensure-defstruct-class-object ,(get-dump-form option-list)
,(get-dump-form doc-string)
,slot-def-list)))
(defvar *ordered-slot-name-htab* (make-hash-table))
(defun LOOKUP-ORDERED-SLOT-NAMES (i)
"NEW: instead of re-calculating the slotnames every time, and sorting them alphabetically,
we cache the sorted list once and refer to it in the hash table. The hash table gets
cleared by SAVE-OBJECT main routine."
(or (gethash (instance-name i) *ordered-slot-name-htab*)
(let ((them
;;kr010610: as (all-slotnames ) presumably is returning a
;; freshly cons'd list, i changed the (remove ) to the
;; destructive (delete ) to avoid even more pointless
;; cons'ing. furthermore, rearranged things such that the
;; nil's are removed before the sort'ing starts.
;;(remove nil (sort (all-slotnames i) #'sym<))
(sort (delete nil (all-slotnames i)) #'sym<)
))
(setf (gethash (instance-name i) *ordered-slot-name-htab*)
them)
them)))
(defun GET-ORDERED-SLOT-NAMES (i)
"Returns a list of the slot names of the instance, alphabetized."
(cond ((instance-p i)(lookup-ordered-slot-names i))
((structure-p i)#-excl (get-defstruct-slot-names i) ;;kr010612: i fixed this presumed typo (get-defstruct-slotnames i)
#+excl (%get-defstruct-slotnames i) ;; ?? this fn doesn't exist in this file...
)
(T (error "couldnt parse object ~a!" i))))
(defun ALLOCATE-HTAB (htab &rest arglist)
"Allocates the empty husk of a hash table,
getting its attributes from the object itself."
(declare (ignore htab))
(let ((size (getf arglist :size))
(rehash-size (getf arglist :rehash-size))
(test (getf arglist :test))
(rehash-threshold (getf arglist :rehash-threshold)))
(make-hash-table :size size
:rehash-size rehash-size
:rehash-threshold
(scale-rehash-threshold rehash-threshold)
:test test)))
(defun GET-CLASS-DOCUMENTATION (c)
""
(or (get-documentation c) ""))
(defun GET-AVAILABLE-TYPES (symbol)
"Returns a list of the types this symbol represents."
;; KOT this first (if) creates a special variable 'answers', should the let
;; be earlier?? RIGHT, FIXED IT, kvk
(let ((answers nil))
(if (not (symbolp symbol))
(push (type-of symbol) answers)
(return-from get-available-types answers))
(if (boundp symbol)(push 'symbol answers))
(if (fboundp symbol)(push 'function answers))
(if (classp symbol)(push 'class answers))
answers))
;;; Vendor independent, PCL/CLOS independent CLOS functions.
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun %GET-SLOT-INITFORM (S)
"Method to create the initform pair, if there is an initform value!"
(list :initform (get-dump-form (EVAL (get-slot-initform s)))))
(defun PAIR-SLOTNAMES (instance)
"Makes an alist of the slotnames with their 'stripped' values."
(let ((slots (all-slotnames instance)))
(pairlis (mapcar #'strip-package slots) slots)))
(defun FIND-PACKAGED-SLOTNAME (instance stripped)
"Given the slotname WITHOUT package, find the slotname WITH package."
(let ((choices (pair-slotnames instance)))
(rest (assoc stripped choices :test #'equal))))
(defun SLOT-VALUE-ANY (instance stripped)
"Find the value of the real slot given the stripped name."
(let ((slotname (find-packaged-slotname instance stripped)))
(when slotname (if (slot-boundp instance slotname)
(slot-value instance slotname)
*unbound-slot-token*))))
(defun GET-UNSAVEABLE-SLOTNAMES (instance)
"Returns a list of the slotnames in instance, or the slotnames
in the class of instance, which have been marked as unsaveable,
appended to the list of *global-unsaveable-slotnames*"
(append (copy-list *global-unsaveable-slotnames*)
(slot-value-any instance 'unsaveable)))
) ;; end of pcl/clos eval-when....
#-(or pcl :SBCL)
(defun GET-DOCUMENTATION (object)
""
(or (documentation object) nil))
;;;kr010208: copied this from the PCL case above:
#+:SBCL
(defun GET-DOCUMENTATION (object)
""
(let ((answers nil))
(dolist (current-type (get-available-types object)(nreverse answers))
(push (documentation object current-type) answers))))
#+ignore
(defun GET-INSTANCE-LABEL (instance)
""
(if (instance-p instance)(get-dump-form (instance-name instance))))
(defun GET-INSTANCE-LABEL (instance)
""
(let* ((lists (if (%classp instance)
(list *classes-seen* *class-vars*)
(case (%type-of instance)
(INSTANCE (list *seen* *vars*))
(STRUCTURE (list *structs-seen* *struct-vars*))
(HASH-TABLE (list *htabs-seen* *htab-vars*))
(otherwise (error "Couldnt parse ~a, of type ~a!"
instance (type-of instance)))))))
(let* ((instance-list (first lists))
(var-list (second lists))
(where (position instance instance-list :test #'equal)))
(if (null where)
(progn (format t "~a was not on the seen list!, creating!~%"
instance)
(case (%type-of instance)
(INSTANCE
(return-from get-instance-label
(get-dump-form (instance-name instance))))
(STRUCTURE
(return-from get-instance-label
(get-dump-form (get-defstruct-name instance))))))
(return-from get-instance-label (nth where var-list))))))
(defun DO-VAR-TYPE-CELLS (vars insts)
"Turns (a b c) and (1 2 3) into ((a 1)(b 2)(c 3))."
(mapcar #'(lambda (a b)(list a b))
vars insts))
(defun MAKE-VAR-TYPE-CELLS (vars insts &optional plists samep)
"An auxilary function for MAKE-LET-FORM..."
(let ((htab-plist (if samep (mapcar #'get-dump-form (first plists))))
(count -1))
(mapappend
#'(lambda (cell)
(incf count)
(list (list (first cell)
(append
(list '%allocate-instance
`(QUOTE ,(instance-name (second cell))))
(if samep htab-plist
(mapcar #'get-dump-form
(nth count plists)))))))
(do-var-type-cells vars insts))))
(defun MAKE-HTAB-PLIST (htab)
"makes a plist for a hash tables inner attributes!"
(list :size (hash-table-size htab)
:rehash-size (hash-table-rehash-size htab)
:test (hash-table-test htab)
:rehash-threshold (hash-table-rehash-threshold htab)))
(defun MAKE-HTAB-PLISTS (list-o-htabs)
"takes a list of htabs: checks to see if the plists are the same,
multiple value return of the attribute plist(s), and whether they
are the same (T or NIL)."
(let ((answers nil)(new-plist nil))
(dolist (htab list-o-htabs answers)
(setf new-plist (make-htab-plist htab))
(push new-plist answers))
(let ((samep (all-htab-plists-samep list-o-htabs)))
(if samep (values (list (first answers)) T)
(values answers NIL)))))
(defun MAKE-ILIST-VAR-TYPE-CELLS (to-be-saved-list)
(declare (ignore to-be-saved-list))
(delete nil (make-var-type-cells *vars* *seen*)))
(defun MAKE-LIST-VAR-TYPE-CELLS (to-be-saved-list)
"SEQUENCES need the whole ball of wax."
(declare (ignore to-be-saved-list))
(multiple-value-bind (plists samep)
(make-htab-plists *htabs-seen*)
(let* ((insts (make-var-type-cells *vars* *seen*))
(classes (make-var-type-cells *class-vars* *classes-seen*))
(structs (make-var-type-cells *struct-vars* *structs-seen*))
(htabs (make-var-type-cells *htab-vars* *htabs-seen*
plists samep))
(end-result (NCONC classes insts structs htabs)))
(when *debug-local-bindings* (format t "~%~A~%" end-result))
(delete nil end-result))))
(defun MAKE-LET-FORM (object &optional other-code)
"This functions constructs the lexical environment for the text
representation of LISP objects --- without this, there could be no self
refererence!"
(cond ((compiled-function-p object)(get-dump-form object))
#|;;kr010615: this is in the wrong location and captures what (cons-p )
;; should take care of. additionally, it is just plain incorrect...
((dotted-list-p object)
(return-from make-let-form (get-dump-form object)))
|#
((simple-list-p object)`(LIST ,@object))
((%classp object)
`(let* ,(make-list-var-type-cells object)
,other-code))
((equal (%type-of object) 'instance)
`(let* ,(make-list-var-type-cells object)
,other-code))
((equal (%type-of object) 'structure)
`(let* ,(make-list-var-type-cells object)
,other-code))
((equal (%type-of object) 'hash-table)
`(let* ,(make-list-var-type-cells object)
,other-code))
((equal (%type-of object) 'circular-list)
`(progn ,other-code))
((equal (%type-of object) 'vector)
`(let* ,(make-list-var-type-cells object) ,other-code))
((equal (%type-of object) 'array)
`(let* ,(make-list-var-type-cells object) ,other-code))
((cons-p object)
`(let* ,(make-list-var-type-cells object) ,other-code))
;;kr010615: had to move dotted lists down here (from second highest position)
;; and repaired it to use (make-list-var-type-cells ) as well
((dotted-list-p object)
`(let* ,(make-list-var-type-cells object) ,other-code))
;; ((simple-list-p object)`(progn ,other-code))
((quoted-list-p object)`(progn ,other-code))
((all-instance-list-p object)
`(let* ,(make-ilist-var-type-cells object)
,other-code))
((LISTP object)
`(let* ,(make-list-var-type-cells object)
,other-code))
(T (warn "FROM MAKE LET FORM: object was of bogus type: ~A!!!"
(%type-of object))
(if other-code `(progn ,other-code)
(progn (warn "there was no code to enclose!") nil)))))
(defun MAP-NONCIRCULAR-ELEMENTS-AND-COPY (function circ-list)
""
(let ((elts (mapcar function
(copy-list (get-circular-list-elements circ-list)))))
(make-circular-list elts)))
#|;;;kr010607: commented this out, whatever it may be. this is not used anywhwere,
;;; but it refers to the fn (mapstruct ) , which is defined nowhere, resulting in
;;; a compiler warning.
;;;
(defun MAP-OBJECT (function object)
"Generalized iterator for PCOs."
(cond ((circular-list-p object)
(map-noncircular-elements-and-copy function object))
((vectorp object)
#-(or akcl excl) ;; Lucid, Symbolics, CMU OK.
(loop for count from 0 to (1- (length object)) do
(setf (aref object count)
(funcall function (aref object count)))
finally (return object))
#+(or akcl excl)
(dotimes (count (1- (length object)) object)
(setf (aref object count)(funcall function (aref object count))))
)
((arrayp object)(map-array function object))
((structure-p object)(mapstruct function object))
((hash-table-p object)(maphash #'(lambda (key val)
(setf (gethash key object)
(funcall function val)))
object) object)
((instance-p object)(map-instance function object))
(T (warn "Couldnt deal with object ~a, type: ~a.~%"
object (type-of object)))))
|#
;;; Functions and Generic Functions.
#+mcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun GET-SLOT-NAME (s)
(ccl::slot-definition-name s))
(defun GENERIC-FUNCTION-NAME (instance)
(get-compiled-function-name instance))
(defun GENERIC-FUNCTION-LAMBDA-LIST (gf)
""
(function-lambda-expression gf))
(defun %GENERIC-FUNCTION-P (X)
""
(ccl::standard-generic-function-p x))
(defun METHOD-SPECIALIZERS (method)
""
(ccl:specializer-direct-generic-functions method))
(defun METHOD-GENERIC-FUNCTION (gf)
""
(ccl:method-generic-function gf))
) ;; end of MCL function & generic function eval-when!
#+allegro-v4.0
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun HASH-TABLE-TEST (htab)
#'eql)
(defun HASH-TABLE-SIZE (htab)
32)
) ;; end of allegro ver 4.0 eval-when....
(defun PARSE-HASH-TABLE-SPEC (htab)
(let ((ans nil)
(*readtable* (copy-readtable)))
(set-dispatch-macro-character #\# #\' (function pseudo-quote-reader))
(set-dispatch-macro-character #\# #\< (function pseudo-quote-reader))
(setq ans (rest (butlast (read-from-string
(concatenate 'string "("
(subseq (format nil "~a" htab) 8)
")")))))
ans))
(defun PARSE-DEFSTRUCT-SPEC (struct)
(let ((ans nil)
(*print-readably* t)
(*readtable* (copy-readtable)))
(set-dispatch-macro-character #\# #\' (function pseudo-quote-reader))
(set-dispatch-macro-character #\# #\< (function pseudo-quote-reader))
(set-dispatch-macro-character #\# #\S (function pseudo-quote-reader))
(setq ans (subseq (format nil "~a" struct) 3))
(setq ans (subseq ans 0 (position #\space ans)))
(read-from-string ans)))
(defun GET-DEFSTRUCT-NAME (instance)
"Given a defstruct instance, return the symbol which is its name."
;; This is an ugly way of doing this, and relies on the print-function
;; correctly taking *print-readably* into account.
;;(parse-defstruct-spec instance)
;; Kerry suggests just changing to this, though he says not always correct
;; KOT -- how could this not be correct??
(type-of instance)
)
#+rel8
(defun HASH-TABLE-REHASH-SIZE (x)
""
(future-common-lisp:hash-table-rehash-size x))
#+rel8
(defun HASH-TABLE-REHASH-THRESHOLD (x)
""
(future-common-lisp:hash-table-rehash-threshold x))
#|;;;kr010602: why the hell would this outdated crap fire ??? seems to mess up
;;; the hash-table stuff, so it is better to comment it out totally !
#+cmu
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (not (fboundp 'cl::hash-table-test))
(defun HASH-TABLE-TEST (htab)
""
(declare (ignore htab))
#'eql)
)
(when (not (fboundp 'cl::hash-table-size))
(defun HASH-TABLE-SIZE (htab)
""
101)
)
) ;; end of cmu eval-when...
|#
#+akcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (not (fboundp 'hash-table-test))
(defun HASH-TABLE-TEST (htab)
""
#'eq)
)
(when (not (fboundp 'hash-table-rehash-size))
(defun HASH-TABLE-REHASH-SIZE (htab)
""
101)
)
(when (not (fboundp 'hash-table-rehash-threshold))
(defun HASH-TABLE-REHASH-THRESHOLD (htab)
""
0.5)
)
) ;; end of AKCL hash table eval-when...
#+rel-7-2
(defun HASH-TABLE-REHASH-SIZE (x)
""
(let ((spec (parse-hash-table-spec x)))
(getf spec :rehash-size 32)))
#+rel-7-2
(defun HASH-TABLE-REHASH-THRESHOLD (x)
""
(let ((spec (parse-hash-table-spec x)))
(getf spec :rehash-threshold 0.5)))
(defun UNBOUND-SLOT-TOKEN-P (x)
"Predicate: "
(and (symbolp x)(equal x *unbound-slot-token*)))
(defun FILL-INSTANCE (classname vals)
"New: allocates an instance given classname, the vals are the alphabetized
list of slot values extracted from the target instance. returns the
newly filled in instance."
(let* ((new (%allocate-instance classname)))
(%fill-instance new vals)
new))
;;;kr010606: for the time being, disable this for sbcl, so it does not overwrite the previous definition above
;;;
#-(or pcl :SBCL)
(defun %ALLOCATE-INSTANCE (class-object &rest htab-plist)
(cond ((instance-p class-object) class-object)
((equal class-object 'HASH-TABLE)
(allocate-htab class-object
:size (getf htab-plist :size 5000)
:rehash-size (getf htab-plist :rehash-size 67)
:rehash-threshold (getf htab-plist
:rehash-threshold 0.67)
:test (getf htab-plist :test #'eql)))
((symbolp class-object)
;; KOT hackery -- Allegro
#+(or allegro-v4.1 allegro-v4.2)
(let ((class (find-class class-object nil)))
(cond
((and class (eq (type-of class) 'structure-class))
(allocate-struct class-object))
(class (clos::allocate-instance class))))
#-(or allegro-v4.1 allegro-v4.2)
(let ((class-object (find-class class-object nil)))
(when class-object
;;kr010120: added SBCL support
#-(or pcl aclpc sbcl)
;;kr010120: the CLOS package is probably totally outdated...
(clos::allocate-instance class-object)
#+pcl (pcl::allocate-instance class-object)
#+(or aclpc sbcl)(allocate-instance class-object)
)))
((%structure-p class-object)
;;kr010120: added SBCL support
#-(or aclpc pcl excl :sbcl)(clos::allocate-instance class-object)
#+cmu (pcl::allocate-instance class-object)
#+(or aclpc :sbcl)(allocate-instance class-object)
#+allegro-v4.0(%%allocate-instance class-object)
#+(or allegro-v4.1 allegro-v4.2)(allocate-struct class-object)
)
(T (when *debug-instance-storage*
(format t "now trying to allocate an instance for ~a!"
class-object))
nil)))
;;; *** Beginning of CLOS eval-when... ***
#+clos
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun CLASSP (x)
"Predicate, determines whether the object x is a class object."
(typep x 'standard-class))
;; KOT this gets done later as more complex thing for excl, why duplicate??
(defun %CLASSP (x)
"Predicate, determines whether the object x is a class object."
(classp x))
;; KOT this gets done later for allegro-v4, maybe conditionalize here??
;; NOTE: this one should really have a test to include CLASSES? kvk
#-(or mcl :allegro-v4.0 :allegro-v4.1 :allegro-v4.2)
(defun INSTANCE-P (x)
""
(and (NOT (%CLASSP x)) ;;; new clause of test, kvk
(typep x 'standard-object)))
;; ALLOCATE INSTANCE methods on STRUCTURE CLASS, for those which dont have
;; them.
#+allegro-v4.0
;; KOT this eval-when is redundant -- maybe just progn? That's obscure
;; questions of what should be at top-level and what shouldn't ...
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod CLOS::ALLOCATE-INSTANCE ((self clos:structure-class)
&rest initargs)
(declare (ignore initargs))
(allocate-struct (instance-name self)))
(defmethod %%ALLOCATE-INSTANCE ((self clos:structure-class))
(allocate-struct (instance-name self)))
(defmethod %%ALLOCATE-INSTANCE ((self symbol))
(if (get-symbol-defstruct-spec self)
(allocate-struct self)))
(defmethod CLOS::ALLOCATE-INSTANCE ((self symbol) &rest init-plist)
(allocate-struct self))
) ;; end of allegro ver4.0 eval-when...
;; *** BEGINNING OF NON-MCL definitions! ***
#-(or akcl mcl pcl)
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun GET-CLASS-DEFAULT-INITARGS (class)
"Gets the default-initargs out of the class object."
(mapcan #'(lambda (l)
(list (first l)(get-dump-form (third l))))
#-aclpc(clos::class-direct-default-initargs class)
#+aclpc(class-direct-default-initargs class)
))
(defmethod ALL-SLOTNAMES ((instance T) &optional (all-allocations T))
"returns the names of the slots in instance, uses what MOP stuff
is available."
;; KOT put this in, probably just there for lambda-list equivalency
(declare (ignore all-allocations))
#-aclpc
(mapcar #'clos::slot-definition-name
;; KOT patch
;;(clos::class-DIRECT-slots (clos::class-of instance))
(clos::class-slots (clos::class-of instance))
)
#+aclpc
(mapcar #'slot-definition-name
(class-DIRECT-slots (class-of instance)))
)
;;******
) ;; end of non-MCL definitions eval-when...
;; *** Allegro non-MCL eval-when (e.g. on Suns.) ***
#+excl
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun GET-SLOT-READERS (slot-object)
(clos::slotd-readers slot-object))
(defun GET-SLOT-WRITERS (slot-object)
(clos::slotd-writers slot-object))
(defun GET-SLOT-ALLOCATION (S)
"Method to get the type of allocation from a standard slot:
one of :CLASS or :INSTANCE."
(let ((alloc (clos::slotd-allocation s)))
(cond ((%classp alloc) :CLASS)
((member alloc '(:INSTANCE :CLASS)) alloc)
(T :INSTANCE))))
(defun GET-SLOT-NAME (S)
"Method to get the name from a standard slot."
(clos::slotd-name s))
(defun %CLASSP (X)
"Predicate, determines whether the object x is a class object."
(or (typep x 'clos::standard-class)(typep x 'clos::built-in-class)))
(defmethod GET-SLOT-INITFORM (s)
""
(when (slot-boundp s 'clos::initform)
(clos::slotd-initform s)))
(defun SLOT-HAS-AN-INITFORM-P (s)
(clos::slotd-initform s))
(defun GET-SLOT-INITARGS (s)
(clos::slotd-initargs s))
(defun GET-SLOT-INITARG (s)
(first (clos::slotd-initargs s)))
(defun BUILTIN-CLASS-P (X)
"Predicate to determine whether class object is a builtin class. returns
T if it is."
(and (%classp x)(typep x 'clos::built-in-class)))
#+(or allegro-v4.1 allegro-v4.2)
(defun INSTANCE-P (X)
"With the 4.0 series, structures are instances as well: exclude these."
(and (not (typep x 'clos::structure-class))
(not (%classp x))(excl::standard-instance-p x)))
#+allegro-v4.0
(defun INSTANCE-P (X)
"With V4.0, structures are instances as well: exclude these:
NOTE, removed the clause testing for clos:structure-object."
(not (%classp x))(excl::standard-instance-p x))
(defun GET-SLOT-DOCUMENTATION (s)
""
(or (documentation s) ""))
) ;; *** end of non-MCL Allegro (like Sun Allegro) CLOS eval-when. ***
;; *** Lisp Machine Genera 8.x CLOS eval-when. ***
#+lispm
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun ALL-SLOTS (instance)
"Gets all the slots from the instances class, whether inherited or not."
(clos::class-slots (clos::class-of instance)))
(defun GET-SUPERCLASS-NAMES (class)
""
(mapcar #'clos::class-name (clos::class-direct-superclasses class)))
(defun %GENERIC-FUNCTION-P (x)
"Predicate, returns t for generic functions. causes symbol conflict
problem in genera 8.0."
(clos-internals::generic-function-p x))
(defun BUILTIN-CLASS-P (class-object)
"Predicate to determine whether a class object (that which is returned
by (FIND-CLASS <NAME>)) is a BUILTIN class or not."
(typep class-object 'clos:built-in-class))
(defmethod CLASS-NAME ((object t))
"We use this in %classp. we already know its either an instance or a
class. if its an instance, it has no name. CLASS-NAME on standard class
takes care of real class objects."
nil)
(defun %CLASSP (X)
"The function CLASSP is not defined at all in Genera."
(and (instance-p x)(find-class (class-name x) nil)))
(defun INSTANCE-P (x)
"This will work in Genera 8x CLOSes: filters out entities that are
flavor instances. Also filters out things that are defstruct instances."
(and (sys:instancep x)(not (flavor:find-flavor (type-of x) nil))))
(defun GET-SLOT-TYPE (S)
"This will work for Genera 8x CLOSses."
(clos:slot-definition-type s))
(defun GET-DIRECT-SLOTS (class-object)
""
(clos:class-direct-slots class-object))
(defun GET-SLOT-NAME (S)
"Method to get the name from a standard slot."
(clos::slot-definition-name s))
(defun SLOT-HAS-AN-INITFORM-P (slot-object)
(clos::slot-definition-initform slot-object))
(defun GET-SLOT-READERS (slot-object)
(clos::slot-definition-readers slot-object))
(defun GET-SLOT-WRITERS (slot-object)
(clos::slot-definition-writers slot-object))
(defun GET-SLOT-NAMED (instance name)
(find-if #'(lambda (slot)(equal (get-slot-name slot) name))
(all-slots instance)))
(defun GET-SLOT-ALLOCATION (S)
"Method to get the type of allocation from a standard slot: oneof :CLASS
or :INSTANCE."
(let ((alloc (clos::slot-definition-allocation s)))
(cond ((%classp alloc) :CLASS)
((member alloc '(:INSTANCE :CLASS)) alloc)
(T :INSTANCE))))
(defmethod GET-SLOT-INITFORM (s)
""
(when (slot-has-an-initform-p s)(clos::slot-definition-initform s)))
(defun GET-SLOT-INITARGS (s)
(clos::slot-definition-initargs s))
(defun GET-SLOT-INITARG (s)
(first (clos::slot-definition-initargs s)))
) ;; end of Genera 8x CLOS eval-when.
;; Lucid CLOS eval when...
#+lucid
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun GET-SUPERCLASS-NAMES (class)
"Expects the object returned by FIND-CLASS."
(mapcar #'clos::class-name (clos::class-direct-superclasses class)))
(defun INSTANCE-P (x)
"Alternate def as a function for lucid 4.0."
(and (system:standard-object-p x)(not (system:classp x))))
(defun GET-SLOT-DOCUMENTATION (s)
""
(or (clos::slotd-documentation s) ""))
(defun GET-SLOT-NAME (S)
"Method to get the name from a standard slot."
(clos::slotd-name s))
(defun GET-SLOT-READERS (slot-object)
(clos::slotd-readers slot-object))
(defun GET-SLOT-WRITERS (slot-object)
(clos::slotd-writers slot-object))
(defun GET-SLOT-ALLOCATION (S)
"Method to get the type of allocation from a standard slot: oneof
:CLASS or :INSTANCE."
(let ((alloc (clos::slotd-allocation s)))
(cond ((%classp alloc) :CLASS)
((member alloc '(:INSTANCE :CLASS)) alloc)
(T :INSTANCE))))
(defun %CLASSP (X)
"CLASSP is not exported in Lucid or EXCL, and is not defined at all in
Genera!"
(clos::classp x))
(defmethod GET-SLOT-INITFORM (s)
""
(when (slot-boundp s 'clos::initform)
(clos::slotd-initform s)))
(defun SLOT-HAS-AN-INITFORM-P (s)
""
(slot-boundp s 'clos::initform))
(defun GET-SLOT-INITARGS (s)
(clos::slotd-initargs s))
(defun GET-SLOT-INITARG (s)
(first (clos::slotd-initargs s)))
(defun BUILTIN-CLASS-P (X)
"Predicate to determine whether a class object is a builtin class.
returns T if it is."
(and (%classp x)(member (%class-name x)
(mapcar #'first clos-system::built-in-classes)
:test #'equal)))
) ;; *** end of Lucid CLOS eval-when. ***
)
;;; THE END OF THE CLOS EVAL-WHEN....
(defun CLEAR-SAVE-OBJECT ()
"shorthand to clear the environment."
(clear-global-vars-and-htabs)
)
;;;kr010601: question: what purpose does this stuff serve ???
;;;
(defun WRITE-GLOBAL-HEADER (stream symbol min max
&optional (pkg-name (package-name *package*)))
(format stream
(format
nil
;;kr010601: added the ANSI-conforming (eval-when ) directives:
#+(or :SBCL :CMU18)
"~%(EVAL-WHEN (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL :EXECUTE)
(DATABASE:MAKESYMS '~A ~A ~A ~s))~%"
#-(or :SBCL :CMU18)
"~%(EVAL-WHEN (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL :EXECUTE)
(DATABASE:MAKESYMS '~A ~A ~A ~s))~%"
symbol min max pkg-name)))
;;;kr010120: added SBCL support
#+(or sbcl mcl)
(defun BUILTIN-CLASS-p (X)
"Predicate to determine whether a class object is a built-in class: this
should be the generic definition of this one."
(cond ((and (symbolp x)(find-class x nil))
(equal (class-name (class-of (find-class x))) 'built-in-class))
((classp x)
(or (typep x 'built-in-class)
(equal (class-name (class-of x)) 'built-in-class)))
((builtin-class-p (type-of x)))
(T NIL)))
(defun ADMISSIBLE-CONSTANT-P (X)
"Predicate: returns T if x is symbol, number, or keyword."
(or (stringp x)
(null x)
(equal x T)
(pathnamep x)
(numberp x)
(keywordp x)
(characterp x)))
(defun ALL-NUMBERS-LIST-P (X)
(and (listp x)(%every #'numberp x)))
(defun SIMPLE-LIST-P (X)
"Predicate: returns t if every element of a list X is an admissible constant"
(and (not (cons-p x))
(listp x)
(not (circular-list-p X))
(%every #'admissible-constant-p x)))
;;; Quoted lists.
(defun SIMPLE-QUOTED-LIST-P (X)
"Predicate, if somethings a quoted list...."
(and (not (cons-p x))
(listp x)
(not (circular-list-p x))
(not (%every #'null x))
(%every #'(lambda (sub)(and (not (special-marker-p sub))
(or (numberp sub)
(characterp sub)
(not (listp sub))
(stringp sub)
(symbolp sub))))
x)))
(defun SAME-KEYWORDS-P (p1 p2)
"Predicate:"
(if (or (not (listp p1))(not (listp p2))) nil
(sameset (get-evens p1)(get-evens p2))))
(defun SAME-PLIST-VALUES-P (p1 p2)
"Use mapplist from the MOP book!"
(let ((kwds1 (get-evens p1))
(kwds2 (get-evens p2)))
(if (not (sameset kwds1 kwds2))
nil
(dolist (kwd kwds1 T)
(when (not (equal (getf p1 kwd)(getf p2 kwd))) (return nil))))))
(defun UNORDERED-PLIST-EQUAL (p1 p2)
"predicate to tell if plist keywords & values are equal,
regardless of attribute pair ordering."
(and (same-keywords-p p1 p2)(same-plist-values-p p1 p2)))
(defun ALL-HTAB-PLISTS-SAMEP (htab-plist-list)
"Predicate: does set equality on plists."
(%every #'(lambda (plist)(unordered-plist-equal plist
(first htab-plist-list)))
(rest htab-plist-list)))
(defun ARRAY-TYPE-T-P (X)
"Predicate, checks type and element-type of x."
(and (arrayp x)(not (stringp x))(equal (array-element-type x) T)))
(defun ALL-NULLS-P (X)
(%every #'null x))
(defun ALL-TS-P (X)
(%every #'(lambda (y)(equal y t))
x))
(defun SIMPLE-LEX-LIST-P (X)
(and (not (cons-p x))
(listp x)
(not (all-nulls-p x))
(not (all-ts-p x))
(not (circular-list-p x))
(%every #'(lambda (e)
(or (special-marker-p e)
(admissible-constant-p e)))
x)))
#|
(defun %CONS-P (X)
"Internal dotted list predicate..."
(and (not (null (%list-length x)))
(listp x)
(atom (cdr (last x)))
(not (null (cdr (last x))))))
(defun CONS-P (x)
"ingenious predicate for testing whether something is a cons cell vs. a list.
note that this returns nil for (LIST 'A 'B) whereas it returns T for
(CONS 'A 'B)."
(cond ((not (listp x)) NIL)
((and (listp x)(null (%list-length x))) nil)
((or (%cons-p x)(and (listp x)(null (listp (rest x))))) T)
(T NIL)))
|#
#|
;;;as an additional step for untangling this stuff, i commented out these two,
;;; and just instituted the straightforward (CONS-P ) below
(defun %CONS-p (X)
(and (listp x)(null (listp (cdr x)))))
(defun CONS-p (x)
(%cons-p x))
|#
(defun CONS-P (X)
(and (listp x)(null (listp (cdr x)))))
#-kcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun ALL-INSTANCE-LIST-P (x)
"Predicate for a list containing only instances!"
(and (listp x) (%every #'instance-p x)))
(defun UNSAVEABLE-SLOT-P (slot instance)
"Predicate returns t if the slotname SLOT is marked as USAVEABLE
for instances of the type of instance."
(or (member slot *global-unsaveable-slotnames* :test #'equal)
(member slot (get-unsaveable-slotnames instance) :test #'equal)))
)
(defun UNSAVEABLE-SLOT-TOKEN-P (X)
"Predicate"
(declare (inline unsaveable-slot-token-p))
(equal x *unsaveable-slot-token*))
(defun CIRCULAR-CONS-P (X)
"Predicate: returns t if <x> is a real cons (not list!) and it is circular."
(and (cons-p x)(eq (rest x) x)))
(defun CIRCULAR-CONS-DUMP-FORM (instance)
"Dump form for circular cons. (REST CONS) is EQ to CONS."
`(let ((first ,(get-dump-form (list (first instance)))))
(setf (rest first) first)))
(defun SLOT-EXISTS-P-ANY (instance name)
"returns t if the slotname exists with any package designator."
(let ((slots (mapcar #'strip-package (all-slotnames instance))))
(member (strip-package name) slots :test #'equal)))
(defun STRIP-PACKAGE (x)
"strip the package designator off the symbol, return the rest,
if keyword, return self.."
(if (keywordp x) x
(intern (symbol-name x))))
;;;#+aclpc ;;kr010616: all implementations should be using this.
(defun %CIRCULAR-LIST-P (X)
"Predicate to determine if something is a circular list, uses
LIST-LENGTH, which, unlike LENGTH, terminates and returns NIL if
the list is circular: LIST-LENGTH may not be in all versions of
LISP, as it is CLtL2: CHANGED TO INCLUDE THE RECURSIVE DEFINITION
OF CIRCULAR LISTS."
(null (list-length x)))
#|;;;kr010616: there really is no point in having this broken version around,
;;; so i commented it out.
#-aclpc
(defun %CIRCULAR-LIST-P (X)
"Predicate to determine if something is a circular list, uses
LIST-LENGTH, which, unlike LENGTH, terminates and returns NIL if
the list is circular: LIST-LENGTH may not be in all versions of
LISP, as it is CLtL2: CHANGED TO INCLUDE THE RECURSIVE DEFINITION
OF CIRCULAR LISTS."
(cond ((not (listp x)) nil)
((cons-p x) nil)
(T (multiple-value-bind (len is-circ)
;;kr010616: the following fn is fairly broken:
(%circular-list-length x)
(declare (ignore len))
is-circ))))
|#
;;; NOTE: the only ones which dont seem to have IGNORE-ERRORS is
;;; AKCL and ACL\PC.
#+(or akcl aclpc)
(defmacro IGNORE-ERRORS (&body body)
`(progn . ,body))
;;; MODIFIED for 9X: MCL def changed to simple version...
;;; differentiate between circular lists and circular conses!
#+mcl
(defun CIRCULAR-LIST-P (x)
(if (not (listp x)) nil
(cond ((cons-p x) nil)
((circular-cons-p x) nil)
((and (listp x)(null (list-length x))) T)
(T NIL))))
;;;kr010616: the following is questionable IMHO
#-(or mcl aclpc :SBCL :CMU)
(defun CIRCULAR-LIST-P (x)
"The point of having the ignore errors is if the some clause of
%circular-list-p encounters a dotted list, it will barf, ignore-errors
prevents the barf and just returns a multiple value of nil and error."
(ignore-errors (%circular-list-p x)))
;;;kr010616: enabled on sbcl and cmucl
#+(or aclpc :SBCL :CMU)
(defun CIRCULAR-LIST-P (x)
;; listp doesnt break on clists in ACL\PC.
(and (listp x)
;;kr010616: however, had to added this to shield (list-length ) from dotted lists
(not (dotted-list-p x))
(null (list-length x))))
#-lucid
(defun CIRCULAR-LIST-DUMP-FORM (clist)
""
(let ((ones (get-dump-form (get-circular-list-elements clist))))
`(make-circular-list ,ones)))
#+lucid
(defun CIRCULAR-LIST-DUMP-FORM (clist)
"NEW for 9X Lucid:"
(list-dump-form (collect-circ-elements clist)))
(defun CIRCULAR-DOTTED-LIST-DUMP-FORM (clist)
""
(let ((ones (get-circular-list-elements clist)))
`(make-circular-dotted-list ,ones)))
(defun CIRCULAR-LIST-EQUAL (a b)
""
(and (equal (circular-list-length a)(circular-list-length b))
(equal (get-circular-list-elements a)(get-circular-list-elements b))))
(defun STREAM-P (x)
"Avoids problems with vendor-made type confusion."
(and (not (%classp x))(streamp x)))
(defun REPEATING-ELEMENT-LIST-P (instance)
""
(if (not (listp instance)) nil
(if (< (%length instance) *make-list-length-threshold*) nil
(let ((test (first instance)))
(loop for elt in instance
do (if (not (equal elt test))
(return-from repeating-element-list-p nil)
nil))
(return-from repeating-element-list-p T)))))
(defun SPECIAL-MARKER-P (X &optional (label ".%%SL%%."))
"label must match with pushsym, and must be upper-case."
(and (symbolp x)(search label (format nil "~A" x) :test #'equal)))
(defun QUOTED-LIST-P (x)
"Predicate, if somethings a quoted list. May contain sublists."
(and (not (cons-p x))
(listp x)
(not (circular-list-p x))
(not (%every #'null x))
(%every #'(lambda (sub)(or (numberp sub)
(characterp sub)
(stringp sub)
(AND (symbolp sub)
(not (special-marker-p sub)))
(quoted-list-p sub)
;; (not (listp sub))
))
x)))
(defun CIRCULAR-DOTTED-LIST-P (X)
"Predicate, returns t if x is a dotted list, and it is also a circular list."
(and (dotted-list-p x)(circular-list-p x)))
#|;;;kr010618: commented out, as this is no longer needed if we use the original
;;; (DOTTED-LIST-P ) again below.
(defun %LAST (p)
(cond ((null p) nil)
((NOT (LISTP P)) P)
((%circular-list-p p)
;;kr010618: comment: whoa! does this have to be so inefficient ??
;; why would (%last ) need to be immune to circular lists in the first place ??
(cons
(first (reverse (get-circular-list-elements p)))
p))
(T (last p))))
|#
;;;kr010618: this is not immune to circular lists, nor should it be. circular lists
;;; should be tested for before calling this.
;;;
(defun DOTTED-LIST-P (x)
"Predicate which returns T if something is a dotted list.
NIL is NOT a dotted list!"
(and (listp x)(cons-p (last x))))
#|;;;kr010618: commented out, so the above definition does not get overwritten anymore.
;;; not only does the #+-mcl below seem bogus, but in conjunction with some other changes,
;;; this led to a circularity in the code, i.e. an infinite loop.
(defun DOTTED-LIST-P (x)
"MODIFIED: Predicate which returns T if something is a dotted list.
NIL is NOT a dotted list!"
(and (listp x)
#-mcl(cons-p (%last x))
#+mcl(cons-p (%last x))
))
|#
#|;;;kr010615: commented out, because apparently used nowhere...
(defun %%LIST-LENGTH (x)
"Differs from ClTl2 LIST-LENGTH in that a multiple value return of
NIL and counter value are returned if its a circular list:
uses %ENDP instead of ENDP to deal with dotted lists."
(do (( n 0 (+ n 2))
(fast x (cddr fast))
(slow x (cdr slow)))
(nil)
(when (endp fast)(return (values nil n)))
(when (endp (cdr fast))(return (values nil (1+ n))))
(when (and (eq fast slow)(> n 0))(return (values T (/ n 2))))))
|#
#|;;;kr010619: commented out this old version, to make a non-backwards compatible change in the versions below...
(defun %LIST-LENGTH (x)
"Differs from ClTl2 LIST-LENGTH in that a multiple value return of
NIL and counter value are returned if its a circular list:
uses %ENDP instead of ENDP to deal with dotted lists."
(cond ((cons-p x)
;;kr010615: this was just a clear-cut basic bug. amazing. was this stuff ever working before ???
;;(length x)
;; let's try this definition for the length of one cons cell instead:
2)
((listp x)(do (( n 0 (+ n 2))
(fast x (cddr fast))
(slow x (cdr slow)))
(nil)
(multiple-value-bind (ended dotted)
(%endp fast x)
(when ended (if dotted (return (values (+ n 2) nil))
(return (values n nil)))))
(multiple-value-bind (ended dotted)
(%endp (cdr fast) x)
(when ended (if dotted (return (values (+ n 3) nil))
(return (values (1+ n) nil)))))
(when (and (eq fast slow)(> n 0))
(return (values nil (/ n 2))))))
(T (values nil nil))))
;;;kr010618: (%LIST-LENGTH ) above is the only place where this is used...
;;; it seems to me that the following is a bit broken in its logic.
;;; it should not be using (dotted-list-p ) , because that is not immune to circular
;;; lists, which is what this fn is used for testing...
;;;
(defun %ENDP (element &optional parent-list)
"Modified definition of ENDP:
checks to see if the parent list is a dotted list, then
compares the last of parent with element, returns t if they are equal.
multiple-value return is whether the element is the end of parent list,
and if the parent list is dotted or not."
;;kr010619: this is also very inefficient. basically, both (dotted-list-p ) and (last )
;; scan the entire last every single time to the very end. a lot of redundant work...
(if (dotted-list-p parent-list)(values (equal (last parent-list) element)
T)
(values (endp element)
NIL)))
|#
;;;kr010619: uses my ne wversion of (%endp ) below, not passing a second argument,
;;; which is no longer necessary. also had to reduce what is added to the returned length n
;;; in the dotted case, which might have been due to different behaviour with the new (%endp ) .
;;;
(defun %LIST-LENGTH (x)
"Differs from ClTl2 LIST-LENGTH in that a multiple value return of
NIL and counter value are returned if its a circular list:
uses %ENDP instead of ENDP to deal with dotted lists."
(cond ((cons-p x)
;;kr010615: this was just a clear-cut basic bug. amazing. was this stuff ever working before ???
;;(length x)
;; let's try this definition for the length of one cons cell instead:
2)
((listp x)(do (( n 0 (+ n 2))
(fast x (cddr fast))
(slow x (cdr slow)))
(nil)
(multiple-value-bind (ended dotted)
(%endp fast)
(when ended (if dotted (return (values (+ n 1) nil))
(return (values n nil)))))
(multiple-value-bind (ended dotted)
(%endp (cdr fast))
(when ended (if dotted (return (values (+ n 2) nil))
(return (values (1+ n) nil)))))
(when (and (eq fast slow)(> n 0))
(return (values nil (/ n 2))))))
(T (values nil nil))))
#|;;;kr010619: examples:
DATABASE >(%list-length '(1 2 . 3))
3
NIL
DATABASE >(%list-length '(1 2 3))
3
NIL
DATABASE >(%list-length (make-circular-list '(1 2 3)))
NIL
3
DATABASE >
|#
;;;kr010619: total rewrite, which redefines the semantics slightly, and removes
;;; the bad inefficiencies, and corrects its behaviour with regard to circular lists.
;;; this here won't hang anymore.
;;;kr010618: (%LIST-LENGTH ) above is the only place where this is used...
;;; it seems to me that the following is a bit broken in its logic.
;;; it should not be using (dotted-list-p ) , because that is not immune to circular
;;; lists, which is what this fn is used for testing...
;;;
(defun %ENDP (element)
"Modified definition of ENDP:
Handles dotted lists, and returns 2 values: NIL for both values
if element is a cons cell. If otherwise, the first value is T, indicating
that the end has been reached. In contrast, the regular ENDP is much more
stringent, and returns T only if element is NIL; any other data type
would be considered an error. However, this modified version merely
returns T as the second value for data types other than a cons or NIL,
indicating that this was the end of a dotted list."
(let* ((end-reached-p (not (consp element))))
(values end-reached-p
;; if element is anything other than NIL, we presumably had a dotted list
(when (and end-reached-p element)
t)
)
)
)
(defun FIRSTN (n list)
"Return the first n elements of a list."
(let ((answers nil))
(dotimes (count (1- n) answers)
(push (nth count list) answers))
(nreverse answers)))
;;; Support for dealing with circular lists...
(defun GET-CIRCULAR-LIST-ELEMENTS (circular-list)
"MODIFIED: Given a circular list, get the repeating pattern."
(if (circular-list-p circular-list)
;;kr010616: switched to (circular-list-length ) from (%circular-list-length )
(let ((len (circular-list-length circular-list)))
(when (numberp len)
(firstn (1+ len) circular-list)))
circular-list))
(defun MAKE-CIRCULAR-LIST (elts)
"Given non circular list elements elts, return a circular list of those
elements."
(rest (rplacd (last elts) elts)))
(defun MAKE-CIRCULAR-DOTTED-LIST (dl)
""
(let* (
;; KOT commented both these out, not used.
;; (elts (get-dump-form (get-circular-list-elements dl)))
;;(dotted (eval `(LIST* ',@elts)))
)
;; KOT x --> dl typos fix.
(rest (rplacd (last dl) dl))))
#|;;;kr010616: just commented out this sorry mess wholesale...
#+ignore
(defun %CIRCULAR-LIST-LENGTH (circ &optional (len 0)(already-seen nil))
(list-length circ))
;;;kr010616: this is quite broken !! in contrast to (list-length ), this compares the
;;; (car ) values of cells, instead of the (cdr ) that always would point to another cons cell.
;;; this will thus erroneously declare (list 2 2 2) as circular, because of the (eq 2 2)
;;; comparisons !!!
(defun %CIRCULAR-LIST-LENGTH (circ &optional (len 0)(already-seen nil))
""
(cond ((null circ)(values len nil))
((not (listp circ))(values (1+ len) nil))
((member circ already-seen :test #'eq)(values len T))
((member (first circ) already-seen :test #'eq)(values len T))
(T (%circular-list-length (rest circ)(incf len)
;;kr010616: comment: using (append ) here is atrociously inefficient
(append already-seen (list (first circ)))))))
|#
(defun CIRCULAR-LIST-LENGTH (clist)
"Given a circular list, returns the number of non-circular elements before
cycle: returns an error if this is not a circular list!"
(multiple-value-bind (status length)
(%list-length clist)
(when status ;;;; (warn "this is not a circular list!")
(return-from circular-list-length (length clist)))
length))
(defun COLLECT-CIRC-ELEMENTS (clist)
"NEW: Just creates a list with the (non-repeating) list length of elements."
(loop for count from 0 to (1- (circular-list-length clist))
collect (nth count clist)))
(defun LIST-TYPE (X)
(cond ((not (listp x))
(format t "error: ~a is not a list~%" x))
((cons-p x) 'cons)
((simple-list-p x) 'simple)
((quoted-list-p x) 'quoted)
(T 'ordinary)))
(defun MAKE-SYM (x)
(if (keywordp x)
(read-from-string (subseq (symbol-name x) 0))
x))
(defun GET-EVENS (l)
(let ((answers nil))
(dotimes (count (1- (length l)) answers)
(if (evenp count)(push (nth count l) answers)))
(nreverse answers)))
(defun GET-ODDS (l)
(let ((answers nil))
(dotimes (count (1- (length l)) answers)
(if (oddp count)(push (nth count l) answers)))
(nreverse answers)))
(defun SYM< (a b)
"Predicate to see if symbol a is alphabetically before symbol b. T if a is."
(string< (format nil "~A" A)(format nil "~A" b)))
(defun SYMF< (a b)
"Predicate to see if symbol a is alphabetically before symbol b. T if a is."
(string< (format nil "~A" (FIRST A))(format nil "~A" (first b))))
(defun ALPHABETIZE-BY-KEYWORD (lst)
""
;;kr010611: replaced (remove-duplicates ) with (delete-duplicates )
;; because (pair-up ) will return a freshly cons'ed list, so this should be safe.
(let ((alpha-cells (sort (delete-duplicates (pair-up lst) :test #'equal)
#'symf<)))
(mapcar #'second alpha-cells)))
#+lucid
(defun MAP-ARRAY (function array)
"like mapcar, but maps a function over each element of an
n-dim array: the function to be applied is a function of two args,
the count and the element value at aref count in the array."
(let* ((vec (sys:underlying-simple-vector array)))
(map-into vec function vec)
array))
;;; (len (1- (length vec))))
;;;(loop for count from 0 to len do (setf (aref vec count)
;;; (funcall function count (aref vec count)))
;;; finally (return array))))
#+lucid
(defun FILL-ARRAY (array l)
"Fill n-dimensional array with values from list."
(let* ((vec (sys:underlying-simple-vector array))
(len (1- (length vec)))
(data (flatten l)))
(loop for index from 0 to len
do (setf (aref vec index)(nth index data))
finally (return array))))
#-(or lispm lucid akcl excl)
(defun FILL-ARRAY (array l)
"Fill n-dimensional array with values from list."
(let ((list (flatten l)))
(if (= 1 (length (array-dimensions array)))
(loop for count from 0 to (1- (length array)) do
(setf (aref array count)(nth count list))
finally (return-from fill-array array))
(progn (dotimes (i (array-total-size array) array)
(setf (row-major-aref array i)(nth i list)))
(return-from fill-array array)))))
#+excl
(defun FILL-ARRAY (array l)
"Fill n-dimensional array with values from list."
(let ((list (flatten l)))
(dotimes (i (array-total-size array) array)
(setf (row-major-aref array i)(nth i list)))
(return-from fill-array array)))
#+lispm
(defun FILL-ARRAY (array l)
"Fill n-dimensional array with values from list."
(let ((list (flatten l))(array array))
(declare (sys:array-register array))
(if (= 1 (length (array-dimensions array)))
(loop for count from 0 to (1- (length array)) do
(setf (si:%1d-aref array count)(nth count list))
finally (return-from fill-array array))
(progn (dotimes (i (array-total-size array) array)
(setf (row-major-aref array i)(nth i list)))
(return-from fill-array array)))))
(defvar *debug-array-operations* t)
(defun ARRAY-ELEMENTS-SAME-P (array)
"Predicate, returns t if every element of an n-dimensional array
is the same, NIL otherwise."
(let ((current nil))
(map-array #'(lambda (count element)
(declare (ignore count))
(if (null current)
(setf current element)
(if (equal element current) nil
(return-from array-elements-same-p nil))))
array)
(return-from array-elements-same-p T)))
#-lucid
(defun MAP-ARRAY (function array)
"like mapcar, but maps a function over each element of an
n-dim array: the function to be applied is a function of two args,
the count and the element value at aref count in the array."
(let ((array array))
#+lispm (declare (sys:array-register-1d array))
(if (= 1 (length (array-dimensions array)))
(dotimes (count (1- (length array)) array)
#+lispm(setf (sys:%1d-aref array count)
(funcall function count (sys:%1d-aref array count)))
#-lispm(setf (aref array count)
(funcall function count (aref array count)))
)
;; this is the multi-dimensional array clause.....
(progn (dotimes (i (array-total-size array) array)
(setf (row-major-aref array i)
(funcall function i (row-major-aref array i))))
(return-from map-array array)))))
;;; CLOS/PCL independent class accessor methods.
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun DO-SPECIALIZER (spec)
"Map objects to class names."
(cond ((SYMBOLP SPEC) spec)
((%CLASSP SPEC)`(FIND-CLASS ',(%class-name spec)))
(T SPEC)))
(defun DO-SPECIALIZERS (lst)
(let ((answers nil))
(dolist (spec lst answers)
(setf answers (append (list (do-specializer spec)))))
answers))
(defun GENERATE-CLASS-SLOT-FORMS (class)
"This generates dump forms for all the slots in the class object."
(let ((slots nil))
(dolist (slot (class-slots class) slots)
(setf slots (append slots
(list (generate-class-slot-form slot)))))
slots))
) ;; end of class-save eval-when.
#+pcl
(format t "COPY INSTANCE NOT DEFINED for PCL!")
#-(or cmu kcl)
(defmethod COPY-INSTANCE ((instance T))
"Provides shallow copying of any instance: returns a new copy of a
given clos instance, writ as a method so youse gys can write ur own."
(let* ((copy (make-instance (instance-name instance)))
(slots (all-slotnames instance)))
(dolist (slot slots)
(if (not (slot-boundp instance slot))
(slot-makunbound copy slot)
(setf (slot-value copy slot)(slot-value instance slot))))
copy))
;;; *** Beginning of CLOS eval-when... ***
#+clos
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
;; *** Dont-care vendor CLOS definitions. ***
(defun GET-CLASS-METACLASS (class-object)
"Given a class object, returns the metaclass name to help build
CLASS-DUMP-FORM: (NEW)."
(when (%classp class-object)
(let ((meta (%class-name (class-of (class-of class-object)))))
(if (not (equal meta #-aclpc 'clos::standard-class
#+aclpc 'standard-class
)) ;; the default...
(list (list :metaclass meta))))))
(defun INSTANCE-NAME (instance)
"returns the symbol naming the given class object.
NOTE: on the slimbolical hash-tables are FLAVORS.
Therefore one must use HASH-TABLE-P instead of TYPE-OF,
and the type returned is a Common Lisp entity, NOT a FLAVOR!"
(cond ((hash-table-p instance) 'hash-table)
((equal (%type-of instance) 'structure)(type-of instance))
(T #-aclpc (clos::class-name
(clos::class-of instance)
#+aclpc(class-name (class-of instance))
))))
) ;; end of CLOS eval-when ....
;;; *** Non-LISP machine CLOS eval-when. ***
;;;kr010120: added SBCL support
#-(or lispm :mcl akcl pcl sbcl)
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun GET-SLOT-TYPE (S)
"Method to get the type from a standard slot:
this works for most things EXCEPT Genera 8x CLOS."
#-aclpc (clos::slotd-type s)
#+aclpc(slot-definition-type s)
)
;;;(defun GET-DIRECT-SLOTS (class-object)
;;;""
;;;(clos::class-class-direct-slots class-object))
(defun %GENERIC-FUNCTION-P (x)
"Predicate, returns t for generic functions. causes symbol conflict problem
in genera 8.0."
#-aclpc(clos::generic-function-p x)
#+aclpc(generic-function-p x)
)
)
;;; *** END OF NON LISPM EVAL-WHEN ***
;;; Independent.
;;; DEFINE-DUMP-FORM macro.
;;; package changed from user to cl-user---NEW CHANGE
(defun HAS-DUMP-FORM-P (class-name)
"Predicate, returns t if a class has a user-defined DUMP FORM method."
(get class-name #+mcl 'cl-user::%%DUMP-FORM-METHOD%%
;;kr010120: did this here too: package changed from user to cl-user
#-mcl 'cl-user::%%DUMP-FORM-METHOD%%
))
(defvar *predicate-dump-forms* nil)
;;; Added: HAS-PREDICATE-DUMP-FORM-P, GET-PREDICATE-DUMP-FORM, and
;;; DEFINE-PREDICATE-DUMP-FORM macro.
(defun HAS-PREDICATE-DUMP-FORM-P (instance)
(some #'(lambda (x)
(not (null (funcall (first x) instance))))
*predicate-dump-forms*))
(defun GET-PREDICATE-DUMP-FORM (instance)
(loop for try in *predicate-dump-forms*
when (funcall (first try) instance)
return (funcall (rest try) instance)))
(defmacro DEFINE-PREDICATE-DUMP-FORM (predicate dump-form)
""
`(pushnew (cons ',predicate ',dump-form) *predicate-dump-forms*))
#|
(define-predicate-dump-form #'(lambda (x)(typep x 'RMS))
#'(lambda (x) "RMS!"))
|#
(defmacro DEFINE-DUMP-FORM (class-name arglist &body body)
"Macro to define a user-defined dump-form for a given class-name.
You could do this as two discrete steps, programmatically where you need it"
`(progn (setf (get ',class-name #+mcl 'cl-user::%%dump-form-method%%
;;kr010120: did this here too: package changed from user to cl-user
#-mcl 'cl-user::%%dump-form-method%%
) T)
(defmethod DUMP-FORM ,arglist ,@body)
',class-name))
;;; Everything except AKCL.
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun GET-CLASS-SUPERCLASSES (class)
"Returns a list of the NAMES (symbol list) of the direct superclasses of
the class object."
(let ((the-ones (get-superclass-names class)))
(if *supress-standard-object* (delete 'standard-object the-ones)
the-ones)))
(defun GET-SLOT-READER (slot-object)
(first (get-slot-readers slot-object)))
(defun GET-SLOT-WRITER (slot-object)
(first (get-slot-writers slot-object)))
(defun ACCESSOR-EXISTS-P (S)
"Predicate: Returns T iff the slot has both a reader and a standard writer"
(let* ((readers (get-slot-readers s))
(writers (get-slot-writers s))
(accessors (%some #'(lambda (writer)
(and (listp writer)
(equal (first writer) 'SETF)
(second writer)
(member (second writer) readers
:test #'equal)))
writers)))
accessors))
(defun GET-SLOT-ACCESSOR (s)
"Returns the first slot accessor alone."
(let ((val (first (get-slot-readers s))))
(when (and val (accessor-exists-p s))
val)))
(defun %GET-SLOT-NAME (S)
"Method to get the name from a standard slot."
(get-slot-name s))
(defun %GET-SLOT-ALLOCATION (S)
"Method to get the type of allocation from a standard slot: oneof :CLASS
or :INSTANCE."
(let ((val (get-slot-allocation s)))
(when val (list :allocation val))))
(defun %GET-SLOT-TYPE (S)
"Method to get the type from a standard slot: NOTE: if nil now, doesnt get added!"
(if (get-slot-type s)(list :type (get-slot-type s))))
(defun %GET-SLOT-INITARG (S)
"Method to get the first initarg found for the standard slot instance
supplied."
(let ((val (or (first (get-slot-initargs s))
(if *use-default-class-initargs* (make-keyword
(get-slot-name s))))))
(when val (list :initarg val))))
(defun %GET-SLOT-READER (slot)
"Method to determine whether to use an accessor or a reader. Does not
splice into the dump form if there is no reader defined."
(when (null (%get-slot-accessor slot))
(let ((val (GET-SLOT-reader slot)))
(when val (list :reader val)))))
(defun %GET-SLOT-WRITER (slot)
"Method to determine whether to use an accessor or a writer. Does not
splice into the dump form if there is no writer defined."
(when (null (%get-slot-accessor slot))
(let ((val (GET-SLOT-WRITER slot)))
(when val (list :writer val)))))
(defun %GET-SLOT-DOCUMENTATION (S)
""
(list :documentation (or (GET-SLOT-DOCUMENTATION s) "")))
(defun %GET-SLOT-ACCESSOR (S)
""
(let ((val (GET-SLOT-READER s)))
(when (and val (accessor-exists-p s))
(list :accessor val))))
(defmethod METHODP ((thing null))
"NIL is not a method."
nil)
(defmethod METHODP ((thing t))
"Anything else is not a method."
nil)
(defmethod MBOUNDP ((name symbol))
"Predicate: returns t if this name is a method as opposed to a
function/macro."
(when (methodp name) T))
(defmethod MBOUNDP ((name null))
"vacuous case for NIL."
NIL)
(defmethod MBOUNDP ((name t))
"Predicate: returns t if this name is a method as opposed to a
function/macro."
(when (methodp name) T))
(defun SLOT-DATA-AS-PLIST (slot)
"Generates the slot value pairs of the slot descriptor as a property list,
of course the name is stuck on the front."
(let ((name (get-slot-name slot))
(initarg (get-slot-initarg slot))
(accessor (get-slot-accessor slot))
(initform (get-slot-initform slot))
(type (get-slot-type slot))
(documentation (get-slot-documentation slot))
(allocation (get-slot-allocation slot)))
(if accessor
(list name :initarg initarg
:accessor accessor
:initform initform
:type type
:documentation documentation
:allocation allocation)
(list name :initarg initarg
:initform initform
:type type
:documentation documentation
:allocation allocation))))
(defun CONSTRUCT-SLOT-SPEC (slot)
"The internal dump-form constructor for slots."
(let ((name (%get-slot-name slot))
(initarg-pair (%get-slot-initarg slot))
(type-pair (%get-slot-type slot))
(accessor-pair (%get-slot-accessor slot))
(reader-pair (%get-slot-reader slot))
(writer-pair (%get-slot-writer slot))
(allocation-pair (%get-slot-allocation slot))
(initform-pair (%get-slot-initform slot))
(documentation-pair (%get-slot-documentation slot)))
`(,name ,@initarg-pair
,@type-pair
,@accessor-pair
,@reader-pair
,@writer-pair
,@allocation-pair
,@initform-pair
,@documentation-pair)))
(defun GENERATE-CLASS-SLOT-FORM (slotd)
"Default method for rev4b --- seems to be defective...
This one gets called by CLASS-DUMP-FORM."
(construct-slot-spec slotd))
(defun SORT-ALLOCATED-SLOTS (class-object)
""
(let ((slots (class-slots class-object)))
(values
(remove-if-not #'(lambda (slot)(equal (get-slot-allocation slot)
:CLASS))
slots)
(remove-if-not #'(lambda (slot)(equal (get-slot-allocation slot)
:INSTANCE))
slots))))
) ;; non-akcl eval when....
;;; Only allow class save, method save, and generic function save when this
;;; file is loaded: control this with :class-save on the features list.
;;; end of lucid eval-when.
;;; NOTE! Returned result from CLASS-DIRECT-SLOTS varies with the vendor!
;;; CLOS/PCL independent class accessor methods.
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun FIND-GENERIC-FUNCTION (name)
"A function given the name of a supposed generic function,
returns the function object if it exists, NIL otherwise."
(cond ((and (fboundp name)(%generic-function-p name))
(symbol-function name))
(T NIL)))
(defun GENERATE-CLASS-OPTIONS-FORM (class)
"Generates a dump form for the default-initargs, metaclass,
documentation components of a class object...."
(let ((default-initargs (get-class-default-initargs class))
(metaclass (get-class-metaclass class)))
(if default-initargs
`((:default-initargs ,@default-initargs)
,@metaclass
(:documentation ,(or (get-class-documentation class) "")))
`(,@metaclass
(:documentation ,(or (get-class-documentation class) ""))))))
) ;; end of class-save eval-when.
#+allegro-v4
(defmethod ALL-SLOTS-AND-VALUES ((instance T))
"returns an alist of slot value pairs.
NOTE: Each alist cell is a LIST, NOT a CONS!
Also, this has been modified to deal with unbound slots."
(let ((answers nil))
(dolist (slot (all-slotnames instance) answers)
(setf answers (nconc answers
(list slot (if (slot-boundp instance slot)
(slot-value instance slot)
*unbound-slot-token*)))))
answers))
#-(or kcl allegro-v4.0 allegro-v4.1 allegro-v4.2)
(defmethod ALL-SLOTS-AND-VALUES ((instance T))
"returns an alist of slot value pairs.
NOTE: Each alist cell is a LIST, NOT a CONS!
Also, this has been modified to deal with unbound slots."
(loop for slot in (all-slotnames instance) nconc
(list slot (if (slot-boundp instance slot)
(slot-value instance slot)
*unbound-slot-token*)) into answers
finally (return answers)))
(defun PRSLOT (key val &optional (stream *standard-output*))
"Simple function to be used by MAP-INSTANCE, printing out a slots key
and value, ala DESCRIBE."
(format stream "Key: ~a, Value: ~a~%" key val))
#+mcl
(defun DEFAULT-SLOTS-AS-PLIST (i)
"Given an instance, finds the default initarg values for each slot, and
returns initarg/value pairs as a property-list."
(loop for slot in (all-slots i) nconc
(list (first (third slot))(second slot))))
(defun INSTANCE-DATA-AS-PLIST (i)
"Given an instance, finds the slot values for each slot, and
returns slotname (as keyword)/slot value pairs as a property-list."
(loop for sn in (get-ordered-slot-names i) nconc
(list (make-keyword sn)(slot-value i sn))))
(defun MAP-INSTANCE (function instance &key (modify T)
(concat nil)
(OPERATE-ON-UNBOUND-SLOTS NIL))
"Iterator over the slots in an instance, ala MAPHASH. Takes a function of the
keyword/ value (2 arguments, not ONE!)."
(let* ((slotnames (all-slotnames instance))
(answers nil)
(result nil))
(when (null slotnames)(return-from map-instance nil))
(dolist (slot slotnames answers)
(IF (SLOT-BOUNDP INSTANCE SLOT)
(setf result (funcall function slot (slot-value instance slot)))
(WHEN OPERATE-ON-UNBOUND-SLOTS
(SETF RESULT (FUNCALL FUNCTION SLOT *UNBOUND-SLOT-TOKEN*)))
)
(when concat (setf answers (append answers (list result))))
(when modify (setf (slot-value instance slot) result)))
(if (null concat) instance (%flatten1 answers))))
(defmacro GET-PLIST-KEYS (plist)
`(get-evens ,plist))
#|
#-(or akcl allegro-v4.0 cmu)
(defun MAP-INSTANCE (function instance &key (modify T)(concat nil))
"Iterator over the slots in an instance, ala MAPHASH. Takes a function of the
keyword/ value (2 arguments, not ONE!)."
(let* ((init (all-slots-and-values instance))
(answer (loop with con = nil
until (null init)
as key = (pop init)
as val = (pop init)
as result = (funcall function key val)
when concat do (setf con (append con (list result)))
when modify do (setf (slot-value instance key) result)
finally (return (if (null concat) instance
(flatten1 con))))))
answer))
|#
(defun QUOTED-SYMBOL-P (X)
"Predicate: returns t if the object is a quoted symbol."
(and (listp x)(equal (first x) 'quote)(symbolp (second x))))
(defun QUOTED-FORM-P (X)
"Predicate: returns t if the object is a quoted form."
#-mcl (and (listp x)(equal (first x) 'quote))
#+mcl (ccl::quoted-form-p x)
)
(defun QUOTED-FORM-DUMP-FORM (instance)
""
`(QUOTE ,(get-dump-form (second instance))))
(defun GET-SLOT-VALUES (clos-instance)
"given a pcl/clos instance,constructs a plist of all the saveable
slot/value pairs."
(incf *global-instance-count*)
(let ((unsaveable (get-unsaveable-slotnames clos-instance)))
;;kr010611: replaced (remove-duplicates ) with (delete-duplicates )
;; because (pair-up ) will return a freshly cons'ed list, so this should be safe.
(%flatten (delete-duplicates
(pair-up
(map-instance #'(lambda (key val)
(if (or (member key unsaveable :test #'equal)
(member key *global-unsaveable-slotnames*
:test #'equal))
(list (make-keyword key) *unsaveable-slot-token*)
(list (make-keyword key)(get-dump-form val))))
clos-instance
:modify nil
:concat t))
:test #'equal))))
;;; Unsaveable slots.
(defun INDEX-UNSAVEABLE-SLOT (class slot)
""
(pushnew slot (gethash class *unsaveable-slotname-hash-table*)))
(defun RETRIEVE-UNSAVEABLE-SLOTS (class)
(gethash class *unsaveable-slotname-hash-table*))
#+mcl
(defun GET-DEFSTRUCT-SLOT-OFFSET (struct slotname)
"New definition of slot offset for MCL 2.0.1. Position 0 of the spec is the
name of the defstruct, assuming GDSNAMES produces the slotnames in the same
order as they occur in the defstruct definition, 1 the position of the slotname
is the correct offset."
(1+ (position slotname (get-defstruct-slot-names struct) :test #'equal)))
#-mcl
(defun GET-DEFSTRUCT-SLOT-OFFSET (struct slotname)
""
(let ((slots (get-defstruct-slot-descriptors
(get-defstruct-name struct)))
(answer nil))
(dolist (slot slots answer)
(if (and (listp slot)(equal (first slot) slotname))
(setf answer (first (reverse slot)))))))
;;; =================== VENDOR INDEPENDENT FUNCTIONS ===================
(defun GET-SD-NAMED (struct slotname)
(dolist (sd (get-defstruct-slot-descriptors struct))
(when (equal (get-defstruct-slot-name sd) slotname)
(return sd))))
#+aclpc
(defun GET-DEFSTRUCT-SLOT-ACCESSOR (struct slotname)
"Given a structure instance and a slotname, ret the accessor for
that name."
(first (cdr (assoc slotname (get-defstruct-slot-descriptors
(get-defstruct-name struct))))))
#-aclpc
(defun GET-DEFSTRUCT-SLOT-ACCESSOR (struct slotname)
"Given a structure instance and a slotname, ret the accessor for
that name."
(let ((sd (get-sd-named struct slotname))
(structname (get-defstruct-name struct)))
(defstruct-slot-descriptor-ref sd :accessor structname)
))
(defun GET-DEFSTRUCT-SLOT-VALUE (instance slotname)
"Given an instance of a defstruct, and the name of some slot, return the
slots value."
(let ((fun (get-defstruct-slot-accessor instance slotname)))
(if fun (funcall fun instance)
(error
"No function was found to access slot ~a in defstruct instance ~a."
slotname instance))))
(defun SET-DEFSTRUCT-SLOT-VALUE (instance slotname newval)
(funcall *vendor-set-slot-function* instance slotname newval))
(defun GET-DEFSTRUCT-VALUES (instance)
""
(let ((answers nil))
(dolist (slot (get-defstruct-slot-names instance)(nreverse answers))
(push (get-dump-form (get-defstruct-slot-value instance slot)) answers)
)))
#-lucid
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(defun GET-DEFSTRUCT-SLOT-LOCATION (i name)
""
(position name (nreverse (get-defstruct-slot-names i))))
) ;; end of no-lucid eval when...
;;; Utilities.
(defun WRITE-ATTRIBUTE-LINE (stream)
""
(format stream
";;;-*- Mode: Lisp; Base: 10; Syntax: Common-Lisp; Package: ~a -*-~%"
(package-name *package*)))
;;;kr010601: it is best to explicitly write out some version info.
;;; needs save-object version and other stuff...
;;;
(defun write-version-line (stream)
(format stream ";;; version ~A in ~A ~A on ~A ~A~&;;; written out on ~A~&"
*save-object-system-date*
(lisp-implementation-type)
(lisp-implementation-version)
(machine-type)
(software-type)
(machine-instance)
)
)
(defun WRITE-PACKAGE-INFO (stream)
""
;; modified by KJ to not quote package name
;;kr010120: added SBCL support. did the same for :cmu on 010601
#+(or :sbcl :cmu mcl) (format stream "~%(in-package :~s)"
(read-from-string (package-name *package*)))
#-(or :sbcl :cmu mcl)
(format stream "~%~s"
`(in-package ',(read-from-string (package-name *package*))))
)
(defun PCO-P (instance)
"A predicate to determine if a LISP object is a PCO."
(declare (inline pco-p))
(and (not (stringp instance))
(member (%type-of instance) *pco-types*)))
(defun SIMPLEST-LIST-P (instance)
"Predicate: lists of constants can be dumped without let form."
(and (listp instance)
(not (null instance))
;;kr010615: had to switch to (%every ) from (every ) here, to not stumble over dotted lists
(%every #'admissible-constant-p instance)))
(defun MAKE-DUMPABLE-FORM (object-instance)
""
(if (simplest-list-p object-instance)
(get-dump-form object-instance) ;;; new line.
(MAKE-LET-FORM object-instance (get-dump-form object-instance))))
(defun SAVE-OBJECT (object-instance filename &key
(compile nil)
(variable '*db-input*)
(if-exists :append)
(print-pretty nil)
;;kr010602: comment: if these two values are superceeded,
;; i suppose the data will be silently truncated and thus corrupted.
;; some kind of warning would be useful to have...
(max-print-level 10000000)
(max-print-length 50000000)
(package nil)
(htab-test #'equal)
(if-does-not-exist :create))
""
(clrhash *ordered-slot-name-htab*)
(init-list-htabs htab-test)
(setf *global-instance-count* 0)
(setf *global-object-count* 0)
(clear-global-vars-and-htabs)
(let* ((*print-level* max-print-level)
(*print-circle* t)
(*print-pretty* print-pretty)
(*print-length* max-print-length)
(*package* (or (and package (find-package package))
*package*))
(filename-result filename)
#+lispm (scl::*print-structure-contents* t)
(form (MAKE-DUMPABLE-FORM object-instance)))
(setf (get '.%%SL%%. 'namecounter) 0)
(with-open-file (stream filename :direction :output :if-exists if-exists
:if-does-not-exist if-does-not-exist)
(when (not (equal if-exists :append))
(write-attribute-line stream)
;;kr010601:
(write-version-line stream)
)
(write-package-info stream)
(write-global-header stream
'.%%SL%%. 0
*global-instance-count*)
(format stream "~%~s" `(setq ,variable ,form)))
(format t "~& object saved to file: ~A"filename)
(when compile (format t "~% compiling file ~A" filename)
(setf filename-result (compile-file filename))
(format t "~% done compiling file ~A"filename))
filename-result))
;;; %EVERY and %SOME: equivalent to EVERY and SOME, but dont blow
;;; up if they encounter a dotted list.
(defun SEQUENCEP (x)
(declare (inline sequencep))
(typep x 'sequence))
;;;kr010615: in some of these functions, it seems like there are plenty of opportunities
;;; for optimizations by a smart compiler that knows something about list manipulation...
;;;
(defun %REVERSE (dl)
""
(if (circular-list-p dl)(reverse (get-circular-list-elements dl))
(if (dotted-list-p dl)
(let ((l (%length dl))
(answers nil))
;;(append (list (first (last dl)))
;;kr010615: instead of the horrific hack above, just do this:
;; (append ) would have copied the freshly created list again !!
(cons (first (last dl))
(dotimes (i (- l 2) answers)
(push (nth i dl) answers))))
(reverse dl))))
(defun %BUTLAST (seq)
""
(if (circular-list-p seq)(butlast (get-circular-list-elements seq))
(if (dotted-list-p seq)
;;kr010615: comment: FIXME: this actually appears to be ridiculously inefficient.
(nreverse ;;%reverse ;;kr010615: given that (%reverse ) already cons'es a fresh list, i used (nreverse ) as a fix
(%reverse seq))
(butlast seq))))
(defun %ELT (seq i)
""
(if (circular-list-p seq)(elt (get-circular-list-elements seq) i)
(cond ((dotted-list-p seq)
(let ((lbl (1- (length (%butlast seq)))))
(if (< i lbl)
(elt (%butlast seq) i)
(if (= i lbl)
(car (last seq))
(cdr (last seq))))))
((not (sequencep seq)) seq)
(T (elt seq i)))))
(defun GET-ELTS (seq loseqs index)
"Subfunction of MAP-INTO...."
(let ((answers nil))
(if (null (sequencep seq))(list seq)
(if (null loseqs)(list (%elt seq index))
(append (list (%elt seq index))
(dolist (req loseqs (nreverse answers))
(if (sequencep req)(push (%elt req index) answers)
(push req answers))))))))
(defun %EVERY (predicate sequence)
"New definition of the every predicate. In MCL, for example, EVERY infinite loops
when it encounters a circular list. This one doesnt. Also processes dotted lists."
(if (circular-list-p sequence)
(every predicate (get-circular-list-elements sequence))
;;kr010615: added the (dotted-list-p ) , because otherwise, it can crap out.
;; as the comment further above seems to say that the whole point of
;; (%every ) was to be immune to dotted lists, i am surprised to
;; find that this seemed to fail so obviously !!
(if (dotted-list-p sequence)
;;kr010615: i hope i got the intent of this fn right with the following:
(and (every predicate (%BUTLAST sequence))
(funcall predicate (cdr (last sequence)))
)
(every predicate sequence))))
#+ignore
(defun %EVERY (predicate sequence &rest more-sequences)
""
(let* ((all-seqs (if more-sequences
(append (list sequence) more-sequences)
(list sequence)))
(min (get-min-seq-length all-seqs)))
;;(format t "sequence == ~a, sequence length == ~d~%" all-seqs min)
(dotimes (index min)
(when (not (apply predicate (get-elts sequence more-sequences index)))
(return-from %every nil)))
(return-from %every T)))
(defun %SOME (predicate sequence &rest more-sequences)
""
(if (circular-list-p sequence)
(some predicate (get-circular-list-elements sequence))
(let* ((all-seqs (if more-sequences
(append (list sequence) more-sequences)
(list sequence)))
(min (get-min-seq-length all-seqs)))
;;(format t "sequence == ~a, sequence length == ~d~%" all-seqs min)
(dotimes (index min)
(when (apply predicate (get-elts sequence more-sequences index))
(return-from %some T)))
(return-from %some nil))))
#|
#+(or lucid allegro)
(setf (symbol-function '%some) #'some)
#+(or lucid allegro)
(setf (symbol-function '%every) #'every)
|#
(defun %LENGTH (lst)
"Just like length, except if its dotted, it uses our %list-length def."
(if (dotted-list-p lst)
(%list-length lst)
(length lst)))
(defun GET-MIN-SEQ-LENGTH (seqs)
"Function which, when given a list of sequences, returns the list of the
shortest, uses the loop MINIMIZE clause if loop is available, otherwise
does some iteration 'hair' to get the same result."
#+(or symbolics lucid aclpc)(loop for seq in seqs minimize (%length seq))
#-(or symbolics lucid aclpc)
(let ((tmp most-positive-fixnum))
(dolist (seq seqs tmp)
(let ((l (%length seq)))
(if (numberp l) ;; if its not circular
(when (< l tmp)
(setf tmp l))))))
)
;;; MAP-INTO: Symbolics and Allegro and MCL have it,
;;; the other big three dont, and Allegro\PC does not have it.
;;; (loop for seq on sequences
;;; for arg on args
;;; do (if (listp (first seq))
;;; (setf (first arg)(pop (first seq)))
;;; (setf (first arg)(aref (first seq) i))))
;;; (apply function args))))
;;; ... seems to cause a bug in ACL\PC.... fixed by patch103.fasl:
#-(or symbolics allegro mcl lucid) ;;; for lucid, you need the patch.
(defun MAP-INTO (result-sequence function &rest sequences)
"Part of CLtL2: only symbolics and allegro and MCL have it...."
(let ((args (make-list (length sequences)))
(n (if (listp result-sequence) most-positive-fixnum
(array-dimension result-sequence 0))))
(when sequences
(setf n (min n (get-min-seq-length sequences))))
(flet
((do-one-call (i)
(loop for seq on sequences
for arg on args
do (if (listp (first seq))
(setf (first arg)(pop (first seq)))
(setf (first arg)(aref (first seq) i))))
(apply function args))
(do-result (i)
(if (and (vectorp result-sequence)
(array-has-fill-pointer-p result-sequence))
(setf (fill-pointer result-sequence)
(max i (fill-pointer result-sequence))))))
(declare (inline do-one-call))
(if (listp result-sequence)
(loop for i from 0 to (- n 1)
for r on result-sequence
do (setf (first r)(do-one-call i)))
(loop for i from 0 to (- n 1)
do (setf (aref result-sequence i)(do-one-call i))
finally (do-result n))))
result-sequence))
#+lucid
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp 'map-into) ;;; you have the lucid patch, use their definition.
(defun MAP-INTO (result-sequence function &rest sequences)
"Part of CLtL2: only symbolics and allegro and MCL have it...."
(let ((args (make-list (length sequences)))
(n (if (listp result-sequence) most-positive-fixnum
(array-dimension result-sequence 0))))
(when sequences
(setf n (min n (get-min-seq-length sequences))))
(flet
((do-one-call (i)
(loop for seq on sequences
for arg on args
do (if (listp (first seq))
(setf (first arg)(pop (first seq)))
(setf (first arg)(aref (first seq) i))))
(apply function args))
(do-result (i)
(if (and (vectorp result-sequence)
(array-has-fill-pointer-p result-sequence))
(setf (fill-pointer result-sequence)
(max i (fill-pointer result-sequence))))))
(declare (inline do-one-call))
(if (listp result-sequence)
(loop for i from 0 to (- n 1)
for r on result-sequence
do (setf (first r)(do-one-call i)))
(loop for i from 0 to (- n 1)
do (setf (aref result-sequence i)(do-one-call i))
finally (do-result n))))
result-sequence))
)
) ;;;; end lucid map-into condition and eval-when....
(defun MAP-VECTOR (func v &key save (modify t))
"Maps a function of one argument over the elements of a simple
vector: if modify is t the vector elements are destructively
modified to contain the result of the function application.
if save is t, the results of the function application are
returned as a list."
(let ((len (length v))
(answers nil)
(result nil))
;; KOT answer and len are never used, whazzup?
(declare (ignore answers len))
(if modify (setf result (map-into v func v))
(progn (map 'vector func v)
(setf result v)))
(if save (return-from map-vector (coerce 'list result))
(return-from map-vector result))))
#|
(if save
(dotimes (i len (nreverse answers))
(setf result (funcall func (svref (the simple-vector v) i)))
(push result answers)
(when modify (setf (svref (the simple-vector v) i) result)))
(dotimes (i len v)
(setf result (funcall func (svref (the simple-vector v) i)))
(when modify (setf (svref (the simple-vector v) i) result))))))
|#
;;; This is where the defstruct access functions are created automatically.
;;;kr010615: question: why would this not be called higher up, a lot closer to the definition ?
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
(make-defstruct-access-functions)
)
;;; KOT hackery -- in Allegro 4.[12], defstructs of the form
;;; (defstruct (foo (:constructor make-foo (<lambda-list>))) slot1 slot2)
;;; result in the standard constructor slot being nil, so look instead at the
;;; boa-constructors slot of the defstruct definition. So redefine one of
;;; the access functions after the make-defstruct-accessor-functions above.
;;; Note however, that in order to be able to just funcall
;;; get-defstruct-constructor with no arguments (see ALLOCATE-STRUCT), the
;;; :constructor must have a lambda-list with no required arguments. with 0
;;; arguments, since allocate-struct does that. Note also that it might be
;;; nicer to have this abstracted a bit, but such is not the nature of the
;;; beast.
#+(or allegro-v4.1 allegro-v4.2)
(defun get-defstruct-constructor (name)
(let* ((struct-def (get-defstruct-descriptor name))
(constructors (excl::dd-boa-constructors struct-def)))
(or
(defstruct-descriptor-ref struct-def :constructor)
(if constructors
(or
(some #'(lambda (constructor)
(when (member (first (second constructor))
lambda-list-keywords)
;; acceptable, return fun-name
(car constructor)))
constructors)
(error
"No constructors are available which can be called without ~
arguments for defstruct type ~A~%" name)))
(error "No constructor defined for defstruct type ~A~%" name))))
(defun LOOKUP-OBJECT (X &key (mode :save))
"Accessor to the global object hashtable."
(rassoc x (gethash (%type-of x)(if (equal mode :save)
*save-object-hash-table*
*load-object-hash-table*))
:test #'equalp))
(defun CACHE-OBJECT (x &key (mode :save))
"If the object is a structured object, cache the object in the object
hash table, if it isnt already there, along with its variable designation."
(push (CONS (makevar) x)
(gethash (%type-of x)
(if (equal mode :save) *save-object-hash-table*
*load-object-hash-table*)))
x)
(defun LOOKUP-OBJECT-OR-CACHE (x)
"Given an object's ascii form, look up the object, or create an object
by evaling x."
(cond ((null (lookup-object (eval x) :mode :load))
(cache-object (eval x) :mode :load))
(T x)))
(defun OBJECT-VAR (some-object &optional mode)
"The structure of the object htabs entries is (key . object),
finding the cell with lookup-object, then the first element of the CONS!"
(if (null mode)(setf mode *mode-for-object-var*))
(let ((lo (lookup-object some-object :mode *mode-for-object-var*)))
(setf lo
(cond ((null lo)(warn "couldnt find ~a in object var!" some-object) NIL)
((listp lo)(first lo))
(T lo)))))
(defun SET-OBJECT-VAR (object new-var)
"Given object and new var, and mode, set the appropriate hash table
key/value to the new-var."
(let* ((mode *mode-for-set-object-var*)
(there (lookup-object object :mode mode)))
(when (not there)(cache-object object :mode *mode-for-object-var*))
(rplaca (lookup-object object :mode *mode-for-object-var*)
(object-var new-var))))
(defsetf object-var set-object-var)
(defun %STRUCTURE-p (symbol)
"predicate, returns t if symbol names a struct."
(funcall *vendor-dependent-defstruct-symbol-function* symbol))
(defun GET-SYMBOL-DEFSTRUCT-SPEC (symbol)
""
(if (not (symbolp symbol)) nil
(funcall *vendor-dependent-defstruct-symbol-function* symbol)))
;;; Structure sharing with lists....
;;; ===================================== TESTS ===============================
#| Directions for using the tests:
========== === ===== === =====
kr010615: started adding :if-exists :supersede to the (save-object ) calls.
kr010620: started adding a section to the test functions that reads back
the saved file, and compared the loaded data with the original,
using (equalp ). this will however not detect any case-differences
in strings, which however are presumably unlikely anyway.
|#
#-(or akcl)
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
;; set the following to an existing directory ! :
(defvar *nasty-path*
#+aclpc "c:\\"
#+lispm "e:>kerry>"
#+mcl "Macintosh HD:Lisp:"
;; UNIX BOX PATH:
#+(or excl akcl lucid) "/users/kerry/save-object/tests/"
#+(or :CMU :SBCL) "/tmp/save-object/tests/"
)
(defvar *nasty-extension* #+aclpc ".lsp" #-aclpc ".lisp")
;;kr010607: let's use this more consistently in the tests...
;; eliminated (NASTY-PATH ) instead.
;;
(defun GET-NASTY-PATH (filename)
(concatenate 'string *nasty-path* filename *nasty-extension*))
(defstruct (WHIZ (:copier %do-whiz))
(A 25.0 :type float :read-only nil)
(b PI :type float :read-only nil)
(c "foo label" :type string :read-only nil)
(d #c(0 1) :type complex :read-only nil)
(e (make-hash-table :test #'equal) :type t :read-only nil)
)
(defun TEST-SO-MULT ()
(let* ((file-path (GET-NASTY-PATH "filetest")))
;; KOT -- this results in compiler warning for var 'it', maybe
;; with-saved-objects isn't quite kosher ...
(with-saved-objects (it file-path ;;;"filetest.dat"
:direction :output
:if-exists :append
:if-does-not-exist :create)
"this is a filetest.")
)
)
(defun TEST-SO-MULT-1 ()
(let* ((file-path (GET-NASTY-PATH "filetest-1")))
;; KOT -- this results in compiler warning for var 'it', maybe
;; with-saved-objects isn't quite kosher ...
(with-saved-objects (it file-path ;;;"filetest.dat"
:direction :output
:if-exists :append
:if-does-not-exist :create)
(make-whiz)
(make-whiz)
(make-whiz)
(make-boo1))
file-path)
)
#+(or pcl clos :SBCL)
(eval-when #+(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
#-(or :SBCL :CMU18) (:compile-toplevel :load-toplevel :execute)
;; *** NASTY TEST SUITE: A collection of self-referencing consolas that
;; put this code to the test!
(setf *print-circle* t)
(defvar l '(a b c d e f) "test list") ;; KOT being anal
(defvar b nil "test boo") ;; KOT being anal
(defvar b1 nil "test boo1") ;; KOT being anal
(defvar n nil "for franz test") ;;kr010607: this is needed too
(setf (third l) (cdr l))
(defstruct (boo (:type list)) x y)
(setq b (make-boo
:x (vector 1 2 (make-hash-table) 4)
:y (make-boo :x '(#\a #c(1.7 4.99)))))
(defstruct boo1 x y)
(setq b1 (make-boo1
:x (vector 1 2 (make-hash-table) 4)
:y (make-boo :x '(#\a #c(1.7 4.99)))))
;; Test Classes:
(defclass SLOTLESS ()
((a)(B)(c)(d)(e)))
(defclass BOGON ()
((name :initarg :name
:type string
:accessor bogon-name
:documentation ""))
(:default-initargs :name "")
(:documentation ""))
(defclass TEST (bogon)
((a :initarg :a)
(b :initarg :b)
(c :initarg :c))
(:default-initargs :a nil
:b nil
:c nil)
(:documentation "Simple test class for the examples below."))
(defclass ZYGON ()
((a :initform (make-instance 'slotless) :allocation :class)
(b :initform (make-instance 'test))
(c :initform (make-instance 'test) :allocation :class))
(:documentation "tests the saving of initforms and slotvalues of
allocation class..."))
(defclass ZYG ()
((a :initform (make-instance 'slotless))
(b :initform (make-instance 'test))
(c :initform (make-instance 'bogon))
(d :initform (make-instance 'zygon))))
;;kr010620: this helps with automated correctness testing.
;; will load back in, and compare with the original data, complaining if necessary.
;;
(defun load-back-and-compare-for-correctness (original-data the-file test-name)
(load the-file)
(if (equalp DATABASE:*DB-INPUT* original-data)
(format t "~%~A passed ok~&" test-name)
(warn "~A failed: not equalp between DATABASE:*DB-INPUT* = ~A and the original data = ~A~&"
test-name DATABASE:*DB-INPUT* original-data)
)
)
(defvar *test-cons-save* (cons 10 (cons (make-hash-table :test #'equal)
(make-array 20))))
(defun TEST-CONS-SAVE ()
"tests a toplevel dotted list, a hash-table, and a vector"
(let* ((the-file (GET-NASTY-PATH "cons-save-test")))
(save-object *test-cons-save* the-file :if-exists :supersede)
;;kr010620: let's load back in, and compare with the original:
(load-back-and-compare-for-correctness *test-cons-save* the-file 'TEST-CONS-SAVE)
)
)
(defun TEST-UNBOUND-SLOT-SAVE ()
"tests a clos object, without setting any of its slots"
(let ((inst (make-instance 'slotless))
(the-file (GET-NASTY-PATH "slotless-test-save"))
)
(save-object inst the-file :if-exists :supersede)
;;kr010620: let's load back in, and compare with the original:
;; this will actually cause an unjustified warning, because apparently clos objects
;; never are (equalp )
;;(load-back-and-compare-for-correctness inst the-file 'TEST-UNBOUND-SLOT-SAVE)
))
(defun FRANZ-TEST ()
(when (probe-file (GET-NASTY-PATH "zood"))
(delete-file (GET-NASTY-PATH "zood")))
(setf n "franz")
(setf l `("hugo" "pepi" ,n "susi" ,n))
(save-object l (GET-NASTY-PATH "zood")))
(defun FRANZ-TEST-1 ()
(when (probe-file (GET-NASTY-PATH "zoob"))
(delete-file (GET-NASTY-PATH "zoob")))
(save-object '(A 'A N '(a b c) (Z Y S) 'S '44 '20.6 'XXXX "dfdfjdh" q)
(GET-NASTY-PATH "zoob")))
(defun LESS-NASTY-INSTANCE-TEST ()
"One instance with one self-reference."
(let ((a (make-instance 'test))
(the-file (GET-NASTY-PATH #-aclpc "little-instance"
#+aclpc "linst1"
))
)
(setf (slot-value a 'a) a)
(setf (slot-value a 'b) a)
(save-object a the-file :if-exists :supersede)
;;kr010620: let's load back in, and compare with the original:
;; this will actually cause an unjustified warning, because apparently clos objects
;; never are (equalp )
;;(load-back-and-compare-for-correctness a the-file 'LESS-NASTY-INSTANCE-TEST)
))
(defvar *a)
(defvar *b)
(defvar *c)
(defvar *d)
(defvar *the-nasties* nil "stored here for later review.")
(defmethod INITIALIZE-INSTANCE :AFTER ((self bogon) &rest plist)
(declare (ignore plist))
(push self *the-nasties*))
#|
#-(or akcl lispm)
(defmethod PRINT-OBJECT ((self bogon) stream)
(with-slots (name) self
(format stream "#<Test Instance ~A>" name)))
#+lispm
(defmethod PRINT-OBJECT ((self bogon) stream)
(with-slots (name) self
(format stream "#<~A: ~A>" name (si:%pointer self))))
|#
(defstruct foo a b c)
(defun NASTY-STRUCT-TEST ()
(let ((a (make-foo))
(the-file (GET-NASTY-PATH "nnn"))
)
(setf (foo-a a) a)
(save-object a the-file :if-exists :supersede)
;;kr010620: let's load back in, and compare with the original:
;; actually, this will hang in an endless loop, caused by (equalp ) running around
;; in the self-referential structure !
;;(load-back-and-compare-for-correctness a the-file 'NASTY-STRUCT-TEST)
))
#+lispm
(defun NASTY-ARRAY-TEST ()
""
(let ((them! nil))
(tv:noting-progress ("Nasty Array Allocation!")
(setf them! (LIST
(make-array '(50 20 36) :element-type 'float
:initial-element PI)
(make-array 10 :initial-contents
(make-list 10
:initial-element "STRINGS!"))
(make-array '(21 16 33 4) :element-type
'(unsigned-byte 32)
:initial-element 1024)
(make-array '(20 20) :element-type 'character
:initial-element #\!)))
)
(tv:noting-progress ("Nasty Array Storage!")
(save-object them! (GET-NASTY-PATH "horrid-arrays")))))
#-lispm
(defun NASTY-ARRAY-TEST ()
""
(let ((them! (LIST
(make-array '(50 20 36) :element-type 'float
:initial-element pi)
(make-array 10 :initial-contents
(make-list 10 :initial-element "STRINGS!"))
(make-array '(21 16 33 4) :element-type
'(unsigned-byte 32)
:initial-element 666)
(make-array '(20 20) :element-type 'character
:initial-element #\!))))
(save-object them! (GET-NASTY-PATH "horrid-arrays"))))
(defun NASTY-INSTANCE-TEST ()
""
(setf *a (make-instance 'test :name "A")
*b (make-instance 'test :name "B")
*c (make-instance 'test :name "C"))
(setf (slot-value *a 'a) *b)
(setf (slot-value *a 'b) *c)
(setf (slot-value *b 'a) *a)
(setf (slot-value *b 'b) *c)
(setf (slot-value *c 'a) *b)
(setf (slot-value *c 'b) *a)
(save-object *a (GET-NASTY-PATH #-aclpc "nasty-inst"
#+aclpc "ninst"
)))
(defun INSTANCE-TEST ()
" A ----> B ----> C ----> D
^ ^ | V
|-------+-------- |
|---------------- "
(setf *a (make-instance 'test :name "A")
*b (make-instance 'test :name "B")
*c (make-instance 'test :name "C")
*d (make-instance 'test :name "D"))
(setf (slot-value *a 'a) *b)
(setf (slot-value *b 'a) *c)
(setf (slot-value *c 'a) *d)
(setf (slot-value *c 'b) *a)
(setf (slot-value *d 'a) *b)
(save-object *a (GET-NASTY-PATH "bobtest")))
;;;;
(defun INSTANCE-TEST-2 ()
"BACKPOINTERS ON ALL THE PREVIOUS EXAMPLES
(two links on each node: twice as many as before, ten.)
A <---> B <---> C <---> D
^ ^ V V
V--<>---+-------^ |
V----<>---------^ "
(setf *a (make-instance 'test :name "A")
*b (make-instance 'test :name "B")
*c (make-instance 'test :name "C")
*d (make-instance 'test :name "D"))
(setf (slot-value *a 'a) *b)
(setf (slot-value *a 'b) *c)
(setf (slot-value *b 'a) *c)
(setf (slot-value *b 'b) *d)
(setf (slot-value *b 'c) *a)
(setf (slot-value *c 'a) *d)
(setf (slot-value *c 'b) *a)
(setf (slot-value *c 'c) *d)
(setf (slot-value *d 'a) *b)
(setf (slot-value *d 'b) *c)
(save-object *a (GET-NASTY-PATH "bobtest2")))
(defvar *nasty-hash-tables* nil)
(defun NASTY-HASH-CHAIN-TEST ()
" Makes a nested hash table net like this:
a->b b->c c->d d->e e->a
a-----b-----c-----d----->e----->|
^ v
|<---------------------<---------
e->a e->a e->a e->"
(setf *nasty-hash-tables* nil)
(let* ((a (make-hash-table))
(b (make-hash-table))
(c (make-hash-table))
(d (make-hash-table))
(e (make-hash-table)))
(pushnew a *nasty-hash-tables*)
(pushnew b *nasty-hash-tables*)
(pushnew c *nasty-hash-tables*)
(pushnew d *nasty-hash-tables*)
(pushnew e *nasty-hash-tables*)
(setf (gethash 'a->b b) a)
(setf (gethash 'b->a a) b)
(setf (gethash 'b->c c) b)
(setf (gethash 'c->b b) c)
(setf (gethash 'c->d d) c)
(setf (gethash 'd->e e) d)
(setf (gethash 'e->a a) e)
(save-object a (GET-NASTY-PATH "qhash"))))
(defun NASTIER-STRUCT-TEST ()
(save-object b1 (GET-NASTY-PATH "b1-test")))
(defun GET-HTAB-KEYS (htab)
(let ((values nil))
(maphash #'(lambda (key val)
(declare (ignore val))
(push key values))
htab)
values))
(defvar *test-struct-form*
'(SETQ *DB-INPUT*
(LET* ((.%%SL%%.1 (%ALLOCATE-INSTANCE 'BOO1)))
(FILL-STRUCT .%%SL%%.1 '(BOO1)))))
(defvar *test1* (list (make-instance 'test)
(make-hash-table :test #'eq)
(list (make-foo)
(make-foo)
(list (make-instance 'test)
#c(0 1)
(make-foo)))))
;;kr010612: ignore this, because this is not referred to from anywhere and generates
;; a bunch of compiler warnings. it is also not clear what the point of it is supposed to be.
#+ignore
(defun DESCRIBE-STRUCT-INSTANCE (name)
(let* ((desc (get-defstruct-descriptor name))
(type (get-defstruct-type name))
(conc-name (get-defstruct-conc-name name))
(predicate (get-defstruct-predicate name))
(include (get-defstruct-include name))
(included-by (get-defstruct-included-by name))
(print-function (get-defstruct-print-function name))
(copier (get-defstruct-copier name))
(constructor (get-defstruct-constructor name))
;; KOT this isn't enough args for get-defstruct-slot-descriptor;
;; it wants struct-name slot-name, not sure which this name is.
(sds (get-defstruct-slot-descriptor name))
)
(dolist (sd sds) (describe-struct-slot sd))))
;;;kr010607: let's start to collect all these test, so it is less of a disorganized zoo.
;;; this really should become a suite of regression tests.
;;;
(defun test-all ()
(TEST-CONS-SAVE)
(TEST-UNBOUND-SLOT-SAVE)
(FRANZ-TEST)
(FRANZ-TEST-1)
(LESS-NASTY-INSTANCE-TEST)
(NASTY-STRUCT-TEST)
(NASTY-ARRAY-TEST)
(NASTY-INSTANCE-TEST)
(INSTANCE-TEST)
;; with backpointers:
(INSTANCE-TEST-2)
(NASTY-HASH-CHAIN-TEST)
(NASTIER-STRUCT-TEST)
;; the following seem to need a global variable IT to be set
;;(TEST-SO-MULT)
;;(TEST-SO-MULT-1)
)
) ;; end of tests eval-when....
) ;; end of eval-when of all TESTS.
;;; ============================== END OF TESTS ===============================
#-(or aclpc :SBCL)
(defun QUIT ()
"sick of having to remember which one it is!"
#+lispm nil
#+aclpc(user::quit)
#+lucid(lcl::quit)
#+mcl (user::quit)
#+akcl(bye)
#+cmu(user::quit)
#+excl(excl::exit)
)
;;;kr010214: let's try this one for sbcl too:
#+(or aclpc :SBCL)
(defun INSTANCE-NAME (instance)
(class-name (class-of instance)))
;;; was in so-other.lisp.
;; Utility for defining downward funargs...
(defvar *verbose* nil)
(defvar *max-list-length-limit* 1000)
#+mcl (setf *global-unsaveable-slotnames* '(CCL::FRED-HISTORY))
(defvar *rep-so-far* nil)
(defmacro EDF (&rest elts)
"Embedded dump-form (EDF) macro. Reconstructs the elements
into a (local) lisp structure using integer encoding."
`(read-object-from-list ,elts))
(defun EDF-DUMP-FORM (instance)
(setf *rep-so-far* nil)
(write-object-to-list instance)
`(EDF . ,(reverse *rep-so-far*))
)
(defvar *list-datum-counter* -1)
(defun LONG-REPEATING-LIST-P (X)
(and (listp x)
(not (stringp x))
(not (%circular-list-p x))
(> (length x) *max-list-length-limit*)
(every #'(lambda (e)(equal e (first x)))
x)))
(defun FUNCTION-P (x)
"Predicate: returns t if something is a compiled function form, or a LAMBDA."
(and (consp x)
(eq (car x) 'function)
(consp (cadr x))
(eq (car (cadr x)) 'lambda)))
(defun GET-COMPILER-MACRO (name)
""
#-mcl (declare (ignore name))
#+mcl (gethash name ccl::*compiler-macros*)
)
(defun CREATE-COMPILER-MACRO (name functional-argument-position)
""
(cond ((get-compiler-macro name)
(format t "~%;~A already defined." name) nil)
(T `(define-compiler-macro ,name (&rest args)
(let ((funarg (nth ,functional-argument-position args)))
(if (function-p funarg)
(make-flet funarg ',name ,functional-argument-position args)
(cons ',name args)))))))
(defun MAKE-FLET (funarg new-name functional-argument-position
args &aux (body (copy-list args)))
""
(setf (nth functional-argument-position body)
(list 'function 'not-alambda))
`(flet ((not-alambda ,(cadr (cadr funarg)) ,@(cddr (cadr funarg))))
(declare (dynamic-extent #'not-alambda))
,(cons new-name body)))
;;; ============ file format encoding and memoization code. ========
;;; Constants.
(defconstant +cons-tag+ 1)
(defconstant +vector-tag+ 2)
(defconstant +hash-table-tag+ 3)
(defconstant +standard-object-tag+ 4)
(defconstant +simple-object-tag+ 5)
(defconstant +table-tag+ 6)
(defconstant table-tag 7)
(defconstant single-tag 8)
(defconstant structure-tag 9)
(defconstant +array-tag+ 10)
(defconstant +compfunction-tag+ 11)
(defconstant +handle-tag+ 12)
(defconstant +defstruct-object-tag+ 13)
;;; Memoization.
(defun MEMO (fn name key test)
""
(let ((table (make-hash-table :test test)))
(setf (get name 'memo) table)
#'(lambda (&rest args)
(let ((k (funcall key args)))
(multiple-value-bind (val found-p)
(gethash k table)
(if found-p val
(setf (gethash k table)(apply fn args))))))))
(defun MEMOIZE (fn-name &key (key #'first)(test #'eql))
""
(setf (symbol-function fn-name)
(memo (symbol-function fn-name) fn-name key test)))
(defun CLEAR-MEMOIZE (fn-name)
""
(let ((table (get fn-name 'memo)))
(when table (clrhash table))))
(defmacro DEFINE-MEMO (fn args &body body)
""
`(memoize (defun ,fn ,args . ,body)))
;;; Recordtable stuff.
(defstruct MEMO
(data (make-hash-table))
(count 0))
(defun GET-TABLE-ENTRY (object rec)
""
(gethash object (memo-data rec)))
(defun SET-TABLE-ENTRY (object rec value)
""
(setf (gethash object (memo-data rec)) value))
(defsetf GET-TABLE-ENTRY SET-TABLE-ENTRY)
(defun WRITE-OBJECT-TO-LIST (object)
""
(setf *rep-so-far* nil)
(let ((table (make-memo)))
(find-multiple-references object table)
(%%save-object object table)))
(defun WRITE-OBJECT-TO-FILE (object file)
""
(let ((table (make-memo)))
(find-multiple-references object table)
(%save-object object file table)))
(defun FIND-MULTIPLE-REFERENCES (object table)
""
(when *verbose*
(format t "MULT: ~A~%" (if (and (listp object)
(not (dotted-list-p object)))
(length object) object)))
(let ((entry (get-table-entry object table)))
(case entry
((nil)
(setf (get-table-entry object table) t)
(find-recursive-references-1 object table))
((t)
(setf (get-table-entry object table)
(memo-count table))
(incf (memo-count table))))))
(defun FIND-RECURSIVE-REFERENCES (object table)
""
(typecase object
(CONS (find-multiple-references (first object) table)
(find-multiple-references (rest object) table))
((OR CHARACTER NUMBER STRING SYMBOL))
(HASH-TABLE
(find-multiple-references (hash-table-test object) table)
(maphash #'(lambda (key value)
(find-multiple-references key table)
(find-multiple-references value table))
object))
(STANDARD-OBJECT
(let* ((class (class-of object))
(name (class-name class))
(named-class (and name (find-class name))))
(find-multiple-references (if named-class name class) table)
(let* ((slots (class-slots class)))
(dolist (slot-description slots)
(let ((name (get-slot-name slot-description)))
(when (slot-boundp object name)
(find-multiple-references name table)
(find-multiple-references (slot-value object name)
table)))))))
(VECTOR
(let ((len (length object)))
(dotimes (i len)
(find-multiple-references (aref object i)
table))))
(T (error "There is no way to save an ~s in a file." object))))
(defun %FUNCTIONP (X)
"Special function symbol predicate."
(compiled-function-p x))
(defun FIND-RECURSIVE-REFERENCES-1 (object table)
""
(when *verbose* (format t "DEALING WITH: ~S.~%" object))
(cond #+mcl ((ccl::handlep object))
((OR
(builtin-instance-p object)
(pathnamep object)
(%FUNCTIONP object)
(CHARACTERP object)
(NUMBERP object)
(stringp object)
(SYMBOLp object)))
((cons-p object)
(find-multiple-references (first object) table)
(find-multiple-references (rest object) table))
((dotted-list-p object)
(find-multiple-references (first object) table)
(find-multiple-references (rest object) table))
((circular-list-p object)
(let ((it (get-circular-list-elements object)))
(find-multiple-references (first it) table)
(find-multiple-references (rest it) table)))
((and (listp object)(> (length object) 1000))
(warn "cant save lists of length: ~d." (length object)))
((consp object)
(find-multiple-references (first object) table)
(find-multiple-references (rest object) table))
((HASH-TABLE-P OBJECT)
(find-multiple-references (hash-table-test object) table)
(maphash #'(lambda (key value)
(find-multiple-references key table)
(find-multiple-references value table))
object))
((structure-p object)
(let* ((name (get-defstruct-name object)))
(format t "doing instance of class: ~a~%" name)
(find-multiple-references name table)
(let* ((slots (get-defstruct-slot-descriptors name)))
(dolist (slot-description slots)
(let ((name (get-defstruct-slot-name slot-description)))
(if (member name *global-unsaveable-slotnames* :test #'equal)
(warn "Wont be saving defstruct slot: ~a" name)
(progn (when (defstruct-slot-boundp object name)
(find-multiple-references name table)
(find-multiple-references (get-defstruct-slot-value object name)
table)))))))))
((typep object 'STANDARD-OBJECT)
(let* ((class (class-of object))
(name (class-name class))
(named-class (and name (find-class name))))
(format t "doing instance of class: ~a~%" name)
(find-multiple-references (if named-class name class) table)
(let* ((slots (class-slots class)))
(dolist (slot-description slots)
(let ((name (get-slot-name slot-description)))
(if (member name *global-unsaveable-slotnames* :test #'equal)
(warn "Wont be saving slot: ~a" name)
(progn (when (slot-boundp object name)
(find-multiple-references name table)
(find-multiple-references (slot-value object name)
table)))))))))
((vectorp object)
(let ((len (length object)))
(dotimes (i len)
(find-multiple-references (aref object i)
table))))
(T (error "There is no way to save an ~s in a file." object))))
(defun %%SAVE-OBJECT (object table)
""
(push (memo-count table) *rep-so-far*)
(%save-object-to-list object table))
(defun %SAVE-OBJECT (object file table)
""
(with-open-file (stream file :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(write-table-size (memo-count table) stream)
(save-object-to-stream object stream table)))
(defun %SAVE-OBJECT-TO-LIST (object table)
""
(let ((entry (get-table-entry object table)))
(cond ((already-saved-p entry)
(push-backward-reference entry))
(T (cond ((multiple-reference-p entry)
(push-enter-multiple-reference entry)
(mark-as-already-saved object table entry))
(T (push-enter-single-reference)))
(%save-actual-object-1 object table)))))
(defun SAVE-OBJECT-TO-STREAM (object stream table)
""
(let ((entry (get-table-entry object table)))
(cond ((already-saved-p entry)
(write-backward-reference entry stream))
(T (cond ((multiple-reference-p entry)
(write-enter-multiple-reference entry stream)
(mark-as-already-saved object table entry))
(T (write-enter-single-reference stream)))
(save-actual-object-1 object stream table)))))
(defun SAVE-ACTUAL-OBJECT (object stream table)
""
(typecase object
(cons
(write-tag +cons-tag+ stream)
(save-object-to-stream (first object) stream table)
(save-object-to-stream (rest object) stream table))
((or character number string symbol)
(write-simple-object object stream))
(hash-table
(write-tag +hash-table-tag+ stream)
(save-object-to-stream (hash-table-test object) stream table)
(write-length (hash-table-count object) stream)
(maphash #'(lambda (key value)
(save-object-to-stream key stream table)
(save-object-to-stream value stream table))
object))
(standard-object
(write-tag +standard-object-tag+ stream)
(let* ((class (class-of object))
(name (class-name class))
(named-class (and name (find-class name))))
(save-object-to-stream (if (eq class named-class) name class)
stream table)
(let* ((slots (class-slots class))
(slot-count (loop for slotd in slots
as name = (get-slot-name slotd)
count (slot-boundp object name))))
(write-length slot-count stream)
(dolist (slot-description slots)
(let ((name (get-slot-name slot-description)))
(when (slot-boundp object name)
(save-object-to-stream name stream table)
(save-object-to-stream (slot-value object name) stream table))
)))))
((vector t)
(write-tag +vector-tag+ stream)
(let ((len (length object)))
(write-length len stream)
(dotimes (i len)
(save-object-to-stream (aref object i) stream table))))))
(defun DEFSTRUCT-SLOT-BOUNDP (instance slotname)
(declare (ignore instance slotname))
T)
(defclass HANDLE ()
())
(defvar *wotf-debug* T)
(defun SAVE-ACTUAL-OBJECT-1 (object stream table)
""
(if (member object *global-unsaveable-slotnames* :test #'equal)
(warn "Wont be saving slot: ~a" object)
(progn
(when *wotf-debug* (format t "SAVING: ~A~%" object))
(cond
#+mcl ((ccl::handlep object)(write-tag +handle-tag+ stream)
(write-simple-object 'HANDLE stream))
((OR (builtin-instance-p object)
(pathnamep object)
(%FUNCTIONP object)
(CHARACTERP object)
(NUMBERP object)
(STRINGP object)
(SYMBOLP object))
(write-simple-object object stream))
((dotted-list-p object)
(write-tag +cons-tag+ stream)
(save-object-to-stream (first object) stream table)
(save-object-to-stream (rest object) stream table))
((cons-p object)
(write-tag +cons-tag+ stream)
(save-object-to-stream (first object) stream table)
(save-object-to-stream (rest object) stream table))
((and (listp object)(> (length object) 1000))
(warn "cant save lists of length: ~d." (length object)))
((and (listp object)(null (list-length object)))
(let ((it (get-circular-list-elements object)))
(write-tag +cons-tag+ stream)
(save-object-to-stream (first it) stream table)
(save-object-to-stream (rest it) stream table)))
((consp object)
(write-tag +cons-tag+ stream)
(save-object-to-stream (first object) stream table)
(save-object-to-stream (rest object) stream table))
((HASH-TABLE-P object)
(write-tag +hash-table-tag+ stream)
(save-object-to-stream (hash-table-test object) stream table)
(write-length (hash-table-count object) stream)
(maphash #'(lambda (key value)
(save-object-to-stream key stream table)
(save-object-to-stream value stream table))
object))
((structure-p object)
(write-tag +defstruct-object-tag+ stream)
(let* ((name (get-defstruct-name object)))
(save-object-to-stream name stream table)
(let* ((slots (get-defstruct-slot-descriptors object))
(slot-count (loop for slotd in slots
as name = (get-defstruct-slot-name slotd)
unless (member name *global-unsaveable-slotnames* :test #'equal)
count (defstruct-slot-boundp object name))))
(write-length slot-count stream)
(dolist (slot-description slots)
(let ((name (get-defstruct-slot-name slot-description)))
(when (and (defstruct-slot-boundp object name)
(not (member name *global-unsaveable-slotnames* :test #'equal)))
(save-object-to-stream name stream table)
(save-object-to-stream (get-defstruct-slot-value object name)
stream table)))))))
((typep object 'STANDARD-OBJECT)
(write-tag +standard-object-tag+ stream)
(let* ((class (class-of object))
(name (class-name class))
(named-class (and name (find-class name))))
(save-object-to-stream (if (eq class named-class) name class)
stream table)
(let* ((slots (class-slots class))
(slot-count (loop for slotd in slots
as name = (get-slot-name slotd)
unless (member name *global-unsaveable-slotnames* :test #'equal)
count (slot-boundp object name))))
(write-length slot-count stream)
(dolist (slot-description slots)
(let ((name (get-slot-name slot-description)))
(when (and (slot-boundp object name)
(not (member name *global-unsaveable-slotnames* :test #'equal)))
(save-object-to-stream name stream table)
(save-object-to-stream (slot-value object name) stream table))
)))))
((vectorp object)
(write-tag +vector-tag+ stream)
(let ((len (length object)))
(write-length len stream)
(dotimes (i len)
(save-object-to-stream (aref object i) stream table))))))))
(defun %SAVE-ACTUAL-OBJECT-1 (object table)
""
(if (member object *global-unsaveable-slotnames* :test #'equal)
(warn "Wont be saving slot: ~a" object)
(progn
(when *wotf-debug* (format t "SAVING: ~A~%" object))
(cond #+mcl ((ccl::handlep object)(push-tag +handle-tag+)
(push-simple-object 'HANDLE))
((OR (builtin-instance-p object)
(pathnamep object)
(%FUNCTIONP object)
(CHARACTERP object)
(NUMBERP object)
(STRINGP object)
(SYMBOLP object))
(push-simple-object object))
((dotted-list-p object)
(push-tag +cons-tag+)
(%save-object-to-list (first object) table)
(%save-object-to-list (rest object) table))
((cons-p object)
(push-tag +cons-tag+)
(%save-object-to-list (first object) table)
(%save-object-to-list (rest object) table))
((and (listp object)(> (length object) 1000))
(warn "cant save lists of length: ~d."
(length object)))
((and (listp object)(null (list-length object)))
(let ((it (get-circular-list-elements object)))
(push-tag +cons-tag+)
(%save-object-to-list (first it) table)
(%save-object-to-list (rest it) table)))
((consp object) (push-tag +cons-tag+)
(%save-object-to-list (first object) table)
(%save-object-to-list (rest object) table))
((HASH-TABLE-P object)
(push-tag +hash-table-tag+)
(%save-object-to-list (hash-table-test object) table)
(push-length (hash-table-count object))
(maphash #'(lambda (key value)
(%save-object-to-list key table)
(%save-object-to-list value table))
object))
((structure-p object)
(push-tag +defstruct-object-tag+)
(let* ((name (get-defstruct-name object)))
(%save-object-to-list name table)
(let* ((slots (get-defstruct-slot-descriptors object))
(slot-count (loop for slotd in slots
as name = (get-defstruct-slot-name slotd)
unless (member name *global-unsaveable-slotnames* :test #'equal)
count (defstruct-slot-boundp object name))))
(push-length slot-count)
(dolist (slot-description slots)
(let ((name (get-defstruct-slot-name slot-description)))
(when (and (defstruct-slot-boundp object name)
(not (member name *global-unsaveable-slotnames* :test #'equal)))
(%save-object-to-list name table)
(%save-object-to-list (get-defstruct-slot-value object name)
table)))))))
((typep object 'STANDARD-OBJECT)
(push-tag +standard-object-tag+)
(let* ((class (class-of object))
(name (class-name class))
(named-class (and name (find-class name))))
(%save-object-to-list (if (eq class named-class) name class) table)
(let* ((slots (class-slots class))
(slot-count (loop for slotd in slots
as name = (get-slot-name slotd)
unless (member name *global-unsaveable-slotnames* :test #'equal)
count (slot-boundp object name))))
(push-length slot-count)
(dolist (slot-description slots)
(let ((name (get-slot-name slot-description)))
(when (and (slot-boundp object name)
(not (member name *global-unsaveable-slotnames* :test #'equal)))
(%save-object-to-list name table)
(%save-object-to-list (slot-value object name) table))
)))))
((vectorp object)
(push-tag +vector-tag+)
(let ((len (length object)))
(push-length len)
(dotimes (i len)
(%save-object-to-list (aref object i) table)))) ))))
(defun ALREADY-SAVED-P (entry)
""
(and (integerp entry)(< entry 0)))
(defun MARK-AS-ALREADY-SAVED (object table entry)
""
(if (null entry)(warn "ENTRY FOR ~A was nil!" object)
(setf (get-table-entry object table)(- (1+ entry)))))
(defun PUSH-BACKWARD-REFERENCE (entry)
""
(if (null entry)(warn "ENTRY was nil!")
(progn (push table-tag *rep-so-far*)
(push (1- (- entry)) *rep-so-far*))))
(defun WRITE-BACKWARD-REFERENCE (entry stream)
""
(if (null entry)(warn "ENTRY was nil!")
(progn (write-datum table-tag stream)
(write-datum (1- (- entry)) stream))))
(defun MULTIPLE-REFERENCE-P (entry)
""
(not (eql entry t)))
(defun PUSH-ENTER-MULTIPLE-REFERENCE (entry)
""
(push +table-tag+ *rep-so-far*)
(push entry *rep-so-far*))
(defun WRITE-ENTER-MULTIPLE-REFERENCE (entry stream)
""
(write-datum +table-tag+ stream)
(write-datum entry stream))
(defun PUSH-ENTER-SINGLE-REFERENCE ()
""
(push single-tag *rep-so-far*))
(defun WRITE-ENTER-SINGLE-REFERENCE (stream)
""
(write-datum single-tag stream))
(defun PUSH-TABLE-SIZE (count)
""
(push count *rep-so-far*))
(defun WRITE-TABLE-SIZE (count stream)
""
(write-datum count stream))
(defun PUSH-TAG (code)
""
(push code *rep-so-far*))
(defun WRITE-TAG (code stream)
""
(write-datum code stream))
(defun PUSH-LENGTH (length)
""
(write-datum length *rep-so-far*))
(defun WRITE-LENGTH (length stream)
""
(write-datum length stream))
(defun PUSH-SIMPLE-OBJECT (object)
""
(cond ((%functionp object)(setf object (get-compiled-function-name object)))
((and (not (symbolp object))(builtin-instance-p object))
(setf object (instance-name object)))
((pathnamep object)(setf object (format nil "~a" object)))
(T NIL))
(push +simple-object-tag+ *rep-so-far*)
(push object *rep-so-far*))
(defun WRITE-SIMPLE-OBJECT (object stream)
""
(cond ((%functionp object)(setf object (get-compiled-function-name object)))
((and (not (symbolp object))(builtin-instance-p object))
(setf object (instance-name object)))
((pathnamep object)(setf object (format nil "~a" object)))
(T NIL))
(write-datum +simple-object-tag+ stream)
(write-datum object stream))
(defun PUSH-DATUM (object)
""
(push object *rep-so-far*))
(defun WRITE-DATUM (object stream)
""
(format stream "~s " object))
(defun READ-OBJECT-FROM-FILE (file)
""
(with-open-file (stream file)
(read-object-from-stream stream)))
(defun READ-OBJECT-FROM-LIST (L)
""
(setf *list-datum-counter* -1)
(%read-object-from-list L))
(defun %READ-OBJECT-FROM-LIST (lst)
""
(let* ((table-size (read-list-datum lst))
(table (make-array table-size)))
(cons-list-object table lst)))
(defun READ-OBJECT-FROM-STREAM (stream)
""
(let* ((table-size (read-datum stream))
(table (make-array table-size)))
(cons-object table stream)))
(defun CONS-LIST-OBJECT (table lst)
""
(let ((entry-code (read-list-datum lst)))
(cond ((equal entry-code +table-tag+)
(read-object-list-contents table lst
(read-list-datum lst)))
((equal entry-code +simple-object-tag+)(read-list-datum lst))
((equal entry-code single-tag)
(read-object-list-contents table lst nil))
((equal entry-code +handle-tag+))
((equal entry-code table-tag)
(svref table (read-list-datum lst)))
(T (error "~a wasnt a valid code!" entry-code)))))
(defun CONS-OBJECT (table stream)
""
(let ((entry-code (read-datum stream)))
(cond ((equal entry-code +table-tag+)
(read-object-contents table stream
(read-datum stream)))
((equal entry-code +simple-object-tag+)(read-datum stream))
((equal entry-code single-tag)
(read-object-contents table stream nil))
((equal entry-code +handle-tag+))
((equal entry-code table-tag)
(svref table (read-datum stream)))
(T (error "~a wasnt a valid code!" entry-code)))))
(defun READ-OBJECT-LIST-CONTENTS (table lst table-index)
""
(let ((tag (read-list-datum lst)))
(cond ((equal tag +cons-tag+)
(let ((object (cons nil nil)))
(when table-index
(setf (aref table table-index) object))
(setf (first object)
(cons-list-object table lst))
(setf (rest object)
(cons-list-object table lst))
object))
((equal tag +hash-table-tag+)
(let ((object (make-hash-table :test
(cons-list-object table lst)))
(count (read-list-datum lst)))
(dotimes (i count)
(setf (gethash (cons-list-object table lst) object)
(cons-list-object table lst)))
object))
((equal tag +standard-object-tag+)
(let* ((class (cons-list-object table lst))
(object (make-instance class))
(slot-count (read-list-datum lst)))
(when table-index
(setf (svref table table-index) object))
(dotimes (i slot-count)
(setf (slot-value object (cons-list-object table lst))
(cons-list-object table lst)))
object))
((equal tag +defstruct-object-tag+)
(let* ((class (cons-list-object table lst))
(object (allocate-struct class))
(slot-count (read-list-datum lst)))
(when table-index
(setf (svref table table-index) object))
(dotimes (i slot-count)
(set-defstruct-slot-value object
(cons-list-object table lst)
(cons-list-object table lst)))
object))
((equal tag +vector-tag+)
(let* ((length (read-list-datum lst))
(vector (make-array length)))
(when table-index (setf (svref table table-index) vector))
(dotimes (i length)
(setf (svref vector i)
(cons-list-object table lst)))
vector))
((equal tag +simple-object-tag+)
(let ((object (read-list-datum lst)))
(when table-index (setf (svref table table-index) object))
object))
((equal tag +handle-tag+))
(T (error "~a wasnt a valid code!" tag)))))
(defun READ-OBJECT-CONTENTS (table stream table-index)
""
(let ((tag (read-datum stream)))
(cond ((equal tag +cons-tag+)
(let ((object (cons nil nil)))
(when table-index
(setf (aref table table-index) object))
(setf (first object)
(cons-object table stream))
(setf (rest object)
(cons-object table stream))
object))
((equal tag +hash-table-tag+)
(let ((object (make-hash-table :test
(cons-object table stream)))
(count (read-datum stream)))
(dotimes (i count)
(setf (gethash (cons-object table stream) object)
(cons-object table stream)))
object))
((equal tag +standard-object-tag+)
(let* ((class (cons-object table stream))
(object (make-instance class))
(slot-count (read-datum stream)))
(when table-index
(setf (svref table table-index) object))
(dotimes (i slot-count)
(setf (slot-value object (cons-object table stream))
(cons-object table stream)))
object))
((equal tag +defstruct-object-tag+)
(let* ((class (cons-object table stream))
(object (allocate-struct class))
(slot-count (read-datum stream)))
(when table-index
(setf (svref table table-index) object))
(dotimes (i slot-count)
(set-defstruct-slot-value object (cons-object table stream)
(cons-object table stream)))
object))
((equal tag +vector-tag+)
(let* ((length (read-datum stream))
(vector (make-array length)))
(when table-index (setf (svref table table-index) vector))
(dotimes (i length)
(setf (svref vector i)
(cons-object table stream)))
vector))
((equal tag +simple-object-tag+)
(let ((object (read-datum stream)))
(when table-index (setf (svref table table-index) object))
object))
((equal tag +handle-tag+))
(T (error "~a wasnt a valid code!" tag)))))
(defun READ-DATUM (stream)
""
(read stream))
(defun READ-LIST-DATUM (lst)
""
(unless (> *list-datum-counter* (1- (length lst)))
(nth (incf *list-datum-counter*) lst)))
;;; eof.
| 270,912 | Common Lisp | .lisp | 6,158 | 35.731893 | 127 | 0.607993 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 253af52d1bc81a514bee0341f0d7c4ec285eecafdb66df8cd51b8e72f165311b | 13,183 | [
-1
] |
13,184 | package.lisp | nixeagle_nisp/mop/package.lisp | (defpackage #:nisp.mop-simple
(:use :cl :eos :iterate :alexandria)
(:export
;; Generic function readers
:generic-function-name :generic-function-method-class
:generic-function-lambda-list :generic-function-method-combination
:generic-function-argument-precedence-order
:generic-function-declarations :generic-function-methods
;; Class readers
:class-direct-slots :class-precedence-list :class-direct-subclasses
:class-direct-default-initargs :class-slots :class-direct-superclasses
:class-default-initargs :class-finalized-p :class-prototype
))
(defpackage #:nisp.mop
(:use :cl :nisp.mop-simple :eos)
(:export :compare-generic-applicable-methods))
(defpackage #:nisp.mop-store
(:use :cl :eos :alexandria :iterate)) | 757 | Common Lisp | .lisp | 18 | 38.722222 | 73 | 0.763908 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | cc42d2c8c515940df8833acbc16142e0176e367c9b46abd05ca248c6444c64b5 | 13,184 | [
-1
] |
13,185 | store.lisp | nixeagle_nisp/mop/store.lisp | (in-package :nisp.mop)
(defun class-slot-name-value-alist (instance)
"Return slot names and values of INSTANCE.
The alist looks something like: ((slot-name . slot-value) ...)."
(mapcar (lambda (slot)
(cons (closer-mop:slot-definition-name slot)
(closer-mop:slot-value-using-class (class-of instance)
instance
slot)))
(class-slots instance)))
(in-package :nisp.mop-store)
(defun generate-slot-specifier (slot)
"Generate a slot-option form for SLOT.
This form is valid for use in `defclass'."
(labels
((format-keyword (keyword function &key bad-result)
(let ((result (funcall function slot)))
(and (not (eq bad-result result)) `(,keyword ,@(ensure-list result)))))
(format-accessors ()
(let ((readers (closer-mop:slot-definition-readers slot))
(writers (closer-mop:slot-definition-writers slot)))
(if (and readers writers)
(list :accessor (car readers))
`(,@(format-keyword :writer
#'closer-mop:slot-definition-writers)
,@(format-keyword :reader
#'closer-mop:slot-definition-readers))))))
`(,(closer-mop:slot-definition-name slot)
,@(format-accessors)
,@(format-keyword :allocation #'closer-mop:slot-definition-allocation
:bad-result :instance)
,@(format-keyword :initarg #'closer-mop:slot-definition-initargs)
,@(when (closer-mop:slot-definition-initform slot)
`(:initform ,(closer-mop:slot-definition-initform slot)))
,@(format-keyword :type #'closer-mop:slot-definition-type
:bad-result t)
,@(when (documentation slot t)
`(:documentation ,(documentation slot t))))))
(macrolet ((define-mop (name function &optional generic-docstring)
`(progn
(defgeneric ,name (class)
,@(if generic-docstring
`(:documentation ,generic-docstring)
(values)))
(defmethod ,name ((class class))
(mapcar #',function (class-direct-slots class)))
(defmethod ,name ((instance standard-object))
(,name (class-of instance)))
(defmethod ,name ((class symbol))
(,name (find-class class)))
(defmethod ,name ((class string))
(,name (find-symbol class))))))
(define-mop class-direct-slot-definitions generate-slot-specifier))
(defgeneric class-direct-slots->list (class))
(defmethod class-direct-slots->list ((class class))
(mapcar #'generate-slot-specifier (closer-mop:class-direct-slots class)))
(defgeneric class-default-initargs->list (class))
(defmethod class-default-initargs->list ((class class))
(mapcan #'butlast (closer-mop:class-default-initargs class)))
(defgeneric class-direct-default-initargs->list (class))
(defmethod class-direct-default-initargs->list ((class class))
(let ((result (closer-mop:class-default-initargs class)))
(when result
`(:default-initargs ,@(mapcan #'butlast result)))))
(defgeneric class-direct-superclasses->list (class))
(defmethod class-direct-superclasses->list ((class class))
(mapcar #'class-name (closer-mop:class-direct-superclasses class)))
(defgeneric store-class (class))
(defmethod store-class ((class class))
`(defclass ,(class-name class)
,(class-direct-superclasses->list class)
,(class-direct-slots->list class)
,(class-direct-default-initargs->list class)
,(when (documentation class t)
`(:documentation ,(documentation class t)))))
(defmethod store-class ((instance standard-object))
(store-class (class-of instance))) | 3,987 | Common Lisp | .lisp | 77 | 39.831169 | 84 | 0.598974 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | f7f3f3f0c5e6d31fbf0b6968b9506796193145e4af1305d19315022ba6112808 | 13,185 | [
-1
] |
13,186 | tests.lisp | nixeagle_nisp/mop/tests.lisp | (in-package :nisp.mop-simple)
(def-suite root)
(test (class-slots :suite root)
"Result of `class-slots' should be list of `standard-effective-slot-definition'."
(mapc (lambda (class)
(is (typep
(car (class-slots class)) '
closer-mop:standard-effective-slot-definition)))
(list 'standard-class
"STANDARD-CLASS"))) | 379 | Common Lisp | .lisp | 10 | 30.3 | 83 | 0.623306 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 3c562ec0b3883e81e010e7d0332c80dcd3a1d398e78e6b87af9e30cde4080fbd | 13,186 | [
-1
] |
13,187 | simple.lisp | nixeagle_nisp/mop/simple.lisp | (in-package :nisp.mop-simple)
(macrolet ((define-mop (name)
`(progn
(defgeneric ,name (class))
(defmethod ,name ((class class))
(,(alexandria:ensure-symbol name :closer-mop) class))
(defmethod ,name ((instance standard-object))
(,name (class-of instance)))
(defmethod ,name ((class symbol))
(,name (find-class class)))
(defmethod ,name ((class string))
(,name (find-symbol class))))))
(define-mop class-default-initargs)
(define-mop class-direct-default-initargs)
(define-mop class-slots)
(define-mop class-direct-slots)
(define-mop class-direct-subclasses)
(define-mop class-direct-superclasses)
(define-mop class-finalized-p)
(define-mop class-precedence-list)
(define-mop class-prototype)
(define-mop compute-class-precedence-list)
(define-mop compute-default-initargs)
(define-mop compute-slots)
(define-mop finalize-inheritance))
(macrolet ((define-mop (name)
`(progn
(defgeneric ,name (generic-function))
(defmethod ,name ((generic-function standard-generic-function))
(,(alexandria:ensure-symbol name :closer-mop)
generic-function))
(defmethod ,name ((generic-function symbol))
(,name (symbol-function generic-function)))
(defmethod ,name ((generic-function string))
(,name (find-symbol generic-function))))))
(define-mop generic-function-argument-precedence-order)
(define-mop generic-function-declarations)
(define-mop generic-function-lambda-list)
(define-mop generic-function-method-class)
(define-mop generic-function-method-combination)
(define-mop generic-function-name)
(define-mop generic-function-methods))
;;; End | 1,894 | Common Lisp | .lisp | 43 | 34.627907 | 79 | 0.632774 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | f75f7e8d6bc296721caf9133d483ed32eb62a418ba047d9de6e1c7e0feee3846 | 13,187 | [
-1
] |
13,188 | mop.lisp | nixeagle_nisp/mop/mop.lisp | (in-package :nisp.mop)
(defun compare-generic-applicable-methods (method-args original-method-args
generic-function)
"True if applicable methods for METHOD-ARGS `equal' set for ORIGINAL-METHOD-ARGS."
(equal (compute-applicable-methods generic-function method-args)
(compute-applicable-methods generic-function original-method-args)))
(define-condition applicable-methods-mismatch-error (error)
((old-args :initarg :old-args
:reader applicable-methods-mismatch-error-original-args)
(new-args :initarg :new-args
:reader applicable-methods-mismatch-error-new-args)
(generic-function :initarg :generic-function
:reader applicable-methods-mismatch-error-generic-function))
(:report (lambda (condition stream)
(let ((generic-function
(applicable-methods-mismatch-error-generic-function condition))
(original-args
(applicable-methods-mismatch-error-original-args condition))
(new-args
(applicable-methods-mismatch-error-new-args condition)))
(format stream
"Applicable methods differ:~% ~
Generic function: ~S~% ~
Old args: ~S~% ~
New args: ~S~% ~
Old set: ~A~% ~
New set: ~A~%"
generic-function
original-args
new-args
(compute-applicable-methods generic-function original-args)
(compute-applicable-methods generic-function new-args)))))
(:documentation "Triggers when the set of applicable methods differ.
See the common lisp specification about applicable methods and how
`call-next-method' must not change the set of applicable methods for a
generic function."))
| 1,964 | Common Lisp | .lisp | 36 | 39.527778 | 84 | 0.599896 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 6e8a69edc519916fadfa06cd5d63935f851ac5f60b3cbac299262f36d97e5ce9 | 13,188 | [
-1
] |
13,189 | util.lisp | nixeagle_nisp/fbi/util.lisp | (defpackage #:nisp.fbi.util
(:use :cl :iterate)
(:export #:make-keyword))
(in-package :nisp.fbi.util)
(defun make-keyword (string)
"Convert STRING to a keyword (uppercased)."
(declare (type string string))
(intern (string-upcase string) :keyword)) | 259 | Common Lisp | .lisp | 8 | 30 | 45 | 0.716 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 7bcb31acfb741b2ebcc53bb9d79113994118d066b3cd4a78ab862dcdaf6c8686 | 13,189 | [
-1
] |
13,190 | json-classes.lisp | nixeagle_nisp/fbi/json-classes.lisp | (defpackage #:nisp.fbi.json-classes
(:use :cl :usocket :json :iterate :alexandria
:nisp.util.json :eos)
(:export :auth :subscribe :json-action-mixin
:commit-author :commit-data
:irc-data :irc-message :irc-private :publish
:sender :url
;; methods
#:json->alist #:make-json-type-signature
#:json->string
#:make-irc-private-message
#:make-subscribe #:json-nisp-message
;; publish
#:action
#:from
;; irc
#:command
#:args
#:sender
#:admin
#:server
#:channel
))
(in-package :nisp.fbi.json-classes)
(defparameter *fbi-json-signatures* (make-hash-table :test #'equal)
"list -> type mapping")
(defun make-json-type-signature (alist)
"Return a list for use as a type signature.
A type signature is basically a list of all keys in a hash table from cl-json"
(mapcar #'car alist))
(defun find-json-type (bindings)
(let ((type-class (gethash (make-json-type-signature bindings)
*fbi-json-signatures* nil)))
(if type-class ;nil for no signature by this binding.
(if (functionp type-class)
(funcall type-class bindings)
type-class)
(progn
(format t
"FBI type signature error: ~A ~
Quickfix: (defclass <classnamehere> (json-mixin) ~A)"
(make-json-type-signature bindings)
(string-downcase
(princ-to-string (make-json-type-signature bindings))))
nil))))
(defgeneric action (object))
(defgeneric from (object)
(:documentation "From is always related to who on FBI sent a message."))
(defclass json-action-mixin (json-mixin)
((action :initform (error "~&Action cannot be left empty! ~
~&FBI fails silently if this is not provided.")
:type string
:accessor action))
(:documentation "All classes representing FBI actions should inherit this."))
(defclass irc-data-mixin () ()
(:documentation "Anything with command info should superclass this."))
(defclass auth (json-action-mixin)
((action :initform "auth")
(user :accessor user
:initarg :user)
(secret :accessor secret
:initarg :secret))
(:documentation "Auth with FBI."))
(defclass subscribe (json-action-mixin)
((action :initform "subscribe")
(channels :accessor channels
:initarg :channels))
(:documentation "Subscribe to FBI channels."))
(defclass publish (json-action-mixin irc-data-mixin)
((from :accessor from) (action :initform "publish") channel
(data :accessor data)))
(defclass author (json-mixin)
(name email))
(defclass commit-author (author) ()
(:documentation "Author of a commit from github."))
(defclass sender (json-mixin) (nick ident host))
(defgeneric long-url (object))
(defgeneric short-url (object))
(defgeneric url (object)
;; We do this by first looking for short-url, if its unbound or does
;; not exist go looking for long-url.
(:documentation "Get the shortest url possible."))
(defclass url ()
((url :type string
:initarg :long-url
:accessor long-url)
(shorturl :type string
:initarg :short-url
:accessor short-url))
(:documentation "Represents a url in FBI data. The server always gets ~
a tiny url if possible, but if not we will be prepared to always get ~
_a_ url."))
(defmethod url ((url url))
(if (slot-boundp url 'shorturl)
(short-url url)
(long-url url)))
(defmethod url ((object publish))
(url (data object)))
(defgeneric command (object)
(:method ((object irc-data-mixin))
(command object)))
(defgeneric args (object)
(:method ((object irc-data-mixin))
(args object)))
(defgeneric sender (object)
(:method ((object irc-data-mixin))
(sender object)))
(defgeneric admin (object)
(:method ((object irc-data-mixin))
(admin object)))
(defgeneric server (object)
(:method ((object irc-data-mixin))
(server object)))
(defgeneric channel (object)
(:method ((object irc-data-mixin))
(channel object)))
(defclass irc-data (irc-data-mixin json-mixin)
((command :accessor command)
(args :accessor args)
(sender :accessor sender)
(admin :accessor admin)
(server :accessor server)
(channel :accessor channel)
(default--project :accessor default-project)))
(macrolet ((publish-irc-data (name)
`(defmethod ,name ((object publish))
(,name (data object)))))
(publish-irc-data command)
(publish-irc-data args)
(publish-irc-data admin)
(publish-irc-data server)
(publish-irc-data channel))
(defclass commit-data (url json-mixin)
(message commit project project-2
(author :accessor author) branch))
(defclass irc-message (json-mixin)
((id :initarg :id)
(server :initarg :server)
(channel :initarg :channel)
(message :initarg :message)))
(defclass irc-private (json-mixin)
((to :initarg :to)
(action :initform "private")
(data :initarg :data
:type irc-message)))
(defun make-irc-private-message (to irc-server irc-channel irc-message)
(declare (type string to irc-channel irc-message)
(type positive-fixnum irc-server))
(make-instance 'irc-private :to to
:data (make-instance 'irc-message
:message irc-message
:channel irc-channel
:server irc-server
:id nil)))
(macrolet ((define-describe-object (object slot)
`(defmethod describe-object ((s ,object) stream)
(call-next-method)
(terpri stream)
(describe (,slot s) stream))))
(define-describe-object publish data)
(define-describe-object commit-data author)
(define-describe-object irc-private data))
(macrolet ((define-signature (key name)
`(setf (gethash ',key *fbi-json-signatures*)
(if (listp ',name) ,name ',name))))
(clrhash *fbi-json-signatures*)
(define-signature (name email) 'commit-author)
(define-signature (message commit project project-2 author url branch shorturl)
'commit-data)
(define-signature (user action) 'auth)
(define-signature (nick ident host) 'sender)
(define-signature (command args sender admin server channel default--project)
'irc-data)
(define-signature (action channels) 'subscribe)
(define-signature (from action channel data)
(lambda (bindings) (intern (nstring-upcase (cdr (assoc 'action bindings)))
:nisp.fbi.json-classes))))
(defgeneric json->alist (object))
(defmethod json->alist ((object json-mixin))
(decode-json-from-string (encode-json-to-string object)))
(defmethod json->alist ((object string))
(decode-json-from-string object))
(defmethod json->alist ((object stream))
(decode-json object))
(defgeneric json->string (object))
(defmethod json->string ((object json-mixin))
(encode-json-to-string object))
#+ ()
(defmethod make-object :around (bindings (symbol symbol) &optional superclasses)
(if (or (null symbol) (find-class symbol nil))
(call-next-method)
(make-object bindings nil superclasses)))
#+ ()
(defmethod make-object :around (bindings (symbol (eql nil)) &optional superclasses)
(let ((type-class (nisp.fbi.json-classes::find-json-type bindings)))
(let ((class (find-class type-class nil))
(signature (make-json-type-signature bindings)))
(format t "~&~16A . ~A~%" type-class signature)
(when (and (null class) type-class)
(nisp.fbi.json-classes::json-nisp-message
(format nil "Class ~A does not exist. Bindings were: ~A"
type-class signature)))
(if (and (null symbol) (null class))
(call-next-method bindings nil
superclasses)
(make-object bindings type-class superclasses))))) | 8,124 | Common Lisp | .lisp | 206 | 32.242718 | 83 | 0.638611 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | f2fb1322979001414125911c56c751f4c7ac3f22cfabba15686401a0bc812e07 | 13,190 | [
-1
] |
13,191 | tests.lisp | nixeagle_nisp/fbi/tests.lisp | (in-package :nisp.fbi.json-classes)
(def-suite root)
(test (make-json-type-signature :suite root)
(with-fbound (make-json-type-signature)
('((a . b) (c . d))) '(a c)))
(defmacro with-fbi-socket ((sock &optional
(host "danopia.net")
(port 5348)) &body body)
`(let ((sock ',sock))
(unwind-protect (progn
(setq sock (json-socket-connect ,host ,port))
,@body)
(close (socket-stream sock) :abort t))))
#+ ()
(with-fbi-socket (sock)
(synchronous-json-request (make-instance 'auth
:secret "sekrit"
:user "Hi danopia from nixeagle!")
sock :json-symbols-package :nisp.fbi.json-classes))
#+ ()
(with-fbi-socket (sock)
(synchronous-request (make-instance 'auth
:secret "sekrit"
:user "Hi danopia from nixeagle!")
sock))
#+ ()
(let ((sock (json-socket-connect "danopia.net" 5348)))
()) | 1,131 | Common Lisp | .lisp | 28 | 26.642857 | 79 | 0.481313 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 199ecaf1269776f9a6a2999494389cd049ee773c1fcf0c084a370a13687c7382 | 13,191 | [
-1
] |
13,192 | fbi.lisp | nixeagle_nisp/fbi/fbi.lisp | (eval-when (:compile-toplevel)
(asdf:load-system :cl-json))
(defpackage #:nisp.fbi
(:use :cl :usocket :json :iterate :nisp.util.json))
(in-package :nisp.fbi)
;(delete-package :nisp.fbi.json-classes)
(defpackage #:nisp.fbi.sockets
(:use :cl :usocket :json :iterate
:nisp.fbi.json-classes :nisp.util.json :nisp.util.usocket)
(:nicknames :fbi-sockets)
(:shadow :socket-connect))
(in-package :nisp.fbi.sockets)
;;; Not sure what these are, messages, commands, part of json-classes...
;;; Going here for now.
(defun authenticate-component (json-socket component password)
"Authenticate to JSON-SOCKET as COMPONENT with PASSWORD."
(declare (type string component password))
(write-json (make-instance 'auth
:user component
:secret password)
json-socket :force t))
;;; End fbi.lisp
| 880 | Common Lisp | .lisp | 22 | 34.227273 | 72 | 0.67609 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 14ead24e6443b6c394f7dd41c20857af7f4ed0339fedcf3299ad0348ef49fa51 | 13,192 | [
-1
] |
13,193 | method.lisp | nixeagle_nisp/loki/object-system/method.lisp | (in-package :loki-object-system)
(defstruct (method-object
(:conc-name method-)
(:include data-mixin)
(:constructor)
(:print-object
(lambda (obj *standard-output*)
(if *print-readably*
(format *standard-output*
"#S(~S :direct-mimics ~S :direct-cells ~S :lambda-list ~S :forms ~S :docstring ~S :declarations ~S)"
(type-of obj) (direct-mimics obj)
(direct-cells obj) (method-lambda-list obj)
(method-forms obj)
(docstring obj)
(method-declarations obj))
(call-next-method)))))
(declarations '() :type list)
(function nil :type (or null function)) ;Slot is temp nil at load/compile
(lambda-list '() :type list)
(forms '() :type list))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro make-method-lambda (this-method declarations docstring
arguments forms)
`(lambda (message receiver context ,@arguments)
,docstring
(declare (type object context message receiver))
,@declarations
(let ((this-method ,this-method)
(|self| (or receiver *ground*))
(@ (or receiver *ground*))
(|currentMessage| message)
(context (or context *context*))
(|surroundingContext| *surrounding-context*))
(declare (ignorable this-method |self| @ |currentMessage|
context |surroundingContext|))
,@forms))))
#+ ()
(defmacro make-method-lambda (this-method arguments expression)
`#',(make-method-lambda-form this-method arguments expression))
(defmethod make-load-form ((self method-object) &optional env)
(declare (ignore env))
(values
`(make-method-object :direct-mimics ',(direct-mimics self)
:direct-cells ',(direct-cells self)
:lambda-list ',(method-lambda-list self)
:docstring ',(docstring self)
:declarations ',(method-declarations self)
:forms ',(method-forms self))
`(setf (method-function ',self)
(make-method-lambda ,self
,(method-declarations self)
,(docstring self)
,(method-lambda-list self)
,(method-forms self)))))
(defun call-method (object receiver &rest args)
"Apply ARGS to OBJECT's `method-function'."
(declare (type method-object object))
(apply (method-function object) (make-object)
receiver (make-object) args))
(defun call (receiver method-name &rest args)
(declare (type object receiver))
(apply (method-function (cell receiver method-name))
(make-object) receiver (make-object) args))
(defmacro make-method (lambda-list &body body)
(multiple-value-bind (forms declarations docstring)
(parse-body body :documentation t :whole t)
(with-gensyms (this-method)
`(let ((,this-method
,(make-method-object #+ :direct-mimics (list *origin*)
:lambda-list lambda-list
:forms forms
:docstring docstring
:declarations declarations)))
(setf (method-function ,this-method)
(make-method-lambda ,this-method ,declarations ,docstring
,lambda-list ,forms))
,this-method)))) | 3,687 | Common Lisp | .lisp | 77 | 33.636364 | 128 | 0.54717 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 775ec30c4096f092c0cc00daf49ad5460b5ee82dcea53bbb5abebc8231e67d41 | 13,193 | [
-1
] |
13,194 | userland-setup.lisp | nixeagle_nisp/loki/object-system/userland-setup.lisp | (in-package :loki-object-system)
(make-string-object :data "a")
(setf (direct-cell *base* "kind") "Base")
(setf (direct-cell *base* "inspect") "Base")
(setf (direct-cell *base* "notice") "Base")
(setf (direct-cell *base* "hash")
(make-method ()
"Hash on Base is as if `eq' is used.
This does not seem to be returning the right hash for two otherwise eq
loki objects."
(sxhash |self|)))
(setf (direct-cell *base* "cell")
(make-method (cell-name)
"Return a cell as if by `cell'."
(etypecase cell-name
(string-object (cell |self| (string-data cell-name)))
(symbol-object (cell |self| (symbol-name (symbol-data cell-name)))))))
(setf (direct-cell *base* "==")
(make-method (other)
"True iff SELF is `eq' to OTHER."
(declare (type object other))
(eq |self| other)) )
(setf (direct-cell *base* "=")
(make-method (place value)
"Set PLACE on @ to VALUE."
(setf (direct-cell @ place) value)))
(setf (direct-cell *base* "documentation")
(make-method ()
"Get documentation string for the receiver."
(docstring @)))
(setf (direct-cell *base* "documentation=")
(make-method (text)
"Make TEXT the documentation string of receiver."
(declare (type string-object text))
(setf (docstring @) (string-data text))
text))
;;;object context message reciever
;;; reciever is @ or self
;;;
;;; currentMessage is message that initiated activation of method
;;;
;;; surroundingContext object that represents the context where this
;;; method was called from
(add-direct-mimic *Ground* *Base*)
(setf (direct-cell *Ground* "Ground") *Ground*)
(setf (direct-cell *Ground* "kind") "Ground")
(add-direct-mimic *origin* *ground*)
(setf (direct-cell *origin* "kind") "Origin")
(defparameter *Default-Behavior-Definitions* (make-object))
(setf (direct-cell *default-behavior-definitions* "kind")
"DefaultBehavior Definitions")
(setf (direct-cell *default-behavior-definitions* "inspect")
"DefaultBehavior Definitions")
(setf (direct-cell *default-behavior-definitions* "notice")
"DefaultBehavior Definitions")
(setf (direct-cell *default-behavior-definitions* "method")
(make-method (&optional body)
"Very crude version of Ioke `method'.
We do not handle any arg parsing or optional user supplied documentation
strings. These will be added in the future as the user level interface
starts to improve.
For starters this really begs to be a macro."
(let ((this-method
(make-method-object :lambda-list ()
:forms (list body)
:docstring ""
:declarations ())))
(setf (method-function this-method)
(lambda () body))
this-method)))
(add-direct-mimic *ground* *default-behavior-definitions*)
(defpackage #:loki-user
(:use))
(define-constant +standard-read-string+ (get-macro-character #\" (copy-readtable nil)))
(defun call-with-loki-readtable (thunk)
(declare (type function thunk))
(let ((*readtable* (copy-readtable nil)))
(setf (readtable-case *readtable*) :preserve)
(set-macro-character #\" (lambda (stream char)
(make-string-object
:data
(funcall +standard-read-string+ stream char))))
(set-syntax-from-char #\, #\Space)
(let ((*package* (find-package :loki-user)))
(walk-loki-list (cl:funcall thunk)))))
(defun walk-loki-list (list)
(declare (type list list))
(mapcar #'make-simple-data-object
list))
(defun make-simple-data-object (input)
(typecase input
(complex (make-complex-object :data input))
(integer (make-integer-object :data input))
(rational (make-rational-object :data input))
(string (make-string-object :data input))
(symbol (princ-to-string input))
(cons (cons (make-simple-data-object (car input))
(and (not (endp (cdr input)))
(make-simple-data-object (cdr input)))))
(otherwise input)))
(defmacro with-loki-syntax (&body body)
`(call-with-loki-readtable (lambda () ,@body)))
(defun loki-repeating-read (input)
(declare (type (or stream string) input))
(let ((input (if (stringp input)
(make-string-input-stream input)
input)))
(with-loki-syntax
(do* ((x nil (read input))
(result () (push x result)))
((eq nil (peek-char t input nil nil)) (nreverse result))
(print x *trace-output*)))))
(defmacro transform (input)
(let ((tree (loki-repeating-read input)))
`(call *ground* ,(car tree)
,@(cadr tree)))) | 4,796 | Common Lisp | .lisp | 116 | 34.224138 | 87 | 0.627151 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | ce8289d6e9514300fd167e75ffef0219cf1f44e36160976f58d494a970a4dc2a | 13,194 | [
-1
] |
13,195 | print-readably.lisp | nixeagle_nisp/loki/object-system/print-readably.lisp | (defpackage #:loki-util
(:use :cl))
(in-package :loki-util)
(defun write-readably (object &optional (stream *standard-output*))
(let ((*print-readably* t)
(*print-pretty* nil)
(*print-circle* t))
(prin1 object stream)))
(defun write-readably-to-string (object)
(let ((*print-readably* t)
(*print-pretty* nil)
(*print-circle* t))
(prin1-to-string object))) | 404 | Common Lisp | .lisp | 13 | 26.384615 | 67 | 0.632391 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 20118c9363ea18015761325e69d4fc8b412e398cf540fe9ae0b22f37888b6421 | 13,195 | [
-1
] |
13,196 | boot.lisp | nixeagle_nisp/loki/object-system/boot.lisp | (defpackage #:loki-object-system
(:use :cl :alexandria :bt :anaphora)
(:shadow :method :call-method :make-method)
(:export #:loki-object))
(in-package :loki-object-system)
(defvar *world-lock* (make-lock "loki-world-lock")
"Master lock for the loki system.
If thread protection is required for some operation and that operation is
not easily localizable or the relevant protocols are still too raw, this
lock should be held.")
(defstruct (object (:conc-name nil)
(:print-object
(lambda (obj stream)
(format stream "#S(~A~@[ direct-mimics: ~S~]~@[ direct-cells: ~S~]~@[ :docstring ~S~]~@[ :data ~S~])"
(type-of obj)
(direct-mimics obj)
(and (not (zerop (hash-table-count
(direct-cells obj))))
(direct-cells obj))
(and (not (string= "" (docstring obj)))
(docstring obj))
(typecase obj
(method-object nil)
(data-mixin (slot-value obj 'data))
(otherwise nil))))))
"All programmer level objects in loki are instances of this object."
(object-lock (make-lock "instance lock")
#+sbcl :type #+sbcl sb-thread:mutex
#+ccl :type #+ccl ccl:lock)
direct-mimics
direct-imitators
(direct-cells (make-hash-table :test 'equalp)
:type hash-table)
(docstring "" :type string))
(defstruct (data-mixin (:conc-name nil)
(:include object)))
(defstruct (number-mixin (:conc-name nil)
(:include data-mixin))
"The top of the numberical tower.")
(defstruct (real-mixin (:conc-name nil)
(:include number-mixin)))
(defstruct (rational-mixin (:conc-name nil)
(:include real-mixin)))
(defstruct (ratio-mixin (:conc-name nil)
(:include rational-mixin)))
(defstruct (string-object (:conc-name string-)
(:include data-mixin))
(data "" :type string))
(defstruct (number-object (:conc-name number-)
(:include number-mixin))
(data 0 :type number))
(defstruct (rational-object (:conc-name rational-)
(:include real-mixin))
(data 0 :type rational))
(defstruct (decimal-object (:conc-name decimal-)
(:include real-mixin))
(data 0 :type real))
(defstruct (complex-object (:conc-name complex-)
(:include number-mixin))
(data 0 :type (or rational real integer complex)))
(deftype infinity ()
'(member :loki-infinity :loki-negative-infinity))
(defstruct (infinity-object (:conc-name infinity-)
(:include ratio-mixin))
(data :loki-infinity :type infinity))
(defstruct (integer-object (:conc-name integer-)
(:include rational-mixin))
(data 0 :type integer))
(defstruct (symbol-object (:conc-name symbol-)
(:include data-mixin))
(data :undefined-symbol :type symbol))
(eval-when (:compile-toplevel :load-toplevel)
(defun object-lock-forms (&rest loki-objects)
"Returns list of ((loki-object-lock LOKI-OBJECT)...)."
(mapcar (lambda (obj) `(object-lock ,obj))
loki-objects))
(defun loki-nested-lock-forms (lock-function-symbol places forms)
(let ((forms-done-p nil))
(reduce (lambda (old new)
`(,lock-function-symbol (,new)
,@(if forms-done-p
(list old)
(progn (setq forms-done-p t)
old))))
(reverse places) :initial-value forms))))
(defmacro with-loki-object-locks-held ((&rest loki-objects) &body body)
(loki-nested-lock-forms 'with-lock-held
(apply #'object-lock-forms loki-objects)
body))
(defun add-direct-mimic (object mimic)
"Make OBJECT directly superclass MIMIC.
Metaprotocol notes:
It is an error to add a MIMIC that is not derived from `loki-object'.
It is an error for an OBJECT to superclass itself. In otherwords OBJECT
and MIMIC may not be the same instance.
The return value of this function is unspecified.
Thoughts:
Do we need to lock OBJECT and MIMIC for this operation? If so why? For
now we lock as a precaution."
(declare (type object object mimic))
(with-loki-object-locks-held (object mimic)
(assert (not (eq object mimic)))
(pushnew mimic (direct-mimics object) :test 'eq)))
(defun remove-direct-mimic (object mimic)
(declare (type object object mimic))
(with-loki-object-locks-held (object mimic)
(assert (not (eq object mimic)))
(setf (direct-mimics object)
(delete mimic (direct-mimics object) :test 'eq))))
(defun add-direct-imitator (object imitator)
"Mark OBJECT as being imitated by IMITATOR.
Metaprotocol notes:
Should be same rules as `add-direct-mimic'."
(declare (type object object imitator))
(with-loki-object-locks-held (object imitator)
(assert (not (eq object imitator)))
(pushnew imitator (direct-imitators object) :test 'eq)))
(defun remove-direct-imitator (object imitator)
(declare (type object object imitator))
(with-loki-object-locks-held (object imitator)
(assert (not (eq object imitator)))
(setf (direct-imitators object)
(delete imitator (direct-imitators object) :test 'eq))))
(defun call-add-direct-cell (object name value)
(declare (type object object)
(type string name))
(with-loki-object-locks-held (object)
(setf (gethash name (direct-cells object))
(if (stringp value)
(make-string-object :data value)
value))))
(defmacro add-direct-cell (object name value)
`(call-add-direct-cell ,object ,name ,value))
#+ () (define-compiler-macro add-direct-cell (&whole whole object name value)
(declare (ignore object name))
(print value *trace-output*)
whole)
(defun remove-direct-cell (object name)
(declare (type object object)
(type string name))
(with-loki-object-locks-held (object)
(remhash name (direct-cells object))))
(defun direct-cell (object name)
"Get the cell value in OBJECT identified by NAME."
(declare (type object object)
(type string name))
(the (or object null) (gethash name (direct-cells object))))
(defsetf direct-cell add-direct-cell)
#+ () (defmacro direct-cell (object name)
"If NAME is a symbol, we convert it to a string."
`(call-direct-cell ,object ,(if (symbolp name)
(symbol-name name)
name)))
(defmacro direct-cellf (object cell value)
`(add-direct-cell ,object ,cell ,(if (stringp value)
(make-string-object :data value)
value)))
(defparameter *base* (make-object :docstring "Root of a loki package.")
"Root of a loki Package.
Scott calls packages a RunTime, and of course packages are not
implemented at this time. [2010-03-17 Wed 07:41]")
(defparameter *Ground* (make-object)
"Usually between `Base' and most anything else.")
(defparameter *origin* (make-object)
"Mimics `Ground' and is where new stuff in loki comes from.")
(defvar *context* *Ground*
"Defaults to `*Ground*', but this can change.")
(defvar *surrounding-context* nil
"Supposed to be the context at the call site.")
(defvar *receiver* *Ground*
"Known as self or @ in loki.")
(defvar *current-message* nil)
(defvar *this-method* nil
"The current method being invoked.")
(defun cell (object name)
"Recursively find cell on OBJECT by NAME."
(or (direct-cell object name)
(loop for mimic in (direct-mimics object)
for result = (cell mimic name)
when result return result))) | 8,149 | Common Lisp | .lisp | 180 | 35.511111 | 123 | 0.607571 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | cee88b8f143eab3ebd2e163a75478387f76a237e4a56433940cc2a76e8954682 | 13,196 | [
-1
] |
13,197 | handle-otherwise.lisp | nixeagle_nisp/dwim/handle-otherwise/handle-otherwise.lisp | (defpackage #:nisp.dwim.handle-otherwise
(:use :cl)
(:export #:handle-otherwise))
(in-package :nisp.dwim.handle-otherwise)
;;; Snagged from hu.dwim.util. Its in its own package so cl-walker can
;;; depend on that rather then on all of hu.dwim.util which is huge! Of
;;; course there is the small problem of "no documentation" but at least
;;; I don't need to pull in 100 dependencies.
;;;
;;; The only meaningful change I did was to prefix def with hu.dwim.def
;;; instead of using that package.
(hu.dwim.def:def (function ioe) handle-otherwise (otherwise)
(cond
((eq otherwise :error)
(error "Otherwise assertion failed"))
((and (consp otherwise)
(member (first otherwise) '(:error :warn) :test #'eq))
(assert (not (null (rest otherwise))))
(apply (ecase (first otherwise)
(:error #'error)
(:warn #'warn))
(rest otherwise)))
((functionp otherwise)
(funcall otherwise))
(t
otherwise))) | 986 | Common Lisp | .lisp | 26 | 33.115385 | 72 | 0.661795 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 4f9daff7762b12c1a1db465d6a19cc0076d88a80928ed0a4407897b967e37d81 | 13,197 | [
-1
] |
13,198 | ppjs.lisp | nixeagle_nisp/ppjs/ppjs.lisp | (defpackage #:ppjs
(:use :cl :alexandria :eos))
(in-package :ppjs)
(nisp.i::define-simple-command ppjs
(let* ((*read-eval* nil))
(nisp.i::reply (format nil "js: ~A"
(remove #\newline
(call-with-js-pprint-table
(lambda ()
(prin1-to-string (read-from-string (nisp.i::remaining-parameters))))))))))
(defvar *recursivep* nil)
(defvar *statementp* nil)
(defvar *functionp* nil)
(defvar *top-block-p* nil)
(defparameter *block-prefix* " ")
(defun call-wrap-parens (*standard-output* thunk)
(pprint-logical-block (nil nil)
(when *recursivep* (princ #\())
(let ((*recursivep* t))
(funcall thunk))
(when *recursivep* (princ #\)))))
(defmacro wrap-parens (stream &body body)
`(call-wrap-parens ,stream (lambda () ,@body)))
(defun call-wrap-statement (*standard-output* thunk)
(let ((*statementp* t))
(pprint-indent :block 0)
(funcall thunk))
(unless *statementp*
(write-char #\;)
(unless *top-block-p*
(pprint-newline :linear))))
(defmacro wrap-statement (stream &body body)
`(call-wrap-statement ,stream (lambda () ,@body)))
(defmacro wrap-braces (stream &body body)
`(call-wrap-braces ,stream (lambda () ,@body)))
(defun wrap-function (*standard-output* list)
(let ((*recursivep* nil)
(*statementp* nil))
(pprint-logical-block (nil list)
(pprint-pop) ;Ignore defun
(princ "function ")
(write (pprint-pop))
(write-char #\Space)
(pprint-function-lambda-list *standard-output* (pprint-pop))
(write-char #\Space)
(wrap-braces *standard-output*
(let (next)
(pprint-logical-block (*standard-output* (cdddr list))
(pprint-exit-if-list-exhausted)
(loop
(setq next (pprint-pop))
(pprint-exit-if-list-exhausted)
(write next)))
(princ "return ")
(let ((*top-block-p* t))
(write next)))))))
(defun call-wrap-braces (*standard-output* thunk)
(write-char #\{)
(pprint-newline :mandatory)
(pprint-logical-block (*standard-output* nil)
(princ *block-prefix*)
(funcall thunk))
(pprint-newline :linear)
(write-char #\}))
(defun print-op (op)
(pprint-indent :block 2)
(write-char #\Space)
(pprint-newline :fill)
(princ op)
(write-char #\Space))
(defmacro noppc (arg stream)
`(let ((*print-pretty* nil))
(princ ,arg ,stream)))
(defun call-print-infix-op (*standard-output* list printing-function)
(pprint-logical-block (*standard-output* list)
(let ((op (pprint-pop)))
(loop
(let ((next (pprint-pop)))
(funcall printing-function next))
(pprint-exit-if-list-exhausted)
(print-op op)))))
(defmacro with-print-infix-op ((var list &optional (stream '*standard-output*)) &body body)
`(call-print-infix-op ,stream ,list
(lambda (,var) ,@body)))
(defun pprint-+ (*standard-output* list)
(wrap-statement *standard-output*
(wrap-parens *standard-output*
(with-print-infix-op (next list)
(write (or next 0))))))
(defun pprint-* (*standard-output* list)
(wrap-statement *standard-output*
(wrap-parens *standard-output*
(with-print-infix-op (next list)
(write (or next 1))))))
(defun pprint-- (*standard-output* list)
(wrap-statement *standard-output*
(wrap-parens *standard-output*
(with-print-infix-op (next list)
(write next)))))
(defun pprint--/one-argument (*standard-output* list)
(pprint-- *standard-output* (list (car list) (- (second list)))))
(defun pprint-/ (*standard-output* list)
(wrap-statement *standard-output*
(wrap-parens *standard-output*
(with-print-infix-op (next list)
(case next
(0 (error 'division-by-zero :operation 'pprint-/
:operands (list 1 (cadr list))))
(null (error "You cannot divide by 0 arguments."))
(otherwise (write next)))))))
(defun pprint-//one-argument (*standard-output* list)
(pprint-/ *standard-output* `(/ ,@(if (= 1 (second list))
(list 1)
(list (second list))))))
(defun pprint-defun (stream list)
(wrap-function stream list))
(defun pprint-function-lambda-list (stream list)
(if list
(prin1 list stream)
(princ "()" stream)))
(defun pprint-symbol (stream symbol)
(princ (string-downcase (symbol-name symbol)) stream))
(define-condition ppjs-program-error (program-error) ())
(define-condition function-error (ppjs-program-error)
((name :reader function-error-name
:initarg :name
:documentation "Function's name we are signaling about.")))
(define-condition argument-count-error (function-error)
((required :reader argument-count-error-required
:initarg :required)
(given :reader argument-count-error-given
:initarg :given))
(:report (lambda (condition stream)
(format stream "The function ~S"
(function-error-name condition))
(pprint-logical-block (stream nil)
(pprint-indent :block 0 stream)
(format stream " expects at least ~S argument~:p"
(argument-count-error-required condition))
(pprint-newline :fill stream)
(format stream " but got ~S argument~:p instead."
(argument-count-error-given condition))))))
(defun dispatch-argument-count-error (stream list &optional (required 1))
(declare (ignore stream))
(error 'argument-count-error
:given (length (cdr list))
:required required
:name (car list)))
(defparameter *js-table*
(let ((*print-pprint-dispatch* (copy-pprint-dispatch nil)))
(set-pprint-dispatch 'symbol 'pprint-symbol)
(set-pprint-dispatch '(cons (member defun)) 'pprint-defun 3)
(set-pprint-dispatch '(cons (member +)) 'pprint-+ 5)
(set-pprint-dispatch '(cons (member -)) 'pprint-- 5)
(set-pprint-dispatch '(cons (member -) (cons number null)) 'pprint--/one-argument 6)
(set-pprint-dispatch '(cons (member *)) 'pprint-* 5)
(set-pprint-dispatch '(cons (member /)) 'pprint-/ 5)
(set-pprint-dispatch '(cons (member /) (cons number null)) 'pprint--/one-argument)
(set-pprint-dispatch '(cons (member - /) null)
'dispatch-argument-count-error 100)
*print-pprint-dispatch*))
(defun js-pprint-table ()
*js-table*)
(defun call-with-js-pprint-table (thunk)
(declare (type function thunk))
(let ((*print-pprint-dispatch* (js-pprint-table)))
(funcall thunk)))
(defmacro ppjs (&body body)
`(call-with-js-pprint-table (lambda () (prin1 ',@body))))
(defmacro ppjsi (&body body)
`(irc:privmsg nisp.i::*devel-bot* "#bots"
(format nil "js: ~A // ~A => ~S"
(remove #\newline (call-with-js-pprint-table (lambda () (prin1-to-string ',@body))))
(prin1-to-string',@body)
,@body)))
| 7,147 | Common Lisp | .lisp | 175 | 33.331429 | 112 | 0.607369 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | a97d0b7402d56b75a8a7aa7166fbaaf75808e87e86491e1a39aeaf0b4f7d308e | 13,198 | [
-1
] |
13,199 | ppjs-tests.lisp | nixeagle_nisp/ppjs/ppjs-tests.lisp | (in-package :ppjs)
(defmacro js (&body body)
`(call-with-js-pprint-table (lambda () (prin1-to-string ',@body))))
(defmacro js= (string &body js-body)
`(is (string= ,(concatenate 'string string ";
")
(js ,@js-body))))
(defvar *test-list*)
(defmacro jst (&body body)
`(let ((*print-pretty* nil))
(prin1
(list 'js= (call-with-js-pprint-table (lambda () (let ((*print-pretty* t)) (prin1-to-string ',@body))))
',@body))))
(defmacro jsti (&body body)
`(progn
(irc:privmsg nisp.i::*devel-bot* "#bots"
(format nil "js: ~A // ~A => ~S"
(remove #\newline (call-with-js-pprint-table (lambda () (prin1-to-string ',@body))))
(prin1-to-string ',@body)
,@body))
(let ((*print-pretty* nil))
(prin1
(list 'js=
(call-with-js-pprint-table (lambda () (let ((*print-pretty* t)) (prin1-to-string ',@body))))
',@body))))
)
(def-suite root
:description "Tests for pretty printing javascript library.")
(in-suite root)
(test pprint-+
(js= "1 + 2" (+ 1 2))
(js= "1" (+ 1))
(js= "0" (+))
(js= "1 + (2 + 3)" (+ 1 (+ 2 3))))
(test pprint--
(js= "-1" (- 1))
(js= "1 - 3" (- 1 3))
(js= "1" (- -1))
(signals argument-count-error (js (-))))
(test pprint-*
(js= "1" (* 1))
(js= "1 * 2" (* 1 2))
(js= "1" (*)))
(test pprint-/
(JS= "1/2" (/ 2))
(JS= "1" (/ 1))
(signals DIVISION-BY-ZERO
(js (/ 0)))
(JS= "1 / 2" (/ 1 2))
(JS= "1 / 2 / 3" (/ 1 2 3))
(signals error
(js (/))))
(test pprint-//nesting
(JS= "1 / (2 + 4) / 3" (/ 1 (+ 2 4) 3)))
(test pprint-defun/hairy
(JS= "function jstest (a b) {
return a / b / c / d / e / f / g / h / i / j / k / l / m / n / o / p / q
/ r / s / t / u / v / w / x / y / z / a / b / c / d / e / f / g
/ h / i / j / k / l / m / n / o / p / q / r / s / t / u / v / w
/ x / y / z / a / b / c / d
/ (a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p
+ q + r + s + t + u + v + w + x + y + z + a + b + c + d + e
+ f + g + h + i + j + k + l + m + n + o + p + q + r + s + t
+ u + v + w + x + y + z + a + b + c + d + e + f + g + h + i
+ j + k + l + m + n + o + p + q + r + s + t + u + v + w + x
+ y + z + a + b + c + d + e + f + g + h + i + j + k + l + m
+ n + o + p + q + r + s + t + u + v + w + x
+ function jstestinner () {
return a * b * c * d * e * f * g * h * i * j * k * l
* m * n * o * p * q * r * s * t * u * v * w
* x * y * z * a * b * c * d * e * f * g * h
* i * j * k * l * m * n * o * p * q * r * s
* t * u * v * w * x * y * z * a * b * c * d
* e * f * g * h * i * j * k * l * m * n * o
* p * q * r * s * t * u * v * w * x * y * z
* a * b * c * d * e * f * g * h * i * j * k
* l * m * n * o * p * q * r * s * t * u * v
* w * x * y * z;
}
+ y + z)
/ e / f / g / h / i / j / k / l / m / n / o / p / q / r / s / t
/ u / v / w / x / y / z / a / b / c / d / e / f / g / h / i / j
/ k / l / m / n / o / p / q / r / s / t / u / v / w / x
/ (a - b - c - d - e - f - g - h - i - j - k - l - m - n - o - p
- q - r - s - t - u - v - w - x - y - z - a - b - c - d - e
- f - g - h - i - j - k - l - m - n - o - p - q - r - s - t
- u - v - w - x - y - z - a - b - c - d - e - f - g - h - i
- j - k - l - m - n - o - p - q - r - s - t - u - v - w - x
- y - z - a - b - c - d - e - f - g - h - i - j - k - l - m
- n - o - p - q - r - s - t - u - v - w - x - y - z)
/ y / z;
}" (DEFUN JSTEST (A B) (/ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D (+ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X (DEFUN JSTESTINNER NIL (* A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)) Y Z) E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X (- A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) Y Z)))) | 5,036 | Common Lisp | .lisp | 92 | 43.195652 | 897 | 0.346169 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | b9e718020d49ef4b1b54296b61dffe03072764bc308ee87c546b40c7ab2b22f9 | 13,199 | [
-1
] |
13,200 | 9p-tests.lisp | nixeagle_nisp/9p/9p-tests.lisp | (in-package :nisp.9p)
(def-suite root)
(test (9p-version-string-p :suite root)
#+ ()
(with-fbound (9p-version-string-p)
("9P") t
("9PP") t
("P") nil
(1) nil))
(HUNCHENTOOT:ACCEPTOR-SSL-P 3) | 213 | Common Lisp | .lisp | 10 | 18 | 39 | 0.605 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 6dfd97a81ca7c6836248477953288abc375f15d8aa0ccd946307469c20ee925c | 13,200 | [
-1
] |
13,201 | 9p.lisp | nixeagle_nisp/9p/9p.lisp | (defpackage #:nisp.9p
(:use :cl :alexandria :iterate :eos :with-fbound)
(:nicknames :9p))
(in-package :nisp.9p)
(defun %make-local-stream-socket ()
"Make a local unix socket."
(make-instance 'sb-bsd-sockets:local-socket :type :stream))
(defparameter *sock* (%make-local-stream-socket))
(defparameter *1* (sb-bsd-sockets:socket-connect *sock* "/tmp/ns.james.:0/wmii"))
(defstruct (tb (:copier nil)
(:predicate nil)
(:type vector)
#+ () :named)
(size #(0 0 0 0) :type (vector unsigned-byte 4))
(type 0 :type unsigned-byte)
(tag #(0 0) :type (vector unsigned-byte 2)))
(defmethod tb ((tb tb))
(describe tb))
(deftype 9p-byte ()
'(unsigned-byte 1))
#+ ()
;;; These enumerations are defined in fcall.h
(macrolet ((define-type (name number)
`(defclass ,(alexandria:format-symbol t "~A-message" name) ()
()
(:default-initargs :type ,number))))
(define-type openfd 98)
(define-type version 100)
(define-type auth 102)
(define-type attach 104)
(define-type error 106)
(define-type flush 108)
(define-type walk 110)
(define-type open 112)
(define-type create 114)
(define-type read 116)
(define-type write 118)
(define-type clunk 120)
(define-type remove 122)
(define-type stat 124)
(define-type wstat 126)
(define-type max 128))
(in-package :9p)
(defclass client-message ()
()
(:documentation "Message is sent by a client."))
(defclass server-message ()
()
(:documentation "Message is sent by a server in reply to a client."))
(defclass no-tag ()
()
(:documentation "No tag on a message means its 0.")
(:default-initargs :tag 0))
(defclass file-id ()
((file-id :type '(unsigned-byte 32)
:documentation "Identifies a current file on the server.")))
(defclass message ()
((size :documentation "Length in bytes of the entire message.")
(type :initarg :type :documentation "Single byte for a message type.")
(tag :documentation "Identifying tag.")))
(defun 9p-version-string-p (string)
"True if STRING begins with \"9P\"."
(and (stringp string)
(< 1 (length string))
(string= "9P" string :end2 2)))
(deftype 9p-version-string ()
"Must be a string and start with \"9P\"."
`(and string (satisfies 9p-version-string-p)))
(defclass version-message (message no-tag)
((message-size-limit :documentation "Largest message ever expected to handle.")
(version :type 9p-version-string :initarg :version))
(:default-initargs :type 100))
(defclass 9P2000-version-message (message)
()
(:default-initargs :version "9P2000b")) | 2,624 | Common Lisp | .lisp | 75 | 30.973333 | 81 | 0.671406 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 4f067721ec5544e6a5732d2be1ee59ea23a24fd4e57b68e2ae0533e3b34d2850 | 13,201 | [
-1
] |
13,202 | check.lisp | nixeagle_nisp/with-fbound/check.lisp | ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
(in-package :Eos)
(defvar *test-dribble* t)
(defmacro with-*test-dribble* (stream &body body)
`(let ((*test-dribble* ,stream))
(declare (special *test-dribble*))
,@body))
(defmacro bind-run-state (requested-vars &body body)
`(let ,requested-vars
(declare (special ,@(mapcar 'car requested-vars)))
,@body))
(defmacro with-run-state (requested-vars &body body)
`(locally (declare (special ,@requested-vars)) ,@body))
(defmethod (setf status) :after ((status (eql :unknown)) (test test-case))
(setf (slot-value test 'sofar) ()))
(defclass test-case (testable-object)
((test-lambda :initarg :test-lambda :accessor test-lambda
:documentation "The function to run.")
(sofar :initform () :reader test-case-sofar
:documentation "Tests run so far.")
(runtime-package :initarg :runtime-package :accessor runtime-package
:documentation "By default it stores *package* from the time this test was defined (macroexpanded)."))
(:documentation "A test case is a single, named, collection of
checks.
A test case is the smallest organizational element which can be
run individually. Every test case has a name, which is a symbol,
a description and a test lambda. The test lambda is a regular
funcall'able function which should use the various checking
macros to collect results.
Every test case is part of a suite, when a suite is not
explicitly specified (either via the :SUITE parameter to the TEST
macro or the global variable *SUITE*) the test is inserted into
the global suite named NIL.
Sometimes we want to run a certain test only if another test has
passed. FiveAM allows us to specify the ways in which one test is
dependent on another.
- AND Run this test only if all the named tests passed.
- OR Run this test if at least one of the named tests passed.
- NOT Run this test only if another test has failed.
FiveAM considers a test to have passed if all the checks executed
were successful, otherwise we consider the test a failure.
When a test is not run due to it's dependencies having failed a
test-skipped result is added to the results."))
(defmethod (setf test-case-sofar) (test-form (test test-case))
"Push a new TEST-FORM onto TEST."
(unless (member test-form (slot-value test 'sofar) :test #'equal)
(setf (slot-value test 'sofar)
(append (slot-value test 'sofar) (list test-form)))))
(defmethod (setf test-case-sofar) (test-form (test test-result))
(setf (test-case-sofar test) test-form))
(defmethod test-case-sofar ((test test-result))
(test-case-sofar (test-case test)))
(defclass test-result ()
((reason :accessor reason :initarg :reason :initform "reason")
(docstring :accessor docstring :initarg :docstring :initform "docstring")
(test-case :accessor test-case :initarg :test-case)
(actual-value :accessor test-actual-value :initarg :actual-value
:initform 'no-result)
(expected-value :accessor test-expected-value :initarg :expected-value
:initform 'no-result)
(test-expr :accessor test-expr :initarg :test-expr))
(:documentation "All checking macros will generate an object of type TEST-RESULT."))
(defclass test-passed (test-result) ()
(:documentation "Class for successful checks."))
(defgeneric test-passed-p (object)
(:method ((o t)) nil)
(:method ((o test-passed)) t))
(define-condition check-failure (error)
((reason :accessor reason :initarg :reason :initform "reason")
(test-case :accessor test-case :initarg :test-case)
(test-expr :accessor test-expr :initarg :test-expr))
(:documentation "Signaled when a check fails.")
(:report (lambda (c stream)
(format stream "The following check failed: ~S~%~A."
(test-expr c) (reason c)))))
(defmacro process-failure (&rest args)
`(progn
(with-simple-restart (ignore-failure "Continue the test run.")
(error 'check-failure ,@args))
(add-result 'test-failure ,@args)))
(defclass test-failure (test-result) ()
(:documentation "Class for unsuccessful checks."))
(defgeneric test-failure-p (object)
(:method ((o t)) nil)
(:method ((o test-failure)) t))
(defclass unexpected-test-failure (test-failure)
((actual-condition :accessor actual-condition :initarg :condition))
(:documentation "Represents the result of a test which neither
passed nor failed, but signaled an error we couldn't deal
with.
Note: This is very different than a SIGNALS check which instead
creates a TEST-PASSED or TEST-FAILURE object."))
(defclass test-skipped (test-result) ()
(:documentation "A test which was not run. Usually this is due
to unsatisfied dependencies, but users can decide to skip test
when appropiate."))
(defgeneric test-skipped-p (object)
(:method ((o t)) nil)
(:method ((o test-skipped)) t))
(defun add-result (result-type &rest make-instance-args)
"Create a TEST-RESULT object of type RESULT-TYPE passing it the
initialize args MAKE-INSTANCE-ARGS and adds the resulting
object to the list of test results."
(with-run-state (result-list current-test)
(let ((result (apply #'make-instance result-type
(append make-instance-args (list :test-case current-test)))))
(setf (test-case-sofar current-test)
(getf make-instance-args :test-expr "no test-expression."))
(format *test-dribble* (etypecase result
(test-passed ".") (test-skipped "s")
(unexpected-test-failure "X") (test-failure "f")))
(push result result-list))))
(defgeneric find-predicate (arg1 arg2))
(macrolet ((define-samep (type1 predicate type2)
`(defmethod find-predicate ((arg1 ,type1) (arg2 ,type2))
,(format nil "Returns predicate: ~A" (symbol-name predicate))
',predicate)))
(define-samep string string= string)
(define-samep character char= character)
(define-samep number = number)
(define-samep t equal t))
(defmacro is (test &rest reason-args)
"The DWIM checking operator.
If TEST returns a true value a test-passed result is generated,
otherwise a test-failure result is generated. The reason, unless
REASON-ARGS is provided, is generated based on the form of TEST:
(predicate expected actual) - Means that we want to check
whether, according to PREDICATE, the ACTUAL value is
in fact what we EXPECTED.
(predicate value) - Means that we want to ensure that VALUE
satisfies PREDICATE.
Wrapping the TEST form in a NOT simply preducse a negated reason
string."
(assert (listp test) (test) "Argument to IS must be a list, not ~S" test)
(let (bindings effective-test default-reason-args)
(with-gensyms (e a v p modified-test result)
(flet ((process-entry (predicate expected actual &optional negatedp)
;; make sure EXPECTED is holding the entry that starts with 'values
(when (and (consp actual) (eq (car actual) 'values))
(assert (not (and (consp expected) (eq (car expected) 'values))) ()
"Both the expected and actual part is a values expression.")
(rotatef expected actual))
(let (setf-forms)
(if (and (consp expected) (eq (car expected) 'values))
(progn
(setf expected (copy-list expected))
(setf setf-forms (loop :for cell := (rest expected) :then (cdr cell)
:for i :from 0
:while cell
:when (eq (car cell) '*)
:collect `(setf (elt ,a ,i) nil)
:and :do (setf (car cell) nil)))
(setf bindings (list (list e `(list ,@(rest expected)))
(list a `(multiple-value-list ,actual)))))
(setf bindings (list (list e expected) (list a actual)
(list p `',predicate))))
(setf effective-test `(progn
,@setf-forms
(setf ,p (if (eq 'find-predicate ,p)
(funcall #'find-predicate
,e ,a)
,p))
,(if negatedp
`(not ,(list 'funcall p e a))
(list 'funcall p e a))))))
(reverse-process-entry (predicate expected actual &optional negatedp)
;; make sure EXPECTED is holding the entry that starts with 'values
(when (and (consp actual) (eq (car actual) 'values))
(assert (not (and (consp expected) (eq (car expected) 'values))) ()
"Both the expected and actual part is a values expression.")
(rotatef expected actual))
(let (setf-forms)
(if (and (consp expected) (eq (car expected) 'values))
(progn
(setf expected (copy-list expected))
(setf setf-forms (loop :for cell := (rest expected) :then (cdr cell)
:for i :from 0
:while cell
:when (eq (car cell) '*)
:collect `(setf (elt ,a ,i) nil)
:and :do (setf (car cell) nil)))
(setf bindings (list (list a `(multiple-value-list ,actual))
(list e `(list ,@(rest expected))))))
(setf bindings (list (list a actual) (list e expected)
(list p `',predicate))))
(setf effective-test `(progn
,@setf-forms
(setf ,p (if (eq 'find-predicate ,p)
(funcall #'find-predicate
,a ,e)
,p))
(multiple-value-bind (,result)
(funcall ,p ,a ,e)
,(if negatedp
`(not ,result)
result)))))))
(list-match-case test
((not (typep ?value ?type))
(setf bindings (list (list v ?value) (list a ?value)
(list e ?type))
effective-test `(not (typep ,v ,e))
modified-test nil
default-reason-args
(list "~S evaluated to ~S, which is a ~S (it should not be)"
`',?value v `,?type)))
((not (comparable (?predicate ?expected ?actual)))
(reverse-process-entry ?predicate ?expected ?actual t)
(setf modified-test `(list ,p ',?actual ',?expected)
default-reason-args
(list "~S evaluated to ~S, which is not ~S to ~S. (it should not be)"
`',?actual e p a)))
((not (?predicate ?expected ?actual))
(process-entry ?predicate ?expected ?actual t)
(setf modified-test `(list ,p ',?expected ',?actual)
default-reason-args
(list "~S evaluated to ~S, which is ~S to ~S (it should not be)"
`',?actual a p e)))
((not (?satisfies ?value))
(setf bindings (list (list v ?value) (list e nil)
(list a ?value))
effective-test `(not (,?satisfies ,v))
modified-test nil
default-reason-args
(list "~S evaluated to ~S, which satisfies ~S (it should not)"
`',?value v `',?satisfies)))
((typep ?value ?type)
(setf bindings (list (list v ?value)
(list e ?type) (list a ?value))
effective-test `(typep ,v ,e)
modified-test nil
default-reason-args
(list "~S evaluated to ~S, which is not a ~S"
`',?value v `,?type)))
((comparable (?predicate ?expected ?actual))
(reverse-process-entry ?predicate ?expected ?actual)
(setf default-reason-args
(list "~S evaluated to ~S, which is not ~S to ~S."
`',?actual e p a)
modified-test `(list ,p ',?actual ',?expected)))
((?predicate ?expected ?actual)
(process-entry ?predicate ?expected ?actual)
(setf modified-test `(list ,p ',?expected ',?actual)
default-reason-args
(list "~S evaluated to ~S, which is not ~S to ~S."
`',?actual a p e)))
((?satisfies ?value)
(setf bindings (list (list v ?value) (list e nil)
(list a ?value))
effective-test `(,?satisfies ,v)
modified-test nil
default-reason-args
(list "~S evaluated to ~S, which does not satisfy ~S"
`',?value v `',?satisfies)))
(?_
(setf bindings '()
modified-test nil
effective-test test
default-reason-args (list "~S was NIL." `',test)))))
`(let ,bindings
(if ,effective-test
(add-result 'test-passed :test-expr (or ,modified-test ',test)
:actual-value ,a
:expected-value ,e
:docstring ,(format nil (or (car reason-args) "")))
(process-failure :reason (format nil ,@default-reason-args)
:docstring (format nil "~A" ,@(or reason-args
(list "")))
:actual-value ,a
:expected-value ,e
:test-expr (or ,modified-test ',test)))))))
(defmacro skip (&rest reason)
"Generates a TEST-SKIPPED result."
`(add-result 'test-skipped :reason (format nil ,@reason)))
(defmacro is-true (condition)
"Like IS this check generates a pass if CONDITION returns true
and a failure if CONDITION returns false. Unlike IS this check
does not inspect CONDITION to determine how to report the
failure."
`(if ,condition
(add-result 'test-passed :test-expr ',condition)
(process-failure
:reason (format nil "~S did not return a true value" ',condition)
:test-expr ',condition)))
(defmacro is-false (condition &rest reason-args)
"Generates a pass if CONDITION returns false, generates a
failure otherwise. Like IS-TRUE, and unlike IS, IS-FALSE does
not inspect CONDITION to determine what reason to give it case
of test failure"
(with-gensyms (value)
`(let ((,value ,condition))
(if ,value
(process-failure
:reason ,(if reason-args
`(format nil ,@reason-args)
`(format nil "~S returned the value ~S, which is true" ',condition ,value ))
:test-expr ',condition)
(add-result 'test-passed :test-expr ',condition)))))
(defmacro signals (condition-spec &body body)
"Generates a pass if BODY signals a condition of type
CONDITION. BODY is evaluated in a block named NIL, CONDITION is
not evaluated."
(let ((block-name (gensym)))
(destructuring-bind (condition &optional reason-args)
(ensure-list condition-spec)
`(block ,block-name
(handler-bind ((,condition (fun (add-result 'test-passed :test-expr ',condition)
(return-from ,block-name t))))
(block nil ,@body))
(process-failure
:reason (format nil "Failed to signal a ~S" ',condition)
:docstring `(format nil "~A" ,@(or reason-args "docstring"))
:expected-value ',condition
:test-expr ',condition)
(return-from ,block-name nil)))))
(defmacro finishes (&body body)
"Generates a pass if BODY executes to normal completion. In
other words if body does signal, return-from or throw this test
fails."
`(let (ok)
(unwind-protect (progn ,@body (setf ok t))
(if ok
(add-result 'test-passed :test-expr ',body)
(process-failure
:reason (format nil "Test didn't finish")
:test-expr ',body)))))
(defmacro pass (&rest message-args)
"Simply generate a PASS."
`(add-result 'test-passed :test-expr ',message-args
,@(when message-args `(:reason (format nil ,@message-args)))))
(defmacro fail (&rest message-args)
"Simply generate a FAIL."
`(process-failure :test-expr ',message-args
,@(when message-args `(:reason (format nil ,@message-args)))))
(defparameter *verbose-failures* t
"T if we should print the expression failing, NIL otherwise.")
(defgeneric explain (explainer results &optional stream recursive-depth)
(:method ((exp detailed-text-explainer) results
&optional (stream *test-dribble*) (recursive-depth 0))
(multiple-value-bind (num-checks passed num-passed passed%
skipped num-skipped skipped%
failed num-failed failed%
unknown num-unknown unknown%)
(partition-results results)
(declare (ignore passed))
(flet ((output (&rest format-args)
(format stream "~&~vT" recursive-depth)
(apply #'format stream format-args)))
(when (zerop num-checks)
(output "Didn't run anything...huh?")
(return-from explain nil))
(output "Did ~D check~P.~%" num-checks num-checks)
(output " Pass: ~D (~2D%)~%" num-passed passed%)
(output " Skip: ~D (~2D%)~%" num-skipped skipped%)
(output " Fail: ~D (~2D%)~%" num-failed failed%)
(when unknown (output " UNKNOWN RESULTS: ~D (~2D)~%" num-unknown unknown%))
(terpri stream)
(when failed
(output "Failure Details:~%")
(dolist (f (reverse failed))
(output "--------------------------------~%")
(output "~A ~@{[~A]~}: ~%"
(name (test-case f))
(description (test-case f)))
(output " ~@{[~A]~}~%~%" (docstring f))
(output " ~A~%~%" (reason f))
(output "-- -- Expected -- --~%")
(output "~A" (with-output-to-string (stream)
(describe (test-expected-value f) stream)))
(output "~%~%-- -- Actual -- --~%")
(output "~A" (with-output-to-string (stream)
(describe (test-actual-value f) stream)))
(output "~%~%")
(when (and *verbose-failures* (test-expr f))
(output "EXPR: ~S~%" (test-expr f)))
(output "--------------------------------~%"))
(terpri stream))
(when skipped
(output "Skip Details:~%")
(dolist (f skipped)
(output "~A ~@{[~A]~}: ~%"
(name (test-case f))
(description (test-case f)))
(output " ~A.~%" (reason f)))
(terpri stream)))))
(:method ((exp simple-text-explainer) results
&optional (stream *test-dribble*) (recursive-depth 0))
(multiple-value-bind (num-checks passed num-passed passed%
skipped num-skipped skipped%
failed num-failed failed%
unknown num-unknown unknown%)
(partition-results results)
(declare (ignore passed passed% skipped skipped% failed failed% unknown unknown%))
(format stream "~&~vTRan ~D checks, ~D passed" recursive-depth num-checks num-passed)
(when (plusp num-skipped)
(format stream ", ~D skipped " num-skipped))
(format stream " and ~D failed.~%" num-failed)
(when (plusp num-unknown)
(format stream "~vT~D UNKNOWN RESULTS.~%" recursive-depth num-unknown)))))
(defun partition-results (results-list)
(let ((num-checks (length results-list)))
(collect (passed skipped failed unknown)
(dolist (result results-list)
(typecase result
(test-passed (passed result))
(test-skipped (skipped result))
(test-failure (failed result))
(otherwise (unknown result))))
(if (zerop num-checks)
(values 0 nil 0 0 nil 0 0 nil 0 0 nil 0 0)
(values
num-checks
(passed) (length (passed)) (floor (* 100 (/ (length (passed)) num-checks)))
(skipped) (length (skipped)) (floor (* 100 (/ (length (skipped)) num-checks)))
(failed) (length (failed)) (floor (* 100 (/ (length (failed)) num-checks)))
(unknown) (length (unknown)) (floor (* 100 (/ (length (failed)) num-checks))))))))
(defgeneric run-test-lambda (test)
(:method ((test test-case))
(with-run-state (result-list)
(bind-run-state ((current-test test))
(labels ((abort-test (e)
(add-result 'unexpected-test-failure
:test-expr nil
:test-case test
:reason (format nil "Unexpected Error: ~S~%~A." e e)
:condition e))
(run-it ()
(let ((result-list '()))
(declare (special result-list))
(handler-bind ((check-failure (lambda (e)
(declare (ignore e))
(unless *debug-on-failure*
(invoke-restart
(find-restart 'ignore-failure)))))
(error (lambda (e)
(unless (or *debug-on-error*
(typep e 'check-failure))
(abort-test e)
(return-from run-it result-list)))))
(restart-case
(let ((*readtable* (copy-readtable))
(*package* (runtime-package test)))
(funcall (test-lambda test)))
(retest ()
:report (lambda (stream)
(format stream "~@<Rerun the test ~S~@:>" test))
(return-from run-it (run-it)))
(ignore ()
:report (lambda (stream)
(format stream "~@<Signal an exceptional test failure and abort the test ~S.~@:>" test))
(abort-test (make-instance 'test-failure :test-case test
:reason "Failure restart."))))
result-list))))
(let ((results (run-it)))
(setf (status test) (results-status results)
result-list (nconc result-list results)))))))) | 24,026 | Common Lisp | .lisp | 455 | 37.923077 | 125 | 0.533262 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 0b974e46d8c3e5adccd85303d9506ad94c0eee94a697af4e45452b56e9d3dbb0 | 13,202 | [
-1
] |
13,203 | tests.lisp | nixeagle_nisp/with-fbound/tests.lisp | (in-package :with-fbound)
(test over-fbounds
(signals (error "No args, expect 2") (macroexpand-1 '(with-fbound)))
#+ () (is (equal (list 'progn) (macroexpand-1 '(with-fbound (+))))
"Expect expansion of (progn) when given no additional arguments.")
(signals (error "Should error when given just a docstring")
(macroexpand-1 '(with-fbound (+) "a docstring/reason.")))
(signals (error "Should error when given function args, but no expected result.")
(macroexpand-1 '(with-fbound (+) (1 2 3))))
(is (equal '(progn (is (eos::find-predicate 6 (+ 1 2 3)) "Should add to 6"))
(macroexpand-1 '(with-fbound (+)
"Should add to 6"
(1 2 3) 6)))
"Simplest generated expansion possible, one reason, one arglist one return.")
(is (equal '(progn (finishes (+ 1 2 3)))
(macroexpand-1 '(with-fbound (+)
"Should add to 6"
(1 2 3) :finishes)))
"Should expand to (finishes ...)")
(is (equal '(progn (finishes (+ 1 2 3)))
(macroexpand-1 '(with-fbound (+)
"Should add to 6"
(1 2 3) :should-finish)))
"Should expand to (finishes ...)")
(is (equal '(progn (signals (error "Should add to 6") (+ 1 2 3)))
(macroexpand-1 '(with-fbound (+)
"Should add to 6"
(1 2 3) :should-signal error)))
"Should expand to (signals (error <formatstring> 'error docstring) ...)")
(is (equal '(progn (signals (error "Should add to 6") (+ 1 2 3)))
(macroexpand-1 '(with-fbound (+) "Should add to 6" (1 2 3) :signals error)))
"Should expand to (signals (error <formatstring> 'error docstring) ...)")
(is (equal '(progn
(signals (error"Should add to 6")
(+ 1 2 3))
(finishes
(+ 4))
(is (eos::find-predicate 4 (+ 4)) "Adds to 4"))
(macroexpand-1 '(with-fbound (+)
"Should add to 6"
(1 2 3) :should-signal error
"Adds to 4"
(4) :finishes
(4) 4)))
"Should expand exactly. This tests complex expansion handling with~
3 different expansions intermixed.")
(is (equal '(progn (is (eos::find-predicate 6 (+ 1 2 3)) "Should add to 6"))
(macroexpand-1 '(with-fbound (+)
"Should add to 6"
(1 2 3) 6)))
"Simple generated expansion, but with a specified predicate.")
(with-fbound (+)
"Should add to 6 and make sure `with-fbound' actually works."
(1 2 3) :satisfies integerp
(1 2 3) :satisfies (not stringp))
(with-fbound (+)
(1 2 3) :should-be integer
(1 2 3) :expects (not string))
(with-fbound (+)
(1 2 3) 6
(1) 1
(1 2 3) (not 5))
(let ((x 0))
(with-fbound (incf)
"Verify actual result is evaluated before expected result."
(x) (1- (incf x))
(x) (not (1+ (incf x)))))) | 3,218 | Common Lisp | .lisp | 67 | 34.955224 | 89 | 0.506744 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 0195fc257c27e52f43ad1a89335778bc927da529eae31b22b5ba0f4d01551950 | 13,203 | [
-1
] |
13,204 | safe-package.lisp | nixeagle_nisp/safe/safe-package.lisp | (in-package :nisp-safe)
;;; utilities first
;;; implentation
(defparameter *prepared-safe-packages*
'(:safe-arithmetic
:safe-arithmetic-trig
:safe-arithmetic-comparision
:safe-arithmetic-type-manipulation
:safe-arithmetic-boole
:safe-arithmetic-implentation-constants
:safe-arithmetic-random
:nisp-safe-introspect
:safe-external
:safe-closure
:safe-testing!)
"Listing of packages that have been prepared or deemed to be safe.
This is the default list, the idea is depending on the situation mix and
match what capacities you want to allow untrusted code to do.
On the todo list is to create a class that allows multiple instances and
tracks currently interned packages and whatnot.")
(defclass safe-package ()
((package :accessor safe-package
:initarg :package)
(creation-time :initform (get-universal-time)
:accessor package-creation-time)
(readtable :accessor safe-package-readtable
:initform (make-readtable))
(owner :accessor safe-package-owner
:initarg :owner)
(use :accessor safe-package-use
:initform *prepared-safe-packages*))
(:documentation "Container class for handling safe packages and doing various operations with them."))
(defun make-safe-package (name)
"Should make a totally independent package. All normal safe stuff
should be in this by default.
"
(with-package (make-empty-package name)
(cl::use-package *prepared-safe-packages*)
*package* ) )
(defmacro with-safe-package (name &body body)
"Use the given package name to read some code."
`(with-package ,name
(with-safe-readtable
,@body)))
(defgeneric create-safe-package (package &optional owner)
(:documentation "Make a brand new safe package.
The optional OWNER parameter defines who owns the package. There is no restriction on what owner can be, but a string is suggested at this time. In the future this parameter may be removed! Its ugly and a kludge."))
(defmethod create-safe-package ((package safe-package) &optional owner)
"If you hand a safe package in, you get that package back."
(declare (ignore owner))
;; Not 100% positive this is the best behavior, but better then the
;; previous behavior that tried to make a new safe package.
(handler-case (progn (setf (safe-package package)
(make-empty-package
(concatenate 'string "SAFE-"
(safe-package-owner package))))
(package-use-from package (safe-package-use package))
(populate-functions (safe-package package))
package)
(error () package)))
(defvar *populate-functions* '(populate-safe-package-closures)
"List of functions to populate packages with")
(defun populate-functions (package)
"Populate package with functions"
(dolist (it *populate-functions*)
(funcall (symbol-function it) package)))
(defmethod create-safe-package ((package package) &optional owner)
(let ((safe (make-instance 'safe-package
:package package
:owner owner)))
(package-use-from safe (safe-package-use safe))
(populate-functions safe)
safe))
(defmethod create-safe-package ((package string) &optional owner)
(let ((safe (make-instance 'safe-package
:package (make-empty-package package)
:owner owner)))
(package-use-from safe (safe-package-use safe))
(populate-functions safe)
safe))
(defmethod create-safe-package ((package symbol) &optional owner)
(let ((safe (make-instance 'safe-package
:package (make-empty-package package)
:owner owner)))
(package-use-from safe (safe-package-use safe))
(populate-functions safe)
safe))
(defgeneric get-package (package-designator)
(:documentation
"Find the package given a safe-package or a string and return that package."))
(defmethod get-package ((package safe-package))
(get-package (safe-package package)))
(defmethod get-package (package-designator)
(find-package package-designator))
(defgeneric package-use-from (package-designator import-from)
(:documentation
"Import into PACKAGE the external symbols of IMPORT-FROM."))
(defmethod package-use-from (package-designator
import-from)
;; Do not specialize on import-from here.
(use-package import-from (get-package package-designator)))
(defgeneric remove-package (safe-package package-name)
(:documentation "remove symbols from another package"))
(defgeneric clear-safe-package (safe-package))
(defgeneric delete-safe-package (safe-package)
;; This is pretty ineffeciant if given a safe-package, however its not
;; that big of a deal to do 3 or 4 calls here as deleting a package is
;; something done fairly rarely.
(:documentation "Given a package related object, delete the package."))
(defmethod delete-safe-package ((package safe-package))
(delete-safe-package (safe-package package)))
(defmethod delete-safe-package ((package package))
(delete-safe-package (package-name package)))
(defmethod delete-safe-package (name)
(delete-package name))
(defmethod (setf reset) ((package safe-package))
"Reset SAFE-PACKAGE by reloading all symbols."
(delete-package (safe-package package))
(setf (safe-package package)
(make-empty-package (concatenate 'string "SAFE-" (safe-package-owner package))))
(package-use-from package (safe-package-use package))
(populate-functions package))
(defgeneric shadowing-intern (package object)
(:documentation "intern a new copy of object and setting that copy to the value of the other package's object."))
(defmethod shadowing-intern ((safe-package safe-package) (symbol symbol))
;; It is critical that the old symbol be shadowed.
(with-package (safe-package safe-package)
(shadowing-import symbol (safe-package safe-package))
(find-symbol (symbol-name symbol))))
| 6,096 | Common Lisp | .lisp | 129 | 40.899225 | 215 | 0.704377 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | a0c9947ec951776631fc1f047a74cc59344b68c44a54c48e6baf0a3e64e27655 | 13,204 | [
-1
] |
13,205 | package.lisp | nixeagle_nisp/safe/package.lisp | (in-package :nisp-safe-system)
(defmacro define-export-system (name from &rest symbol-list)
`(defpackage ,name
(:use)
(:import-from ,from ,@(values symbol-list))
(:export ,@(values symbol-list))))
(defpackage #:nisp-introspect
(:use :cl :lift)
(:export #:function-lambda-list))
(define-export-system :nisp-safe-introspect :nisp-introspect
#:function-lambda-list)
;;; This is NOT safe on its own currently, however testing timeouts in
;;; the irc portion. Eventually that needs to move here.
(define-export-system :nisp-unsafe-iteration :cl
#:loop)
;;; things required to get some minimal support going
(define-export-system :nisp-safe-misc :cl
#:list)
(defpackage #:nisp-empty-package
(:use :cl :lift :nistilities)
(:export #:with-empty-package
#:make-empty-package
#:with-package
#:gen-empty-package
))
(defpackage #:nisp-safe
(:use :common-lisp
:lift
:nisp-empty-package
:nistilities)
(:export #:with-safe-package
#:with-safe-readtable
:safe-set
#:safe-read
#:safe-select
#:make-safe-set
))
;;; Used as subpackages for sandboxed code
(defpackage #:safe-testing!
(:use)
(:shadowing-import-from :cl :t :nil)
(:export
:t
:nil))
(define-export-system #:safe-external :cl
:string :integer :typep :character
:vector :array :sequence :atom :bignum
:class
:extended-char :base-char :ratio :real :symbol
:type :fixnum :type-of
:and :or :not :member :mod :eql :eq :equal
:values
:cons :list :mapcar :mapc)
(defpackage #:safe-closure
(:use)
(:export #:reset :nisp-test #:ldap-entry #:ircUser #:hello)) | 1,726 | Common Lisp | .lisp | 56 | 25.660714 | 70 | 0.652358 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | b43c02a902ea36658056dbc04b4288a8a90fcd62e9ae7080b6810f905c315ec3 | 13,205 | [
-1
] |
13,206 | safe-tests.lisp | nixeagle_nisp/safe/safe-tests.lisp |
(in-package #:nisp-safe)
;; Tests
(deftestsuite root-suite ()
()
(:categories))
(deftestsuite base-packages (root-suite)
()
(:setup
(make-empty-package "test1"))
(:teardown
(delete-safe-package-old "test1")))
(deftestsuite test-make-readtable (root-suite)
()
(:documentation
"Make sure that a new read table also comes with #\\\: function bound.")
:test (colon-macro-function-bound?
(ensure (functionp (get-macro-character #\: (make-readtable))))))
(deftestsuite test-with-safe-readtable (base-packages)
()
(:documentation "Test the readtable stuff with a focus towards attempting to break the assumptions made.")
:test (modify-readtable
(:documentation
"Make sure that inside this form *readtable* is set to
*safe-readtable*")
(with-safe-readtable
(ensure (eq *readtable* *safe-readtable*))))
:test (double-colon
(:documentation
"IF YOU SEE THIS:: DO NOT EVEN THINK ABOUT IGNORING IT!
This message means that a function outside of a socalled 'safe' package
was accessed. This test does the following:
1) create an empty package, eg one with no internal symbols
2) runs read-from-string using the package as the *PACKAGE* variable.
3) reads the following string \"cl::+\".
4) If cl::+ is an fbound symbol a critical assumption failed
or a regression has occured.
AGAIN DO NOT EVEN THINK ABOUT USING WHILE THIS TEST FAILS!")
(ensure
(not
(fboundp
(with-safe-readtable
(read-using-package "test1" "cl::+")))))))
(deftestsuite test-*safe-readtable* (root-suite)
()
:documentation "Make sure we get a readtable."
:test (is-readtable
(ensure (readtablep *safe-readtable*))))
;;; Tests
(deftestsuite make-safe-package (root-suite)
()
(:teardown (delete-safe-package-old :test-keyword)
(delete-safe-package-old "test-string"))
:test (pass-keyword
(ensure (packagep (make-safe-package :test-keyword))))
:test (pass-string
(ensure (packagep (make-safe-package "test-string")))))
(deftestsuite test-colon-reader (base-packages)
()
(:documentation "Verify that the reader function for #\\\: throws an error when it is supposed to and permits what it is not supposed to throw an error on. Currently this latter part is largely forgotten as we prefer to default to sane (overly restrictive) then too loose with regards to package access.
Please note that at this time we know the reader macro prevents things that it should not prevent. Example(s) follow.
- :keyword")
;; This is not even remotely correct arguments passed, the point is
;; to verify that we send an error
:test (expect-error
(:documentation "Calling the custom reader function should automaticallythrow an error at this point. This is what I (nixeagle) term defaulting to sane defaults. Deny everything!")
(ensure-condition 'simple-error
(colon-reader nil nil))))
(deftestsuite safe-package-suite ()
()
(:documentation "Tests for correct safe package objects."))
(deftestsuite test-*prepared-safe-packages* (safe-package-suite)
()
(:documentation "Prepared safe packages should be a list of keywords
mapping to *existing* packages")
(:function
(keyword-package-p (possible-package)
(ensure (packagep (find-package possible-package))
:report "Keyword ~S does not refer to a package"
:arguments (possible-package))))
(:test (is-a-list
(:documentation "If this is not a list, we are out of luck.")
(ensure (listp *prepared-safe-packages*))))
(:test (list-of-keywords
(:documentation "all values in the list should be :keywords")
(ensure-same (member-if-not #'keywordp *prepared-safe-packages*)
nil)))
(:test (list-of-packages
(:documentation "All the items in the list should refer to a package. Please note that we expect to return nil, on failure we will return the erroring element.")
(mapc (lambda (x) (keyword-package-p x))
*prepared-safe-packages*))))
;; (deftestsuite safe-package-fixture (safe-package-suite)
;; ((~package~))
;; (:setup (setq ~package~ (create-safe-package "SAFE-PACKAGE-TEST-PACKAGE"
;; "SAFE-PACKAGE-TEST-OWNER")))
;; (:teardown (delete-safe-package "SAFE-PACKAGE-TEST-PACKAGE")))
;; (defmacro with-safe-package-fixture (&body body)
;; `(let ((~package~ (create-safe-package "SAFE-PACKAGE-TEST-PACKAGE"
;; "SAFE-PACKAGE-TEST-OWNER")))
;; (prog1
;; (progn
;; ,@body)
;; '(delete-package :safe-package-test-package))))
;; (deftestsuite test-package-use-from (safe-package-suite)
;; ()
;; (:documentation "Verify that different parameters to import do not
;; cause issues and that the imports do what they are supposed to
;; do. Nothing should be shadowed by default.")
;; (:test
;; (pass-string-and-keyword
;; (with-safe-package-fixture
;; (ensure (package-use-from "SAFE-PACKAGE-TEST-PACKAGE" :nisp)))))
;; (:test
;; (pass-keyword-and-keyword
;; (with-safe-package-fixture
;; (ensure (package-use-from :safe-package-test-package :nisp)))))
;; (:test
;; (pass-keyword-and-string
;; (with-safe-package-fixture
;; (ensure (package-use-from :safe-package-test-package "NISP")))))
;; (:tests
;; (pass-package
;; (with-safe-package-fixture
;; (ensure (package-use-from (find-package
;; :safe-package-test-package) "NISP"))))
;; (pass-safe-package
;; (with-safe-package-fixture
;; (ensure (package-use-from ~package~ "NISP"))))))
;; (deftestsuite test-get-package (safe-package-suite)
;; ()
;; (:documentation "Test that getting a package works as expected for all types.")
;; (:function
;; (ensure-packagep (x)
;; (ensure (with-safe-package-fixture (packagep (get-package x)))
;; :report "Input ~A is not a package object."
;; :arguments (x))))
;; (:tests
;; (pass-string
;; (ensure-packagep "SAFE-PACKAGE-TEST-PACKAGE"))
;; (pass-keyword
;; (ensure-packagep :safe-package-test-package))
;; (pass-package
;; (ensure-packagep (find-package :safe-package-test-package)))))
;; (deftestsuite test-shadowing-intern ()
;; ()
;; (:documentation "Verify that interning a symbol works as expected.")
;; (:test
;; (intern-in-safe
;; (ensure-same (with-safe-package-fixture (shadowing-intern ~package~ '+))
;; nil) ) ))
(defpackage #:safe-external-tests
(:use :lift
:safe-external
:safe-closure)
(:documentation "This package is largely reserved for testing "))
;(use-package *prepared-safe-packages* (find-package :safe-external-tests))
| 7,036 | Common Lisp | .lisp | 155 | 40.812903 | 305 | 0.649905 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | c7b70beed3c89af0d4f1fcb12b587ced45666f346adbe02fc27de6449c72e778 | 13,206 | [
-1
] |
13,207 | empty-package.lisp | nixeagle_nisp/safe/empty-package.lisp | ;;;; Handle the creation, and deletion of empty packages.
;;; Contained here is lisp that creates a totally empty package with
;;; nothing in it by a given name, or by a unique name. Additionally a
;;; few macros are exported to handle the basic use cases with clean
;;; syntax.
;;;
;;; This by itself does not ensure safety of foreign code
;;; evaluation. The major point of empty packages are so that the lisp
;;; reader sees no interned symbols but what is put in there by the
;;; application programmer. Reading from inside an empty package alone
;;; does not ensure saftey. You can access symbols outside of an empty
;;; package with cl::+ syntax.
;;;
;;; The basic idea with this is to make a package that has nothing in it,
;;; and to be able to make these packages without specifying a name every
;;; time we make one. This property is useful for tests as well as for
;;; making a new empty package on user request. Some examples of use
;;; include giving each 'user' their own namespace so experiments by one
;;; user will not cause clashes by experiments of the other.
(in-package :nisp-empty-package)
(deftestsuite root-suite () ())
(defun make-empty-package (name)
"Create an empty package called NAME.
This is just a wrapper around (make-package) with extra arguments to
ensure the generated package really is empty on all implentations. We
have to do this because the ansi standard leaves what to do with
MAKE-PACKAGE with no arguments implentation defined."
(make-package name :use 'nil))
;;;; Generate an empty package.
;;; Please note this used to be a closure, but it is now defined as a
;;; global internal variable as the closure gets reset when the lisp
;;; file gets recompiled. Ideas or advice on how to have a closure set
;;; itself only once and never reset are welcome.
(defvar *empty-package-counter* 0
"Internal global variable to increment the ids instead of using a
closure as a closure gets reset whenever a file gets re-compiled.")
(defun gen-empty-package (&optional prefix)
"Generate and return a package with a unique name prefixed by an integer
If prefix is not supplied, default to G-SAFE-"
(let ((prefix (or prefix "G-SAFE-")))
(make-empty-package
(concatenate 'string
prefix (write-to-string (incf *empty-package-counter*))))))
(deftestsuite test-gen-empty-package (root-suite)
()
(:test (generate-different-packages
(:documentation "
Should not get the same object from two
different calls to gen-empty-package
")
(ensure-different (gen-empty-package)
(gen-empty-package))))
(:documentation "Generating an empty package gives us a new
package. If at any time we are able to generate a package collision a
bug has been found."))
#+ (or)
(test (gen-empty-package :depends-on (and make-empty-package))
"Generating an empty package should always give us a new package. If
at any time we are able to generate a package collision a bug has been
found."
;; test fails, not implemented
(let ((package1 (gen-empty-package))
(package2 (gen-empty-package)))
(is (not (eq package1 package2))
"Should not get the same object from two different calls to
gen-empty-package")))
;;; I've chosen to name this 'with-empty-package' and not
;;; 'with-temp-empty-package' as it is implied that the package is
;;; temporary given there are no other arguments to the macro other then
;;; the body forms. There is no real good way for passed body forms to
;;; get the name of the package other then to wrap the macro around in a
;;; let form or some other method of passing the package name from
;;; inside the macro outside of it.
(defmacro with-empty-package (&body body)
"Run body with *package* set to an empty package and remove the
package after the body is done executing.
This is mostly motivated for use in test cases."
`(let* ((name (gensym))
(*package* (gen-empty-package)))
(progn
(setq name (package-name *package*))
(apply #'values
(prog1 (multiple-value-list ,@body)
(delete-package name))))))
;;;; Handle creating empty packages.
(deftestsuite test-make-empty-package (root-suite)
((empty-name "safe-SoMe-Long-paKAGeName")
(empty-package))
(:setup (setq empty-package (make-empty-package empty-name)))
(:teardown (delete-package empty-name))
:test (expect-package
(ensure (packagep empty-package)))
:test (expect-zero-elements
(ensure-same (nistilities::count-symbols empty-name) 0)))
(deftestsuite test-with-empty-package (root-suite)
()
;; commenting this one out for now, its giving a spurious test
;; failure. The package when deleted is still a package.
#+ (or) (:test
(deleted-package
(:documentation "Returned (deleted) package will be nil
according to packagep. If this returns an undeleted function then we did
not do the cleanup work properly")
(ensure (not (packagep (with-empty-package *package*))))))
:test (package-has-no-symbols
(ensure (with-empty-package
(= 0 (nistilities::count-symbols)))))
:test (multiple-return-values
(ensure-same
(multiple-value-list
(with-empty-package
(values '1 'a))) '(1 a)))
:test (single-return-value
(ensure-same (with-empty-package 3) 3)))
(defmacro with-package (package &body body)
"Evaluate body in the context of package-name."
`(let ((*package* (find-package ,package)))
,@body))
(deftestsuite test-with-package (root-suite)
()
:test (pass-string
(ensure-same
(with-package "ASDF"
(package-name *package*))
"ASDF"))
:test (pass-keyword
(ensure-same
(with-package :asdf
(package-name *package*))
"ASDF"))
:documentation "Getting the package name of *package* should be
changed to the package specified in the call to with-package") | 5,984 | Common Lisp | .lisp | 132 | 40.780303 | 79 | 0.70562 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | c8b7c13e2c2e48120fd4d085be784c49b9d0c57d7581f6c6b85c0e08a3576a7a | 13,207 | [
-1
] |
13,208 | safe.lisp | nixeagle_nisp/safe/safe.lisp | ;;; The idea here is to do safe evaluation by reading using alternate
;;; packages
;;;
;;; This is not _intended_ for use by anyone anywhere other then the author.
;;; the package is still very incomplete and untested.
;;;
;;; Please note this code is highly experimental, if it blows up the
;;; moon, its not my fault ;)
(in-package :nisp-safe)
(defun delete-safe-package-old (name)
"Delete package NAME unless its already deleted.
DEPRECIATED
Moving to all safe-package operations being on safe-package and or safe."
(when (packagep (find-package name))
(delete-package name)))
(defun read-using-package (name string)
"read STRING using package NAME."
(let ((*package* (find-package name)))
(read-from-string string)))
(defclass safe-set ()
((packages :accessor safe-set
:initform (make-hash-table :test 'equal)))
(:documentation
"Primary class for groupings of safe packages and manipulation of
these packages. These are used to group related packages together and
perform operations on sets of packages."))
(defgeneric safe-select (safe owner))
(defmethod safe-select ((safe safe-set) (owner string))
"Select a package, if the package does not exist create one and return it."
(or (gethash owner (safe-set safe))
(setf (gethash owner (safe-set safe))
(create-safe-package (concatenate 'string "SAFE-" owner)
owner))))
(defgeneric safe-delete-package-list (safe)
(:documentation "Delete the list of packages known to a safe object."))
(defmethod safe-delete-package-list ((safe safe-set))
(maphash (lambda (key package)
(declare (ignore key))
(delete-safe-package package))
(safe-set safe))
(clrhash (safe-set safe)))
(defun make-safe-set ()
"Make a new instance of a safe package set."
(make-instance 'safe-set))
(defgeneric safe-read (package forms &optional owner)
(:documentation "(read input using the namespace of the safe package"))
(defmethod safe-read ((package safe-package) (forms string) &optional owner)
(declare (ignore owner))
(with-package (package-name (safe-package package))
(let ((*readtable* (safe-package-readtable package))
(*read-eval* nil)) ;disable #.foo
(multiple-value-bind (result)
(read-from-string forms)
result))))
(defmethod safe-read ((safe safe-set) (forms string) &optional owner)
(safe-read (safe-select safe owner) forms))
(defun safe-external::describe (object)
"Special describe function for our sandbox testing stuff."
;; Needs rewritten to not depend on swank!
(swank::describe-to-string object))
(defparameter safe-external::help "Welcome to nisp-safe! This is a tool for evaluating common lisp in a safe environment. Currently you can reset your 'sandbox' with (reset). Each user gets their own area."
"The help message when a user types the word help in.")
(defparameter safe-external::test-results "http://paste.nixeagle.org/lift-nisp/"
"Location of the latest test run results.")
(defmacro setq-single (var value)
(list 'cl:setq var value))
;;; Also from metatilities
(defun group (list n)
"Return the elements of `list' grouped in sublists of length `n,'
which should be a positive integer. For example, the list '(a b c d)
grouped by 2 yields '((a b) (c d)). Definition of `group' taken from On
Lisp, by Paul Graham. The definition is not hugely efficient, so this
function is appropriate for parsing macro args, but no for inner loops.
Example:
(group (range 1 10) 2)
=> ((1 2) (3 4) (5 6) (7 8) (9 10))
(group (range 1 10) 5)
=> ((1 2 3 4 5) (6 7 8 9 10))
(group (range 1 10) 7)
=> ((1 2 3 4 5 6 7) (8 9 10))
"
(check-type list list)
(check-type n (integer 1 #.most-positive-fixnum))
(labels ((next (list n acc)
(let ((rest (nthcdr n list)))
(if (consp rest)
(next rest n (cons (subseq list 0 n) acc))
(nreverse (cons list acc))))))
(next list n nil)))
(defun nisp-safe::populate-safe-package-closures (safe-package)
"Reset the functions that have some hidden state."
(defun safe-closure::reset ()
"Reset the sandbox you are in. Generally this will delete the sandbox and create a new one in its place."
(setf (nisp-safe::reset) safe-package))
(defmacro safe-closure::setq (&rest things)
"Special macro defined to wrap around the base setq given by the
lisp implentation. The primary thing we do in this macro is be sure to intern new symbols in the safe-package and not allow modification of symbols exported from other packages."
`(mapcar #'safe-closure::setq-pair
',(group things 2))) ;;; metautilities group being used here.
(defun safe-closure::setq-pair (pair)
(let ((f (shadowing-intern safe-package (first pair)))
(l (second pair)))
(setq f (first pair)) ;Set a copy... leaving f interned right
(safe-closure::setq-trace2 f l)))
;; THIS IS SO WRONG! But it works. Find out why and do this right!
(defun safe-closure::setq-trace2 (first2 last2)
(eval `(setq ,first2 ,last2)))
(defun safe-closure::safe-intern (thing)
"Given a thing, intern it if its something that can cause package classes otherwise just leave it alone."
(if (typep thing 'symbol)
(shadowing-intern safe-package thing)
thing))
(defun safe-closure::nisp-test (&rest things)
(let ((*package* (safe-package safe-package)))
(prin1-to-string (macroexpand-1 `(safe-closure::setq ,things)))
#+ () (mapcar #'safe-closure::safe-intern things))
#+ () (mapcar #'class-of things))) | 5,617 | Common Lisp | .lisp | 117 | 43.65812 | 206 | 0.695589 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | c6f0a9e935dc333d2df09a95f35f59a08f38be2df39c381d8b42f43a09ef9b14 | 13,208 | [
-1
] |
13,209 | readtable.lisp | nixeagle_nisp/safe/readtable.lisp | (in-package :nisp-safe)
(defun colon-reader (stream char)
"Signal an error if a colon is used to access another package."
(declare (ignore stream char))
;; For now we just error out. This is a safe thing to do as far as
;; disabling package access goes, but in the process use of : is
;; broken for :keywords and possibly other things too.
(error "Accessing packages outside of the current one is disabled."))
(defun make-readtable ()
"Create readtable that prevents any syntax that can cause a package
change."
(let ((*readtable* (copy-readtable nil)))
(set-macro-character #\: #'colon-reader nil *readtable*)
*readtable*))
;;; Moving this down here for now after make-readtable is defined
;;; because this depends on that function being defined. I want to
;;; depreciate this in the near future and get away from the package
;;; global if possible. Not doing so unless the solution is elegent. The
;;; primary constraint is not re-creating a new readtable on every
;;; evaluation call. Closures may do it.
(defparameter *safe-readtable* (make-readtable)
"The safe readtable that is used by the with-safe-readtable macro.
This is currently a parameter but should be made into a constant at some
point so a warning or error can block it being changed in a running
program.")
(defmacro with-safe-readtable (&body body)
"Use readtable for all read calls in body.If readtable is not passed,
we default to instantiating a new one using make-readtable"
`(let ((*readtable* *safe-readtable*))
,@body)) | 1,539 | Common Lisp | .lisp | 30 | 48.9 | 72 | 0.751995 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 8fdef4736f97bb6e03ab33703460944d99263be5c071bae4307eaf52e75f266f | 13,209 | [
-1
] |
13,210 | nisp-introspect.lisp | nixeagle_nisp/safe/nisp-introspect.lisp | ;;; Introspection of lisp systems. May be portable one day.
(in-package :nisp-introspect)
(deftestsuite root-suite () ())
(defgeneric function-lambda-list (symbol)
(:documentation
"Return lambda list description given a string or a valid function designator."))
(defmethod function-lambda-list :around (symbol)
"Handle errors originating from a function-lambda list call."
(handler-case (call-next-method)
(error ()
(format nil "Passed input type ~A not valid extended function designator."
(type-of symbol)))))
(defmethod function-lambda-list (symbol)
#+sbcl (sb-introspect::function-lambda-list symbol))
(defmethod function-lambda-list ((symbol string))
"If we get a string, read it and re-call."
(function-lambda-list (read-from-string symbol)))
#+sbcl
(deftestsuite test-function-lambda-list (root-suite)
((plus-arg-list '(&REST SB-KERNEL::ARGS)))
:test (pass-valid-symbol
(ensure-same (function-lambda-list '+)
plus-arg-list))
:test (pass-invalid-symbol
(ensure (stringp (function-lambda-list 1))))
:test (pass-valid-string
(ensure-same (function-lambda-list "+")
plus-arg-list))) | 1,225 | Common Lisp | .lisp | 28 | 37.785714 | 84 | 0.683193 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 6f0c8c6ab37057b68d8e37026fa410c7b731a0c4a87b1ae859d4c982261125f6 | 13,210 | [
-1
] |
13,211 | arithmetic.lisp | nixeagle_nisp/safe/arithmetic.lisp | ;;; These package and function definitions are *alpha* quality.
(in-package :nisp-safe-system)
;;; These should be fairly safe as there are no side effects,
;;; at least according to the standard.
(define-export-system #:safe-arithmetic :cl
#:+
#:-
#:*
#:/
#:=
;; basic incrementers
#:1+
#:1-
;; common denometer stuff
#:gcd
#:lcm
#:abs
#:conjugate
#:cis
#:sqrt
#:isqrt
#:exp
#:expt
#:log
#:signum
#:phase
pi)
(define-export-system #:safe-arithmetic-trig :cl
#:sin
#:cos
#:tan
#:asin
#:acos
#:atan
#:sinh
#:cosh
#:tanh
#:asinh
#:acosh
#:atanh)
(define-export-system #:safe-arithmetic-comparision :cl
#:/=
#:<
#:<=
#:=
#:>
#:>=
#:oddp
#:evenp
#:plusp
#:max
#:zerop
#:min
#:minusp)
(define-export-system #:safe-arithmetic-type-manipulation :cl
#:ceiling
#:float-radix
#:rational
#:complex
#:float-sign
#:rationalize
#:decode-float
#:floor
#:realpart
#:denominator
#:fround
#:rem
#:fceiling
#:ftruncate
#:round
#:ffloor
#:imagpart
#:scale-float
#:float
#:integer-decode-float
#:truncate
#:float-digits
#:mod
#:float-precision
#:numerator)
(define-export-system #:safe-arithmetic-boole :cl
#:ash
#:boole
boole-1
boole-2
boole-and
boole-andc1
boole-andc2
boole-c1
boole-c2
boole-clr
boole-eqv
boole-ior
boole-nand
boole-nor
boole-orc1
boole-orc2
boole-set
boole-xor
#:integer-length
#:logand
#:logandc1
#:logandc2
#:logbitp
#:logcount
#:logeqv
#:logior
#:lognand
#:lognor
#:lognot
#:logorc1
#:logorc2
#:logtest
#:logxor)
(define-export-system #:safe-arithmetic-byte :cl
#:byte
#:deposit-field
#:ldb-test
#:byte-position
#:dpb
#:mask-field
#:byte-size
#:ldb)
(define-export-system #:safe-arithmetic-implentation-constants :cl
double-float-epsilon most-negative-fixnum
double-float-negative-epsilon most-negative-long-float
least-negative-double-float most-negative-short-float
least-negative-long-float most-negative-single-float
least-negative-short-float most-positive-double-float
least-negative-single-float most-positive-fixnum
least-positive-double-float most-positive-long-float
least-positive-long-float most-positive-short-float
least-positive-short-float most-positive-single-float
least-positive-single-float short-float-epsilon
long-float-epsilon short-float-negative-epsilon
long-float-negative-epsilon single-float-epsilon
most-negative-double-float single-float-negative-epsilon)
(define-export-system #:safe-arithmetic-random :cl
#:random)
;;; These do modifications to variables, eg side effects.
(defpackage #:safe-arithmetic!
(:use :cl)
(:export
;; basic incrementers
#:decf
#:incf)) | 3,008 | Common Lisp | .lisp | 146 | 16.445205 | 66 | 0.648895 | nixeagle/nisp | 7 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | e2620f48f186f768a9887cc7566ddc99a87ff4f1cfeb88f6f3369a4d220c2fb6 | 13,211 | [
-1
] |
13,212 | skeleton.lisp | ahungry_ahungry-fleece/skel/src/skeleton.lisp | ;; skeleton - A project template generated by ahungry-fleece
;; Copyright (C) 2016 Your Name <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; skeleton.lisp
(in-package #:cl-user)
(defpackage skeleton
(:use :cl)
(:export :main
:print-usage))
(in-package #:skeleton)
(defun print-usage ()
(format t
"skeleton v/~a.
Usage:
$ skeleton [-h, --help] # Print this help
"
(asdf:component-version (asdf:find-system :skeleton))))
(defun main (&rest argv)
(unless argv
(setf argv (cdr sb-ext:*posix-argv*)))
(if (or (equal (first argv) "-h")
(equal (first argv) "--help"))
(print-usage)
(cond
(t (print-usage)))))
;;; "skeleton" goes here. Hacks and glory await!
| 1,378 | Common Lisp | .lisp | 38 | 33.236842 | 78 | 0.701807 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 875c1f207cedec6bc109d1a6ecd5b0d29c1cc97a8320d91b5b0200f116e26089 | 13,212 | [
-1
] |
13,213 | skeleton.lib.stub.lisp | ahungry_ahungry-fleece/skel/src/libs/skeleton.lib.stub.lisp | ;; skeleton - A project template generated by ahungry-fleece
;; Copyright (C) 2016 Your Name <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; skeleton.lib.stub.lisp
(in-package #:cl-user)
(defpackage skeleton.lib.stub
(:use :cl)
(:export
:echo))
(in-package #:skeleton.lib.stub)
(defun echo (input)
input)
;;; "skeleton.lib.stub" goes here. Hacks and glory await!
| 1,028 | Common Lisp | .lisp | 25 | 39.52 | 78 | 0.752257 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | e32301660816429eef686f592192202d667ca5b4fc38e511ee60e16dccb6ec60 | 13,213 | [
-1
] |
13,214 | skeleton.run.tests.lisp | ahungry_ahungry-fleece/skel/t/skeleton.run.tests.lisp | ;; skeleton - A project template generated by ahungry-fleece
;; Copyright (C) 2016 Your Name <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; skeleton.run.tests.lisp
(in-package #:cl-user)
(defpackage skeleton.run.tests
(:use :cl
:skeleton.lib.stub
:af.lib.ansi-colors
:af.lib.coverage
:af.lib.testy)
(:export :main))
(in-package #:skeleton.run.tests)
(defparameter *base-directory* (asdf:system-source-directory :skeleton))
(defun main ()
"Run the tests, or the tests with coverage."
(if (and (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE")
(> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE")) 0))
(coverage)
(test)
))
(defun test ()
"Begin the tests!"
(unless (and (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE")
(> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE")) 0))
(setf af.lib.ansi-colors:*colorize-p* nil))
(if (suite
"skeleton.lib"
(desc
"skeleton.lib.stub"
(it "Should echo the input"
(eq 3 (skeleton.lib.stub:echo 3)))
)
) ;; end suite
(setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 0))))
(setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 1)))))
)
(defun coverage ()
"Begin the tests!"
;; See if we're in the shell environment or not (SLIME will use 'dumb' here)
(af.lib.coverage:with-coverage :skeleton
(test)
(terpri)
(with-color :blue (format t "Summary of coverage:~%"))
(with-open-stream (*error-output* (make-broadcast-stream))
(af.contrib.sb-cover:report (merge-pathnames #P"coverage/" *base-directory*)))
(with-open-stream (*error-output* (make-broadcast-stream))
(af.lib.coverage:report-cli (merge-pathnames #P"coverage/" *base-directory*))
)
(with-open-stream (*error-output* (make-broadcast-stream))
(af.lib.coverage:report-json (merge-pathnames #P"coverage/" *base-directory*))
)
(with-color :light-blue
(format t "~%Full coverage report generated in: ~a" (merge-pathnames #P"coverage/" *base-directory*))
(format t "~%Coverage summary generated in: ~acoverage.json~%~%" (merge-pathnames #P"coverage/" *base-directory*))
)
)
)
;;; "skeleton.run.tests" goes here. Hacks and glory await!
| 2,988 | Common Lisp | .lisp | 71 | 36.915493 | 120 | 0.665059 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 3ecfa7d991f17e93fa7694d4d09385a3c87da6522f8fe5e9ee87eefeb3a0b8c4 | 13,214 | [
-1
] |
13,215 | ahungry-fleece.lisp | ahungry_ahungry-fleece/src/ahungry-fleece.lisp | ;; Ahungry Fleece - A utility library.
;; Copyright (C) 2016 Matthew Carter <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; ahungry-fleece.lisp
(in-package #:cl-user)
(defpackage ahungry-fleece
(:use :cl
:cl-json
:af.lib.io
:af.lib.clone
:af.lib.hashy)
(:export :main
:make-skelly-project
:print-usage
))
(in-package #:ahungry-fleece)
(defparameter *base-directory* (asdf:system-source-directory :ahungry-fleece))
(defun make-skelly-project (directory)
"Create a new project in DIREcTORY with name equal to the directory.
Similar to quickproject:make-project, but also ensures the
created files closely match what is available in this own project's
directory structure setup (with CLI based unit test etc.)."
(print
(clone-project
(merge-pathnames #P"skel" *base-directory*)
directory
"skeleton"
(pathname-name directory)))
(pushnew (truename directory) asdf:*central-registry* :test 'equal)
(file-get-contents (merge-pathnames "README.md" (truename directory))))
(defun print-usage ()
(format t
"ahungry-fleece v/~a.
Usage:
$ ahungry-fleece [-h, --help] # Print this help
$ ahungry-fleece make-skelly-project /path/to/directory # Make a skeleton project
"
(asdf:component-version (asdf:find-system :ahungry-fleece))))
(defun main (&rest argv)
(unless argv
(setf argv (cdr sb-ext:*posix-argv*)))
(if (or (equal (first argv) "-h")
(equal (first argv) "--help"))
(print-usage)
(cond
((equal "make-skelly-project" (first argv))
(make-skelly-project (second argv)))
(t (print-usage)))))
;;; "ahungry-fleece" goes here. Hacks and glory await!
| 2,360 | Common Lisp | .lisp | 61 | 34.754098 | 85 | 0.70565 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 053aa9812a52cd0ae70f3311fec3b10a12ff04cd03deb647d6dd29bb383755c3 | 13,215 | [
-1
] |
13,216 | af.lib.loggy.lisp | ahungry_ahungry-fleece/src/libs/af.lib.loggy.lisp | ;; Ahungry Fleece - A utility library.
;; Copyright (C) 2016 Matthew Carter <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; af.lib.loggy.lisp
(in-package #:cl-user)
(defpackage af.lib.loggy
(:use :cl
:cl-json)
(:export
:Loggy
:Level
:Output
:Output-Args
:Output-Stream
:log->
:flog
:*loggy*
))
(in-package #:af.lib.loggy)
(defclass Loggy ()
((Level
:accessor Level
:initarg :level
:initform 'debug)
(Output
:accessor Output
:initarg :output
:initform 'format)
(Output-Args
:accessor Output-Args
:initarg :output-args
:initform '("~a~%"))
(Output-Stream
:accessor Output-Stream
:initarg :output-stream
:initform t)
))
(defun get-level (level)
"Get a numeric level from LEVEL."
(case level
(debug 9)
(warn 7)
(info 5)
(crit 3)
(t 0)))
(defgeneric log-> (object level &rest message)
(:documentation "Write a log level message."))
(defmethod log-> ((logger Loggy) level &rest message)
"Produce a log level message.
Sample call:
(log-> *loggy* 'debug \"Hello World\")"
(when (>= (get-level (Level logger))
(get-level level))
(apply (Output logger) (Output-Stream logger)
(append (Output-Args logger) message))
(car message)))
(defparameter *loggy* (make-instance 'Loggy))
(defun flog (level &rest message)
"Log to the singleton."
(apply #'log-> *loggy* level message))
;;; "af.lib.loggy" goes here. Hacks and glory await!
| 2,141 | Common Lisp | .lisp | 73 | 25.849315 | 78 | 0.685158 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 3c5db1f52fbfaa0b375096e8f72ac9bb1b9ceb7f8b316fe627b24ccc4133f5d6 | 13,216 | [
-1
] |
13,217 | af.lib.testy.lisp | ahungry_ahungry-fleece/src/libs/af.lib.testy.lisp | ;; Ahungry Fleece - A utility library.
;; Copyright (C) 2016 Matthew Carter <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; af.lib.testy.lisp
(in-package #:cl-user)
(defpackage af.lib.testy
(:use :cl
:cl-json
:af.lib.ansi-colors)
(:export
:suite
:desc
:it))
(in-package #:af.lib.testy)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro test-wrapper (format-title format-summary desc &rest results)
"Describe a suite of tests."
`(progn
(af.lib.ansi-colors:with-color :blue
(format t ,format-title ,desc))
(let* ((results (list ,@results))
(test-success-p (zerop (count nil results)))
(color (if test-success-p :light-green :light-red)))
(with-color color
(format t ,format-summary
(length results)
(count nil results)))
test-success-p)))
(defmacro suite (desc &rest results)
"Describe a suite of tests."
`(test-wrapper "~%~a~%" "~%~a tests, ~a failures~%" ,desc ,@results))
(defmacro desc (desc &rest results)
"Describe a set of test."
`(test-wrapper "~%~% ~a~%~%" "~% ~a assertions, ~a failures~%" ,desc ,@results))
) ;; eval-when
(defun it (desc result)
"Assert the body evaluates as expected."
(let ((color (if result :green :red)))
(af.lib.ansi-colors:with-color color
(format t " ~a ~a~%"
(if result "+" "-")
desc)))
result)
;;; "af.lib.testy" goes here. Hacks and glory await!
| 2,178 | Common Lisp | .lisp | 56 | 33.75 | 86 | 0.647894 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | b308d3d1533aae38e096e22067c7bba4ed94649f2efe6b415c7a75c1a84e1bb4 | 13,217 | [
-1
] |
13,218 | af.lib.ansi-colors.lisp | ahungry_ahungry-fleece/src/libs/af.lib.ansi-colors.lisp | ;; Ahungry Fleece - A utility library.
;; Copyright (C) 2016 Matthew Carter <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; af.lib.hashy.lisp
(in-package #:cl-user)
(defpackage af.lib.ansi-colors
(:use :cl
:split-sequence)
(:export
:colorize
:with-color
:*colorize-p*
))
(in-package #:af.lib.ansi-colors)
(defparameter *colors*
(list :black "0;30"
:blue "0;34"
:green "0;32"
:cyan "0;36"
:red "0;31"
:purple "0;35"
:brown "0;33"
:light-gray "0;37"
:dark-gray "1;30"
:light-blue "1;34"
:light-green "1;32"
:light-cyan "1;36"
:light-red "1;31"
:light-purple "1;35"
:yellow "1;33"
:white "1;37"))
(defparameter *colorize-p* t)
(defun colorize (color)
"Set the active color of the terminal."
(when *colorize-p*
(format t "~c[~am"
#\Esc
(or (getf *colors* color)
(getf *colors* :white)))))
(defmacro with-color (color &rest body)
"Activate COLOR and execute BODY (while reseting back to base color)."
`(progn
(colorize ,color)
,@body
(colorize :light-gray)))
;;; "af.lib.hashy" goes here. Hacks and glory await!
| 1,872 | Common Lisp | .lisp | 58 | 27.448276 | 78 | 0.644321 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 871329b7f2d6fdd16f578a15a5c6042b1a199dd5bd39720a2c5716b8e04edf62 | 13,218 | [
-1
] |
13,219 | af.lib.clone.lisp | ahungry_ahungry-fleece/src/libs/af.lib.clone.lisp | ;; Ahungry Fleece - A utility library.
;; Copyright (C) 2016 Matthew Carter <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; af.lib.clone.lisp
(in-package #:cl-user)
(defpackage af.lib.clone
(:use :cl
:af.lib.io
:cl-ppcre
:cl-json)
(:export
:clone-project
:rename-path
))
(in-package #:af.lib.clone)
(defun rename-path (from-path to-path file-name from-name to-name)
"Rename a file in a path, as such:
Given a FILE-NAME /one/two/sub/three with a FROM-PATH of /one/two
and a TO-PATH of /uno/dos/sub/, with a FROM-NAME three and TO-NAME tres,
produce a path of /uno/dos/sub/tres.
@todo Add test
"
(let* ((file-segment (subseq (af.lib.io:pathname-to-string file-name)
(1+ (length (af.lib.io:pathname-to-string from-path)))))
(file-renamed (cl-ppcre:regex-replace-all from-name file-segment to-name)))
(merge-pathnames file-renamed to-path)))
(defun clone-project (from-path to-path from-name to-name)
"Recursively copy FROM-PATH to TO-PATH, while replacing all
occurences of FROM-NAME to TO-NAME."
(let ((nodes (directory-tree from-path))
(to-path (format nil "~a/" to-path)))
(loop for node in nodes
when (file-p node)
collect
(let ((out-file (rename-path from-path to-path node from-name to-name)))
(handler-case
(let* ((in-content (file-get-contents node))
(out-content (cl-ppcre:regex-replace-all from-name in-content to-name)))
(file-put-contents out-file out-content :overwrite t)
out-file)
(sb-int:stream-decoding-error ()
;; UTF8 binary issue with characters most likely...
(progn
(file-put-binary-contents out-file (file-get-binary-contents node) :overwrite t)
out-file))
(error (err)
(print err)))))))
;;; "af.lib.clone" goes here. Hacks and glory await!
| 2,624 | Common Lisp | .lisp | 60 | 37.4 | 97 | 0.657926 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | a77da025c9a4f0d94e3cc122d7f01a54f06e833207373a73a8c52c0722cc49a9 | 13,219 | [
-1
] |
13,220 | af.run.tests.lisp | ahungry_ahungry-fleece/t/af.run.tests.lisp | ;; Ahungry Fleece - A utility library.
;; Copyright (C) 2016 Matthew Carter <[email protected]>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; 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 Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;; af.run.tests.lisp
(in-package #:cl-user)
(defpackage af.run.tests
(:use :cl
:af.lib.io
:af.lib.ansi-colors
:af.lib.loggy
:af.lib.hashy
:af.lib.coverage
:af.lib.testy)
(:export :main
:coverage))
(in-package #:af.run.tests)
(defparameter *base-directory* (asdf:system-source-directory :ahungry-fleece))
(defparameter *yml* nil "The yml file for testing.")
(defun main ()
"Run the tests, or the tests with coverage."
(if (and (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE")
(> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE")) 0))
(coverage)
(test)
))
(defun test ()
"Begin the tests!"
(unless (and (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE")
(> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE")) 0))
(setf af.lib.ansi-colors:*colorize-p* nil))
(if (suite
"af.lib"
(desc
"af.lib.io"
(it "Should be able to tell a directory"
(eq t (af.lib.io:directory-p (user-homedir-pathname))))
(it "Should be able to tell a file"
(eq t (af.lib.io:file-p "/dev/null")))
)
(desc
"af.lib.loggy"
(it "Should send to proper stream when levels are set"
(progn
(setf (af.lib.loggy:Level *loggy*) 'debug)
(setf (af.lib.loggy:Output-Stream *loggy*) nil)
(eq "Hello" (log-> *loggy* 'debug "Hello"))))
(it "Should not print debug when set to warn"
(progn
(setf (af.lib.loggy:Level *loggy*) 'warn)
(not (eq "Hello" (log-> *loggy* 'debug "Hello")))))
)
(desc
"af.lib.hashy"
(it "Should let me easily access a yml property"
(and
(setf *yml* (hash-from-yaml-file
(format nil "~a/t/fixtures/pets.yml"
(asdf:system-source-directory :ahungry-fleece))))
(equal "object" (af.lib.hashy:ref "#/definitions/Pet/type" *yml*))))
(it "Should parse alist to hash properly"
(equal 1 (ref "#/one/ione"
(alist-to-hash
'((:one . ((:ione . 1))) (:two . 2))))))
(it "Should undo cl-json key mangling"
(equal "DogTime" (stringify :*dog-time)))
(it "Should return same results from yaml or json"
(let* ((fpath (format nil "~a/t/fixtures/"
(asdf:system-source-directory :ahungry-fleece)))
(yamlobj (hash-from-yaml-file (format nil "~a~a"
fpath
"pets.yml")))
(jsonobj (hash-from-json-file (format nil "~a~a"
fpath
"pets.json"))))
(equal (dump yamlobj)
(dump jsonobj))))
(it "Should allow setting of nested hash tables"
(let ((hash1 (make-hash-table :test #'equal))
(hash2 (make-hash-table :test #'equal)))
(setf (gethash "findme" hash2) 42)
(setf (gethash "hash2" hash1) hash2)
(and
(equal 42 (gethash "findme" (gethash "hash2" hash1)))
(progn
(setf (gethash "findme" hash2) 33)
(equal 33 (gethash "findme" (gethash "hash2" hash1)))
)
(equal 33 (ref "#/hash2/findme" hash1))
(progn
(ref "#/hash2/findme" hash1 99)
(equal 99 (ref "#/hash2/findme" hash1)))
t)
))
)
(desc
"af.lib.hashy:with-hashy"
(it "Should bind inline JSON to hashy"
(af.lib.hashy:with-hashy
(hashy "[1, 2, 3]" :type :json)
(equal '(1 2 3) hashy))
)
(it "Should bind a YAML TARGET to the hashy variable"
(progn
(let ((pathname
(pathname (format nil "~a/t/fixtures/pets.yml"
(asdf:system-source-directory :ahungry-fleece)))))
(af.lib.hashy:with-hashy
(hashy pathname :type :yaml)
(and
(equal "petType" (ref "#/definitions/Pet/discriminator" hashy)))
)))
) ; it
) ; desc
) ;; end suite
(setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 0))))
(setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 1)))))
)
(defun coverage ()
"Begin the tests!"
;; See if we're in the shell environment or not (SLIME will use 'dumb' here)
(af.lib.coverage:with-coverage :ahungry-fleece
(test)
(terpri)
(with-color :blue (format t "Summary of coverage:~%"))
(with-open-stream (*error-output* (make-broadcast-stream))
(af.contrib.sb-cover:report (merge-pathnames #P"coverage/" *base-directory*)))
(with-open-stream (*error-output* (make-broadcast-stream))
(af.lib.coverage:report-cli (merge-pathnames #P"coverage/" *base-directory*))
)
(with-open-stream (*error-output* (make-broadcast-stream))
(af.lib.coverage:report-json (merge-pathnames #P"coverage/" *base-directory*))
)
(with-color :light-blue
(format t "~%Full coverage report generated in: ~a" (merge-pathnames #P"coverage/" *base-directory*))
(format t "~%Coverage summary generated in: ~acoverage.json~%~%" (merge-pathnames #P"coverage/" *base-directory*))
)
)
)
;;; "af.run.tests" goes here. Hacks and glory await!
| 6,533 | Common Lisp | .lisp | 151 | 31.860927 | 120 | 0.542736 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 58fdbbdf142ddbd43591a234c834cd73165ad6b77c3ff7e19d6a7f64f6918eb7 | 13,220 | [
-1
] |
13,221 | rotate-byte.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/rotate-byte.lisp | (in-package "af.contrib.sb-rotate-byte")
(defun rotate-byte (count bytespec integer)
"Rotates a field of bits within INTEGER; specifically, returns an
integer that contains the bits of INTEGER rotated COUNT times
leftwards within the byte specified by BYTESPEC, and elsewhere
contains the bits of INTEGER."
(rotate-byte count bytespec integer))
(defun %rotate-byte (count size pos integer)
(let ((count (nth-value 1 (round count size)))
(mask (1- (ash 1 size))))
(logior (logand integer (lognot (ash mask pos)))
(let ((field (logand (ash mask pos) integer)))
(logand (ash mask pos)
(if (> count 0)
(logior (ash field count)
(ash field (- count size)))
(logior (ash field count)
(ash field (+ count size)))))))))
(defun %unsigned-32-rotate-byte (count integer)
;; inhibit transforms
(declare (notinline %rotate-byte))
(%rotate-byte count 32 0 integer))
#+64-bit
(defun %unsigned-64-rotate-byte (count integer)
(%unsigned-64-rotate-byte count integer))
| 1,149 | Common Lisp | .lisp | 25 | 37.04 | 67 | 0.621429 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | f18a9ef47f52cb56e47e7214415a0c69b908fc6d02fe41057525fa417911f3a9 | 13,221 | [
-1
] |
13,222 | package.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/package.lisp | (defpackage "af.contrib.sb-rotate-byte"
(:use "CL" "SB-C" "SB-VM" "SB-INT" "SB-KERNEL" "SB-ASSEM")
(:export "ROTATE-BYTE"))
| 128 | Common Lisp | .lisp | 3 | 40.333333 | 60 | 0.632 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | fef80eed84986c4796aec639f961d0226d7ce12b41ae219585db2cd8825aaee7 | 13,222 | [
-1
] |
13,223 | arm-vm.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/arm-vm.lisp | (in-package "af.contrib.sb-rotate-byte")
(define-vop (%32bit-rotate-byte/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:info count)
(:args (integer :scs (sb-vm::unsigned-reg) :target res))
(:arg-types (:constant (integer -31 31)) sb-vm::unsigned-byte-32)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 5
;; the 0 case is an identity operation and should be
;; DEFTRANSFORMed away.
(aver (not (= count 0)))
(inst mov res (sb-vm::ror integer (if (plusp count)
(- 32 count)
(- count))))))
(define-vop (%32bit-rotate-byte-fixnum/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:info count)
(:args (integer :scs (sb-vm::any-reg) :target res))
(:arg-types (:constant (integer -31 31)) sb-vm::positive-fixnum)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 5
(aver (not (= count 0)))
(cond
((= count n-fixnum-tag-bits))
(t
(inst mov res (sb-vm::ror integer (if (> count 2)
(- (+ 32 n-fixnum-tag-bits) count)
(- 2 count))))))))
(macrolet ((def (name arg-type)
`(define-vop (,name)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit rotation")
(:args (count :scs (sb-vm::signed-reg) :target res)
(integer :scs (sb-vm::unsigned-reg)))
(:arg-types sb-vm::tagged-num ,arg-type)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 10
(inst cmp count 0)
(inst rsb :gt res count 32)
(inst rsb :le res count 0)
(inst mov res (sb-vm::ror integer res))))))
(def %32bit-rotate-byte sb-vm::unsigned-byte-32)
;; FIXME: see x86-vm.lisp
(def %32bit-rotate-byte-fixnum sb-vm::positive-fixnum))
| 2,239 | Common Lisp | .lisp | 52 | 32.807692 | 79 | 0.544872 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | cea04a6d13a17cdc7facbb205198e74490fa7baa95f26228066299515936da49 | 13,223 | [
-1
] |
13,224 | x86-64-vm.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/x86-64-vm.lisp | (in-package "af.contrib.sb-rotate-byte")
;;; 32-bit rotates
(define-vop (%32bit-rotate-byte/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:args (integer :scs (sb-vm::unsigned-reg) :target result))
(:info count)
(:arg-types (:constant (integer -31 31)) sb-vm::unsigned-num)
(:results (result :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-num)
(:generator 5
(aver (not (= count 0)))
(move result integer)
(if (> count 0)
(inst rol (sb-vm::reg-in-size result :dword) count)
(inst ror (sb-vm::reg-in-size result :dword) (- count)))))
(define-vop (%32bit-rotate-byte)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:args (count :scs (sb-vm::signed-reg) :target rcx)
(integer :scs (sb-vm::unsigned-reg) :target result))
(:arg-types sb-vm::tagged-num sb-vm::unsigned-num)
(:temporary (:sc sb-vm::signed-reg :offset sb-vm::rcx-offset)
rcx)
(:results (result :scs (sb-vm::unsigned-reg) :from :load))
(:result-types sb-vm::unsigned-num)
(:generator 10
(let ((label (gen-label))
(end (gen-label)))
(move result integer)
(move rcx count)
(inst cmp (sb-vm::reg-in-size rcx :dword) 0)
(inst jmp :ge label)
(inst neg (sb-vm::reg-in-size rcx :dword))
(inst ror (sb-vm::reg-in-size result :dword) :cl)
(inst jmp end)
(emit-label label)
(inst rol (sb-vm::reg-in-size result :dword) :cl)
(emit-label end))))
;;; 64-bit rotates
(define-vop (%64bit-rotate-byte/c)
(:policy :fast-safe)
(:translate %unsigned-64-rotate-byte)
(:note "inline 64-bit constant rotation")
(:args (integer :scs (sb-vm::unsigned-reg) :target result))
(:info count)
(:arg-types (:constant (integer -63 63)) sb-vm::unsigned-num)
(:results (result :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-num)
(:generator 5
(aver (not (= count 0)))
(move result integer)
(if (> count 0)
(inst rol result count)
(inst ror result (- count)))))
(define-vop (%64bit-rotate-byte)
(:policy :fast-safe)
(:translate %unsigned-64-rotate-byte)
(:args (count :scs (sb-vm::signed-reg) :target rcx)
(integer :scs (sb-vm::unsigned-reg) :target result))
(:arg-types sb-vm::tagged-num sb-vm::unsigned-num)
(:temporary (:sc sb-vm::signed-reg :offset sb-vm::rcx-offset)
rcx)
(:results (result :scs (sb-vm::unsigned-reg) :from :load))
(:result-types sb-vm::unsigned-num)
(:generator 10
(let ((label (gen-label))
(end (gen-label)))
(move result integer)
(move rcx count)
(inst cmp rcx 0)
(inst jmp :ge label)
(inst neg rcx)
(inst ror result :cl)
(inst jmp end)
(emit-label label)
(inst rol result :cl)
(emit-label end))))
| 2,868 | Common Lisp | .lisp | 79 | 31.164557 | 66 | 0.623022 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 30de5b54125b2e9dbac125ba0a9f262b1024eee2cb79602b0270f886bd87a6a8 | 13,224 | [
-1
] |
13,225 | compiler.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/compiler.lisp | (in-package "af.contrib.sb-rotate-byte")
(defknown rotate-byte (integer byte-specifier integer) integer
(foldable flushable)
:overwrite-fndb-silently t)
(defknown %rotate-byte (integer bit-index bit-index integer) integer
(foldable flushable)
:overwrite-fndb-silently t)
(defknown %unsigned-32-rotate-byte ((integer -31 31) (unsigned-byte 32))
(unsigned-byte 32)
(foldable flushable)
:overwrite-fndb-silently t)
#+64-bit
(defknown %unsigned-64-rotate-byte ((integer -63 63) (unsigned-byte 64))
(unsigned-byte 64)
(foldable flushable)
:overwrite-fndb-silently t)
(macrolet (;; see src/compiler/srctran.lisp
(with-byte-specifier ((size-var pos-var spec) &body body)
(once-only ((spec `(macroexpand ,spec))
(temp '(gensym)))
`(if (and (consp ,spec)
(eq (car ,spec) 'byte)
(= (length ,spec) 3))
(let ((,size-var (second ,spec))
(,pos-var (third ,spec)))
,@body)
(let ((,size-var `(byte-size ,,temp))
(,pos-var `(byte-position ,,temp)))
`(let ((,,temp ,,spec))
,,@body))))))
(define-source-transform rotate-byte (count spec num)
(with-byte-specifier (size pos spec)
`(%rotate-byte ,count ,size ,pos ,num))))
(defoptimizer (%rotate-byte derive-type) ((count size posn num))
;; FIXME: this looks fairly unwieldy. I'm sure it can be made
;; simpler, and also be made to deal with negative integers too.
(declare (ignore count posn))
(let ((size (sb-c::lvar-type size)))
(if (numeric-type-p size)
(let ((size-high (numeric-type-high size))
(num-type (sb-c::lvar-type num)))
(if (and size-high
num-type
(<= size-high sb-vm:n-word-bits)
(csubtypep num-type
(specifier-type `(unsigned-byte ,size-high))))
(specifier-type `(unsigned-byte ,size-high))
*universal-type*))
*universal-type*)))
(deftransform %rotate-byte ((count size pos integer)
((integer -31 31)
(constant-arg (member 32))
(constant-arg (member 0))
(unsigned-byte 32)) *)
"inline 32-bit rotation"
'(%unsigned-32-rotate-byte count integer))
;; Generic implementation for platforms that don't supply VOPs for 32-bit
;; rotate.
#-(or x86 x86-64 ppc arm arm64)
(deftransform %unsigned-32-rotate-byte ((.count. .integer.)
((integer -31 31)
(unsigned-byte 32)) *)
'(if (< .count. 0)
(logior (ldb (byte 32 0) (ash .integer. (+ .count. 32)))
(ash .integer. .count.))
(logior (ldb (byte 32 0) (ash .integer. .count.))
(ash .integer. (- .count. 32)))))
#+64-bit
(deftransform %rotate-byte ((count size pos integer)
((integer -63 63)
(constant-arg (member 64))
(constant-arg (member 0))
(unsigned-byte 64)) *)
"inline 64-bit rotation"
'(%unsigned-64-rotate-byte count integer))
;;; This transform needs to come after the others to ensure it gets
;;; first crack at a zero COUNT, since transforms are currently run
;;; latest-defined first.
(deftransform %rotate-byte ((count size pos integer)
((constant-arg (member 0)) * * *) *)
"fold identity operation"
'integer)
| 3,745 | Common Lisp | .lisp | 82 | 33.243902 | 76 | 0.536379 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 0de76043da44dd8e52d33259860a9acf505a9abaaac53e1b0fce149edf3cb835 | 13,225 | [
-1
] |
13,226 | arm64-vm.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/arm64-vm.lisp | (in-package "af.contrib.sb-rotate-byte")
;;; 32-bit
(define-vop (%32bit-rotate-byte/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:args (integer :scs (sb-vm::unsigned-reg) :target result))
(:info count)
(:arg-types (:constant (integer -31 31)) sb-vm::unsigned-num)
(:results (result :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-num)
(:generator 5
(aver (not (= count 0)))
(inst ror (sb-vm::32-bit-reg result) (sb-vm::32-bit-reg integer)
(if (plusp count)
(- 32 count)
(abs count)))))
(define-vop (%32bit-rotate-byte)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit rotation")
(:args (count :scs (sb-vm::signed-reg))
(integer :scs (sb-vm::unsigned-reg)))
(:arg-types sb-vm::tagged-num sb-vm::unsigned-num)
(:temporary (:sc sb-vm::signed-reg) temp)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-num)
(:generator 10
(inst mov temp 32)
(inst cmp count 0)
(inst csel temp sb-vm::zr-tn temp :le)
(inst sub temp temp count)
(inst ror (sb-vm::32-bit-reg res)
(sb-vm::32-bit-reg integer) (sb-vm::32-bit-reg temp))))
;;; 64-bit
(define-vop (%64bit-rotate-byte/c)
(:policy :fast-safe)
(:translate %unsigned-64-rotate-byte)
(:note "inline 64-bit constant rotation")
(:args (integer :scs (sb-vm::unsigned-reg) :target result))
(:info count)
(:arg-types (:constant (integer -63 63)) sb-vm::unsigned-num)
(:results (result :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-num)
(:generator 5
(aver (not (= count 0)))
(inst ror result integer (if (plusp count)
(- 64 count)
(abs count)))))
(define-vop (%64bit-rotate-byte)
(:policy :fast-safe)
(:translate %unsigned-64-rotate-byte)
(:note "inline 64-bit rotation")
(:args (count :scs (sb-vm::signed-reg))
(integer :scs (sb-vm::unsigned-reg)))
(:arg-types sb-vm::tagged-num sb-vm::unsigned-num)
(:temporary (:sc sb-vm::signed-reg) temp)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-num)
(:generator 10
(inst mov temp 64)
(inst cmp count 0)
(inst csel temp sb-vm::zr-tn temp :le)
(inst sub temp temp count)
(inst ror res integer temp)))
| 2,411 | Common Lisp | .lisp | 65 | 32 | 68 | 0.623932 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 0902b41a0adbce455d6e464729b8d4dbfff8cb6dbbd6b23cee3d21360c5007f4 | 13,226 | [
-1
] |
13,227 | ppc-vm.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/ppc-vm.lisp | (in-package "af.contrib.sb-rotate-byte")
(define-vop (%32bit-rotate-byte/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:info count)
(:args (integer :scs (sb-vm::unsigned-reg) :target res))
(:arg-types (:constant (integer -31 31)) sb-vm::unsigned-byte-32)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 5
;; the 0 case is an identity operation and should be
;; DEFTRANSFORMed away.
(aver (not (= count 0)))
(if (> count 0)
(inst rotlwi res integer count)
(inst rotrwi res integer (- count)))))
(define-vop (%32bit-rotate-byte-fixnum/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:info count)
(:args (integer :scs (sb-vm::any-reg) :target res))
(:arg-types (:constant (integer -31 31)) sb-vm::positive-fixnum)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 5
(aver (not (= count 0)))
(cond
;; FIXME: all these 2s should be n-fixnum-tag-bits.
((= count 2))
((> count 2) (inst rotlwi res integer (- count 2)))
(t (inst rotrwi res integer (- 2 count))))))
(macrolet ((def (name arg-type)
`(define-vop (,name)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit rotation")
(:args (count :scs (sb-vm::signed-reg))
(integer :scs (sb-vm::unsigned-reg) :target res))
(:arg-types sb-vm::tagged-num ,arg-type)
(:temporary (:scs (sb-vm::unsigned-reg) :from (:argument 0))
realcount)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 10
(let ((label (gen-label))
(end (gen-label)))
(inst cmpwi count 0)
(inst bge label)
(inst addi realcount count 32)
(inst rotlw res integer realcount)
(inst b end)
(emit-label label)
(inst rotlw res integer count)
(emit-label end))))))
(def %32bit-rotate-byte sb-vm::unsigned-byte-32)
;; FIXME: see x86-vm.lisp
(def %32bit-rotate-byte-fixnum sb-vm::positive-fixnum))
| 2,467 | Common Lisp | .lisp | 59 | 32.542373 | 75 | 0.565073 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | 09208b0417760a683f9bf34fe1efaa3d17f2f5f82d2dd82da4ab9010d6dc0625 | 13,227 | [
-1
] |
13,228 | x86-vm.lisp | ahungry_ahungry-fleece/contrib/sb-rotate-byte/x86-vm.lisp | (in-package "af.contrib.sb-rotate-byte")
(define-vop (%32bit-rotate-byte/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:info count)
(:args (integer :scs (sb-vm::unsigned-reg) :target res))
(:arg-types (:constant (integer -31 31)) sb-vm::unsigned-byte-32)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 5
;; the 0 case is an identity operation and should be
;; DEFTRANSFORMed away.
(aver (not (= count 0)))
(move res integer)
(if (> count 0)
(inst rol res count)
(inst ror res (- count)))))
(define-vop (%32bit-rotate-byte-fixnum/c)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit constant rotation")
(:info count)
(:args (integer :scs (sb-vm::any-reg) :target res))
(:arg-types (:constant (integer -31 31)) sb-vm::positive-fixnum)
(:results (res :scs (sb-vm::unsigned-reg)))
(:result-types sb-vm::unsigned-byte-32)
(:generator 5
(aver (not (= count 0)))
(inst mov res integer)
(cond
;; FIXME: all these 2s should be n-fixnum-tag-bits.
((= count 2))
((> count 2) (inst rol res (- count 2)))
(t (inst ror res (- 2 count))))))
(macrolet ((def (name arg-type)
`(define-vop (,name)
(:policy :fast-safe)
(:translate %unsigned-32-rotate-byte)
(:note "inline 32-bit rotation")
(:args (count :scs (sb-vm::signed-reg) :target ecx)
(integer :scs (sb-vm::unsigned-reg) :target res))
(:arg-types sb-vm::tagged-num ,arg-type)
(:temporary (:sc sb-vm::signed-reg :offset sb-vm::ecx-offset)
ecx)
(:results (res :scs (sb-vm::unsigned-reg) :from :load))
(:result-types sb-vm::unsigned-byte-32)
(:generator 10
(let ((label (gen-label))
(end (gen-label)))
(move res integer)
(move ecx count)
(inst cmp ecx 0)
(inst jmp :ge label)
(inst neg ecx)
(inst ror res :cl)
(inst jmp end)
(emit-label label)
(inst rol res :cl)
(emit-label end))))))
(def %32bit-rotate-byte sb-vm::unsigned-byte-32)
;; FIXME: it's not entirely clear to me why we need this second
;; definition -- or rather, why the compiler isn't smart enough to
;; MOVE a POSITIVE-FIXNUM argument to an UNSIGNED-BYTE-32 argument,
;; and then go from there. Still, not having it leads to scary
;; compilation messages of the form:
;;
;; unable to do inline 32-bit constant rotation (cost 5) because:
;; This shouldn't happen! Bug?
;; argument types invalid
;; argument primitive types:
;; (SB-VM::POSITIVE-FIXNUM SB-VM::POSITIVE-FIXNUM)
;;
;; so better leave it in.
(def %32bit-rotate-byte-fixnum sb-vm::positive-fixnum))
| 3,069 | Common Lisp | .lisp | 75 | 32.506667 | 76 | 0.574724 | ahungry/ahungry-fleece | 7 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:27:05 AM (Europe/Amsterdam) | a00465044e793867d8eb5e54dd42883a5b05afc9aec3476fa9d18cd3139369f4 | 13,228 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.