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
listlengths
1
47
4,724
image.lisp
informatimago_lisp/pgl/examples/image.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: image.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Example taken from https://cs.stanford.edu/people/eroberts/jtf/tutorial/UsingTheGraphicsPackage.html ;;;; ;;;; This program displays an image file give in argument. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-11-13 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.IMAGE" (:use "COMMON-LISP" "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY") (:export "RUN")) (in-package "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.IMAGE") (defun run (image-filename) (let* ((image (make-instance 'image :filename (namestring image-filename))) (width (width image)) (height (height image)) (win (make-instance 'window :width width :height height :title (file-namestring image-filename)))) (compound-add win image))) ;;;; THE END ;;;;
2,196
Common Lisp
.lisp
50
41.08
108
0.613806
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4cb86821e8049e929c5f7cf7b92c5fe4cc6443c6410e3e2eaef54e1fe0fb8b25
4,724
[ -1 ]
4,725
yarn-pattern.lisp
informatimago_lisp/pgl/examples/yarn-pattern.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: yarn-pattern.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Example taken from https://cs.stanford.edu/people/eroberts/jtf/tutorial/UsingTheGraphicsPackage.html ;;;; ;;;; This program illustrates the use of the GLine class to simulate ;;;; winding a piece of colored yarn around a set of pegs equally ;;;; spaced along the edges of the canvas. At each step, the yarn is ;;;; stretched from its current peg to the one DELTA pegs further on. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-11-13 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.YARN-PATTERN" (:use "COMMON-LISP" "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY") (:export "RUN")) (in-package "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.YARN-PATTERN") (defvar *n-across* 50) (defvar *n-down* 30) (defvar *peg-sep* 10) (defvar *delta* 67) (defun create-peg-list (across down peg-sep) (coerce (nconc (loop :for i :below across :collect (make-point :x (* i peg-sep))) (loop :for i :below down :collect (make-point :x (* across peg-sep) :y (* i peg-sep))) (loop :for i :from across :above 0 :collect (make-point :x (* i peg-sep) :y (* down peg-sep))) (loop :for i :from down :above 0 :collect (make-point :y (* i peg-sep)))) 'vector)) (defun run () (let* ((width 521) (height 342) (win (make-instance 'window :width 512 :height 342 :title "Yarn Pattern")) ;; (cx (/ width 2)) ;; (cy (/ height 2)) (cx 0) (cy 0) (pegs (create-peg-list *n-across* *n-down* *peg-sep*)) (pegs.size (length pegs)) (this-peg 0) (next-peg -1)) (loop :repeat pegs.size ; :while (or (plusp this-peg) (minusp next-peg)) :do (setf next-peg (mod (+ this-peg *delta*) pegs.size)) (let* ((p0 (aref pegs this-peg)) (p1 (aref pegs next-peg)) (line (make-instance 'line :x0 (+ cx (x p0)) :y0 (+ cy (y p0)) :x1 (+ cx (x p1)) :y1 (+ cy (y p1)) :color *magenta*))) (compound-add win line)) (setf this-peg next-peg)))) ;;;; THE END ;;;;
3,831
Common Lisp
.lisp
84
37.464286
108
0.531926
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
20e590893917ac6321292976ef13fbbe9379d634a316b20dc672022ff7e07279
4,725
[ -1 ]
4,726
yin-yang.lisp
informatimago_lisp/pgl/examples/yin-yang.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: yin-yang.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Example taken from https://cs.stanford.edu/people/eroberts/jtf/tutorial/UsingTheGraphicsPackage.html ;;;; ;;;; This program draws the Taoist yin-yang symbol at the center of ;;;; the graphics window. The height and width of the entire figure ;;;; are both specified by the constant FIGURE_SIZE. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-11-13 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.YIN-YANG" (:use "COMMON-LISP" "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY") (:export "RUN")) (in-package "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.YIN-YANG") (defun run (&optional (figure-size 150)) (let* ((width 521) (height 342) (win (make-instance 'window :width 512 :height 342 :title "Yin-Yang")) (x (/ width 2)) (y (/ height 2)) (r (/ figure-size 2)) (big-black (make-instance 'arc :x (- x r) :y (- y r) :width (* 2 r) :height (* 2 r) :start -90 :sweep 180 :filled t)) (small-white (make-instance 'arc :x (- x (/ r 2)) :y (- y r) :width r :height r :start -90 :sweep 180 :filled t :color *white* :fill-color *white*)) (small-black (make-instance 'arc :x (- x (/ r 2)) :y y :width r :height r :start 90 :sweep 180 :filled t)) (outer-circle (make-instance 'arc :x (- x r) :y (- y r) :width (* 2 r) :height (* 2 r) :start 0 :sweep 360))) (compound-add win big-black) (compound-add win small-white) (compound-add win small-black) (compound-add win outer-circle))) ;;;; THE END ;;;;
3,523
Common Lisp
.lisp
74
36.743243
108
0.499275
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
dfdfe33b0f91155004ef85fa599a2630afcde39323358c6f1290647cdcd6f9bb
4,726
[ -1 ]
4,727
checkerboard.lisp
informatimago_lisp/pgl/examples/checkerboard.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: checkerboard.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Example taken from https://cs.stanford.edu/people/eroberts/jtf/tutorial/UsingTheGraphicsPackage.html ;;;; ;;;; This program draws a checkerboard. The dimensions of the ;;;; checkerboard is specified by the constants NROWS and ;;;; NCOLUMNS, and the size of the squares is chosen so ;;;; that the checkerboard fills the available vertical space. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-11-13 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.CHECKERBOARD" (:use "COMMON-LISP" "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY") (:export "RUN")) (in-package "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.CHECKERBOARD") (defun run (&optional (nrows 8) (ncolumns 8)) (let* ((width 512) (height 342) (win (make-instance 'window :width width :height height :title "Checkerboard")) (sqsize (/ height nrows))) (loop :for i :below nrows :for y := (* i sqsize) :do (loop :for j :below ncolumns :for x := (* j sqsize) :for sq := (make-instance 'rect :x x :y y :width sqsize :height sqsize) :do (set-filled sq (plusp (mod (+ i j) 2))) (compound-add win sq))))) ;;;; THE END ;;;;
2,651
Common Lisp
.lisp
59
40.677966
108
0.598687
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
840b29d71f61c6947223b2403b6d635259a5d5c749d2bff6820dd92ed22f21ed
4,727
[ -1 ]
4,728
all.lisp
informatimago_lisp/pgl/examples/all.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: all.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Main examples driver. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2017-03-10 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2017 - 2017 ;;;; ;;;; 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/>. ;;;;************************************************************************** (defpackage "COM.INFORMATIMAGO.PGL.EXAMPLES" (:use "COMMON-LISP") (:export "RUN-ALL")) (in-package "COM.INFORMATIMAGO.PGL.EXAMPLES") (defun run-all () (setf com.informatimago.pgl:*program-name* "Examples") (unwind-protect (progn (ignore-errors (com.informatimago.portable-graphics-library.example.yarn-pattern:run)) (ignore-errors (com.informatimago.portable-graphics-library.example.yin-yang:run)) (ignore-errors (com.informatimago.portable-graphics-library.example.checkerboard:run)) (ignore-errors (com.informatimago.portable-graphics-library.example.felt-board:run)) (ignore-errors (com.informatimago.portable-graphics-library.example.image:run (merge-pathnames #P"tierra-desde-luna.jpg" (or *compile-file-pathname* *load-pathname)))) #+bordeaux-threads (bt:make-thread (lambda () (ignore-errors (com.informatimago.portable-graphics-library.example.ball:run)))) #-bordeaux-threads (ignore-errors (com.informatimago.portable-graphics-library.example.ball:run))) (com.informatimago.pgl:close-backend)) (values)) ;;;; THE END ;;;;
2,575
Common Lisp
.lisp
57
40.333333
95
0.614558
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
76a826660f907e45f81f02447fcf9d0b2bb27204a9e9724026889495b9b047d7
4,728
[ -1 ]
4,729
ball.lisp
informatimago_lisp/pgl/examples/ball.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: ball.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test the pgl library with a bouncing ball. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-11-13 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.BALL" (:use "COMMON-LISP" "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY") (:export "RUN")) (in-package "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.BALL") (defclass ball (compound) ((vx :initarg :vx :accessor vx :initform (- (+ 10 (random 20.0d0)) 15)) (vy :initarg :vy :accessor vy :initform (- (+ 10 (random 30.0d0)) 15)) (gx :initarg :gx :accessor gx :initform 0 ) (gy :initarg :gy :accessor gy :initform (random 10.0d0) ))) (defun make-ball (diameter) (let* ((components (cons (make-instance 'oval :x 0 :y 0 :width diameter :height diameter :color *red* :fill-color *red* :filled t) (loop :for alpha :from 0 :below 360 :by 30 :collect (make-instance 'arc :x 0 :y 0 :width diameter :height diameter :start alpha :sweep 15 :color *yellow* :fill-color *yellow* :filled t)))) (ball (make-instance 'ball :x 0 :y 0 :width diameter :height diameter :components components :vx (random 30.0d0) :vy 0 :gx 0 :gy (random 10.0d0)))) (dolist (component components) (send-to-front component)) ball)) (defun update-position-velocity (x vx gx w) (incf x vx) (unless (<= 0 x w) (setf x (- x vx vx) vx (* 0.9 (- vx)))) (incf vx gx) (values x vx gx)) (defmethod update ((b ball) w h) (let ((x (x b)) (y (y b)) (vx (vx b)) (vy (vy b)) (gx (gx b)) (gy (gy b)) (s (width b))) (multiple-value-setq (x vx gx) (update-position-velocity x vx gx (- w s))) (multiple-value-setq (y vy gy) (update-position-velocity y vy gy (- h s))) (setf (vx b) vx (vy b) vy (gx b) gx (gy b) gy) (set-location b x y))) (defclass ball-window (window) ((ball :initarg :ball :accessor ball))) (defun make-ball-window () (let* ((w 512) (h 342) (ball (make-ball 80)) (background (make-instance 'compound :x 0 :y 0 :width w :height h :components (list (make-instance 'rect :filled t :fill-color *blue* :color *blue* :x 0 :y 0 :width w :height h) ball)))) (make-instance 'ball-window :ball ball :title "Beach Ball" :color *blue* :x 20 :y 40 :width w :height h :components (list background)))) (defmethod tick ((window ball-window)) (update (ball window) (width window) (height window))) (defun run () (let ((w (make-ball-window)) (dt (make-instance 'timer :duration-ms 100))) (start-timer dt) (unwind-protect (loop :for e := (get-next-event (logior +timer-event+ +window-event+)) :do (case (event-type-keyword e) (:timer-ticked (when (eql dt (event-timer e)) (tick w))) (:window-closed (when (eql w (event-window e)) (loop-finish))))) (stop-timer dt) (free dt) (close-window w)))) ;;; THE END ;;;;
5,134
Common Lisp
.lisp
120
32.425
111
0.502798
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5d29baf3363214b74b6abae73d08131c6a55136840c05d044ee56eae2110e78d
4,729
[ -1 ]
4,730
unicode.lisp
informatimago_lisp/clmisc/unicode.lisp
;;;; -*- mode:emacs-lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: pjb-unicode.lisp ;;;;LANGUAGE: Common Lisp ;;;;SYSTEM: POSIX ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Implements functions to offset unicode strings to different planes. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2020-12-04 <PJB> Converted to Common Lisp from emeacs lisp. ;;;; 2017-01-25 <PJB> Added this header. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2017 - 2020 ;;;; ;;;; 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/>. ;;;;************************************************************************** (defpackage "COM.INFORMATIMAGO.CLMISC.UNICODE" (:nicknames "FMT-UNICODE") (:use "COMMON-LISP") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SYMBOL" "SCAT") ;; formatter functions: (:export "PARENTHESIZED-LATIN" "CIRCLED-LATIN" "FULLWIDTH-LATIN" "MATHEMATICAL-BOLD" "MATHEMATICAL-BOLD-ITALIC" "MATHEMATICAL-SCRIPT" "MATHEMATICAL-SCRIPT-BOLD" "MATHEMATICAL-DOUBLE-STRUCK" "MATHEMATICAL-FRAKTUR" "MATHEMATICAL-FRAKTUR-BOLD" "MATHEMATICAL-SANS-SERIF" "MATHEMATICAL-SANS-SERIF-BOLD" "MATHEMATICAL-SANS-SERIF-ITALIC" "MATHEMATICAL-SANS-SERIF-BOLD-ITALIC" "MATHEMATICAL-MONOSPACE") (:export "UNICODE-OFFSET" "MAP-NAMES" "MAP-NAMED" "MAP-NAME" "MAP-OFFSET-FUNCTION" "MAP-RANGES" "DEFINE-UNICODE-OFFSET-MAP")) (in-package "COM.INFORMATIMAGO.CLMISC.UNICODE") (defparameter *maps* (make-hash-table)) (defun map-names () (let ((names '())) (maphash (lambda (name map) (declare (ignore map)) (push name names)) *maps*) names)) (defun map-named (name) (gethash name *maps*)) (defstruct (map (:type list)) offset-function name ranges) (defun format-string (stream string colon at parameters) ;; justification: ;; left ;; right : ;; centered @ ;; parameters: width, padding-character ;; if no width or length>=width, then no justification. (let ((width (pop parameters))) (if width (let ((length (length string))) (if (< length width) (let* ((padding-character (or (pop parameters) #\space)) (padding-string (make-string (- width length) :initial-element padding-character))) (cond (colon ; right (write-string padding-string stream) (write-string string stream)) (at ; centered (let ((middle (truncate (length padding-string) 2))) (write-string (subseq padding-string 0 middle) stream) (write-string string stream) (write-string (subseq padding-string middle) stream))) (t ; left (write-string string stream) (write-string padding-string stream)))) (write-string string stream))) (write-string string stream)))) (defun generate-formatter-function (name) `(defun ,name (stream arg colon at &rest parameters) (format-string stream (unicode-offset (function ,(scat 'offset- name)) (typecase arg (string arg) (t (prin1-to-string arg)))) colon at parameters))) (defun offset-clauses-to-case-clauses (offset-clauses) (let ((case-clauses '()) (uppercase-clause nil)) (labels ((add-clauses (min max start) (loop :for ch-code :from (char-code min) :to (char-code max) :for offset-code :from start :do (add-clause (list (list (code-char ch-code)) (code-char offset-code))))) (add-clause (clause) (let ((clause-pos (position (first (first clause)) case-clauses :key (lambda (x) (first (first x)))))) (setf case-clauses (if clause-pos (subst clause (nth clause-pos case-clauses) case-clauses) (nconc case-clauses (list clause))))))) #+(and nil testing-add-clause) (progn (add-clauses #\a #\z 65) (print case-clauses) (add-clause (list (list #\b) #\3)) (add-clause (list (list #\3) #\z)) (print case-clauses)) (dolist (clause offset-clauses case-clauses) (case (length clause) ((2) (if (eq :lower (first clause)) (if uppercase-clause (add-clauses #\a #\z (+ (second clause) (third uppercase-clause))) (error ":LOWER clause without an uppercase #\\A #\\Z clause.")) (add-clause (list (list (character (first clause))) (code-char (second clause)))))) ((3) (add-clauses (first clause) (second clause) (third clause)) (when (and (char= #\A (first clause)) (char= #\Z (second clause))) (setf uppercase-clause clause))) (otherwise (error "Invalid offset-clause: ~S" clause))))))) (defun offset-clauses-to-ranges (offset-clauses) (let ((ranges '()) (uppercase-clause nil)) (labels ((add-clauses (min max start) (declare (ignore start)) (push (list min max) ranges)) (add-clause (clause) (let ((clause-pos (position (first (first clause)) ranges :test (lambda (char range) (and (char<= char (first range)) (char<= (second range) char)))))) (unless clause-pos (push (list (first (first clause)) (first (first clause))) ranges))))) (dolist (clause offset-clauses (sort ranges (lambda (r1 r2) (char< (first r1) (first r2))))) (case (length clause) ((2) (if (eq :lower (first clause)) (if uppercase-clause (add-clauses #\a #\z 0)) (add-clause (list (list (character (first clause))) #\a)))) ((3) (add-clauses (character (first clause)) (character (second clause)) (third clause))) (otherwise (error "Invalid offset-clause: ~S" clause))))))) (defun generate-offset-function (name offset-clauses) (let ((fname (scat 'offset- name))) `(progn (defun ,fname (char) (case char ,@(offset-clauses-to-case-clauses offset-clauses) (otherwise char))) (setf (gethash ',name *maps*) (make-map :offset-function (function ,fname) :name ',name :ranges ',(offset-clauses-to-ranges offset-clauses))) ',fname))) (defun unicode-offset (map-name string) (map 'string (etypecase map-name (function map-name) (symbol (let ((map (map-named map-name))) (if map (map-offset-function map) (error "There's no map named ~S" map-name))))) string)) (defmacro define-unicode-offset-map (name (&rest offset-clauses)) `(progn ,(generate-offset-function name offset-clauses) ,(generate-formatter-function name))) (define-unicode-offset-map parenthesized-latin ((#\0 #\9 #x1d7f6) (#\a #\z 9372))) (define-unicode-offset-map circled-latin ((#\0 9450) (#\1 #\9 #x2460) (#\A #\Z 9398) (:lower +26))) (define-unicode-offset-map fullwidth-latin ((#\0 #\9 65296) (#\A #\Z 65313) (:lower +32))) (define-unicode-offset-map mathematical-bold ((#\0 #\9 #x1d7f6) (#\A #\Z 119808) (:lower +26))) (define-unicode-offset-map mathematical-bold-italic ((#\0 #\9 #x1d7f6) (#\A #\Z 119912) (:lower +26))) ;; (define-unicode-offset-map mathematical-script ;; ((#\0 #\9 #x1d7f6) ;; (#\A 119964) ;; (#\C #\D 119965) ;; (#\G #\D #x1D4A2) ;; (:lower +26) ;; (#\e #x212f) ;; (#\g #x210A) ;; (#\o #x2134))) (define-unicode-offset-map mathematical-script-bold ((#\0 #\9 120782) (#\A #\Z 120016) (:lower +26))) (define-unicode-offset-map mathematical-double-struck ((#\0 #\9 120792) (#\A #\Z #x1d538) (:lower +26) (#\C 8450) (#\H 8461) (#\N 8469) (#\P 8473) (#\Q 8474) (#\R 8477) (#\Z 8484))) (define-unicode-offset-map mathematical-fraktur ((#\1 #\9 #x02170) (#\A #\Z #x1d504) (:lower +26) (#\C 8493) (#\H 8460) (#\I 8465) (#\R 8476) (#\Z 8488))) (define-unicode-offset-map mathematical-fraktur-bold ((#\1 #\9 #x02160) (#\A #\Z #x1d56c) (:lower +26))) (define-unicode-offset-map mathematical-sans-serif ((#\0 #\9 120802) (#\A #\Z #x1d5A0) (:lower +26))) (define-unicode-offset-map mathematical-sans-serif-bold ((#\0 #\9 120812) (#\A #\Z #x1d5D4) (:lower +26))) (define-unicode-offset-map mathematical-sans-serif-italic ((#\0 #\9 #x1d7ce) (#\A #\Z #x1d608) (:lower +26))) (define-unicode-offset-map mathematical-sans-serif-bold-italic ((#\0 #\9 #x1d7ce) (#\A #\Z 120380) (:lower +26))) (define-unicode-offset-map mathematical-monospace ((#\0 #\9 #x1D7F6) (#\A #\Z #x1D670) (:lower +26))) ;; braille has more complex rules. (defparameter *braille* '((capital "⠠") (number "⠼") (bracket "⠶") ("1" "⠼⠁") ("2" "⠼⠂") ("3" "⠼⠃") ("4" "⠼⠄") ("5" "⠼⠅") ("6" "⠼⠆") ("7" "⠼⠇") ("8" "⠼⠈") ("9" "⠼⠉") ("0" "⠼⠊") ("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" "⠠⠵") ("Ç" "⠠⠯") ("É" "⠠⠿") ("À" "⠠⠷") ("È" "⠠⠮") ("Ù" "⠠⠾") ("Â" "⠠⠡") ("Ê" "⠠⠣") ("Î" "⠠⠩") ("Ô" "⠠⠹") ("Û" "⠠⠱") ("Ë" "⠠⠫") ("Ï" "⠠⠻") ("Ü" "⠠⠳") ("Ö" "⠠⠪") ("Ì" "⠠⠌") ("Ä" "⠠⠜") ("Ò" "⠠⠬") )) (defun test () (mapc (lambda (test-string) (format t (format nil "~{~40A~:*~~0@*~~/fmt-unicode:~A/~%~}" (map-names)) test-string)) '("0123456789" "MONSIEUR JACK, VOUS DACTYLOGRAPHIEZ BIEN MIEUX QUE WOLF." "monsieur jack, vous dactylographiez bien mieux que wolf.")) (format t "~30/fmt-unicode:mathematical-monospace/~%" "Hello, World!") (format t "~30:/fmt-unicode:mathematical-monospace/~%" "Hello, World!") (format t "~30@/fmt-unicode:mathematical-monospace/~%" "Hello, World!")) ;;;; THE END ;;;;
13,696
Common Lisp
.lisp
399
24.345865
97
0.466853
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c570f1dc08e4f25fdfee0a50417aaee391abe51ddaea08dfb0b2e4f9f99e02fd
4,730
[ -1 ]
4,731
resource-utilization-test.lisp
informatimago_lisp/clmisc/resource-utilization-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: resource-utilization-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests resource-utilization.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-25 <PJB> Extracted from resource-utilization.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLMISC.RESOURCE-UTILIZATION.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.CLMISC.RESOURCE-UTILIZATION") (:import-from "COM.INFORMATIMAGO.CLMISC.RESOURCE-UTILIZATION" "READ-PARENTHESIZED-STRING") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.CLMISC.RESOURCE-UTILIZATION.TEST") (define-test test/read-parenthesized-string () (loop :with success = 0 :for tcount :from 0 :for (input . output) :in '(("" :eof) (" " :eof) ("(" :eof) (" ( " :eof) (" (a(b)" :eof) (" (a(b)c" :eof) (" (a\\" :eof) (" (a\\b" :eof) (" (howdy doo ?)" "howdy doo ?") ("(howdy \\( doo ?)" "howdy ( doo ?") ("(howdy \\) doo ?)" "howdy ) doo ?") ("(a(b(c(d)e)f)g)h" "a(b(c(d)e)f)g")) :for result = (with-input-from-string (stream input) (multiple-value-list (ignore-errors (read-parenthesized-string stream nil :eof)))) :do (if (equal result output) (progn (incf success) (progress-success)) (progress-failure-message input "~2%Reading parenthesized string ~S~ ~% --> ~S~%expected ~S~%" input result output))) :success) (defun test/all () (test/read-parenthesized-string)) #|| (reporting-sru () (with-open-file (input "/usr/share/dict/words") (loop :for line = (read-line input nil nil) :while line)) (loop :repeat 5000 :collect (make-string 1000) :finally (terpri) (return nil))) ||# ;;;; THE END ;;;;
3,308
Common Lisp
.lisp
82
33.756098
83
0.551338
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ce30ae9bb75c2c31937f2c469569b59359ba67843673b892db011fe15218fa79
4,731
[ -1 ]
4,732
resource-utilization.lisp
informatimago_lisp/clmisc/resource-utilization.lisp
;;;; -*- mode:lisp; coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: resource-utilization.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; See defpackage documentation string. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2006-11-10 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2006 - 2016 ;;;; ;;;; 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/> ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLMISC.RESOURCE-UTILIZATION" (:use "COMMON-LISP" "SPLIT-SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SYMBOL" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.CLEXT.SHELL") (:export "REPORTING-SRU" "SUMMARY-RESOURCE-UTILIZATION" ) (:documentation " Gather resource utilization statistics and report them. Usage: (reporting-sru (:job-origin (remote-client) :stream (remote-stream)) (do-something-lengthy)) (reporting-sru (:job-origin (remote-client) :stream (remote-stream) :report-to (lambda (cpu-time sys-time device-i/o paging-i/o job-origin &key (stream t)) (SUMMARY-RESOURCE-UTILIZATION cpu-time sys-time device-i/o paging-i/o job-origin :stream stream))) (do-something-lengthy)) Example: (reporting-sru (:job-origin \"REPL\") (asdf-load :com.informatimago.clext)) prints: Summary of resource utilization ------------------------------- CPU time: 0.300 sec Device I/O: 175 Overhead CPU: 0.012 sec Paging I/O: 1 CPU model: AMD Athlon(tm) Processor 6.4.2 1200.303 MHz (2402.66 bogomips) Job origin: REPL License: AGPL3 Copyright Pascal J. Bourguignon 2006 - 2012 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/> ")) (in-package "COM.INFORMATIMAGO.CLMISC.RESOURCE-UTILIZATION") (defun split-attribute-line (line) (let* ((colon (position #\: line)) (var (and colon (string-trim " " (subseq line 0 colon)))) (val (and colon (string-trim " " (subseq line (1+ colon)))))) (when (and var val) (cons (keywordize (string-upcase (substitute-if #\- (lambda (ch) (position ch "_ ")) var))) (multiple-value-bind (n p) (parse-integer val :junk-allowed t) (if (= p (length val)) n val)))))) (defun sysctl-info () " RETURN: An A-list containing the data from sysctl -a. " (let ((text (shell-command-to-string "sysctl -a"))) (when text (delete nil (mapcar (function split-attribute-line) (split-sequence #\newline text)))))) (defun cpu-info () " RETURN: An A-list containing the data from /proc/cpuinfo. " (let ((text (text-file-contents "/proc/cpuinfo" :if-does-not-exist nil))) (when text (when text (delete nil (mapcar (function split-attribute-line) (split-sequence #\newline text))))))) (defun cpu-short-description () " RETURN: A short description of the CPU. " (let ((info (append (cpu-info) (sysctl-info)))) (flet ((gac (x) (cdr (assoc x info)))) (format nil "~A ~A.~A.~A ~A MHz (~A bogomips)" (or (gac :model-name) (gac :machdep.cpu.brand-string) "") (or (gac :cpu-family) (gac :machdep.cpu.family) "") (or (gac :model) (gac :machdep.cpu.model) "") (or (gac :stepping) (gac :machdep.cpu.stepping) "") (or (gac :cpu-mhz) (truncate (gac :hw.cpufrequency) 1e6) "") (or (gac :bogomips) (let ((freq (gac :hw.cpufrequency))) (if freq (* 2.5e-6 freq ) 0))))))) (defun read-parenthesized-string (&optional (stream t) (eof-error-p t) (eof-value nil) (recursive-p nil)) " DO: Skip spaces, and read a string in parentheses (like in Postscript). RETURN: The string read (without the external parentheses), or the EOF-VALUE if EOF occured and EOF-ERROR-P is NIL. NIL is returned if the next non whitespace character is not a left parenthesis. NOTE: Parentheses inside the string must be escaped by \ unless balanced. " (let ((token (peek-char t stream nil :eof recursive-p))) (cond ((eq :eof token) (if eof-error-p (error 'end-of-file :stream stream) eof-value)) ((eql #\( token) (read-char stream) (loop :with buffer = (make-array 8 :adjustable t :fill-pointer 0 :element-type 'character :initial-element #\space) :with level = 0 :with escape = nil :for ch = (read-char stream nil nil recursive-p) :while ch :do (cond (escape (vector-push-extend ch buffer) (setf escape nil)) ((char= #\( ch) (vector-push-extend ch buffer) (incf level)) ((char= #\) ch) (decf level) (if (minusp level) #-mocl (loop-finish) #+moc (if ch (return buffer) (if eof-error-p (error 'end-of-file :stream stream) (return eof-value))) (vector-push-extend ch buffer))) ((char= #\\ ch) (setf escape t)) (t (vector-push-extend ch buffer))) :finally (if ch (return buffer) (if eof-error-p (error 'end-of-file :stream stream) (return eof-value)))))))) (defun process-status (&optional (pid "self")) " PID: Normally it's a small integer, pid_t number. But for /proc/, we can also use ''self'', as in '/proc/self/stat'. RETURN: The status of the specified process. " (loop :for input :in '(("/proc/~A/stat" :pid (:comm read-parenthesized-string) :state :ppid :pgrp :session :tty-nr :tpgid :flags :minflt :cminflt :majflt :cmajflt :utime :stime :cutime :cstime :priority :nice nil :it-real-value :start-time :vsize :rss :rlim :start-code :end-code :start-stack :ktskesp :kstkeip :signal :blocked :sigignore :sigcatch :wchan :nswap :cnswap :exit-signal :processor) ("/proc/~A/statm" :size :resident :share :trs :drs :lrs :dt)) :nconc (with-open-file (info (format nil (pop input) pid) :if-does-not-exist nil) (and info (loop :for field :in input :for tag = (if (atom field) field (first field)) :for reader = (if (atom field) 'read (second field)) :when tag :collect (cons tag (funcall reader info))))))) (defun disk-statistics (&optional disk) " RETURN: Statistics from the DISK usage, obtained from /proc/diskstats. " (declare (ignore disk)) ;; TODO: Implement disk filter. (with-open-file (info "/proc/diskstats" :if-does-not-exist nil) (and info (let ((*readtable* (copy-readtable))) (setf (readtable-case *readtable*) :preserve) (loop :with part-keys = '(:device-major :device-minor :device-name :completed-reads :merged-reads :read-sectors :read-time :completed-writes :merged-writes :written-sectors :write-time :current-i/os :current-i/o-time :current-i/o-load) :with part-nfields = (length part-keys) :with disk-keys = '(:device-major :device-minor :device-name :completed-reads :read-sectors :completed-writes :written-sectors) :with disk-nfields = (length disk-keys) :for line = (read-line info nil nil) :while line :collect (let* ((nfields 0) (data (with-input-from-string (fields line) (loop :for item = (read fields nil nil) :while item :do (incf nfields) :collect (if (symbolp item) (string item) item))))) (cond ((= nfields part-nfields) (pairlis part-keys data '((:type . :partition)))) ((= nfields disk-nfields) (pairlis disk-keys data '((:type . :disk))))))))))) (defun device-i/o () " RETURN: The number of disk I/O collected by (DISK-STATISTICS). " (reduce (function +) (remove-if (lambda (entry) (eq :partition (cdr (assoc :type entry)))) (disk-statistics)) :key (lambda (entry) (+ (or (cdr (assoc :written-sectors entry)) 0) (or (cdr (assoc :read-sectors entry)) 0))) :initial-value 0)) (defparameter *jiffy* ;; TODO: Use a CL implementation of gzip/zlib. #-(and clisp #.(cl:if (cl:find-package "LINUX") '(and) '(or))) 1/250 #+(and clisp #.(cl:if (cl:find-package "LINUX") '(and) '(or))) (or (ignore-errors (with-open-stream (config (cond ((probe-file "/proc/config") (open "/proc/config")) ((probe-file "/proc/config.gz") (ext:run-program "gzip" :arguments '("-d") :input "/proc/config.gz" :output :stream)) (t (error "No such file.")))) (and config (loop :with target = "CONFIG_HZ=" :for line = (read-line config nil nil) :while (and line (or (< (length line) (length target)) (not (string-equal line target :end1 (length target))))) :finally (return (when line (/ (parse-integer line :start (length target) :junk-allowed t)))))))) 1/250) "The JIFFY value of the Linux kernel (1/CONFIG_HZ)") (defun summary-resource-utilization (cpu-time sys-time device-i/o paging-i/o job-origin &key (stream t)) " DO: Reports resource utilisaty summary. CPU-TIME: CPU time used, in seconds. SYS-TIME: System time used, in seconds. DEVICE-I/O: Number of Disk I/O. PAGING-I/O: Number of Swap I/O. JOB-ORIGIN: Label of the originator of the job. STREAM: Output stream (the default T means *standard-output*). " (let ((*print-circle* nil)) (format stream "Summary of resource utilization ------------------------------- CPU time: ~8,3F sec Device I/O: ~8D Overhead CPU:~8,3F sec Paging I/O: ~8D CPU model: ~A Job origin: ~A " cpu-time device-i/o sys-time paging-i/o (cpu-short-description) job-origin))) (defmacro reporting-sru ((&key (job-origin '(short-site-name)) (stream t) (report-to nil report-to-p)) &body body) " DO: Execute the BODY collecting resource usage statistics, and finally reporting them. JOB-ORIGIN: Label of the originator of the job; defaults to (SHORT-SITE-NAME). STREAM: Output stream (the default T means *standard-output*). REPORT-TO: If provided, it's a function with the same signature as SUMMARY-RESOURCE-UTILIZATION, ie.: (cpu-time sys-time device-i/o paging-i/o job-origin &key (stream t)) which is called to report the collected statistics. The default is SUMMARY-RESOURCE-UTILIZATION. " (let ((vstart-run 'sr) (vend-run 'er) (vstat-before 'sb) (vstat-after 'sa) (vdeio-before 'db) (vdeio-after 'da)) `(let ((,vstat-before (process-status)) (,vstat-after) (,vstart-run (get-internal-run-time)) (,vend-run) (,vdeio-before (device-i/o)) (,vdeio-after)) (unwind-protect (progn ,@body) (setf ,vend-run (get-internal-run-time) ,vstat-after (process-status) ,vdeio-after (device-i/o)) (flet ((before (x) (or (cdr (assoc x ,vstat-before)) 0)) (after (x) (or (cdr (assoc x ,vstat-after)) 0))) (let* ((page-io (+ (- (after :majflt) (before :majflt)) #|(- (after :minflt) (before :minflt))|#)) (devi-io (max 0 (- ,vdeio-after ,vdeio-before page-io)))) (,@(if report-to-p (list 'funcall report-to) '(summary-resource-utilization)) (/ (- ,vend-run ,vstart-run) internal-time-units-per-second) (* *jiffy* (- (after :stime) (before :stime))) devi-io page-io ,job-origin :stream ,stream))))))) ;;;; THE END ;;;;
16,171
Common Lisp
.lisp
354
32.200565
99
0.502756
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7b4e8630be485226f0e51265a0bc8ed9967d2fd91f8cc602c5a82c69cd4439b6
4,732
[ -1 ]
4,733
init.lisp
informatimago_lisp/clmisc/init.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: init.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Initialization for clext packages. ;;;; ;;;; This files remove some specificities from the lisp environment ;;;; (to make it more Common Lisp), ;;;; initialize the environment ;;;; and add logical pathname translations to help find the other packages. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2006-06-05 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2006 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (setq *load-verbose* nil) ;; clean the imported packages: (mapc (lambda (used) (unuse-package used "COMMON-LISP-USER")) (remove (find-package "COMMON-LISP") (copy-seq (package-use-list "COMMON-LISP-USER")))) (progn (defvar *directories* '()) (defun get-directory (key &optional (subpath "")) (unless *directories* (with-open-file (dirs (make-pathname :name "DIRECTORIES" :type "TXT" :version nil :case :common :defaults (user-homedir-pathname))) (loop :for k = (read dirs nil dirs) :until (eq k dirs) :do (push (string-trim " " (read-line dirs)) *directories*) :do (push (intern (substitute #\- #\_ (string k)) "KEYWORD") *directories*)))) (unless (getf *directories* key) (error "~S: No directory keyed ~S" 'get-directory key)) (merge-pathnames subpath (getf *directories* key) nil))) #+clisp (when (string= (lisp-implementation-version) "2.33.83" :end1 (min (length (lisp-implementation-version)) 7)) (ext:without-package-lock ("COMMON-LISP") (let ((oldload (function cl:load))) (fmakunbound 'cl:load) (defun cl:load (filespec &key (verbose *load-verbose*) (print *load-print*) (if-does-not-exist t) (external-format :default)) (handler-case (funcall oldload filespec :verbose verbose :print print :if-does-not-exist if-does-not-exist :external-format external-format) (system::simple-parse-error () (funcall oldload (translate-logical-pathname filespec) :verbose verbose :print print :if-does-not-exist if-does-not-exist :external-format external-format))))))) (defparameter *default-version* #+clisp nil #+sbcl nil #-(or clisp sbcl) (progn (warn "What default version to use in ~A?" (lisp-implementation-type)) :newest)) (defparameter *project-directory* (truename (merge-pathnames (make-pathname :directory '(:relative)) (make-pathname :name nil :type nil :version nil :defaults *load-truename*) *default-version*)) "The directory of this project.") (defun make-translations (host logical-dir physical-dir) (mapcar (lambda (item) (destructuring-bind (logical-tail physical-tail) item (list (apply (function make-pathname) :host host :directory `(:absolute ,@logical-dir :wild-inferiors) logical-tail) (format nil "~A**/~A" physical-dir physical-tail)))) #+clisp '(((:name :wild :type :wild :version nil) "*.*") ((:name :wild :type nil :version nil) "*")) #+sbcl '(((:name :wild :type :wild :version :wild) "*.*")) #-(or clisp sbcl) '(((:name :wild :type nil :version nil) "*") ((:name :wild :type :wild :version nil) "*.*") ((:name :wild :type :wild :version :wild) "*.*")))) (setf (logical-pathname-translations "PACKAGES") nil (logical-pathname-translations "PACKAGES") (append (make-translations "PACKAGES" '("COM" "INFORMATIMAGO" "CLMISC") *project-directory*) ;; clext packages dont depend on com.informatimago.common-lisp (yet) ;; but compile.lisp uses com.informatimago.common-lisp.make-depends.make-depends (make-translations "PACKAGES" '() (get-directory :share-lisp "packages/")))) (handler-case (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE") (t () (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE.LISP"))) (import 'package:define-package) ;;;; init.lisp -- -- ;;;;
5,644
Common Lisp
.lisp
124
37.91129
87
0.577321
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0258f4ce518e420d38cc4b3f1276495077443feb5487112983bbaec644b5e6da
4,733
[ -1 ]
4,734
pbxproj.lisp
informatimago_lisp/xcode/pbxproj.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: pbxproj.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A program to read Xcode .pbxproj files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-12-10 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.XCODE" (:use "COMMON-LISP" "COM.INFORMATIMAGO.RDP" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER") (:export "READ-PBXPROJ" "WRITE-PBXPROJ")) (in-package "COM.INFORMATIMAGO.XCODE") ;;---------------------------------------------------------------------- ;; pbxproj scanner ;;---------------------------------------------------------------------- (defclass pbxproj-scanner (rdp-scanner) ((bom :initform nil :accessor pbxproj-bom))) (defun eofp (object) (null object)) (defvar *eof* nil) (defun unquoted-string-char-p (ch) (or (alphanumericp ch) (find ch ".$_/"))) (defmethod scan-next-token ((scanner pbxproj-scanner) &optional parser-data) (declare (ignore parser-data)) (when (zerop (scanner-line scanner)) (setf (pbxproj-bom scanner) (readline scanner))) (setf (scanner-current-token scanner) (flet ((scan-unquoted-string (scanner) (loop :with string = (make-array 8 :element-type 'character :initial-element #\space :adjustable t :fill-pointer 0) :for ch = (getchar scanner) :while (unquoted-string-char-p ch) :do (vector-push-extend ch string (length string)) :finally (progn (ungetchar scanner ch) (return (make-instance 'token :kind 'string :text string :column (scanner-column scanner) :line (scanner-line scanner))))))) (let ((ch (nextchar scanner))) (case ch ((nil) *eof*) ((#\{) (getchar scanner) (make-instance 'token :kind 'left-brace :text "{" :column (scanner-column scanner) :line (scanner-line scanner))) ((#\;) (getchar scanner) (make-instance 'token :kind 'semi-colon :text ";" :column (scanner-column scanner) :line (scanner-line scanner))) ((#\}) (getchar scanner) (make-instance 'token :kind 'right-brace :text "}" :column (scanner-column scanner) :line (scanner-line scanner))) ((#\() (getchar scanner) (make-instance 'token :kind 'left-paren :text "(" :column (scanner-column scanner) :line (scanner-line scanner))) ((#\,) (getchar scanner) (make-instance 'token :kind 'comma :text "," :column (scanner-column scanner) :line (scanner-line scanner))) ((#\)) (getchar scanner) (make-instance 'token :kind 'right-paren :text ")" :column (scanner-column scanner) :line (scanner-line scanner))) ((#\=) (getchar scanner) (make-instance 'token :kind 'equal :text "=" :column (scanner-column scanner) :line (scanner-line scanner))) ((#\") (getchar scanner) (loop :named :eat-string :with column = (scanner-column scanner) :with line = (scanner-line scanner) :with string = (make-array 8 :element-type 'character :initial-element #\space :adjustable t :fill-pointer 0) :for ch = (getchar scanner) :while (and ch (char/= ch #\")) :do (vector-push-extend (if (char= #\\ ch) (let ((ch (getchar scanner))) (case ch ((#\n) #\newline) ((#\t) #\tab) ((#\v) #\vt) ((#\b) #\bell) ((#\r) #\return) ;; TODO: Perhaps scan octal character codes? (otherwise ch))) ch) string (length string)) :finally (let ((token (make-instance 'token :kind 'string :text string :column column :line line))) (unless ch (error 'scanner-error :line line :column column :current-token token :scanner scanner :format-control "End of file while reading a string.")) (return-from :eat-string token)))) ((#\/) (getchar scanner) (if (char= #\* (nextchar scanner)) (progn ; comment (getchar scanner) (loop :named :eat-comment :with column = (scanner-column scanner) :with line = (scanner-line scanner) :for ch = (getchar scanner) :while (and ch (not (and (eql #\* ch) (eql #\/ (nextchar scanner))))) :finally (progn (unless ch (error 'scanner-error :line line :column column :scanner scanner :format-control "End of file while reading a comment.")) (getchar scanner) (return-from :eat-comment (scan-next-token scanner))))) (progn (ungetchar scanner #\/) (scan-unquoted-string scanner)))) ((#\space #\newline #\vt #\tab) (getchar scanner) (scan-next-token scanner)) (otherwise (if (unquoted-string-char-p ch) (scan-unquoted-string scanner) (progn (getchar scanner) ; let's eat it so that error recovery skips it. (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :scanner scanner :format-control "Unexpected character '~C' (code ~D)." :format-arguments (list ch (char-code ch)))))))))) (setf (scanner-current-text scanner) (token-text (scanner-current-token scanner))) (scanner-current-token scanner)) (defmethod advance-line ((scanner pbxproj-scanner)) (scan-next-token scanner)) (defmethod scanner-end-of-source-p ((scanner pbxproj-scanner)) (eofp (scanner-current-token scanner))) (defmethod word-equal ((a symbol) (b token)) (eql a (token-kind b))) (defmethod word-equal ((a token) (b symbol)) (eql (token-kind a) b)) ;; (when (find-method (function scanner-current-token) '() '(rdp-scanner) nil) ;; (remove-method (function scanner-current-token) (find-method (function scanner-current-token) '() '(rdp-scanner)))) (defmethod accept ((scanner pbxproj-scanner) expected) (let ((token (scanner-current-token scanner))) (if (word-equal expected token) (prog1 (list (token-kind token) (token-text token) (token-column token)) (scan-next-token scanner)) (call-next-method)))) ;;---------------------------------------------------------------------- ;; pbxproj parser ;;---------------------------------------------------------------------- #-mocl (when (and (find-package "COM.INFORMATIMAGO.RDP") (find-symbol "*BOILERPLATE-GENERATED*" "COM.INFORMATIMAGO.RDP") (boundp (find-symbol "*BOILERPLATE-GENERATED*" "COM.INFORMATIMAGO.RDP"))) (setf (symbol-value (find-symbol "*BOILERPLATE-GENERATED*" "COM.INFORMATIMAGO.RDP")) nil)) #-mocl (defgrammar pbxproj :scanner pbxproj-scanner :terminals ((string "…") (equal "=") (left-brace "{") (semi-colon ";") (right-brace "}") (left-paren "(") (comma ",") (right-paren ")")) :start file :rules ((--> file object) (--> object left-brace slots right-brace :action $2) (--> slots (rep slot semi-colon :action $1) :action (cons 'object $1)) (--> slot string equal data :action (list (second $1) (second $3))) (--> data (alt (seq string :action (second $1)) (seq object :action $1) (seq list :action $1))) (--> list left-paren (rep data comma :action (second $1)) right-paren :action (cons 'list $2)))) #+mocl (let ((com.informatimago.rdp::*linenum* 0) (#2=#:|grammar148137| (make-grammar :name 'pbxproj :terminals '((string "…") (equal "=") (left-brace "{") (semi-colon ";") (right-brace "}") (left-paren "(") (comma ",") (right-paren ")")) :start 'file :rules '((file (seq (object) #28=((list* 'file . #1=($0))))) #5=(object (seq (left-brace slots right-brace) #23=($2))) (slots (seq ((rep ((seq (slot semi-colon) #26=($1))))) #27=((cons 'object $1)))) #25=(slot (seq (string equal data) #24=((list (second $1) (second $3))))) #20=(data (seq ((alt ((seq (string) #3=((second $1))) (seq (object) #6=($1)) (seq (list) #15=($1))))) #16=((list* 'data . #1#)))) #14=(list (seq (left-paren (rep ((seq (data comma) #21=((second $1))))) right-paren) #22=((cons 'list $2))))) :scanner 'pbxproj-scanner :skip-spaces 't))) (setf (gethash (grammar-name #2#) com.informatimago.rdp::*grammars*) #2#) (com.informatimago.rdp::compute-all-terminals #2#) (com.informatimago.rdp::compute-all-non-terminals #2#) (com.informatimago.rdp::compute-first-follow #2#) nil 'pbxproj-scanner (progn (defun pbxproj/parse-data #17=(scanner) "(data (seq ((alt ((seq (string) ((second $1))) (seq (object) ($1)) (seq (list) ($1))))) ((list* 'data $0))))" (com.informatimago.rdp::with-non-terminal data (let (($1 (cond ((word-equal #4=(scanner-current-token scanner) 'string) (let (($1 (accept scanner 'string))) (let (($0 (list $1)) (string $1) (string.1 $1)) (declare (ignorable $0 string.1 string)) . #3#))) ((word-equal #4# 'left-brace) (let (($1 (if (word-equal #4# 'left-brace) (pbxproj/parse-object . #7=(scanner)) (error #8='unexpected-token-error :line #9=(scanner-line scanner) :column #10=(scanner-column scanner) :scanner scanner :non-terminal-stack #11=(copy-list *non-terminal-stack*) :format-control #12="Unexpected token ~S~%~S~%~{~A --> ~S~}" :format-arguments (list #13=(scanner-current-token scanner) *non-terminal-stack* '#5#))))) (let (($0 (list $1)) (object $1) (object.1 $1)) (declare (ignorable $0 object.1 object)) . #6#))) ((word-equal #4# 'left-paren) (let (($1 (if (word-equal #4# 'left-paren) (pbxproj/parse-list . #7#) (error #8# :line #9# :column #10# :scanner scanner :non-terminal-stack #11# :format-control #12# :format-arguments (list #13# *non-terminal-stack* '#14#))))) (let (($0 (list $1)) (list $1) (list.1 $1)) (declare (ignorable $0 list.1 list)) . #15#)))))) (let (($0 (list $1))) (declare (ignorable $0)) . #16#))))) (progn (defun pbxproj/parse-list #17# "(list (seq (left-paren (rep ((seq (data comma) ((second $1))))) right-paren) ((cons 'list $2))))" (com.informatimago.rdp::with-non-terminal list (let (($1 (accept scanner 'left-paren)) ($2 (loop :while (member #18=(scanner-current-token scanner) '(left-brace left-paren string) . #19=(:test #'word-equal)) :collect (let (($1 (if (member #18# '(string left-paren left-brace) . #19#) (pbxproj/parse-data . #7#) (error #8# :line #9# :column #10# :scanner scanner :non-terminal-stack #11# :format-control #12# :format-arguments (list #13# *non-terminal-stack* '#20#)))) ($2 (accept scanner 'comma))) (let (($0 (list $1 $2)) (data $1) (data.1 $1) (comma $2) (comma.1 $2)) (declare (ignorable $0 comma.1 comma data.1 data)) . #21#)))) ($3 (accept scanner 'right-paren))) (let (($0 (list $1 $2 $3)) (left-paren $1) (left-paren.1 $1) (right-paren $3) (right-paren.1 $3)) (declare (ignorable $0 right-paren.1 right-paren left-paren.1 left-paren)) . #22#))))) (progn (defun pbxproj/parse-object #17# "(object (seq (left-brace slots right-brace) ($2)))" (com.informatimago.rdp::with-non-terminal object (let (($1 (accept scanner 'left-brace)) ($2 (when (word-equal #4# 'string) (pbxproj/parse-slots scanner))) ($3 (accept scanner 'right-brace))) (let (($0 (list $1 $2 $3)) (left-brace $1) (left-brace.1 $1) (slots $2) (slots.1 $2) (right-brace $3) (right-brace.1 $3)) (declare (ignorable $0 right-brace.1 right-brace slots.1 slots left-brace.1 left-brace)) . #23#))))) (progn (defun pbxproj/parse-slot #17# "(slot (seq (string equal data) ((list (second $1) (second $3)))))" (com.informatimago.rdp::with-non-terminal slot (let (($1 (accept scanner 'string)) ($2 (accept scanner 'equal)) ($3 (if (member #18# '(string left-paren left-brace) . #19#) (pbxproj/parse-data . #7#) (error #8# :line #9# :column #10# :scanner scanner :non-terminal-stack #11# :format-control #12# :format-arguments (list #13# *non-terminal-stack* '#20#))))) (let (($0 (list $1 $2 $3)) (string $1) (string.1 $1) (equal $2) (equal.1 $2) (data $3) (data.1 $3)) (declare (ignorable $0 data.1 data equal.1 equal string.1 string)) . #24#))))) (progn (defun pbxproj/parse-slots #17# "(slots (seq ((rep ((seq (slot semi-colon) ($1))))) ((cons 'object $1))))" (com.informatimago.rdp::with-non-terminal slots (let (($1 (loop :while (word-equal #4# 'string) :collect (let (($1 (if (word-equal #4# 'string) (pbxproj/parse-slot . #7#) (error #8# :line #9# :column #10# :scanner scanner :non-terminal-stack #11# :format-control #12# :format-arguments (list #13# *non-terminal-stack* '#25#)))) ($2 (accept scanner 'semi-colon))) (let (($0 (list $1 $2)) (slot $1) (slot.1 $1) (semi-colon $2) (semi-colon.1 $2)) (declare (ignorable $0 semi-colon.1 semi-colon slot.1 slot)) . #26#))))) (let (($0 (list $1))) (declare (ignorable $0)) . #27#))))) (progn (defun pbxproj/parse-file #17# "(file (seq (object) ((list* 'file $0))))" (com.informatimago.rdp::with-non-terminal file (let (($1 (if (word-equal #4# 'left-brace) (pbxproj/parse-object . #7#) (error #8# :line #9# :column #10# :scanner scanner :non-terminal-stack #11# :format-control #12# :format-arguments (list #13# *non-terminal-stack* '#5#))))) (let (($0 (list $1)) (object $1) (object.1 $1)) (declare (ignorable $0 object.1 object)) . #28#))))) (progn (defun parse-pbxproj (com.informatimago.rdp::source) " SOURCE: When the grammar has a scanner generated, or a scanner class name, SOURCE can be either a string, or a stream that will be scanned with the generated scanner. Otherwise, it should be a SCANNER instance. " (com.informatimago.rdp::with-non-terminal pbxproj (let ((scanner (make-instance 'pbxproj-scanner :source com.informatimago.rdp::source))) (advance-line scanner) (prog1 (pbxproj/parse-file scanner) (unless (scanner-end-of-source-p scanner) (error 'parser-end-of-source-not-reached :line (scanner-line scanner) :column (scanner-column scanner) :grammar (grammar-named 'pbxproj) :scanner scanner :non-terminal-stack (copy-list *non-terminal-stack*)))))))) 'pbxproj) (defun read-pbxproj (path) (with-open-file (stream path) (parse-pbxproj stream))) ;;;; THE END ;;;;
25,950
Common Lisp
.lisp
483
28.194617
121
0.358258
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d0bbe39dab2142f712528edcd623abbd143274b90cd3d06a496b084299c69030
4,734
[ -1 ]
4,735
pbxproj-test.lisp
informatimago_lisp/xcode/pbxproj-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: pbxproj-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; pbxproj tests. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Extracted from pbxproj.lisp. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.XCODE.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.XCODE" "COM.INFORMATIMAGO.RDP" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER") (:import-from "COM.INFORMATIMAGO.XCODE" "EOFP") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.XCODE.TEST") (defun test-scan-stream (src) (loop :with scanner = (make-instance 'com.informatimago.xcode::pbxproj-scanner :source src :state 0) ;; :initially (progn ;; (advance-line scanner) ;; (format t "~2%;; ~A~%;; ~A~%" ;; (scanner-buffer scanner) ;; (scanner-current-token scanner))) :do (progn (scan-next-token scanner) (format t "~&~3A ~20A ~20S ~3A ~3A ~20A ~A~%" (scanner-state scanner) (token-kind (scanner-current-token scanner)) (token-text (scanner-current-token scanner)) (eofp (scanner-current-token scanner)) (eofp (scanner-current-token scanner)) "-" ;; (scanner-previous-token-kind scanner) (type-of (scanner-current-token scanner))) (finish-output)) :while (scanner-current-token scanner))) (defun test-scan-file (path) (with-open-file (src path) (test-scan-stream src))) (defun test-scan-string (source) (with-input-from-string (src source) (test-scan-stream src))) (defun test-parse-stream (src) (let ((scanner (make-instance 'com.informatimago.xcode::pbxproj-scanner :source src :state 0))) (com.informatimago.xcode::parse-pbxproj scanner))) (defun test-parse-file (path) (with-open-file (src path) (test-parse-stream src))) (defun test-parse-string (source) (with-input-from-string (src source) (test-parse-stream src))) ;; (test-scan-file #P"~/works/abalone-macosx/Abalone-10.7/Abalone.xcodeproj/project.pbxproj") (defvar *dirpath* nil) (eval-when (:compile-toplevel) (defparameter *dirpath* (make-pathname :name nil :type nil :version nil :defaults *compile-file-pathname*))) (eval-when (:load-toplevel :execute) (defparameter *dirpath* (or *dirpath* (make-pathname :name nil :type nil :version nil :defaults *load-pathname*)))) (define-test test/parse-file () (let ((pbxproj-path (merge-pathnames #P"test.pbxproj" *dirpath* nil))) (assert-true (with-output-to-string (*standard-output*) (test-scan-file pbxproj-path))) (assert-true (with-output-to-string (*standard-output*) (test-parse-file pbxproj-path))))) (define-test test/all () (test/parse-file)) ;;;; THE END ;;;;
4,212
Common Lisp
.lisp
94
39.680851
98
0.611897
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
861f406cc1a983ca004c427e49300e206328272e46828dac805c4df6f6876ee1
4,735
[ -1 ]
4,736
check-uses.lisp
informatimago_lisp/tools/check-uses.lisp
;;;; ;;;; Analyses the output of the objecteering macro dumpUses.jmf ;;;; ;;;; (C) 2008 Anevia ;;;; ;;;; Authors: Pascal J. Bourguignon ;;;; ;;;; (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "CHECK-USES" (:use "CL" "COM.INFORMATIMAGO.COMMON-LISP.GRAPH" "COM.INFORMATIMAGO.COMMON-LISP.GRAPH-DOT")) (in-package "CHECK-USES") (defgeneric uses (object) (:method ((self null)) '())) (defclass uml-object (element-class) ((path :initarg :path :accessor path :initform nil) (classof :initarg :classof :accessor classof :initform nil) (description :initarg :description :accessor description :initform nil) (owns :initarg :owns :accessor owns :initform '()) (uses :initarg :uses :accessor uses :initform '()) (usedby :initarg :usedby :accessor usedby :initform '()) (owns-reachable :accessor owns-reachable :initform '()) (uses-reachable :accessor uses-reachable :initform '()) (usedby-reachable :accessor usedby-reachable :initform '()))) (defmethod initialize-instance :after ((self uml-object) &rest args) (declare (ignore args)) (setf (slot-value self 'ident) (path self)) self) (defmethod name ((self uml-object)) (format nil "~A ~A" (classof self) (path self))) (defmethod print-object ((self uml-object) stream) (print-unreadable-object (self stream :identity t :type t) (princ (name self) stream)) self) (defun load-uses (path) (with-open-file (stream path :external-format charset:iso-8859-1) (loop :for form = (read stream nil stream) :until (eq form stream) :when (listp form) :collect (loop :for clause :in (rest form) :when (eq (first clause) :owns) :collect (rest clause) :into owns :when (eq (first clause) :uses) :collect (rest clause) :into uses :when (eq (first clause) :usedby) :collect (rest clause) :into usedby :finally (return (make-instance 'uml-object :classof (getf (first form) :classof) :path (getf (first form) :path) :description (first form) :uses uses :usedby usedby :owns owns)))))) ;;; ;;; :OWNS should be a tree, so we will only run a topological sort on it. ;;; (DEFUN TOPOLOGICAL-SORT (NODES LESSP) " RETURN: A list of NODES sorted topologically according to the partial order function LESSP. If there are cycles (discounting reflexivity), then the list returned won't contain all the NODES. " (LOOP :WITH SORTED = '() :WITH INCOMING = (MAP 'VECTOR (LAMBDA (TO) (LOOP :FOR FROM :IN NODES :WHEN (AND (NOT (EQ FROM TO)) (FUNCALL LESSP FROM TO)) :SUM 1)) NODES) :WITH Q = (LOOP :FOR NODE :IN NODES :FOR INCO :ACROSS INCOMING :WHEN (ZEROP INCO) :COLLECT NODE) :WHILE Q :DO (LET ((N (POP Q))) (PUSH N SORTED) (LOOP :FOR M :IN NODES :FOR I :FROM 0 :DO (WHEN (AND (AND (NOT (EQ N M)) (FUNCALL LESSP N M)) (ZEROP (DECF (AREF INCOMING I)))) (PUSH M Q)))) :FINALLY (RETURN (NREVERSE SORTED)))) (defun reachable (root successors) " RETURN: A list of objects reachable from O traversing SUCCESSORS. " (loop :with reachable = '() :with old = (funcall successors root) :while old :do (let ((current (pop old))) (pushnew current reachable) (dolist (successor (funcall successors current)) (unless (member successor reachable) (pushnew successor old)))) :finally (return reachable))) (defpackage "UML-OBJECT-NAMES" (:nicknames "UON") (:use)) (declaim (inline unify)) (defun unify (x) (intern x "UML-OBJECT-NAMES")) (defvar *objects* '()) (defvar *objects-index* (make-hash-table)) (defvar *sorted-objects* '()) (declaim (inline find-object owns-objects uses-objects usedby-objects)) (defun find-object (path) (gethash path *objects-index*)) (defun owns-objects (object) (mapcar (function find-object) (owns object))) (defun uses-objects (object) (mapcar (function find-object) (uses object))) (defun usedby-objects (object) (mapcar (function find-object) (usedby object))) (declaim (inline owns* uses* usedby*)) (defun owns* (p q) (member q (owns-reachable p))) (defun uses* (p q) (member q (uses-reachable p))) (defun usedby* (p q) (member q (usedby-reachable p))) (defun closest-to-root (nodes) " RETURN: the node in NODES that is the closest to ROOT according to *SORTED-OBJECTS* " (loop :with closest = (pop nodes) :with minimum = (position closest *sorted-objects*) :for node :in nodes :for distance = (position node *sorted-objects*) :initially (assert minimum) :when (and distance (< distance minimum)) :do (setf closest node minimum distance) :finally (return (values closest minimum)))) (defun closer-to-root (a b) (let ((p (position a *sorted-objects*)) (q (position b *sorted-objects*))) (and p q (< p q)))) (defun find-shortest-path (from to successors) " RETURN: The shortest path of length>0 from FROM to TO if it exists, or NIL. " ;; breadth first search (loop :with processed = '() :for paths = (list (list from)) :then new-paths :for new-paths = (remove-if (lambda (head) (member head processed)) (mapcan (lambda (path) (mapcar (lambda (new-node) (cons new-node path)) (funcall successors (first path)))) paths) :key (function first)) :for shortest-path = (find to new-paths :key (function first)) :do (setf paths (nconc paths new-paths) processed (nconc (delete-duplicates (mapcar (function first) new-paths)) processed)) :until (or shortest-path (endp new-paths)) :finally (return (reverse shortest-path)))) (defun print-cycle (path) (format t "~%There is a cycle going ~%from ~A" (name (first path))) (dolist (node (rest path)) (format t "~% to ~A" (name node))) (format t " !!!~%")) (defun find-uses-cycles (objects) (mapcar (lambda (cycle) (find-shortest-path cycle cycle (function uses-objects))) (remove-if-not (lambda (x) (member x (uses-reachable x))) objects))) (defun find-package-class-uses (objects) (let ((deps '())) (dolist (o objects deps) (when (string-equal "package" (classof o)) (dolist (u (uses-objects o)) (when (string-equal "class" (classof u)) (push (list o u) deps))))))) (defun report-problems (objects) (let ((cycles (find-uses-cycles objects))) (when cycles (format *error-output* "~&There are ~A cycles in the USES relationship!~%" (length cycles)) (dolist (path cycles) (print-cycle path)))) (let ((bad-uses (find-package-class-uses objects))) (when bad-uses (loop :with ps = (make-hash-table) :for (p c) :in bad-uses :do (pushnew c (gethash p ps '())) :finally (loop :for p :being :the :hash-keys :in ps :using (:hash-value cs) :initially (format *error-output* "~&There are ~A packages using classes!~%" (hash-table-count ps)) :do (format *error-output* "~%~A uses ~%" (name p)) (dolist (c cs) (format *error-output* "~& ~A~%" (name c)))))))) (defun uses-graph (objects) (let ((graph (make-instance 'graph-class :edge-class 'directed-edge-class ))) (add-nodes graph objects) (dolist (from objects) (dolist (to (uses-objects from)) (when (member to objects) (add-edge-between-nodes graph from to)))) graph)) (defun generate-uses-graph (objects path) (with-open-file (dot path :direction :output :if-does-not-exist :create :if-exists :supersede :external-format charset:iso-8859-1) (let ((graph (uses-graph objects))) (set-property graph :nodesep 3) (set-property graph :ranksep 7) (set-property graph :page "64,48") (set-property graph :ratio :fill) (princ (generate-dot graph) dot)))) (defun process-dump (path) (setf *objects* (load-uses path)) (format *trace-output* "~&Read ~D objects~%" (length *objects*)) (setf *objects-index* (let ((table (make-hash-table))) (dolist (object *objects*) (setf (path object) (unify (path object)) (owns object) (mapcar (lambda (x) (unify (first x))) (owns object)) (uses object) (mapcar (lambda (x) (unify (first x))) (uses object)) (usedby object) (mapcar (lambda (x) (unify (first x))) (usedby object))) (setf (gethash (path object) table) object)) table)) (dolist (object *objects*) (setf (owns-reachable object) (reachable object (function owns-objects)) (uses-reachable object) (reachable object (function uses-objects)) (usedby-reachable object) (reachable object (function usedby-objects)))) ;; (print (list (mapcar (lambda (x) (length (owns-reachable x))) *objects*) ;; (mapcar (lambda (x) (length (uses-reachable x))) *objects*) ;; (mapcar (lambda (x) (length (usedby-reachable x))) *objects*)) ;; *trace-output*) (setf *sorted-objects* (topological-sort *objects* (function owns*))) (unless (= (length *sorted-objects*) (length *objects*)) (format *error-output* "~&The OWNS relationship contains cycles! It should be a tree.~%")) (report-problems *objects*)) #- (and) (progn (let ((filter (lambda (x) (and (string= (classof x) "Package") (COM.INFORMATIMAGO.COMMON-LISP.STRING:PREFIXP "manager:Streamers:" (string (path x)))))) (name "uses-packages")) (generate-uses-graph (remove-if-not filter *objects*) (make-pathname :name name :type "dot")) (ext:shell (format nil "(twopi -Tps -Gcharset=latin1 -o~A.ps ~:*~A.dot;gsview ~:*~A.ps )&" name))) (let ((filter (lambda (x) (and (string= (classof x) "Class") (COM.INFORMATIMAGO.COMMON-LISP.STRING:PREFIXP "manager:Streamers:" (string (path x)))))) (name "uses-classes")) (generate-uses-graph (remove-if-not filter *objects*) (make-pathname :name name :type "dot")) (ext:shell (format nil "(twopi -Tps -Gcharset=latin1 -o~A.ps ~:*~A.dot;gsview ~:*~A.ps )&" name))) ) (print '(in-package "CHECK-USES")) (print '(check-uses:process-dump "~/uses.dump"))
11,831
Common Lisp
.lisp
257
35.385214
107
0.556617
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6bca99632c014b4ee0718c49cdefb7c0faaa7f8014a76f7647f575d9ccab908c
4,736
[ -1 ]
4,737
com.informatimago.tools.quicklisp.asd
informatimago_lisp/tools/com.informatimago.tools.quicklisp.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: quicklisp.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Quicklisp tools. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-12-06 <PJB> Extracted from ~/rc/common.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2013 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (asdf:defsystem "com.informatimago.tools.quicklisp" :description "Quicklisp tools." :author "Pascal J. Bourguignon" :version "1.3.0" :license "GPL3" :depends-on ( ;; assumed ;; "quicklisp" "com.informatimago.tools.pathname" "com.informatimago.common-lisp.cesarum") :components ((:file "dummy-quicklisp" :depends-on ()) (:file "dummy-asdf" :depends-on ()) (:file "asdf-tools" :depends-on ("dummy-asdf")) (:file "quicklisp" :depends-on ("dummy-quicklisp" "asdf-tools"))) #+asdf-unicode :encoding #+asdf-unicode :utf-8) ;;;; THE END ;;;;
2,042
Common Lisp
.lisp
48
38.541667
83
0.569277
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cb88add4a8f16e4b54883710b3eb5760377e6d490bfac6e7e0cc09d9d96f840e
4,737
[ -1 ]
4,738
susv3-compile.lisp
informatimago_lisp/tools/susv3-compile.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: compile.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Replaces the Makefile. ;;;; ;;;; Usage: (load "compile.lisp") ;;;; ;;;; will compile all outdated files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-07-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (defpackage "COM.INFORMATIMAGO.COMMON-LISP.COMPILE" ;; (:use "COMMON-LISP") ;; (:export "MAIN")) ;; (in-package "COM.INFORMATIMAGO.COMMON-LISP.COMPILE") ;; Not used yet. (defvar prefix "/usr/local/") (defvar module "common-lisp") (defvar package-path "com/informatimago/common-lisp") (defun logger (ctrl &rest args) (format *trace-output* "~&;;;;~%;;;; ~?~%;;;;~%" ctrl args)) (logger "*** COMPILING COM.INFORMATIMAGO.SYSV3 ***") (load "init.lisp") ;; package.lisp is loaded by init.lisp. #+(or allegro ccl ecl) (load (compile-file #p"PACKAGES:net;sourceforge;cclan;asdf;asdf.lisp")) #-(or allegro ccl ecl) (load (compile-file #p"PACKAGES:NET;SOURCEFORGE;CCLAN;ASDF;ASDF.LISP")) (push (function package:package-system-definition) asdf:*system-definition-search-functions*) ;;(asdf:operate 'asdf:load-op :com.informatimago.common-lisp) (asdf:operate 'asdf:load-op :com.informatimago.clisp) (defparameter *sources* (append '( #+ffi tools ) (when (find-package "LINUX") '( #+ffi dirent #+ffi ipc #+ffi process)))) (defparameter *source-type* "lisp") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Generate the asdf system file, loading the sources. (logger "GENERATING THE ASDF SYSTEM FILE") (com.informatimago.common-lisp.make-depends.make-depends:generate-asd :com.informatimago.susv3 *sources* *source-type* :version "1.0.0" :predefined-packages '("COMMON-LISP" "FFI" "EXT" "LINUX" "REGEXP" "GRAY" "SYS") :depends-on '(:com.informatimago.common-lisp :com.informatimago.clisp) :vanillap t) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Now, we generate a summary.html page. ;;; (logger "GENERATING THE SUMMARY.HTML") (com.informatimago.common-lisp.make-depends.make-depends:generate-summary *sources* :source-type *source-type* :summary-path "summary.html" :repository-url (lambda (pp) (format nil ;; "http://darcs.informatimago.com~ ;; /darcs/public/lisp/~(~A/~A~).lisp" ;; "com/informatimago/~(~A/~A~).lisp" "~(~*~A~).lisp" (car (last (pathname-directory pp))) (pathname-name pp))) #-clisp :comment-start #-clisp ";;;;") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Finally, we compile and load the system ;;; (logger "COMPILING THE ASDF SYSTEM") (setf asdf:*compile-file-warnings-behaviour* :ignore) (let ((*load-verbose* t) (*compile-verbose* t) (asdf::*verbose-out* t)) (asdf:operate 'asdf:load-op :com.informatimago.susv3)) ;;;; compile.lisp -- -- ;;;;
4,297
Common Lisp
.lisp
105
37.257143
94
0.582115
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bc95d9753ed522f4cf7ccee3441541490171694821a4dac28db3d15134e47369
4,738
[ -1 ]
4,739
clisp-compile.lisp
informatimago_lisp/tools/clisp-compile.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: compile.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Replaces the Makefile. ;;;; ;;;; Usage: (load "compile.lisp") ;;;; ;;;; will compile all outdated files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-08-13 <PJB> Added generation of ASD file and use of ASDF. ;;;; 2004-07-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (defpackage "COM.INFORMATIMAGO.COMMON-LISP.COMPILE" ;; (:use "COMMON-LISP") ;; (:export "MAIN")) ;; (in-package "COM.INFORMATIMAGO.COMMON-LISP.COMPILE") ;;; Not used yet (defvar prefix "/usr/local/") (defvar module "common-lisp") (defvar package-path "com/informatimago/common-lisp") ;;; ---- (defun logger (ctrl &rest args) (format *trace-output* "~&;;;;~%;;;; ~?~%;;;;~%" ctrl args)) (logger "*** COMPILING COM.INFORMATIMAGO.CLISP ***") (load "init.lisp") ;; package.lisp is loaded by init.lisp. #+(or allegro ccl ecl) (load (compile-file #p"PACKAGES:net;sourceforge;cclan;asdf;asdf.lisp")) #-(or allegro ccl ecl) (load (compile-file #p"PACKAGES:NET;SOURCEFORGE;CCLAN;ASDF;ASDF.LISP")) (push (function package:package-system-definition) asdf:*system-definition-search-functions*) (asdf:operate 'asdf:load-op :com.informatimago.common-lisp) (defparameter *sources* (append '( syslog ;; #+FFI uffi ;;uffi-test disk objc string fifo-stream iotask rfc1413 ) (when (find-package "LINUX") '( raw-memory susv3 susv3-mc3 susv3-xsi script ; use linux shell ; use linux xterm ; use susv3 make-volumes ; use susv3 )))) (defparameter *source-type* "lisp") (com.informatimago.common-lisp.make-depends.make-depends:generate-asd :com.informatimago.clisp *sources* *source-type* :version "1.0.0" :predefined-packages '("COMMON-LISP" "FFI" "EXT" "LINUX" "REGEXP" "SOCKET" "GRAY" "SYS" "CLOS") :depends-on '(:com.informatimago.common-lisp) :vanillap t) (com.informatimago.common-lisp.make-depends.make-depends:generate-summary *sources* :source-type *source-type* :summary-path "summary.html" :repository-url (lambda (pp) (format nil ;; "http://darcs.informatimago.com~ ;; /darcs/public/lisp/~(~A/~A~).lisp" ;; "com/informatimago/~(~A/~A~).lisp" "~(~*~A~).lisp" (car (last (pathname-directory pp))) (pathname-name pp))) #-clisp :comment-start #-clisp ";;;;") (asdf:operate 'asdf:load-op :com.informatimago.clisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4,142
Common Lisp
.lisp
105
33.580952
94
0.55807
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0880a19f8957a21bf70e8f3d9b8177a0d150b793e3c3c68f4bb5adfdf8637007
4,739
[ -1 ]
4,740
html-wrap-document.lisp
informatimago_lisp/tools/html-wrap-document.lisp
#!/usr/local/bin/clisp -ansi -q -E utf-8 ;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: html-wrap-document ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This script takes a file containing a <div class="document"> entity ;;;; and produces a HTML page containing it, with site header and footer. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-10-20 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (defmacro redirecting-stdout-to-stderr (&body body) (let ((verror (gensym)) (voutput (gensym))) `(let* ((,verror nil) (,voutput (with-output-to-string (stream) (let ((*standard-output* stream) (*error-output* stream) (*trace-output* stream)) (handler-case (progn ,@body) (error (err) (setf ,verror err))))))) (when ,verror (terpri *error-output*) (princ ,voutput *error-output*) (terpri *error-output*) (princ ,verror *error-output*) (terpri *error-output*) (terpri *error-output*) #+(and clisp (not testing-script)) (ext:exit 1))))) (redirecting-stdout-to-stderr (load (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname)))) (redirecting-stdout-to-stderr (ql:quickload :com.informatimago.common-lisp)) (use-package "COM.INFORMATIMAGO.COMMON-LISP.HTML-PARSER.PARSE-HTML") (use-package "COM.INFORMATIMAGO.COMMON-LISP.HTML-BASE.ML-SEXP") (defun wrap (input output) (let ((document (child-tagged-and-valued (parse-html-stream input) :div "class" "document"))) (unless document (error "Not a <div class=\"document\">…</div> input file.")) (let ((class (value-of-attribute-named document :class )) (id (value-of-attribute-named document :id )) (title (value-of-attribute-named document :title )) (author (value-of-attribute-named document :author )) (description (value-of-attribute-named document :description )) (keywords (value-of-attribute-named document :keywords )) (language (value-of-attribute-named document :language ))) (write-line "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" output) (write-line "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" output) (write-line "<!-- THIS FILE IS GENERATED BY html-wrap-document -->" output) (write-line "<!-- PLEASE DO NOT EDIT THIS FILE! -->" output) (format output "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"~A\"~:* lang=\"~A\">~%" language) (unparse-html `(:head () (:title () ,title) (:link (:rel "stylesheet" :href "/default.css" :type "text/css")) (:link (:rel "icon" :href "/favicon.ico" :type "image/x-icon")) (:link (:rel "shortcut icon" :href "/favicon.ico" :type "image/x-icon")) (:meta ( :content "text/html; charset=utf-8" :http-equiv "Content-Type" )) (:meta (:name "author" :content ,author)) (:meta (:name "description" :content ,description :http-equiv "Description")) (:meta (:name "keywords" :content ,keywords))) output) (write-string "<body> <!-- TOP-BEGIN --> <!-- TOP-END --> <!-- MENU-BEGIN --> <!-- MENU-END --> " output) (unparse-html `(:div (:class ,class :id ,id) ,@(element-children document)) output) (write-string " <!-- MENU-BEGIN --> <!-- MENU-END --> <!-- BOTTOM-BEGIN --> <!-- BOTTOM-END --> </body></html> " output))) (values)) (defun main (&optional arguments) (declare (ignore arguments)) (wrap *standard-input* *standard-output*)) #+(and clisp (not testing-script)) (progn (main ext:*args*) (ext:exit 0)) (pushnew :testing-script *features*) #-(and) (progn (with-open-file (*standard-input* #P"/Users/pjb/public_html/sites/com.informatimago.www/develop/lisp/com/informatimago/small-cl-pgms/botihn/botihn-fr.html.in") (parse-html-stream *standard-input*)) (with-open-file (*standard-input* #P"/Users/pjb/public_html/sites/com.informatimago.www/develop/lisp/com/informatimago/small-cl-pgms/aim-8/aim-8.html.in") (parse-html-stream *standard-input*))) ;;;; THE END ;;;;
5,799
Common Lisp
.lisp
119
41.97479
168
0.577507
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0b0d7bf4a5cc42b7faadbb032040005df4b1278dba7178e771a9c0f60657532a
4,740
[ -1 ]
4,741
undefmethod.lisp
informatimago_lisp/tools/undefmethod.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: undefmethod.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A macro to undefine methods. ;;;; ;;;;AUTHORS ;;;; <PJB> irc://[email protected] <[email protected]> ;;;;MODIFICATIONS ;;;; 2014-12-26 <PJB> Imported Shinmera's undefmethod from his paste ;;;; http://plaster.tymoon.eu/view/3N ;;;;BUGS ;;;;LEGAL ;;;; GPL3 ;;;; ;;;; Copyright Copyright irc://[email protected] 2014 - 2014 ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.UNDEFMETHOD" (:use "COMMON-LISP") (:export "UNDEFMETHOD") (:documentation " ;; Find your defmethod (defmethod find-place ((switch string) place) (gethash string place)) ;; Change to undefmethod (undefmethod find-place ((switch string) place) (gethash string place)) ;; Hit C-c C-c again and gone it is! Copyright irc://[email protected] ")) (in-package "COM.INFORMATIMAGO.TOOLS.UNDEFMETHOD") (defmacro undefmethod (name &rest args) (flet ((lambda-keyword-p (symbol) (find symbol lambda-list-keywords))) (destructuring-bind (qualifiers args) (loop for thing = (pop args) until (listp thing) collect thing into qualifiers finally (return (list qualifiers thing))) `(remove-method #',name (find-method #',name ',qualifiers (mapcar #'find-class ',(loop for arg in args until (lambda-keyword-p arg) collect (if (listp arg) (second arg) T)))))))) ;;;; THE END ;;;;
2,741
Common Lisp
.lisp
67
35.477612
89
0.57952
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1a0d34a949eb3fc7e4c708d54864f5655819070f2e99d74b2e06ba13884bd194
4,741
[ -1 ]
4,742
asdf-tools.lisp
informatimago_lisp/tools/asdf-tools.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: asdf-tools.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASDF tools. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2021-05-12 <PJB> Moved asdf-system-name and ;;;; asdf-system-license in here from manifest. ;;;; 2013-12-06 <PJB> Extracted from rc/common.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2013 - 2021 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.ASDF" (:use "COMMON-LISP" "ASDF" "QUICKLISP") (:shadowing-import-from "COM.INFORMATIMAGO.TOOLS.PATHNAME" "USER-HOMEDIR-PATHNAME" "MAKE-PATHNAME" "TRANSLATE-LOGICAL-PATHNAME") (:export "ASDF-LOAD" "ASDF-LOAD-SOURCE" "ASDF-INSTALL" "ASDF-SYSTEM-NAME" "ASDF-SYSTEM-LICENSE" "ASDF-DELETE-SYSTEM" "FIND-ASDF-SUBDIRECTORIES" "UPDATE-ASDF-REGISTRY") (:documentation "ASDF tools -- somewhat deprecated by quicklisp.")) (in-package "COM.INFORMATIMAGO.TOOLS.ASDF") ;; (asdf:output-files 'asdf:program-op "my-system") (defun asdf-system-name (system) "Return the name of the ASDF system." (slot-value system 'asdf::name)) (defparameter *system-licenses* '(("cl-ppcre" . "bsd-2") ("split-sequence" . :unknown) ("terminfo" . "mit") ("closer-mop" . "MIT"))) (defun asdf-system-license (system-name) "Return the license of the ASDF system." (let ((system (asdf:find-system system-name))) (or (cdr (assoc system-name *system-licenses* :test 'string-equal)) (and (slot-boundp system 'asdf::licence) (slot-value system 'asdf::licence)) :unknown))) (defun asdf-load (&rest systems) "Load the ASDF systems. See also (QL:QUICKLOAD system) to install them." (dolist (system systems systems) #+quicklisp (ql:quickload system) #-quicklisp (asdf:operate 'asdf:load-op system))) (defun asdf-load-source (&rest systems) "Load the sources of the ASDF systems. See also (QL:QUICKLOAD system) to install them." (dolist (system systems systems) (asdf:operate 'asdf:load-source-op system))) (defun asdf-install (&rest systems) "Download and install a system. Now, uses quicklisp." (dolist (system systems systems) (declare (ignorable system)) #+quicklisp (ql:quickload system) #-quicklisp (error "Please install and use quicklisp!"))) (defun asdf-delete-system (system) "Clear the system from ASDF, to force reloading them on next ASDF-LOAD." ;;(remhash (string-downcase system) asdf::*defined-systems*) (asdf:clear-system system) (values)) ;;;------------------------------------------------------------------------ ;;; (defparameter *asdf-interval-between-rescan* (* 7 24 60 60) "Force rescan at leastr once this amount of seconds.") (defparameter *asdf-registry-file* (merge-pathnames (user-homedir-pathname) (make-pathname :name "ASDF-CENTRAL-REGISTRY" :type "DATA" :version :newest :case :common :defaults (user-homedir-pathname)) nil) "Cache file.") (defparameter *original-asdf-registry* asdf:*central-registry*) (defvar *asdf-install-location* #P"") (defun find-asdf-subdirectories (&optional (directories (list *asdf-install-location*))) "Return a list of all the subdirectories of DIRECTORIES that contain .asd files. It is sorted in ascending namestring length." (format *trace-output* "~&;; Scanning ASDF packages...~%") (prog1 (sort (delete-duplicates (mapcar (lambda (p) (make-pathname :name nil :type nil :version nil :defaults p)) (mapcan (lambda (dir) (directory (merge-pathnames (make-pathname :directory (if (pathname-directory dir) '(:relative :wild-inferiors) '(:absolute :wild-inferiors)) :name :wild :type "ASD" :version :newest :case :common :defaults dir) dir nil))) directories)) :test (function equal)) (lambda (a b) (if (= (length a) (length b)) (string< a b) (< (length a) (length b)))) :key (function namestring)) (format *trace-output* "~&;; Done.~%"))) (defun update-asdf-registry (&key (force-scan nil) (directories nil directoriesp)) "Update asdf:*central-registry* with the subdirectories of DIRECTORIES containing ASD files, either scanned, or from the cache." (length (setf asdf:*central-registry* (nconc (if (and (not force-scan) (probe-file *asdf-registry-file*) (let ((fdate (file-write-date *asdf-registry-file*))) (and fdate (< (get-universal-time) (+ fdate *asdf-interval-between-rescan*))))) ;; Get it from the cache. (with-open-file (in *asdf-registry-file*) (format *trace-output* "~&;; Reading ASDF packages from ~A...~%" *asdf-registry-file*) (let ((*read-eval* nil)) (read in nil nil))) ;; Scan it anew. (let ((scan (apply (function find-asdf-subdirectories) (when directoriesp (list directories))))) (unless force-scan ; we save only when not :force-scan t (format *trace-output* "~&;; Writing ASDF packages to ~A...~%" *asdf-registry-file*) (with-open-file (out *asdf-registry-file* :direction :output :if-does-not-exist :create :if-exists :supersede) (print scan out))) scan)) *original-asdf-registry*)))) ;;;; THE END ;;;;
7,529
Common Lisp
.lisp
160
36.24375
107
0.546333
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
321d9acf89907871b63518af1f0d7daca7354603784d154e66598d36424ca97b
4,742
[ -1 ]
4,743
patch.lisp
informatimago_lisp/tools/patch.lisp
(defpackage "COM.INFORMATIMAGO.TOOLS.PATCH" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE")) (in-package "COM.INFORMATIMAGO.TOOLS.PATCH") (defstruct patch name description files) ;; diff -- …/ +++ … / --- … section (defstruct file old new hunks) ;; @@ … @@ … section (defstruct hunk ;; @@ … @@ … section header lines) (defmethod equals ((a file) (b file)) (and (equal (file-old a) (file-old b)) (equal (file-new a) (file-new b)) (= (length (file-hunks a)) (length (file-hunks b))) (every (function equals) (file-hunks a) (file-hunks b)))) (defmethod equals ((a hunk) (b hunk)) (and (equal (hunk-header a) (hunk-header b)) ;; (= (length (hunk-lines a)) (length (hunk-lines b))) ;; (every (function equal) (hunk-lines a) (hunk-lines b)) )) (defmethod print-object ((patch patch) stream) (print-unreadable-object (patch stream :type t :identity t) (format stream "~S~{~&~A~}" (patch-name patch) (patch-files patch))) patch) (defmethod print-object ((file file) stream) (print-unreadable-object (file stream :type t :identity t) (format stream "~S~{~&~A~}" (subseq (file-old file) 4) (file-hunks file))) file) (defmethod print-object ((hunk hunk) stream) (print-unreadable-object (hunk stream :type t :identity t) (let ((nlines (length (hunk-lines hunk)))) (format stream "~S ~A line~P" (hunk-header hunk) nlines (/= 1 nlines)))) hunk) (defgeneric serialize (object stream)) (defmethod serialize ((patch patch) stream) (write-string (patch-description patch) stream) (dolist (file (patch-files patch)) (serialize file stream)) patch) (defmethod serialize ((file file) stream) (write-line (file-old file) stream) (write-line (file-new file) stream) (dolist (hunk (file-hunks file)) (serialize hunk stream)) file) (defmethod serialize ((hunk hunk) stream) (write-line (hunk-header hunk) stream) (dolist (line (hunk-lines hunk)) (write-line line stream)) hunk) (defun split-hunks (lines) (loop :with hunks := '() :while (and lines (prefixp "@@ " (first lines))) :do (push (make-hunk :header (pop lines) :lines (loop :for line :in lines :while (and (not (or (prefixp "@@ " line) (prefixp "--- " line) (prefixp "+++ " line))) (or (prefixp " " line) (prefixp "-" line) (prefixp "+" line))) :collect (pop lines))) hunks) :finally (return (values (nreverse hunks) lines)))) (defun split-files (lines) (when (prefixp "diff --" (first lines)) (pop lines)) (loop :with files := '() :while (and lines (prefixp "--- " (first lines)) (prefixp "+++ " (second lines))) :do (push (make-file :old (pop lines) :new (pop lines) :hunks (multiple-value-bind (hunks rest-lines) (split-hunks lines) (setf lines rest-lines) hunks)) files) :finally (return (nreverse files)))) (defun load-patch-file (pathname) (loop :with lines := (string-list-text-file-contents pathname) :for line := (and lines (pop lines)) :while (and line (prefixp " " line)) :collect line :into description-lines :finally (return (make-patch :name (namestring pathname) :description (format nil "~{~A~%~}" description-lines) :files (split-files (cons line lines)))))) (defun diff-hunks (a b) "Return the hunks from the list A that are not in the list B." ;; Since hunks are sorted, we could be more efficient processing them sequencially. (set-difference a b :test (function equals))) (defun diff-patches (a b) "Return a PATCH with only the hunks in A that are not in B = A-B files that have identical hunks in both are removed. " (let ((a-files (patch-files a)) (b-files (patch-files b))) (make-patch :name (format nil "diff-~A-~A" (patch-name a) (patch-name b)) :description (format nil " diff-~A-~A~%~A~%~A" (patch-name a) (patch-name b) (patch-description a) (patch-description b)) :files (loop :for a-file :in (loop ;; remove identical files :for a-file :in a-files :for b-file := (find a-file b-files :test (function equals)) :unless b-file :collect a-file) :for b-file := (find (file-old a-file) b-files :key (function file-old) :test 'equal) :if b-file :collect (make-file :old (file-old a-file) :new (file-new a-file) :hunks (diff-hunks (file-hunks a-file) (file-hunks b-file))) :else :collect a-file)))) (defun save-patch-file (patch &optional pathname) (with-open-file (out (or pathname (patch-name patch)) :if-does-not-exist :create :if-exists :supersede :direction :output) (serialize patch out)) patch) #-(and) (progn (load-patch-file "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-o.patch") (diff-patches (load-patch-file "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-o.patch") (load-patch-file "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1.patch")) (setf (text-file-contents "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-r.patch") (with-output-to-string (out) (serialize (diff-patches (load-patch-file "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-o.patch") (load-patch-file "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1.patch")) out))) ; (save-patch-file (load-patch-file "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-o.patch") ; "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-o-2.patch") ; (let ((p (load-patch-file "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-o.patch"))) ;; keep only the hunks that contain "+.*VAR" or "+.*FLET" or "+.*};" (save-patch-file (let ((f (make-patch :name "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-f.patch" :description (patch-description p) :files (loop :for f :in (patch-files p) :for remaining-hunks := (loop :for h :in (file-hunks f) :if (loop :for l :in (hunk-lines h) :thereis (or (and (prefixp "+" l) (search "VAR" l)) (and (prefixp "+" l) (search "FLET" l)) (and (prefixp "+" l) (search "};" l)))) :collect h) :when remaining-hunks :collect (make-file :old (file-old f) :new (file-new f) :hunks remaining-hunks))))) (save-patch-file f) (save-patch-file (diff-patches p f) "/build/pbourguignon/clang/src.devel/hypervisor/tests/unit/ceedling/nkernel/1-r.patch")))) ) ;; progn
8,734
Common Lisp
.lisp
166
36.138554
130
0.509347
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4dc82ca143d6b09fd075ad74d8128907d976ed41a3bba04ad8353b3468e056ab
4,743
[ -1 ]
4,744
package-symbols.lisp
informatimago_lisp/tools/package-symbols.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: package-symbols.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A few package functions. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-04-09 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; No in-package. (defun package-internal-symbols (pack) (let ((result '())) (do-symbols (s pack) (when (eq (symbol-package s) pack) (push s result))) (sort result (function string<) :key (function symbol-name)))) (defun package-external-symbols (pack) (let ((result '())) (do-external-symbols (s pack) (push s result)) (sort result (function string<) :key (function symbol-name)))) (defun package-imported-symbols (pack) (let ((result '())) (do-symbols (s pack) (unless (eq (symbol-package s) pack) (push s result))) (sort result (function string<) :key (function symbol-name)))) (defmacro packages-created-by (&body body) (let ((vold (gensym))) `(let ((,vold (copy-list (list-all-packages)))) (progn ,@body) (set-difference (list-all-packages) ,vold)))) ;;;; THE END ;;;;
2,334
Common Lisp
.lisp
62
34.645161
83
0.594523
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7ccbebfe4c00d4190230af29a007ab92e19047eadda2f627ae4c4503b033fb04
4,744
[ -1 ]
4,745
source.lisp
informatimago_lisp/tools/source.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: source.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: UNIX ;;;;USER-INTERFACE: UNIX ;;;;DESCRIPTION ;;;; ;;;; This package exports functions to read source files and parse ;;;; their headers. ;;;; ;;;; Source files can be either elisp (.el) or Common Lisp (.lisp, ;;;; .lsp, .cl), and elisp sources may (require) common-lisp files ;;;; (.lisp, .lsp, .cl extensions for sources). ;;;; ;;;;USAGE ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Extracted from MAKE-DEPENDS. ;;;; 2015-02-22 <PJB> Moved MAKE-COMPONENTS MAKE-ASD-SEXP GENERATE-ASD to ;;;; com.informatimago.tools.asdf-file. ;;;; 2005-08-10 <PJB> Completed MAKE-ASD. ;;;; 2003-05-04 <PJB> Converted to Common-Lisp from emacs. ;;;; 2002-11-16 <PJB> Created. ;;;;BUGS ;;;; ;;;; - replace clisp regexp by cl-ppcre. ;;;; ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2002 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.SOURCE" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "SAFE-TEXT-FILE-TO-STRING-LIST") (:export "GET-CLOSED-DEPENDENCIES" "GET-DEPENDENCIES" "GET-PACKAGE" "GET-DEPENDS" "READ-SOURCE-HEADER" "READ-SOURCE-CODE" "SOURCE-PACKAGE" "SOURCE-PACKAGE-NAME" "SOURCE-PACKAGE-NICKNAMES" "SOURCE-PACKAGE-DOCUMENTATION" "SOURCE-PACKAGE-USE" "SOURCE-PACKAGE-SHADOW" "SOURCE-PACKAGE-SHADOWING-IMPORT-FROM" "SOURCE-PACKAGE-IMPORT-FROM" "SOURCE-PACKAGE-EXPORT" "SOURCE-PACKAGE-INTERN" "SOURCE-FILE" "SOURCE-FILE-PATHNAME" "SOURCE-FILE-EXTERNAL-FORMAT" "SOURCE-FILE-EMACS-VARIABLES" "SOURCE-FILE-HEADER" "SOURCE-FILE-PACKAGES-DEFINED" "SOURCE-FILE-PACKAGES-USED" "SOURCE-FILE-ADDED-NICKNAMES" "SOURCE-FILE-REQUIRES" "SOURCE-FILE-PROVIDES" "DEPENDENCIES" "HEADER-SLOT" "HEADER-LICENCE" "HEADER-DESCRIPTION" "HEADER-AUTHORS" "PARSE-EMACS-VARIABLES" "FILE-EMACS-VARIABLES" "WRITE-EMACS-HEAD-VARIABLES" "WRITE-EMACS-TAIL-VARIABLES" "READ-SOURCE-HEADER" "WRITE-SOURCE-HEADER" "*LINE-LENGTH*" "*EMACS-HEAD-VARIABLES*" "*FILE-HEADERS*" "READ-SOURCE-CODE" "ENSURE-SOURCE-FILE-PATHNAME" "SCAN-SOURCE-FILE" "GET-SOURCE-FILE" "EXTRACT-SOURCE-FROM-REQUIRE-SEXP" "GET-REQUIRES" "GET-PACKAGE" "SOURCE-FILE-FOR-OBJECT" "FIND-FILE-PATH" "FIND-FILE-WITH-EXTENSION" "FIND-FILE-IN-DIRECTORY" "PACKAGE-MEMBER-P" "GET-DEPENDENCIES" "GET-CLOSED-DEPENDENCIES" "GET-DEPENDS") (:documentation " This package exports functions to read source files and parse their headers. Source files can be either elisp (.el) or Common Lisp (.lisp, .lsp, .cl), and elisp sources may (require) common-lisp files (.lisp, .lsp, .cl extensions for sources). USAGE: (file-emacs-variables \"source.lisp\") --> (:|mode| \"lisp\" :|coding| \"utf-8\") (scan-source-file \"source.lisp\" :external-format :utf-8) --> #<source-file …> (get-package \"source.lisp\") --> #<source-package …> LICENSE: AGPL3 Copyright Pascal J. Bourguignon 2002 - 2015 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/> ")) (in-package "COM.INFORMATIMAGO.TOOLS.SOURCE") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro pdebug (&rest args) #-debug (declare (ignore args)) #+debug `(progn (format t ,@args)) #-debug '(progn)) (defmacro show (&rest expressions) #-debug (declare (ignore expressions)) #+debug `(progn ,@(mapcar (lambda (expr) `(format *trace-output* "~20A = ~S~%" ',expr ,expr)) expressions)) #-debug '(progn)) (defvar extensions-emacs '(("el" . "elc")) "A list of cons of extensions for emacs lisp source and object files.") (defvar extensions-clisp '(("lisp" . "fas") ("lsp" . "fas") ("cl" . "fas") ("lisp" . "fasl") ("lsp" . "fasl") ("cl" . "fasl") ("lisp" . "x86f") ("lsp" . "x86f") ("cl" . "x86f")) "A list of cons of extensions for Common-Lisp source and object files.") (defun object-extensions (sext-oext-list) (delete-duplicates (mapcar (function cdr) sext-oext-list))) (defun source-extensions (sext-oext-list) (delete-duplicates (mapcar (function car) sext-oext-list))) (defun read-sexp-from-file (stream &optional (eof-symbol :eof)) (handler-case (read stream nil eof-symbol) (error (err) (format *error-output* ";; !!! ~A: ~A~%" (pathname stream) err) nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass source-package () ((name :initarg :name :type string :accessor source-package-name) (nicknames :initarg :nicknames :type list :accessor source-package-nicknames) (documentation :initarg :documentation :type (or null string) :accessor source-package-documentation) (use :initarg :use :type list :accessor source-package-use) (shadow :initarg :shadow :type list :accessor source-package-shadow) (shadowing-import-from :initarg :shadowing-import-from :type list :accessor source-package-shadowing-import-from) (import-from :initarg :import-from :type list :accessor source-package-import-from) (export :initarg :export :type list :accessor source-package-export) (intern :initarg :intern :type list :accessor source-package-intern)) (:documentation "The description of a defpackage in a source file.")) (defmethod print-object ((self source-package) stream) (flet ((option (key slot) (when (slot-value self slot) `((,key ,(slot-value self slot)))))) (format stream "#.~S" `(defpackage ,(source-package-name self) ,@(option :nicknames 'nicknames) ,@(option :use 'use) ,@(option :shadow 'shadow) ,@(option :shadowing-import-from 'shadowing-import-from) ,@(option :import-from 'import-from) ,@(option :export 'export) ,@(option :intern 'intern) ,@(when (source-package-documentation self) `((:documentation ,(source-package-documentation self))))))) self) (defclass source-file () ((pathname :initarg :pathname :type pathname :accessor source-file-pathname) (external-format :initarg :external-format :initform :default :accessor source-file-external-format) (emacs-variables :initarg :emacs-variables :type list :accessor source-file-emacs-variables) (header :initarg :header :type list :accessor source-file-header) (packages-defined :initarg :packages-defined :type list :accessor source-file-packages-defined :documentation "A list of SOURCE-PACKAGE instances, one for each of the DEFPACKAGE forms found in the source file.") (packages-used :initarg :packages-used :type list :accessor source-file-packages-used :documentation "Each item is (operator package-name) with operator being one of CL:IN-PACKAGE CL:USE-PACKAGE CL-USER::ALSO-USE-PACKAGES CL:IMPORT CL:SHADOWING-IMPORT") (added-nicknames :initarg :added-nicknames :type list :accessor source-file-added-nicknames :documentation "A list of PACKAGE:ADD-NICKNAMES forms.") (requires :initarg :requires :type list :accessor source-file-requires :documentation "A list of CL:REQUIRE forms.") (provides :initarg :provides :type list :accessor source-file-provides :documentation "A list of CL:PROVIDES forms.")) (:documentation "The description of the packages and dependencies of a source file.")) (defmethod print-object ((self source-file) stream) (print-unreadable-object (self stream :identity t :type t) (format stream "~& :PATHNAME ~S" (source-file-pathname self)) (format stream "~& :EXTERNAL-FORMAT ~S" (source-file-external-format self)) (format stream "~& :HEADER ~S" (source-file-header self)) (format stream "~& :PACKAGES-DEFINED ~S" (source-file-packages-defined self)) (format stream "~& :PACKAGES-USED ~S" (source-file-packages-used self)) (format stream "~& :ADDED-NICKNAMES ~S" (source-file-added-nicknames self)) (format stream "~& :REQUIRES ~S" (source-file-requires self)) (format stream "~& :PROVIDES ~S" (source-file-provides self))) self) (defun symbol-package-name (symbol) (package-name (symbol-package symbol))) (defgeneric dependencies (self) (:documentation " RETURN: A list of packages the source object depends on. ")) (defmethod dependencies ((self source-package)) (delete-duplicates (nconc (copy-list (source-package-use self)) ;; Kind of an anti-dependency: ;; (mapcar (function symbol-package-name) (source-package-shadow self)) (mapcar (function first) (source-package-shadowing-import-from self)) (mapcar (function first) (source-package-import-from self))) :test (function string=))) (defmethod dependencies ((self source-file)) (delete-duplicates (nconc (mapcan (lambda (used) (ecase (first used) ((cl:in-package cl:use-package) (list (second used))) ((cl-user::also-use-packages) (copy-list (rest used))) ((cl:import cl:shadowing-import) (when (eq 'quote (caadr used)) (if (consp (cadadr used)) (mapcar (function symbol-package-name) (cadadr used)) (list (symbol-package-name (cadadr used)))))))) (source-file-packages-used self)) (mapcan (function dependencies) (source-file-packages-defined self))) :test (function string=))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Scan a header p-list for specific fields: ;;; (defun header-slot (header slot) (getf header slot)) (defun header-licence (header) " RETURN: Just the LICENCE from the LEGAL section. " (let ((legal (member :legal header))) (when legal (first (ensure-list (cadr legal)))))) (defun header-description (header) (let ((description (member :description header))) (when description (list-trim '("") (ensure-list (cadr description)) :test (function string=))))) (defun header-authors (header) (let ((authors (member :authors header))) (when authors (list-trim '("") (ensure-list (cadr authors)) :test (function string=))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Emacs File Local Variables ;;; (defun parse-emacs-variables (line) (when (search "-*-" line) (flet ((chunk (text start end) (string-trim " " (subseq text start end)))) (loop :with start = (+ 3 (search "-*-" line)) :with end = (or (search "-*-" line :start2 start) (length line)) :with result = '() :for colon = (and (< start end) (position #\: line :start start)) :while (and colon (< colon end)) :do (let ((vend (or (and (< (1+ colon) end) (position #\; line :start (1+ colon) :end end)) end))) (push (list (intern (chunk line start colon) "KEYWORD") (chunk line (1+ colon) vend)) result) (setf start (1+ vend))) :finally (return (nreverse result)))))) (defun file-emacs-variables (filepath) " RETURN: A p-list containing the emacs file local variables in the file at FILEPATH. " (let* ((start-label "Local Variables:") (end-label "End:") (lines (let ((*readtable* (copy-readtable))) ;; Quick and dirty disable : --> read three or four tokens ;; for pack:sym or pack::sym (set-macro-character #\: (lambda (stream char) (declare (ignore stream char)) #\:) nil) (safe-text-file-to-string-list filepath))) (first-line (if (and (< 2 (length (first lines))) (string= "#!" (first lines) :end2 2)) (second lines) (first lines))) (first-line-variables (parse-emacs-variables first-line)) (rlines (reverse lines)) (endc (loop :for cur :on rlines :until (or (null cur) (search end-label (car cur))) :finally (return cur))) (begc (loop :for cur :on endc :until (or (null cur) (search start-label (car cur))) :finally (return cur))) (vars (or (nreverse (ldiff endc (cdr begc))) (return-from file-emacs-variables first-line-variables))) (start (search start-label (first vars))) (end (+ start (length start-label))) (prefix (subseq (first vars) 0 start)) (suffix (subseq (first vars) end)) (vars (mapcan (lambda (line) (if (and (<= (+ (length prefix) (length suffix)) (length line)) (string= prefix line :end2 (length prefix)) (string= suffix line :start2 (- (length line) (length suffix)))) (list (subseq line (length prefix) (- (length line) (length suffix)))) nil)) vars)) (vars (loop :with result = '() :with line = "" :for cur :in vars :do (if (and (< 1 (length cur)) (char= #\\ (aref cur (1- (length cur))))) (setf line (concatenate 'string line (subseq cur 0 (1- (length cur))))) (progn (push (concatenate 'string line cur) result) (setf line ""))) :finally (return (nreverse result))))) (nconc first-line-variables (let ((*readtable* (copy-readtable))) ;; (setf (readtable-case *readtable*) :preserve) (mapcar (lambda (line) (let ((colon (position #\: line))) (when colon (list (intern (string-trim " " (subseq line 0 colon)) "KEYWORD") (read-from-string (subseq line (1+ colon))))))) (butlast (rest vars))))))) (defun write-emacs-head-variables (bindings stream &key (comment-start ";;;;") (comment-end)) "Write on the STREAM an emacs -*- comment line containing the given BINDINGS." (format stream "~@[~A ~]-*- ~{~{~A:~A~}~^;~} -*-~@[ ~A~]~%" comment-start bindings comment-end)) (defun write-emacs-tail-variables (bindings stream &key (comment-start ";;;;") (comment-end)) "Write on the STREAM an emacs file variable block containing the given BINDINGS." (flet ((format-line (control-string &rest arguments) (format stream "~@[~A ~]~?~@[ ~A~]~%" comment-start control-string arguments comment-end))) (format-line "Local Variables:") (dolist (binding bindings) (destructuring-bind (var val) binding (format-line "~A: ~A" var val))) (format-line "End:"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; SOURCE-HEADER ;;; ;; Patch #+clisp REGEXP:MATCH-STRING to work on multi-byte encodings: ;; (in-package :regexp) ;; (ext:without-package-lock (:regexp) ;; (intern "BYTES" :regexp)) ;; (ext:without-package-lock (:regexp) ;; (defun match-string (string match) ;; (let ((start (match-start match)) ;; (end (match-end match)) ;; (bytes (ext:convert-string-to-bytes ;; string custom:*misc-encoding*))) ;; (ext:convert-string-from-bytes ;; (make-array (- end start) ;; :element-type '(unsigned-byte 8) ;; :displaced-to bytes ;; :displaced-index-offset start) ;; custom:*misc-encoding*)))) ;; (in-package :source) (defun count-re-groups (re) " RETURN: The number of occurences of '\(' in the string RE. " (loop :for pos = (search "\\(" re) :then (search "\\(" re :start2 (1+ pos)) :while pos :count 1)) #+clisp (defun safe-encode (string) (ext:convert-string-from-bytes (ext:convert-string-to-bytes string charset:utf-8) charset:iso-8859-1)) #+clisp (defun safe-decode (string) (ext:convert-string-from-bytes (ext:convert-string-to-bytes string charset:iso-8859-1) charset:utf-8)) #+clisp (defparameter *patched-clisp-p* (ext:letf ((custom:*misc-encoding* charset:iso-8859-1)) (= 1 (regexp:match-start (regexp:match "t" "été" ))))) (defun safe-regexp-compile (regexp) #-clisp (declare (ignore regexp)) #+clisp (ext:letf ((custom:*misc-encoding* charset:iso-8859-1)) (if *patched-clisp-p* ;; We've got an unpatched clisp (regexp:regexp-compile (safe-encode regexp)) ;; We've got a patched clisp (regexp:regexp-compile regexp))) #-clisp nil) (defun safe-regexp-exec (regexp string) #-clisp (declare (ignore regexp string)) #+clisp (ext:letf ((custom:*misc-encoding* charset:iso-8859-1)) (if *patched-clisp-p* ;; We've got an unpatched clisp (regexp:regexp-exec regexp (safe-encode string)) ;; We've got a patched clisp (regexp:regexp-exec regexp string))) #-clisp (values)) (defun safe-regexp-match-string (string match) #-clisp (declare (ignore string match)) #+clisp (ext:letf ((custom:*misc-encoding* charset:iso-8859-1)) (if *patched-clisp-p* ;; We've got an unpatched clisp (safe-decode (regexp:match-string (safe-encode string) match)) ;; We've got a patched clisp (regexp:match-string string match))) #-clisp "") (defvar *file-headers* '(:file :language :system :user-interface :description :usage :authors :modifications :bugs :legal) "The file header section in order generated.") (defvar *emacs-head-variables* '(:|mode| :|coding|) "The emacs file variables that go to the head comment. Any other will go to the tail file variables.") (defvar *line-length* 79 "Maximum number of character per line.") #-sbcl (defun write-source-header (headers stream &key (comment-start ";;;;") (comment-end) (line-char #\*)) "Write a source header in a comment. HEADERS: A P-list containing the header data. COMMENT-START: NIL or a string containing the start of comment lines. COMMENT-END: NIL or a string containing the end of comment lines. LINE-CHAR: A filler character used to draw a line in a comment. *LINE-LENGTH* The length of the line comment lines generated. The values may be strings or list of strings (lines). Possible keys are: - :file name of the file. - :language the programming language in the file. - :system the operating system this source runs on. - :user-interface the user interface framework this source uses. - :description a multi-line description of this source file. - :usage usage indications. - :authors a list of authors. - :modifications a changelog list. - :bugs a list of bugs. - :legal the license section. " (let ((sections-with-spacer '(:description :usage :bugs :legal))) (flet ((line () (format stream "~@[~A~]~V,,,V<~>~@[~A~]~%" comment-start (- *line-length* (length comment-start) (length comment-end)) line-char comment-end)) (format-line (control-string &rest arguments) (format stream "~@[~A~]~?~@[ ~A~]~%" comment-start control-string arguments comment-end)) (indent-non-date-line (line) (if (and (< 16 (length line)) (every (function digit-char-p) (subseq line 0 4)) (char= #\- (aref line 4)) (every (function digit-char-p) (subseq line 5 7)) (char= #\- (aref line 7)) (every (function digit-char-p) (subseq line 8 10))) line (concatenate 'string " " line)))) (line) (dolist (key *file-headers*) (let ((val (header-slot headers key))) (etypecase val (list (format-line "~:@(~A~):" key) (when (member key sections-with-spacer) (format-line "")) (if (eql key :modifications) (dolist (line val) (format-line " ~A" (indent-non-date-line line))) (dolist (line val) (format-line " ~A" line))) (when (and val (member key sections-with-spacer)) (format-line ""))) (string (format-line "~:@(~A~):~V<~>~A" key (max 1 (- 20 (length (string key)))) val))))) (line)))) #+sbcl (defun wsb-line (stream comment-start line-char comment-end) (format stream "~@[~A~]~V,,,V<~>~@[~A~]~%" comment-start (- *line-length* (length comment-start) (length comment-end)) line-char comment-end)) #+sbcl (defun wsb-format-line (stream comment-start comment-end control-string &rest arguments) (format stream "~@[~A~]~?~@[ ~A~]~%" comment-start control-string arguments comment-end)) #+sbcl (defun wsb-indent-non-date-line (line) (if (and (< 16 (length line)) (char= #\- (aref line 4)) (char= #\- (aref line 7)) (let ((s (subseq line 0 4))) (loop for ch across s always (digit-char-p ch))) (let ((s (subseq line 5 7))) (loop for ch across s always (digit-char-p ch))) (let ((s (subseq line 8 10))) (loop for ch across s always (digit-char-p ch)))) line (concatenate 'string " " line))) #+sbcl (defun wsb (headers stream comment-start comment-end line-char) (let ((sections-with-spacer '(:description :usage :bugs :legal))) (wsb-line stream comment-start line-char comment-end) (dolist (key *file-headers*) (let ((val (header-slot headers key))) (etypecase val (list (wsb-format-line stream comment-start comment-end "~:@(~A~):" key) (when (member key sections-with-spacer) (wsb-format-line stream comment-start comment-end "")) (if (eql key :modifications) (dolist (line val) (wsb-format-line stream comment-start comment-end " ~A" (wsb-indent-non-date-line line))) (dolist (line val) (wsb-format-line stream comment-start comment-end " ~A" line))) (when (and val (member key sections-with-spacer)) (wsb-format-line stream comment-start comment-end ""))) (string (wsb-format-line stream comment-start comment-end "~:@(~A~):~V<~>~A" key (max 1 (- 20 (length (string key)))) val))))) (wsb-line stream comment-start line-char comment-end))) #+sbcl (defun write-source-header (headers stream &key (comment-start ";;;;") (comment-end) (line-char #\*)) "Write a source header in a comment. HEADERS: A P-list containing the header data. COMMENT-START: NIL or a string containing the start of comment lines. COMMENT-END: NIL or a string containing the end of comment lines. LINE-CHAR: A filler character used to draw a line in a comment. *LINE-LENGTH* The length of the line comment lines generated. The values may be strings or list of strings (lines). Possible keys are: - :file name of the file. - :language the programming language in the file. - :system the operating system this source runs on. - :user-interface the user interface framework this source uses. - :description a multi-line description of this source file. - :usage usage indications. - :authors a list of authors. - :modifications a changelog list. - :bugs a list of bugs. - :legal the license section. " (wsb headers stream comment-start comment-end line-char)) (defun read-source-header (stream &key (comment-start #+clisp "^[;]\\+" #-clisp ";") (comment-end) (line-char #\*) (keep-spaces nil)) " RETURN: A p-list containing the header found in the stream at the current position; the last line read. NOTE: Reading stops as soon as a non-comment line is read. If the stream can be positionned, the FILE-POSITION is set at the beginning of this first non-comment line. " (show stream (stream-external-format stream) keep-spaces comment-start comment-end) (flet ((chunk (text start end) (string-trim " " (subseq text start end))) (clean (cont) (when (and cont (every (lambda (ch) (char= line-char ch)) (string-trim " " (first cont)))) (pop cont)) (setf cont (nreverse cont)) (when (string= "" (car cont)) (pop cont)) cont)) (let (#+clisp(saved custom:*misc-encoding*)) (unwind-protect (progn #+clisp(setf custom:*misc-encoding* (stream-external-format stream)) (loop :with asso = '() :with cont = '() #+clisp :with #+clisp re #+clisp = #+clisp (safe-regexp-compile (format nil "~A\\(.*\\)~:[~;~:*~A~]" comment-start comment-end)) #+clisp :with #+clisp gindex #+clisp = #+clisp (1+ (count-re-groups comment-start)) :for pos = (file-position stream) :for line = (read-line stream nil nil) :for meat = (and line #+clisp (let ((matches (multiple-value-list (safe-regexp-exec re line)))) (when (and matches (nth gindex matches)) (safe-regexp-match-string line (nth gindex matches)))) #-clisp (let ((pstart (length comment-start))) (when (and (<= (length comment-start) (length line)) (string= comment-start line :end2 (length comment-start))) (let ((pend (if comment-end (let ((pend (- (length line) (length comment-end)))) (if (and (<= pstart pend) (string= comment-end line :start2 pend)) pend (length line))) (length line)))) (subseq line pstart pend))))) :while meat :do (cond ((zerop (length meat))) ((search "-*-" meat) (let ((ev (flatten (parse-emacs-variables meat)))) #+(and clisp ffi) (when (getf ev :coding) (setf custom:*foreign-encoding* (or (symbol-value (find-symbol (string-upcase (getf ev :coding)) "CHARSET")) custom:*foreign-encoding*))) (setf asso (nconc (nreverse ev ) asso)))) ((alpha-char-p (aref meat 0)) ; a keyword (when cont (push (clean cont) asso) (setf cont nil)) (let ((pcolon (position (character ":") meat))) (if pcolon (progn ; "keyword : value" (push (intern (chunk meat 0 pcolon) "KEYWORD") asso) (push (chunk meat (1+ pcolon) nil) asso)) (progn ; "keyword" alone (push (intern (chunk meat 0 nil) "KEYWORD") asso) (push "" cont))))) ((keywordp (car asso)) ; a value (push (if keep-spaces meat (chunk meat 0 nil)) cont))) :finally (when pos (file-position stream pos)) (when cont (push (clean cont) asso)) (return (values (nreverse asso) line)))) ;; cleanup: #+clisp (setf custom:*misc-encoding* saved) #-clisp nil)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Reading the source files ;;; ;; in-package common-lisp-user ;; declaim also-use-packages ;; eval-when add-nickname ... ;; defpackage ... ;; in-package x ;; added nicknames ;; defpackage ;; require ;; provide (defun read-source-code (stream &key (test (constantly nil))) " RETURN: An a-list of interesting forms from the source code: :PACKAGES-DEFINED, :PACKAGES-USED, :ADDED-NICKNAMES, :PROVIDES, :REQUIRES, and :TEST. TEST: A predicate for forms that should be returned in the :TEST entry. BUGS: This should be rewritten using COM.INFORMATIMAGO.COMMON-LISP.SOURCE " (let ((*readtable* (copy-readtable nil)) (*package* (find-package "COMMON-LISP-USER")) (defined-packages '()) (nicknames '()) (provides '()) (requires '()) (used-packages '()) (user-selected '()) (eof (gensym "EOF"))) ;; We keep evaluating the readtime expressions, assuming ;; none has any deleterious side effect, and none is used ;; to variate what we depend on from source files. #-(and) (set-dispatch-macro-character #\# #\. (lambda (stream subchar arg) (declare (ignore subchar arg)) (read-sexp-from-file stream eof))) (labels ((process-sexp (sexp) ;; (let ((*print-readably* t)) (print sexp *trace-output*)) (case (first sexp) ((defpackage) (ignore-errors (eval sexp)) (push sexp defined-packages)) ((in-package) (setf *package* (or (ignore-errors (find-package (second sexp))) *package*)) (push sexp used-packages)) ((use-package import shadowing-import) (push sexp used-packages)) ((declaim) (dolist (decl (cdr sexp)) (when (and (consp decl) (eql 'common-lisp-user::also-use-packages (car decl))) (push decl used-packages)))) ((cl-user::requires ;; norvig code uses it. require) (push sexp requires)) ((provide) (push sexp provides)) ((progn) (dolist (item (cdr sexp)) (process-sexp item))) ((eval-when) (dolist (item (cddr sexp)) (process-sexp item))) ((com.informatimago.common-lisp.cesarum.package:add-nickname) (push (cdr sexp) nicknames)) (otherwise (when (funcall test sexp) (push sexp user-selected)))))) (loop :for sexp = (read-sexp-from-file stream eof) :until (eql sexp eof) :do (when (consp sexp) (process-sexp sexp)) :finally (return (list (cons :packages-defined (nreverse defined-packages)) (cons :packages-used (nreverse used-packages)) (cons :added-nicknames (nreverse nicknames)) (cons :provides (nreverse provides)) (cons :requires (nreverse requires)) (cons :test (nreverse user-selected)))))))) (defun ensure-source-file-pathname (source-file &key (source-type "lisp")) (if (ignore-errors (probe-file source-file)) source-file (make-pathname :type source-type :defaults source-file))) (defun scan-source-file (source-filepath &key (external-format nil) (load nil) (verbose nil) (keep-spaces nil)) " DO: Makes a SOURCE-FILE instance and fills it with data got from the source file at SOURCE-FILEPATH. EXTERNAL-FORMAT: NIL => try to guess the encoding (use emacs local variables). LOAD: Whether the file should be loaded before scanning it. (needed until COM.INFORMATIMAGO.COMMON-LISP.SOURCE is used). COMMENT-START: A regexp matching the line comment start for the header lines. COMMENT-END: A regexp matching the line comment end for the header lines. KEEP-SPACES: NOTE: COMMENT-START and COMMENT-END are regexp only on clisp until COM.INFORMATIMAGO.COMMON-LISP.REGEXP can be used. RETURN: A SOURCE-FILE instance filled with the data from the source file. " (let* ((emacs-variables (file-emacs-variables source-filepath)) (external-format (or external-format (let ((coding (header-slot emacs-variables :coding))) (when coding (emacs-encoding-to-lisp-external-format coding))) :default))) (when load (load source-filepath :external-format external-format :verbose verbose)) (with-open-file (src source-filepath :direction :input :external-format external-format :if-does-not-exist :error) (let ((header (read-source-header src :comment-start #+clisp "^[;]\\+" #-clisp ";;;;" :comment-end nil :keep-spaces keep-spaces)) (forms (read-source-code src))) (make-instance 'source-file :pathname (truename source-filepath) :external-format external-format :emacs-variables emacs-variables :header header :packages-defined (flet ((select (key alist) (mapcan (lambda (ass) (when (eq key (car ass)) (list (copy-list (cdr ass))))) alist)) (selectn (key alist) (mapcan (lambda (ass) (when (eq key (car ass)) (copy-list (cdr ass)))) alist))) (mapcar (lambda (defpack) (let ((options (cddr defpack))) (make-instance 'source-package :name (second defpack) :nicknames (selectn :nicknames options) :documentation (second (assoc :documentation options)) :use (selectn :use options) :shadow (selectn :shadow options) :shadowing-import-from (select :shadowing-import-from options) :import-from (select :import-from options) :export (selectn :export options) :intern (selectn :intern options)))) (cdr (assoc :packages-defined forms)))) :packages-used (cdr (assoc :packages-used forms)) :added-nicknames (cdr (assoc :added-nicknames forms)) :requires (cdr (assoc :requires forms)) :provides (cdr (assoc :provides forms))))))) (defparameter *source-file-db* (make-hash-table :test (function equal))) (defun get-source-file (filepath &key (external-format nil)) " RETURN: a source-file read from FILEPATH. EXTERNAL-FORMAT: used to read the source file. If NIL, it's determined from emacs file variables. " ;; In clisp with ext:fasthash-equal, hashing pathname doesn't work. (let ((filepath (ensure-source-file-pathname filepath))) (or (gethash (namestring (truename filepath)) *source-file-db*) (let ((source-file (block :source-file (handler-bind ((error (lambda (err) (princ err *error-output*) (invoke-debugger err) (return-from :source-file nil)))) (scan-source-file filepath :load (string/= "el" (pathname-type filepath)) :verbose *load-verbose* :keep-spaces t :external-format external-format))))) (when source-file (setf (gethash (namestring (truename filepath)) *source-file-db*) source-file (gethash (namestring (truename (source-file-pathname source-file))) *source-file-db*) source-file)))))) (defun extract-source-from-require-sexp (sexp) " PRE: sexp is of the form: (REQUIRE module-name &OPTIONAL pathname-list) module-name can be 'toto or (quote toto). Each path name can be either a namestring, a physical path name or a logical path name. RETURN: A new list containing the pathname-list if present, or a list containing the symbol-name of the module-name. " (let ((symb (nth 1 sexp)) (files (cddr sexp)) ) (if (null files) (list (symbol-name (eval symb))) (copy-seq files)))) (defun get-requires (source-filepath &key (external-format nil)) " RETURN: A list of REQUIRE sexps found on the top-level of the SOURCE-FILE. EXTERNAL-FORMAT: used to read the source file. If NIL, it's determined from emacs file variables. " (let ((source-file (get-source-file source-filepath :external-format external-format))) (when source-file (source-file-requires source-file)))) (defun get-package (source-filepath &key (external-format nil)) " RETURN: The first DEFINE-PACKAGE sexp found on the top-level of the SOURCE-FILE. If none found, then the first DEFPACKAGE sexp. Or else, the first provide sexp, or else the file-name. EXTERNAL-FORMAT: used to read the source file. If NIL, it's determined from emacs file variables. " (let ((source-file (get-source-file source-filepath :external-format external-format))) (if source-file (or (first (source-file-packages-defined source-file)) (source-file-provides source-file) `(file-name ,(pathname-name (source-file-pathname source-file)))) `(file-name ,(pathname-name (source-file-pathname source-file)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; OBSOLETE: Source pathnames computed from package names with ;;; com.informatimago.common-lisp.cesarum.package::package-pathname ;;; in get-dependencies predates asdf. ;;; ;; object-file can be either .fas or .elc ;; ;; In both cases, it may have as source, either a common-lisp source ;; (.lisp, .lsp or .cl), or a elisp source (.el). (If a .fas, we seach ;; first for a .lisp, and if a .elc, we search first for a .el). ;; ;; ;; For required files, we search whatever source file (first of same ;; class as the source found for object-file), and return in anycase a ;; corresponding object file of the same class (extension) as ;; object-file. ;; ;; A .fas cannot require and load a .elc, it requires and loads only a ;; .fas, while a .elc cannot require and load a .fas, it requires and ;; loads only a .elc. (defun source-file-for-object (object-file) " RETURN: The source file for OBJECT-FILE (finding the right extension); the extension of the object-file; and the list of extensions couples. " (unless (pathname-type object-file) (error "make-depends: expected an object file name with an extension, not ~S.~%" object-file)) (let* ((extension (pathname-type object-file)) (extensions (if (member extension (object-extensions extensions-clisp) :test (function string=)) (append extensions-clisp extensions-emacs) (append extensions-emacs extensions-clisp))) (source-file ;; given the object-file extension, find the source file extension ;; for which a source file exists. (do* ((sext-oext extensions (cdr sext-oext)) (sext (caar sext-oext) (caar sext-oext)) ;;(OEXT (CDAR SEXT-OEXT) (CDAR SEXT-OEXT)) (sname nil) (result nil)) ((or (null sext-oext) (progn (setf sname (make-pathname :type sext :defaults object-file)) (setf result (ignore-errors (probe-file sname))))) (if result sname nil))))) (values source-file extension extensions))) (defun find-file-path (fname dir-paths) " RETURN: NIL or the path of FNAME found in one of DIR-PATHS. " (do* ((paths dir-paths (cdr paths)) (dpath (car paths) (car paths)) (fpath ) ) ( (or (null dpath) (probe-file (setq fpath (if (string= dpath ".") fname (sconc dpath "/" fname))))) (if dpath fpath nil) ))) (defun find-file-with-extension (path extensions) (assert path (path) "FIND-FILE-WITH-EXTENSION needs a path for PATH") (loop for ext in extensions for path-ext = (make-pathname :type ext :defaults path) do (progn (pdebug "~&;; -------------------------------------~%") (pdebug "~&;; FFWE: EXTENSION = ~S~%" ext) (pdebug "~&;; FFWE: PATH-EXT = ~S~%" path-ext) (pdebug "~&;; FFWE: PROBE-FILE = ~S~%" (handler-case (probe-file path-ext) (error () nil)))) (when (handler-case (probe-file path-ext) (error () nil)) (return-from find-file-with-extension path-ext)) finally (return nil))) (defun find-file-in-directory (file directories extensions) (assert file (file) "FIND-FILE-IN-DIRECTORY needs a path for FILE") (loop for directory in directories for dir-file = (merge-pathnames (parse-namestring directory) file nil) for found = (find-file-with-extension dir-file extensions) until found finally (return found))) (defun package-member-p (package packlist) (let* ((packname (etypecase package (string package) (symbol (string package)) (package (package-name package)))) (dotted (position (character ".") packname)) (packlist (mapcar (lambda (package) (etypecase package (string package) (symbol (string package)) (package (package-name package)))) packlist))) (or (member packname packlist :test (function string=)) (when dotted (find-if (lambda (pack) (and (prefixp pack packname) (< (length pack) (length packname)) (char= (character ".") (aref packname (length pack))))) packlist))))) (defun get-dependencies (object-file packages load-paths &key (verbose nil)) " PRE: OBJECT-FILE is foo.fas or foo.elc, etc. RETURN: A list of dependency for this OBJECT-FILE, including the source-file and all the object files of required files. OBJECT-FILE: The file of which the dependencies are computed. PACKAGES: A list of preloaded package names. LOAD-PATHS: A list of directory path names where to find the files when not found thru the logical pathname translations. The presence in LOAD-PATHS of a logical pathname warrants the presence in HOST-LPT of an entry mapping it to a physical path. VERBOSE: Prints information on *TRACE-OUTPUT*. " (pdebug "~&;; -------------------------------------~%") (pdebug "~&;; get-dependencies ~S~%" object-file) (when verbose (format *trace-output* "~&;; get-dependencies ~S~%" object-file)) (multiple-value-bind (source-filepath obj-ext extensions) (source-file-for-object object-file) (when source-filepath (cons source-filepath (mapcan (lambda (pack-name) (pdebug "~&;; processing ~S~%" pack-name) (when verbose (format *trace-output* "~&;; processing ~S~%" pack-name)) ;; "COM.INFORMATIMAGO.TOOLS.MAKE-DEPENDS.MAKE-DEPENDS" ;; --> PACKAGE::PACKAGE-PATHNAME ;; "DICTIONARY" ;; "PJB-STRING" ;; --> LOAD-PATHS (unless (member pack-name com.informatimago.common-lisp.cesarum.package::*built-in-package-names* :test (function string=)) (let* ((src-ext (source-extensions extensions)) (pack-path (com.informatimago.common-lisp.cesarum.package::package-pathname pack-name)) (path (or (find-file-with-extension pack-path src-ext) (find-file-in-directory pack-name load-paths src-ext)))) (pdebug "~&;; source extensions are ~S~%" src-ext) (pdebug "~&;; path of package is ~S~%" (com.informatimago.common-lisp.cesarum.package::package-pathname pack-name)) (pdebug "~&;; path is ~S~%" path) (if path (progn (setf path (let ((fntlp (file-namestring (translate-logical-pathname path)))) (if (and (string= (directory-namestring (translate-logical-pathname path)) (directory-namestring (translate-logical-pathname pack-path))) (ignore-errors (probe-file fntlp))) fntlp path))) (pdebug "~&;; short path is ~S~%" path)) (warn "Can't find a source file for package ~A" pack-name)) (when path (setf path (make-pathname :type obj-ext :defaults path))) (pdebug "~&;; result is ~S~%" path) (list path)))) (remove-if (lambda (pack) (pdebug "~&;; package dependencies: ~S~%" pack) (package-member-p pack packages)) (dependencies (get-source-file source-filepath)))))))) (defun get-closed-dependencies (object-file load-paths &key (verbose nil)) " PRE: OBJECT-FILE is foo.fas or foo.elc, etc. RETURN: A list of object files recursively required by OBJECT-FILE. " (multiple-value-bind (source-file extension extensions) (source-file-for-object object-file) (when source-file (cons object-file (mapcan ;; for each required file (lambda (item) (mapcar ;; find the object file path corresponding to an ;; existing source file path. (lambda (sext-oext) (let* ((sname (sconc item (car sext-oext))) (spath (find-file-path sname load-paths))) (if spath (get-closed-dependencies (if (string= "." (directory-namestring spath)) (sconc item extension) (sconc (directory-namestring spath) "/" item extension)) load-paths :verbose verbose) nil))) extensions)) (get-requires source-file)))))) (defun get-depends (object-files packages load-paths) " RETURN: A list of (cons object-file dependency-list). NOTE: GET-DEPENDS uses the logical pathname translations in place when called. " (mapcar (lambda (object) (cons object (get-dependencies object packages load-paths))) object-files)) ;;;; THE END ;;;;
53,227
Common Lisp
.lisp
1,126
35.741563
129
0.541006
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
eb9a189d9fa50bd0a54c2ddee6696ca6ce8cc7ecb3364d2fd42ba86e6914b69e
4,745
[ -1 ]
4,746
clext-compile.lisp
informatimago_lisp/tools/clext-compile.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: compile.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Replaces the Makefile. ;;;; ;;;; Usage: (load "compile.lisp") ;;;; ;;;; will compile all outdated files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-08-13 <PJB> Added generation of ASD file and use of ASDF. ;;;; 2004-07-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (defpackage "COM.INFORMATIMAGO.COMMON-LISP.COMPILE" ;; (:use "COMMON-LISP") ;; (:export "MAIN")) ;; (in-package "COM.INFORMATIMAGO.COMMON-LISP.COMPILE") ;;; Not used yet: (defvar *prefix* "/usr/local/") (defvar *module* "clext") (defvar *package-path* "com/informatimago/clext") ;;; ---- (defun logger (ctrl &rest args) (format *trace-output* "~&;;;;~%;;;; ~?~%;;;;~%" ctrl args)) (logger "*** COMPILING COM.INFORMATIMAGO.CLEXT ***") (load "init.lisp") ;; package.lisp is loaded by init.lisp. #+(or allegro ccl ecl) (load (compile-file #p"PACKAGES:net;sourceforge;cclan;asdf;asdf.lisp")) #-(or allegro ccl ecl) (load (compile-file #p"PACKAGES:NET;SOURCEFORGE;CCLAN;ASDF;ASDF.LISP")) (push (function package:package-system-definition) asdf:*system-definition-search-functions*) (asdf:oos 'asdf:load-op :com.informatimago.common-lisp) (unless (fboundp 'com.informatimago.common-lisp.html-generator.html:title) (error "~S is not fbound" 'com.informatimago.common-lisp.html-generator.html:title)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *sources* '( closer-weak ;; closer-weak-test.lisp ;; tests.lisp )) ;;*SOURCES* (defparameter *source-type* "lisp") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun version++ (&optional path) " DO: Increment the version compilation number. The version is persistent, stored in a file named VERSION.DAT in the same directory as *LOAD-PATHNAME*, or at PATH. RETURN: The version as a string \"major.minor.compilation\" " (flet ((read-version (file) (loop :for line = (read-line file nil nil) :for =pos = (when line (position (character "=") line)) :while line :when =pos :collect (list (intern (string-upcase (subseq line 0 =pos)) "KEYWORD") (read-from-string (subseq line (1+ =pos))))))) (let* ((default-path (or *load-pathname* *default-pathname-defaults*)) (version.path (or path (make-pathname :name "VERSION" :type "DAT" :version :newest :defaults default-path))) (version (with-open-file (file version.path :direction :input :if-does-not-exist :error) (read-version file))) (version.major (or (second (assoc :major version)) 0)) (version.minor (or (second (assoc :minor version)) 0)) (version.compilation (1+ (or (second (assoc :compilation version)) 0))) (new-version `((:major ,version.major) (:minor ,version.minor) (:compilation ,version.compilation)))) (with-open-file (file version.path :direction :output :if-does-not-exist :create :if-exists :supersede) (format file "~(~:{~A=~A~%~}~)" new-version)) (values (format nil "~A.~A.~A" version.major version.minor version.compilation) version.major version.minor version.compilation)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Generate the asdf system file, loading the sources. (logger "GENERATING THE ASDF SYSTEM FILE") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends.make-depends:generate-asd :com.informatimago.clext *sources* *source-type* :version (version++) :licence "GPL" :depends-on '() :implicit-dependencies '() :vanillap t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Now, we generate a summary.html page. ;;; (logger "GENERATING THE SUMMARY.HTML") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends.make-depends:generate-summary *sources* :verbose t :source-type *source-type* :summary-path "summary.html" :repository-url (lambda (pp) (format nil ;; "http://darcs.informatimago.com~ ;; /darcs/public/lisp/~(~A/~A~).lisp" ;; "com/informatimago/~(~A/~A~).lisp" "~(~*~A~).lisp" (car (last (pathname-directory pp))) (pathname-name pp))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Cleanup before asdf:load-op: ;;; we delete the package to let asdf:load-op load them cleanly. ;;; (logger "CLEANING THE LOADED PACKAGES") (defun package-use*-package-p (p q) " RETURN: Whether the package P uses the package Q, or a package that uses the package Q. NOTE: By definition, (PACKAGE-USE*-PACKAGE-P X X) " (setf p (find-package p) q (find-package q)) (loop :with processed = '() :with used = (list p) :while used ;; :do (print (list used processed)) :do (let ((current (pop used))) (if (eq current q) (return-from package-use*-package-p t) (progn (push current processed) (dolist (new (package-use-list current)) (unless (member new processed) (pushnew new used)))))) :finally (return-from package-use*-package-p nil))) (defun topological-sort (nodes lessp) " RETURN: A list of NODES sorted topologically according to the partial order function LESSP. If there are cycles (discounting reflexivity), then the list returned won't contain all the NODES. " (loop :with sorted = '() :with incoming = (map 'vector (lambda (to) (loop :for from :in nodes :when (and (not (eq from to)) (funcall lessp from to)) :sum 1)) nodes) :with q = (loop :for node :in nodes :for inco :across incoming :when (zerop inco) :collect node) :while q :do (let ((n (pop q))) (push n sorted) (loop :for m :in nodes :for i :from 0 :do (when (and (and (not (eq n m)) (funcall lessp n m)) (zerop (decf (aref incoming i)))) (push m q)))) :finally (return (nreverse sorted)))) ;; (defun print-graph (nodes edge-predicate) ;; (flet ((initiale (package) ;; (if (< (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (length (package-name package))) ;; (subseq (package-name package) ;; (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (1+ (length "COM.INFORMATIMAGO.COMMON-LISP."))) ;; (subseq (package-name package) 0 1)))) ;; (let* ((nodes (coerce nodes 'vector)) ;; (width (ceiling (log (length nodes) 10)))) ;; (loop ;; :for i :from 0 ;; :for node :across nodes ;; :initially (format t "~2%") ;; :do (format t " ~VD: ~A~%" width i node) ;; :finally (format t "~2%")) ;; (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t " ~VD " width "") ;; :do (format t " ~VD" width j) ;; :finally (format t "~%")) ;; (loop ;; :for i :from 0 :below (length nodes) ;; :do (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t "~A ~VD:" (initiale (aref nodes i)) width i) ;; :do (format t " ~VD" ;; width ;; (if (funcall edge-predicate ;; (aref nodes i) (aref nodes j)) ;; (concatenate 'string ;; (initiale (aref nodes i)) ;; (initiale (aref nodes j))) ;; "")) ;; :finally (format t "~%")) ;; :finally (format t "~%"))))) ;;; With topological-sort, we mustn't use a total order function like this one: ;; (defun package<= (p q) ;; (cond ((eq p q) t) ;; ((package-use*-package-p p q) ;; (assert (not (package-use*-package-p q p)) ;; (p q) "A circle could happen but it should not.") ;; t) ; p<q ;; ((package-use*-package-p q p) nil) ; p>q ;; (t (string<= (package-name p) (package-name q))))) (dolist (p (let* ((nodes (delete-if-not (lambda (p) (let ((prefix "COM.INFORMATIMAGO.CLMISC.")) (and (< (length prefix) (length (package-name p))) (string= prefix (package-name p) :end2 (length prefix))))) (copy-list (list-all-packages)))) (sorted (topological-sort nodes (function package-use*-package-p))) (cyclic (set-difference nodes sorted))) (when cyclic (format t "Cyclic nodes = ~S~%" cyclic)) (nconc cyclic sorted))) (delete-package p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Finally, we compile and load the system ;;; (logger "COMPILING THE ASDF SYSTEM") (setf asdf:*compile-file-warnings-behaviour* :ignore) (let ((*load-verbose* t) (*compile-verbose* t) (asdf::*verbose-out* t)) (asdf:operate 'asdf:load-op :com.informatimago.clext)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11,863
Common Lisp
.lisp
267
35.977528
94
0.495629
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8ecbac00671adb872a06b1ef5057c404082ae30e73ea84730a3d79cf8b94ce0f
4,746
[ -1 ]
4,747
dummy-uiop.lisp
informatimago_lisp/tools/dummy-uiop.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: dummy-uiop.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines a dummy UIOP package to be able to compile packages ;;;; depending on UIOP even when it is not available. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-07 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") #-(and) (progn (eval-when (:compile-toplevel) (print (list :compile-toplevel :asdf-version asdf::*asdf-version* :features (find :uiop *features*) :uiop-size (when (find-package "UIOP") (let ((n 0)) (do-external-symbols (s "UIOP") (incf n)) n)) :packages (sort (mapcar (function package-name) (list-all-packages)) (function string<)))) (terpri)) (eval-when (:load-toplevel) (print (list :load-toplevel :asdf-version asdf::*asdf-version* :features (find :uiop *features*) :uiop-size (when (find-package "UIOP") (let ((n 0)) (do-external-symbols (s "UIOP") (incf n)) n)) :packages (sort (mapcar (function package-name) (list-all-packages)) (function string<)))) (terpri)) (eval-when (:execute) (print (list :execute :asdf-version asdf::*asdf-version* :features (find :uiop *features*) :uiop-size (when (find-package "UIOP") (let ((n 0)) (do-external-symbols (s "UIOP") (incf n)) n)) :packages (sort (mapcar (function package-name) (list-all-packages)) (function string<)))) (terpri))) #-uiop (defpackage "UIOP" (:use "COMMON-LISP") (:export "SYMBOL-CALL" "RUN-PROGRAM" "GETENV")) #-uiop (defmacro uiop::generate-dummy-functions (&rest funames) `(progn ,@(mapcar (lambda (funame) `(defun ,funame (&rest args) (declare (ignore args)) nil)) funames))) #-uiop (uiop::generate-dummy-functions UIOP:SYMBOL-CALL UIOP:RUN-PROGRAM uiop:getenv) ;;;; THE END ;;;;
3,388
Common Lisp
.lisp
81
34.851852
88
0.557139
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
372668a548d6eb044f19c1c49a9f3980656ef30296b42551386c1f14e4c268b2
4,747
[ -1 ]
4,748
quicklisp-test.lisp
informatimago_lisp/tools/quicklisp-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: quicklisp-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test quicklisp.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.QUICKLISP.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.QUICKLISP") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.QUICKLISP.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,746
Common Lisp
.lisp
44
38.090909
83
0.609412
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e6d60e5bf1413ed876a401eb025727c79fae62fd057a651da7e153230008bdbb
4,748
[ -1 ]
4,749
compile-with-asdf.lisp
informatimago_lisp/tools/compile-with-asdf.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: compile-with-asdf.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Compile the com.informatimago.common-lisp libraries with ASDF. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2010-11-01 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2010 - 2016 ;;;; ;;;; 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/> ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (load (merge-pathname (make-pathname :name "INIT-ASDF" :type "LISP" :case :common) *load-pathname*)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Compiling com.informatimago.common-lisp ;;; (setf asdf:*central-registry* (append (remove-duplicates (mapcar (lambda (path) (make-pathname :name nil :type nil :version nil :defaults path)) (directory "**/*.asd")) :test (function equalp)) asdf:*central-registry*)) (asdf-load :com.informatimago.common-lisp) ;;;; THE END ;;;;
2,081
Common Lisp
.lisp
50
38
89
0.574679
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a6933983287b25afba84637cc59b2ee64e02dd37f00641ccfaf9952e026ea416
4,749
[ -1 ]
4,750
dummy-asdf.lisp
informatimago_lisp/tools/dummy-asdf.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: dummy-asdf.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines a dummy ASDF package to be able to compile packages ;;;; depending on ASDF even when ASDF is missing. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-07 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") #-asdf (defpackage "ASDF" (:use "COMMON-LISP") (:export "DEFSYSTEM" "LOAD-OP" "TEST-OP" "OOS" "OPERATE" "*COMPILE-FILE-WARNINGS-BEHAVIOUR*" "*SYSTEM-DEFINITION-SEARCH-FUNCTIONS*" "*CENTRAL-REGISTRY*" "FIND-SYSTEM" "SYSTEM" "COMPONENT-NAME" "COMPONENT-DEPENDS-ON" "RUN-SHELL-COMMAND") (:intern "*VERBOSE-OUT*" "NAME" "LICENCE")) #-asdf (progn (defvar asdf:*compile-file-warnings-behaviour* nil) (defvar asdf:*system-definition-search-functions* nil) (defvar asdf:*verbose-out* nil) (defvar asdf:*central-registry* nil)) ;;;; THE END ;;;;
2,228
Common Lisp
.lisp
56
37.053571
83
0.594557
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9a2c6fec74afcbbf67db41ae5e74374f03bd172848969b47787d0cbae5481969
4,750
[ -1 ]
4,751
make.lisp
informatimago_lisp/tools/make.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defvar *modules* '(common-lisp clext clmisc sbcl clisp susv3)) (defmacro define-implementation (name &key feature executable default-options load-option eval-option quit-option ; to quit once arguments processing is done quit-expression) `'(,name ,feature ,executable ,default-options ,load-option ,eval-option ,quit-option ,quit-expression)) (define-implementation abcl :feature :abcl :executable "abcl" :default-options () :load-option ("--load" <arg>) :eval-option ("--eval" <arg>) :quit-option ("--eval" "(quit)") :quit-expression "(extensions:quit)") (define-implementation allegro :feature :allegro :executable "alisp" :default-options ("-batch" "-q") :load-option ("-L" <arg>) :eval-option () :quit-option "-kill" :quit-expression "(excl:exit)") ; dumps an "; Exiting" message... (define-implementation ccl :feature :ccl :executable "ccl" :default-options ("--batch" "--o-init") :load-option ("--load" <arg>) :eval-option ("--eval" <arg>) :quit-option "--quit" :quit-expression "(ccl:quit)") (define-implementation clisp :feature :clisp :executable "clisp" :default-options ("-ansi" "-q" "-norc" "-Kfull" "-Efile" "UTF-8" #|"-on-error" "debug"|#) :load-option (<arg>) :eval-option ("-x" <arg>) :quit-option () :quit-expression "(ext:quit)") (define-implementation ecl :feature :ecl :executable "ecl" :default-options ("-norc") :load-option ("-shell" <arg>) :eval-option ("-eval" <arg>) :quit-option ("-quit") :quit-expression "(ext:quit)") sbcl := sbcl cmucl := cmucl openmcl := openmcl abcl_flags := allegro_flags := ccl_flags := clisp_flags := -ansi -q -norc -kfull -e iso-8859-1 -efile utf-8 -eterminal utf-8 -on-error debug cmucl_flags := -noinit -nositeinit ecl_flags := -norc openmcl_flags := sbcl_flags := --noinform --sysinit /dev/null --userinit /dev/null
2,176
Common Lisp
.lisp
61
30.344262
106
0.617102
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
fdb53037321926c196cd3a829ecf0579f487cea7dd9d810d48e74f7c3ed90eaf
4,751
[ -1 ]
4,752
source-test.lisp
informatimago_lisp/tools/source-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: source-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test source.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.SOURCE.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.SOURCE") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.SOURCE.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,731
Common Lisp
.lisp
44
37.75
83
0.605935
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5b5e27e021d0b8c155a358f4efe2ac3151eec95326b3aa3c22f5c5b800df0cd0
4,752
[ -1 ]
4,753
analyze.lisp
informatimago_lisp/tools/analyze.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: analyze.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-03-30 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :xref)) (defpackage "RP-USER" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.PACKAGE" "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.READER" "COM.INFORMATIMAGO.XREF" "COM.INFORMATIMAGO.XREF.READER-SETUP") (:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.READER" "READTABLE" "COPY-READTABLE" "MAKE-DISPATCH-MACRO-CHARACTER" "READ" "READ-PRESERVING-WHITESPACE" "READ-DELIMITED-LIST" "READ-FROM-STRING" "READTABLE-CASE" "READTABLEP" "SET-DISPATCH-MACRO-CHARACTER" "GET-DISPATCH-MACRO-CHARACTER" "SET-MACRO-CHARACTER" "GET-MACRO-CHARACTER" "SET-SYNTAX-FROM-CHAR" "WITH-STANDARD-IO-SYNTAX" "*READ-BASE*" "*READ-DEFAULT-FLOAT-FORMAT*" "*READ-EVAL*" "*READ-SUPPRESS*" "*READTABLE*") (:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.PACKAGE" "SYMBOL" "SYMBOLP" "MAKE-SYMBOL" "SYMBOL-NAME" "SYMBOL-PACKAGE" "SYMBOL-VALUE" "SYMBOL-FUNCTION" "SYMBOL-PLIST" "BOUNDP" "FBOUNDP" "KEYWORD" "KEYWORDP" "PACKAGE" "PACKAGEP" "MAKE-PACKAGE" "FIND-PACKAGE" "DELETE-PACKAGE" "FIND-SYMBOL" "IMPORT" "INTERN" "SHADOW" "SHADOWING-IMPORT" "EXPORT" "UNEXPORT" "UNINTERN" "USE-PACKAGE" "UNUSE-PACKAGE" "PACKAGE-NAME" "PACKAGE-NICKNAMES" "PACKAGE-USE-LIST" "PACKAGE-USED-BY-LIST" "PACKAGE-SHADOWING-SYMBOLS" "LIST-ALL-PACKAGES" "FIND-ALL-SYMBOLS" "RENAME-PACKAGE" "*PACKAGE*" "WITH-PACKAGE-ITERATOR" "DO-SYMBOLS" "DO-EXTERNAL-SYMBOLS" "DO-ALL-SYMBOLS" "DEFPACKAGE" "IN-PACKAGE" "PACKAGE-ERROR" "PACKAGE-ERROR-PACKAGE")) (in-package "RP-USER") (defparameter *sources* (sort (remove-if-not (function alpha-char-p) (directory "/home/pjb/works/patchwork/pw-src/**/*.lisp") :key (lambda (path) (aref (pathname-name path) 0))) (function string<) :key (function namestring))) (com.informatimago.xref.reader-setup:setup) (com.informatimago.xref:xref-files *sources*) #|| ;; (progn (mapc 'print *packages-created-automatically*) (terpri) (values)) (progn (mapc 'print (sort (copy-seq (list-all-packages)) (function string<) :key (function package-name))) (terpri) (values)) (let ((*print-case* :upcase)) (dolist (s (package-symbols "FFI") (terpri)) (terpri) (princ s))) (let ((*print-case* :upcase)) (dolist (db '(:file) (values)) (print db) (terpri) (display-database db) (terpri))) (let ((*print-case* :upcase)) (dolist (db '(:callers :readers :setters) (values)) (print db) (terpri) (display-database db) (terpri))) (let ((*print-case* :upcase)) (print-caller-trees)) (let ((*print-case* :upcase)) (dolist (mode '(:call-graph :caller-graph) (values)) (print mode) (terpri) (make-caller-tree mode) (terpri))) (determine-file-dependencies) (let ((*print-case* :upcase)) (print-file-dependencies)) ||# ;;; The following functions may be useful for viewing the database and ;;; debugging the calling patterns. ;;; ;;; DISPLAY-DATABASE (&optional database types-to-ignore) [FUNCTION] ;;; Prints out the name of each symbol and all its callers. Specify ;;; database :callers (the default) to get function call references, ;;; :file to the get files in which the symbol is called, :readers to get ;;; variable references, and :setters to get variable binding and ;;; assignments. Ignores functions of types listed in types-to-ignore. ;;; ;;; PRINT-CALLER-TREES (&key (mode *default-graphing-mode*) [FUNCTION] ;;; (types-to-ignore *types-to-ignore*) ;;; compact root-nodes) ;;; Prints the calling trees (which may actually be a full graph and not ;;; necessarily a DAG) as indented text trees using ;;; PRINT-INDENTED-TREE. MODE is :call-graph for trees where the children ;;; of a node are the functions called by the node, or :caller-graph for ;;; trees where the children of a node are the functions the node calls. ;;; TYPES-TO-IGNORE is a list of funcall types (as specified in the ;;; patterns) to ignore in printing out the database. For example, ;;; '(:lisp) would ignore all calls to common lisp functions. COMPACT is ;;; a flag to tell the program to try to compact the trees a bit by not ;;; printing trees if they have already been seen. ROOT-NODES is a list ;;; of root nodes of trees to display. If ROOT-NODES is nil, tries to ;;; find all root nodes in the database. ;;; ;;; MAKE-CALLER-TREE (&optional (mode *default-graphing-mode*) [FUNCTION] ;;; (types-to-ignore *types-to-ignore*) ;;; compact) ;;; Outputs list structure of a tree which roughly represents the ;;; possibly cyclical structure of the caller database. ;;; If mode is :call-graph, the children of a node are the functions ;;; it calls. If mode is :caller-graph, the children of a node are the ;;; functions that call it. ;;; If compact is T, tries to eliminate the already-seen nodes, so ;;; that the graph for a node is printed at most once. Otherwise it will ;;; duplicate the node's tree (except for cycles). This is usefull ;;; because the call tree is actually a directed graph, so we can either ;;; duplicate references or display only the first one. ;;; ;;; DETERMINE-FILE-DEPENDENCIES (&optional database) [FUNCTION] ;;; Makes a hash table of file dependencies for the references listed in ;;; DATABASE. This function may be useful for automatically resolving ;;; file references for automatic creation of a system definition ;;; (defsystem). ;;; ;;; PRINT-FILE-DEPENDENCIES (&optional database) [FUNCTION] ;;; Prints a list of file dependencies for the references listed in ;;; DATABASE. This function may be useful for automatically computing ;;; file loading constraints for a system definition tool. ;;; ;;; WRITE-CALLERS-DATABASE-TO-FILE (filename) [FUNCTION] ;;; Saves the contents of the current callers database to a file. This ;;; file can be loaded to restore the previous contents of the ;;; database. (For large systems it can take a long time to crunch ;;; through the code, so this can save some time.) ;;; LIST-CALLERS (symbol) [FUNCTION] ;;; Lists all functions which call SYMBOL as a function (function ;;; invocation). ;;; ;;; LIST-READERS (symbol) [FUNCTION] ;;; Lists all functions which refer to SYMBOL as a variable ;;; (variable reference). ;;; ;;; LIST-SETTERS (symbol) [FUNCTION] ;;; Lists all functions which bind/set SYMBOL as a variable ;;; (variable mutation). ;;; ;;; LIST-USERS (symbol) [FUNCTION] ;;; Lists all functions which use SYMBOL as a variable or function. ;;; ;;; WHO-CALLS (symbol &optional how) [FUNCTION] ;;; Lists callers of symbol. HOW may be :function, :reader, :setter, ;;; or :variable." ;;; ;;; WHAT-FILES-CALL (symbol) [FUNCTION] ;;; Lists names of files that contain uses of SYMBOL ;;; as a function, variable, or constant. ;;; ;;; SOURCE-FILE (symbol) [FUNCTION] ;;; Lists the names of files in which SYMBOL is defined/used. ;;; ;;; LIST-CALLEES (symbol) [FUNCTION] ;;; Lists names of functions and variables called by SYMBOL. ;;; ;;; ----- (defparameter *read-packages* '("C-GET-NOTE-SLOTS" "C-GET-SELECTIONS" "C-PATCH-ACCUM" "C-PATCH-BUFFER" "C-PATCH-CHORD-LINE" "C-PATCH-FILE-BUFFER" "C-PATCH-LIST-EDITOR" "C-PW-MIDI-IN" "C-PW-SEND-MIDI-NOTE" "C-PW-TEXT-BOX" "C-PW-TEXT-INPUT" "CCL" "CLENI" "CLPF-Util" "COMBINATORIAL-INTERV" "COMMON-LISP" "COMMON-LISP-USER" "EPW" "FFI" "KEYWORD" "MIDI" "MIDISHARE" "PATCH-WORK" "PW" "SCHEDULER")) (defparameter *grep-packages* '("QUANTIZING" "C-PATCH-CHORD-LINE" "C-PW-SEND-MIDI-NOTE" "C-PW-MIDI-IN" "C-GET-NOTE-SLOTS" "C-GET-SELECTIONS" "CLENI" "COMBINATORIAL-INTERV" "MIDISHARE" "USER-ABSTRACTION" "USER-COMP-ABSTR" "C-LIST-ITEM-H" "C-LIST-ITEM" "C-TABLE-WINDOW-H" "C-TABLE-WINDOW" "C-PATCH-LIST-EDITOR" "C-PATCH-BUFFER" "C-PATCH-ACCUM" "C-PATCH-FILE-BUFFER" "C-PW-TEXT-INPUT" "C-PW-TEXT-BOX" "USER-SUPPLIED-IN-OUTS" "LeLisp-macros" "PW-STYPE" "EPW" "CLPF-Util" "popUp-menu" "MIDI" "SCHEDULER")) (set-difference *read-packages* *grep-packages* :test (function string=)) (set-difference *grep-packages* *read-packages* :test (function string=)) ;; ("PW" "PATCH-WORK" "KEYWORD" "FFI" "COMMON-LISP-USER" "COMMON-LISP" "CCL") ;; ("popUp-menu" "PW-STYPE" "LeLisp-macros" "USER-SUPPLIED-IN-OUTS" "C-TABLE-WINDOW" "C-TABLE-WINDOW-H" "C-LIST-ITEM" "C-LIST-ITEM-H" "USER-COMP-ABSTR" "USER-ABSTRACTION" "QUANTIZING") (defparameter *in-packages* '("C-GET-NOTE-SLOTS" "C-GET-SELECTIONS" "C-LIST-ITEM-H" "C-PATCH-ACCUM" "C-PATCH-BUFFER" "C-PATCH-CHORD-LINE" "C-PATCH-FILE-BUFFER" "C-PATCH-LIST-EDITOR" "C-PW-MIDI-IN" "C-PW-SEND-MIDI-NOTE" "C-PW-TEXT-BOX" "C-PW-TEXT-INPUT" "C-TABLE-WINDOW-H" "CLENI" "CLPF-Util" "COMBINATORIAL-INTERV" "EPW" "LeLisp-macros" "MIDI" "MIDISHARE" "PATCH-WORK" "PW" "PW-STYPE" "QUANTIZING" "SCHEDULER")) (defparameter *defpackages* '("C-GET-NOTE-SLOTS" "C-GET-SELECTIONS" "C-LIST-ITEM" "C-LIST-ITEM-H" "C-PATCH-ACCUM" "C-PATCH-BUFFER" "C-PATCH-CHORD-LINE" "C-PATCH-FILE-BUFFER" "C-PATCH-LIST-EDITOR" "C-PW-MIDI-IN" "C-PW-SEND-MIDI-NOTE" "C-PW-TEXT-BOX" "C-PW-TEXT-INPUT" "C-TABLE-WINDOW" "C-TABLE-WINDOW-H" "CLENI" "CLPF-Util" "COMBINATORIAL-INTERV" "EPW" "LeLisp-macros" "MIDI" "MIDISHARE" "PW-STYPE" "QUANTIZING" "SCHEDULER" "USER-ABSTRACTION" "USER-COMP-ABSTR" "USER-SUPPLIED-IN-OUTS")) (set-difference *in-packages* *defpackages* :test 'string=) (set-difference *defpackages* *in-packages* :test 'string=) ;; ("PW" "PATCH-WORK") ;; ("USER-SUPPLIED-IN-OUTS" "USER-COMP-ABSTR" "USER-ABSTRACTION" "C-TABLE-WINDOW" "C-LIST-ITEM")
12,412
Common Lisp
.lisp
271
40.339483
184
0.610739
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
43e04f992847f6713b99a307053b5975b515e93d701d5f572ab0f4a6f77f29fa
4,753
[ -1 ]
4,754
asdf-file-test.lisp
informatimago_lisp/tools/asdf-file-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: asdf-file-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test asdf-file.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.ASDF-FILE.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.ASDF-FILE") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.ASDF-FILE.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,746
Common Lisp
.lisp
44
38.090909
83
0.606471
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6ebea9fd3af8e5935542bf8e4291579f028be47c265e7b9776e89cccb814b2df
4,754
[ -1 ]
4,755
clmisc-compile.lisp
informatimago_lisp/tools/clmisc-compile.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: compile.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Replaces the Makefile. ;;;; ;;;; Usage: (load "compile.lisp") ;;;; ;;;; will compile all outdated files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-08-13 <PJB> Added generation of ASD file and use of ASDF. ;;;; 2004-07-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (defpackage "COM.INFORMATIMAGO.COMMON-LISP.COMPILE" ;; (:use "COMMON-LISP") ;; (:export "MAIN")) ;; (in-package "COM.INFORMATIMAGO.COMMON-LISP.COMPILE") ;;; Not used yet: (defvar *prefix* "/usr/local/") (defvar *module* "clmisc") (defvar *package-path* "com/informatimago/clmisc") ;;; ---- (defun logger (ctrl &rest args) (format *trace-output* "~&;;;;~%;;;; ~?~%;;;;~%" ctrl args)) (logger "*** COMPILING COM.INFORMATIMAGO.CLMISC ***") (load "init.lisp") ;; package.lisp is loaded by init.lisp. #+(or allegro ccl ecl) (load (compile-file #p"PACKAGES:net;sourceforge;cclan;asdf;asdf.lisp")) #-(or allegro ccl ecl) (load (compile-file #p"PACKAGES:NET;SOURCEFORGE;CCLAN;ASDF;ASDF.LISP")) (push (function package:package-system-definition) asdf:*system-definition-search-functions*) (asdf:oos 'asdf:load-op :com.informatimago.common-lisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *sources* '( resource-utilization ;; closer-weak-test.lisp ;; tests.lisp )) ;;*SOURCES* (defparameter *source-type* "lisp") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun version++ (&optional path) " DO: Increment the version compilation number. The version is persistent, stored in a file named VERSION.DAT in the same directory as *LOAD-PATHNAME*, or at PATH. RETURN: The version as a string \"major.minor.compilation\" " (flet ((read-version (file) (loop :for line = (read-line file nil nil) :for =pos = (when line (position (character "=") line)) :while line :when =pos :collect (list (intern (string-upcase (subseq line 0 =pos)) "KEYWORD") (read-from-string (subseq line (1+ =pos))))))) (let* ((default-path (or *load-pathname* *default-pathname-defaults*)) (version.path (or path (make-pathname :name "VERSION" :type "DAT" :version :newest :defaults default-path))) (version (with-open-file (file version.path :direction :input :if-does-not-exist :error) (read-version file))) (version.major (or (second (assoc :major version)) 0)) (version.minor (or (second (assoc :minor version)) 0)) (version.compilation (1+ (or (second (assoc :compilation version)) 0))) (new-version `((:major ,version.major) (:minor ,version.minor) (:compilation ,version.compilation)))) (with-open-file (file version.path :direction :output :if-does-not-exist :create :if-exists :supersede) (format file "~(~:{~A=~A~%~}~)" new-version)) (values (format nil "~A.~A.~A" version.major version.minor version.compilation) version.major version.minor version.compilation)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Generate the asdf system file, loading the sources. (logger "GENERATING THE ASDF SYSTEM FILE") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends.make-depends:generate-asd :com.informatimago.clmisc *sources* *source-type* :version (version++) :licence "GPL" :depends-on '() ;; '("zlib") ;; :IMPLICIT-DEPENDENCIES '("package") :vanillap t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Now, we generate a summary.html page. ;;; (logger "GENERATING THE SUMMARY.HTML") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends.make-depends:generate-summary *sources* :verbose t :source-type *source-type* :summary-path "summary.html" :repository-url (lambda (pp) (format nil ;; "http://darcs.informatimago.com~ ;; /darcs/public/lisp/~(~A/~A~).lisp" ;; "com/informatimago/~(~A/~A~).lisp" "~(~*~A~).lisp" (car (last (pathname-directory pp))) (pathname-name pp))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Cleanup before asdf:load-op: ;;; we delete the package to let asdf:load-op load them cleanly. ;;; (logger "CLEANING THE LOADED PACKAGES") (defun package-use*-package-p (p q) " RETURN: Whether the package P uses the package Q, or a package that uses the package Q. NOTE: By definition, (PACKAGE-USE*-PACKAGE-P X X) " (setf p (find-package p) q (find-package q)) (loop :with processed = '() :with used = (list p) :while used ;; :do (print (list used processed)) :do (let ((current (pop used))) (if (eq current q) (return-from package-use*-package-p t) (progn (push current processed) (dolist (new (package-use-list current)) (unless (member new processed) (pushnew new used)))))) :finally (return-from package-use*-package-p nil))) (defun topological-sort (nodes lessp) " RETURN: A list of NODES sorted topologically according to the partial order function LESSP. If there are cycles (discounting reflexivity), then the list returned won't contain all the NODES. " (loop :with sorted = '() :with incoming = (map 'vector (lambda (to) (loop :for from :in nodes :when (and (not (eq from to)) (funcall lessp from to)) :sum 1)) nodes) :with q = (loop :for node :in nodes :for inco :across incoming :when (zerop inco) :collect node) :while q :do (let ((n (pop q))) (push n sorted) (loop :for m :in nodes :for i :from 0 :do (when (and (and (not (eq n m)) (funcall lessp n m)) (zerop (decf (aref incoming i)))) (push m q)))) :finally (return (nreverse sorted)))) ;; (defun print-graph (nodes edge-predicate) ;; (flet ((initiale (package) ;; (if (< (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (length (package-name package))) ;; (subseq (package-name package) ;; (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (1+ (length "COM.INFORMATIMAGO.COMMON-LISP."))) ;; (subseq (package-name package) 0 1)))) ;; (let* ((nodes (coerce nodes 'vector)) ;; (width (ceiling (log (length nodes) 10)))) ;; (loop ;; :for i :from 0 ;; :for node :across nodes ;; :initially (format t "~2%") ;; :do (format t " ~VD: ~A~%" width i node) ;; :finally (format t "~2%")) ;; (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t " ~VD " width "") ;; :do (format t " ~VD" width j) ;; :finally (format t "~%")) ;; (loop ;; :for i :from 0 :below (length nodes) ;; :do (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t "~A ~VD:" (initiale (aref nodes i)) width i) ;; :do (format t " ~VD" ;; width ;; (if (funcall edge-predicate ;; (aref nodes i) (aref nodes j)) ;; (concatenate 'string ;; (initiale (aref nodes i)) ;; (initiale (aref nodes j))) ;; "")) ;; :finally (format t "~%")) ;; :finally (format t "~%"))))) ;;; With topological-sort, we mustn't use a total order function like this one: ;; (defun package<= (p q) ;; (cond ((eq p q) t) ;; ((package-use*-package-p p q) ;; (assert (not (package-use*-package-p q p)) ;; (p q) "A circle could happen but it should not.") ;; t) ; p<q ;; ((package-use*-package-p q p) nil) ; p>q ;; (t (string<= (package-name p) (package-name q))))) (dolist (p (let* ((nodes (delete-if-not (lambda (p) (let ((prefix "COM.INFORMATIMAGO.CLMISC.")) (and (< (length prefix) (length (package-name p))) (string= prefix (package-name p) :end2 (length prefix))))) (copy-list (list-all-packages)))) (sorted (topological-sort nodes (function package-use*-package-p))) (cyclic (set-difference nodes sorted))) (when cyclic (format t "Cyclic nodes = ~S~%" cyclic)) (nconc cyclic sorted))) (delete-package p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Finally, we compile and load the system ;;; (logger "COMPILING THE ASDF SYSTEM") (setf asdf:*compile-file-warnings-behaviour* :ignore) (let ((*load-verbose* t) (*compile-verbose* t) (asdf::*verbose-out* t)) (asdf:operate 'asdf:load-op :com.informatimago.clmisc)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11,741
Common Lisp
.lisp
265
35.803774
94
0.491997
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a8a97c7b63de828f106d4b8af0832645697fccc53f52c5b43f3baaad7deaa7ea
4,755
[ -1 ]
4,756
sbcl-compile.lisp
informatimago_lisp/tools/sbcl-compile.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: compile.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Replaces the Makefile. ;;;; ;;;; Usage: (load "compile.lisp") ;;;; ;;;; will compile all outdated files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-08-13 <PJB> Added generation of ASD file and use of ASDF. ;;;; 2004-07-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (defpackage "COM.INFORMATIMAGO.COMMON-LISP.COMPILE" ;; (:use "COMMON-LISP") ;; (:export "MAIN")) ;; (in-package "COM.INFORMATIMAGO.COMMON-LISP.COMPILE") ;;; Not used yet (defvar prefix "/usr/local/") (defvar module "common-lisp") (defvar package-path "com/informatimago/sbcl") ;;; ---- (defun logger (ctrl &rest args) (format *trace-output* "~&;;;;~%;;;; ~?~%;;;;~%" ctrl args)) (logger "*** COMPILING COM.INFORMATIMAGO.SBCL ***") (load "init.lisp") ;; package.lisp is loaded by init.lisp. #+(or allegro ccl ecl) (load (compile-file #p"PACKAGES:net;sourceforge;cclan;asdf;asdf.lisp")) #-(or allegro ccl ecl) (load (compile-file #p"PACKAGES:NET;SOURCEFORGE;CCLAN;ASDF;ASDF.LISP")) (push (function package:package-system-definition) asdf:*system-definition-search-functions*) (asdf:operate 'asdf:load-op :com.informatimago.common-lisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *sources* '(posix readline)) (defparameter *source-type* "lisp") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun version++ (&optional path) " DO: Increment the version compilation number. The version is persistent, stored in a file named VERSION.DAT in the same directory as *LOAD-PATHNAME*, or at PATH. RETURN: The version as a string \"major.minor.compilation\" " (flet ((read-version (file) (loop :for line = (read-line file nil nil) :for =pos = (when line (position (character "=") line)) :while line :when =pos :collect (list (intern (string-upcase (subseq line 0 =pos)) "KEYWORD") (read-from-string (subseq line (1+ =pos))))))) (let* ((default-path (or *load-pathname* *default-pathname-defaults*)) (version.path (or path (make-pathname :name "VERSION" :type "DAT" :version :newest :defaults default-path))) (version (with-open-file (file version.path :direction :input :if-does-not-exist :error) (read-version file))) (version.major (or (second (assoc :major version)) 0)) (version.minor (or (second (assoc :minor version)) 0)) (version.compilation (1+ (or (second (assoc :compilation version)) 0))) (new-version `((:major ,version.major) (:minor ,version.minor) (:compilation ,version.compilation)))) (with-open-file (file version.path :direction :output :if-does-not-exist :create :if-exists :supersede) (format file "~(~:{~A=~A~%~}~)" new-version)) (values (format nil "~A.~A.~A" version.major version.minor version.compilation) version.major version.minor version.compilation)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Generate the asdf system file, loading the sources. (logger "GENERATING THE ASDF SYSTEM FILE") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends.make-depends:generate-asd :com.informatimago.sbcl *sources* *source-type* :version (version++) :licence "GPL" :predefined-packages '("COMMON-LISP" "SB-EXT" "SB-ALIEN" "SB-C" "SB-SYS") :depends-on '(:com.informatimago.common-lisp) :implicit-dependencies '() :vanillap t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Now, we generate a summary.html page. ;;; (logger "GENERATING THE SUMMARY.HTML") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends.make-depends:generate-summary *sources* :verbose nil :source-type *source-type* :summary-path "summary.html" :repository-url (lambda (pp) (format nil ;; "http://darcs.informatimago.com~ ;; /darcs/public/lisp/~(~A/~A~).lisp" ;; "com/informatimago/~(~A/~A~).lisp" "~(~*~A~).lisp" (car (last (pathname-directory pp))) (pathname-name pp))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Cleanup before asdf:load-op: ;;; we delete the package to let asdf:load-op load them cleanly. ;;; (logger "CLEANING THE LOADED PACKAGES") (defun package-use*-package-p (p q) " RETURN: Whether the package P uses the package Q, or a package that uses the package Q. NOTE: By definition, (PACKAGE-USE*-PACKAGE-P X X) " (setf p (find-package p) q (find-package q)) (loop :with processed = '() :with used = (list p) :while used ;; :do (print (list used processed)) :do (let ((current (pop used))) (if (eq current q) (return-from package-use*-package-p t) (progn (push current processed) (dolist (new (package-use-list current)) (unless (member new processed) (pushnew new used)))))) :finally (return-from package-use*-package-p nil))) (defun topological-sort (nodes lessp) " RETURN: A list of NODES sorted topologically according to the partial order function LESSP. If there are cycles (discounting reflexivity), then the list returned won't contain all the NODES. " (loop :with sorted = '() :with incoming = (map 'vector (lambda (to) (loop :for from :in nodes :when (and (not (eq from to)) (funcall lessp from to)) :sum 1)) nodes) :with q = (loop :for node :in nodes :for inco :across incoming :when (zerop inco) :collect node) :while q :do (let ((n (pop q))) (push n sorted) (loop :for m :in nodes :for i :from 0 :do (when (and (and (not (eq n m)) (funcall lessp n m)) (zerop (decf (aref incoming i)))) (push m q)))) :finally (return (nreverse sorted)))) ;; (defun print-graph (nodes edge-predicate) ;; (flet ((initiale (package) ;; (if (< (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (length (package-name package))) ;; (subseq (package-name package) ;; (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (1+ (length "COM.INFORMATIMAGO.COMMON-LISP."))) ;; (subseq (package-name package) 0 1)))) ;; (let* ((nodes (coerce nodes 'vector)) ;; (width (ceiling (log (length nodes) 10)))) ;; (loop ;; :for i :from 0 ;; :for node :across nodes ;; :initially (format t "~2%") ;; :do (format t " ~VD: ~A~%" width i node) ;; :finally (format t "~2%")) ;; (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t " ~VD " width "") ;; :do (format t " ~VD" width j) ;; :finally (format t "~%")) ;; (loop ;; :for i :from 0 :below (length nodes) ;; :do (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t "~A ~VD:" (initiale (aref nodes i)) width i) ;; :do (format t " ~VD" ;; width ;; (if (funcall edge-predicate ;; (aref nodes i) (aref nodes j)) ;; (concatenate 'string ;; (initiale (aref nodes i)) ;; (initiale (aref nodes j))) ;; "")) ;; :finally (format t "~%")) ;; :finally (format t "~%"))))) ;;; With topological-sort, we mustn't use a total order function like this one: ;; (defun package<= (p q) ;; (cond ((eq p q) t) ;; ((package-use*-package-p p q) ;; (assert (not (package-use*-package-p q p)) ;; (p q) "A circle could happen but it should not.") ;; t) ; p<q ;; ((package-use*-package-p q p) nil) ; p>q ;; (t (string<= (package-name p) (package-name q))))) (dolist (p (let* ((nodes (delete-if-not (lambda (p) (let ((prefix "COM.INFORMATIMAGO.CLMISC.")) (and (< (length prefix) (length (package-name p))) (string= prefix (package-name p) :end2 (length prefix))))) (copy-list (list-all-packages)))) (sorted (topological-sort nodes (function package-use*-package-p))) (cyclic (set-difference nodes sorted))) (when cyclic (format t "Cyclic nodes = ~S~%" cyclic)) (nconc cyclic sorted))) (delete-package p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Finally, we compile and load the system ;;; (logger "COMPILING THE ASDF SYSTEM") (setf asdf:*compile-file-warnings-behaviour* :ignore) (let ((*load-verbose* t) (*compile-verbose* t) (asdf::*verbose-out* t)) (asdf:operate 'asdf:load-op :com.informatimago.sbcl)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11,748
Common Lisp
.lisp
263
36.140684
94
0.493838
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e63265972d4cd1994d0177344ceb4110c0e057d33554b3918749c166f0bd3b5f
4,756
[ -1 ]
4,757
make-depends-test.lisp
informatimago_lisp/tools/make-depends-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: make-depends-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test make-depends.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.MAKE-DEPENDS.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.MAKE-DEPENDS") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.MAKE-DEPENDS.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,761
Common Lisp
.lisp
44
38.431818
83
0.609913
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
33bb2166959a3e06436ee9650319e97a1cd4036046b7c0ffb1725f32bce8ec8f
4,757
[ -1 ]
4,758
thread-test.lisp
informatimago_lisp/tools/thread-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: thread-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test thread.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.THREAD.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.KILL-THREAD") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.THREAD.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,736
Common Lisp
.lisp
44
37.863636
83
0.606509
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
3fce65a81109ba488d4ab9328ae6a3e1e365360125a40ba8a3d598ef1bdea74b
4,758
[ -1 ]
4,759
make-depends.lisp
informatimago_lisp/tools/make-depends.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: make-depends.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: UNIX ;;;;USER-INTERFACE: UNIX ;;;;DESCRIPTION ;;;; ;;;; This script generates dependencies for lisp sources, based on ;;;; (require) sexps, a load-path, a set of logical pathname translations ;;;; and ad-hoc processing. ;;;; ;;;; Object files can be either elisp compiled (.elc) or clisp compiled ;;;; (.fas), cmucl compiled (.x86f), or sbcl compiled (.fasl). ;;;; and source files can be either elisp (.el) or clisp or cmucl (.lisp, ;;;; .lsp, .cl), and elisp sources may (require) common-lisp files ;;;; (.lisp, .lsp, .cl extensions for sources, but .elc compiled form). ;;;; ;;;;USAGE ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-22 <PJB> Moved MAKE-COMPONENTS MAKE-ASD-SEXP GENERATE-ASD to ;;;; com.informatimago.tools.asdf-file. ;;;; 2005-08-10 <PJB> Completed MAKE-ASD. ;;;; 2003-05-04 <PJB> Converted to Common-Lisp from emacs. ;;;; 2002-11-16 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2002 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.MAKE-DEPENDS" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS" "COM.INFORMATIMAGO.TOOLS.SOURCE") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "SAFE-TEXT-FILE-TO-STRING-LIST") (:export "MAKE-DEPENDS") (:documentation " This script generates dependencies for lisp sources, based on (require) sexps, a load-path, a set of logical pathname translations and ad-hoc processing. LICENSE: AGPL3 Copyright Pascal J. Bourguignon 2002 - 2015 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/> ")) (in-package "COM.INFORMATIMAGO.TOOLS.MAKE-DEPENDS") (defun make-depends (object-files packages translations load-paths &key (idf nil) (verbose nil)) " DO: Finds the dependencies of the object files. PACKAGES: A list of names of the packages preloaded. NOTE: Since the list of preloaded packages depends on the lisp compiler, it should be given along with object files compiled by this compiler. However, if it is known that only a common list of predefined package is used in the source packages, it can be given. TRANSLATIONS: A list of (CONS HOST TRANSLATIONS) that will be used to set the logical pathname translations. These translations are used first NOTE: We set the logical pathname translations only in here to avoid problems loading this program. LOAD-PATHS: A list of directory path names where to find the files when not found thru the logical pathname translations. The presence in LOAD-PATHS of a logical pathname warrants the presence in HOST-LPT of an entry mapping it to a physical path. IDF: If NIL, write the dependencies on the standard output, else, write the dependencies of each object file into its own .d file. " (mapc (lambda (args) (setf (logical-pathname-translations (car args)) (cdr args))) translations) (setq packages (mapcar (function string) packages)) (dolist (object object-files) (when verbose (format *trace-output* "# Processing ~A~%" object)) (let ((line (format nil "~A :: ~A" object (unsplit-string (mapcar (lambda (item) (if item (string (namestring (translate-logical-pathname item))) "")) (get-dependencies object packages load-paths)) " ")))) (if idf (with-open-file (out (merge-pathnames (make-pathname :name (concatenate 'string (pathname-name object) "." (pathname-type object)) :type "d") object) :direction :output :if-exists :overwrite :if-does-not-exist :create) (format out "~A~%" line)) (format t "~A~%" line))))) ;;;; THE END ;;;;
6,428
Common Lisp
.lisp
137
39.124088
83
0.607678
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5efe878be737c664a69426a8d920f6232f20daa61b31f8cc54fef0d9dbcd8805
4,759
[ -1 ]
4,760
thread.lisp
informatimago_lisp/tools/thread.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: thread.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Exports threads manipulation commands. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Added this header. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.THREAD" (:use "COMMON-LISP" "BORDEAUX-THREADS") (:export "LIST-THREADS" "KILL-THREAD" "KILL-THREADS" "PERIODICALLY" "DO-PERIODICALLY" "DONE")) (in-package "COM.INFORMATIMAGO.TOOLS.THREAD") (defun periodically (period thunk &key (name "Peridic Task") initially finally) (bt:make-thread (lambda () (when initially (funcall initially)) (catch :exit-periodically (loop (sleep period) (funcall thunk))) (when finally (funcall finally))) :name name :initial-bindings (list (cons '*standard-output* *standard-output*) (cons '*standard-input* *standard-input*) (cons '*error-output* *error-output*) (cons '*trace-output* *trace-output*) (cons '*terminal-io* *terminal-io*)))) (defmacro do-periodically ((period &key (name "Periodic Task") initially finally) &body body) `(periodically ,period (flet ((done () (throw :exit-periodically nil))) (lambda () ,@body)) :name ,name :initially (lambda () ,initially) :finally (lambda () ,finally))) (defun list-threads (&key (threads (bt:all-threads)) (stream *standard-output*)) (loop :named menu :for i :from 1 :for thread :in threads :do (format stream "~&~2D) ~A~%" i thread)) (values)) (defun kill-threads (&optional (*query-io* *query-io*)) (loop :while (kill-thread))) (defun kill-thread (&optional thread (*query-io* *query-io*)) (if thread (progn (bt:destroy-thread thread) t) (loop :named select :do (let ((threads (bt:all-threads))) (list-threads :threads threads :stream *query-io*) (format *query-io* "~&Number of thread to kill (or 0 to abort): ") (let ((choice (let ((*read-eval* nil)) (read *query-io*)))) (cond ((not (integerp choice))) ((zerop choice) (format *query-io* "~&Aborted.~%") (return-from select nil)) ((<= 1 choice (length threads)) (bt:destroy-thread (nth (1- choice) threads)) (return-from select t))) (format *query-io* "~&Invalid answer, try again.~%")))))) ;; (loop :repeat 3 :do (bt:make-thread (lambda () (sleep 2232)))) ;; (kill-thread) ;;;; THE END ;;;;
4,115
Common Lisp
.lisp
92
36.097826
85
0.544096
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
37f599e31b6ac2586f739cabbb999b8ee869cc7e46654a8aefa3b8f450002c85
4,760
[ -1 ]
4,761
html-unwrap-document.lisp
informatimago_lisp/tools/html-unwrap-document.lisp
#!/usr/local/bin/clisp -ansi -q -E utf-8 ;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: html-unwrap-document ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This script takes a HTML page containing a <div class="document"> entity ;;;; and produces file containing only this element. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-10-20 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (defmacro redirecting-stdout-to-stderr (&body body) (let ((verror (gensym)) (voutput (gensym))) `(let* ((,verror nil) (,voutput (with-output-to-string (stream) (let ((*standard-output* stream) (*error-output* stream) (*trace-output* stream)) (handler-case (progn ,@body) (error (err) (setf ,verror err))))))) (when ,verror (terpri *error-output*) (princ ,voutput *error-output*) (terpri *error-output*) (princ ,verror *error-output*) (terpri *error-output*) (terpri *error-output*) #+(and clisp (not testing-script)) (ext:exit 1))))) (redirecting-stdout-to-stderr (load (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname)))) (redirecting-stdout-to-stderr (ql:quickload :com.informatimago.common-lisp)) (use-package "COM.INFORMATIMAGO.COMMON-LISP.HTML-PARSER.PARSE-HTML") (use-package "COM.INFORMATIMAGO.COMMON-LISP.HTML-BASE.ML-SEXP") (com.informatimago.common-lisp.cesarum.package:add-nickname "COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML" "<") (defun unwrap (input output) (let* ((html (child-tagged (parse-html-stream input) :html)) (head (child-tagged html :head)) (title (element-child (child-tagged head :title))) (author (value-of-attribute-named (child-tagged-and-valued head :meta :name "author") :content)) (description (value-of-attribute-named (child-tagged-and-valued head :meta :name "description") :content)) (keywords (value-of-attribute-named (child-tagged-and-valued head :meta :name "keywords") :content)) (language (or (value-of-attribute-named html :lang) (value-of-attribute-named html :xml\:lang) "en")) (class "document") (document (first (grandchildren-tagged-and-valued html :div :class class))) (id (value-of-attribute-named document :id))) (write-line "<!-- THIS FILE IS GENERATED BY html-unwrap-document -->" output) (write-line "<!-- PLEASE DO NOT EDIT THIS FILE! -->" output) (unparse-html `(:div (:class ,class :id ,id :title ,(or title "") :author ,(or author "") :description ,(or description "") :keywords ,(or keywords "") :language ,(or language "en")) ,@(element-children document)) output)) (values)) (defun main (&optional arguments) (declare (ignore arguments)) (unwrap *standard-input* *standard-output*)) #+(and clisp (not testing-script)) (progn (main ext:*args*) (ext:exit 0)) (pushnew :testing-script *features*) ;;;; THE END ;;;;
4,609
Common Lisp
.lisp
98
39.857143
115
0.57635
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
53c5073e2634de9332f06c609e7eb322951b250f7805153e1ca774ecf72026b0
4,761
[ -1 ]
4,762
dependency-cycles-test.lisp
informatimago_lisp/tools/dependency-cycles-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: dependency-cycles-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test dependency-cycles.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,786
Common Lisp
.lisp
44
39
83
0.615517
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d3ab38e8fc6d61635475f053eda9a1883dab85c8ec39a616c80048c8a2669745
4,762
[ -1 ]
4,763
pathname.lisp
informatimago_lisp/tools/pathname.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: pathname.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Pathname utilities. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-12-06 <PJB> Extracted from rc/common.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2013 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.PATHNAME" (:use "COMMON-LISP") (:shadow "MAKE-PATHNAME" "USER-HOMEDIR-PATHNAME" "TRANSLATE-LOGICAL-PATHNAME") (:export "MAKE-PATHNAME" "USER-HOMEDIR-PATHNAME" "TRANSLATE-LOGICAL-PATHNAME") (:documentation "Pathname tools.")) (in-package "COM.INFORMATIMAGO.TOOLS.PATHNAME") (defparameter *case-common-is-not-downcased-on-posix-systems* #+(or allegro ccl emacs-cl) t #-(or allegro ccl emacs-cl) nil) (defun user-homedir-pathname () "On CCL on MS-Windows, it's not the USER-HOMEDIR-PATHNAME." #+(and ccl windows-target) (let ((home (ccl::getenv "HOME"))) (if home (pathname (format nil "~A\\" home)) ;; Fucking MoCL can't handle #+#P!!! (pathname "C:\\cygwin\\home\\pjb\\"))) #-(and ccl windows-target) (cl:user-homedir-pathname)) (defun make-pathname (&key (host nil hostp) (device nil devicep) (directory nil directoryp) (name nil namep) (type nil typep) (version nil versionp) (defaults nil defaultsp) (case :local casep)) (declare (ignorable casep)) (if *case-common-is-not-downcased-on-posix-systems* (labels ((localize (object) (typecase object (list (mapcar (function localize) object)) (string (string-downcase object)) (t object))) (parameter (indicator key value) (when indicator (list key (if (eql case :common) (localize value) value))))) (apply (function cl:make-pathname) (append (parameter hostp :host host) (parameter devicep :device device) (parameter directoryp :directory directory) (parameter namep :name name) (parameter typep :type type) (parameter versionp :version version) (parameter defaultsp :defaults defaults) (list :case :local)))) (apply (function cl:make-pathname) (append (when hostp (list :host host)) (when devicep (list :device device)) (when directoryp (list :directory directory)) (when namep (list :name name)) (when typep (list :type type)) (when versionp (list :version version)) (when defaultsp (list :defaults defaults)) (when casep (list :case case)))))) (defun translate-logical-pathname (pathname) (cl:translate-logical-pathname (etypecase pathname (string (translate-logical-pathname (pathname pathname))) #-mocl ; !!!! (logical-pathname (make-pathname :host (pathname-host pathname) :device (pathname-device pathname) :directory (pathname-directory pathname) :name (pathname-name pathname) :type (pathname-type pathname) :version (pathname-version pathname) :defaults pathname :case :common)) (pathname pathname)))) ;;;; THE END ;;;;
4,985
Common Lisp
.lisp
107
36.485981
91
0.538304
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
77b080bef031f316a609e7f662030b53a3d617bb8aae755a0d34c52d9188769a
4,763
[ -1 ]
4,764
symbol-test.lisp
informatimago_lisp/tools/symbol-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: symbol-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test symbol.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.SYMBOL.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.SYMBOL") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.SYMBOL.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,731
Common Lisp
.lisp
44
37.75
83
0.605935
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
3b31c07ec4fdca501bd0cc22971391c40218d571c84aa1876045817858929c92
4,764
[ -1 ]
4,765
dummy-quicklisp.lisp
informatimago_lisp/tools/dummy-quicklisp.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: dummy-quicklisp.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines a dummy QUICKLISP package to be able to compile ;;;; packages depending on QUICKLISP even when it is not present. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-07 <PJB> Extracted from quicklisp.lisp. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") #-quicklisp (defpackage "QUICKLISP" (:nicknames "QL-DIST" "QL" "QUICKLISP-CLIENT") (:export "CLEAN" "DIST" "ENABLED-DISTS" "ENSURE-INSTALLED" "INSTALLED-RELEASES" "NAME" "PROJECT-NAME" "PROVIDED-RELEASES" "PROVIDED-SYSTEMS" "QUICKLOAD" "REGISTER-LOCAL-PROJECTS" "RELEASE" "UNINSTALL" "UPDATE-ALL-DISTS" "UPDATE-CLIENT" "WHERE-IS-SYSTEM")) #-quicklisp (defmacro quicklisp::generate-dummy-functions (&rest funames) `(progn ,@(mapcar (lambda (funame) `(defun ,funame (&rest args) (declare (ignore args)) nil)) funames))) #-quicklisp (quicklisp::generate-dummy-functions QUICKLISP:DIST QUICKLISP:ENABLED-DISTS QUICKLISP:ENSURE-INSTALLED QUICKLISP:INSTALLED-RELEASES QUICKLISP:PROVIDED-RELEASES QUICKLISP:PROVIDED-SYSTEMS QUICKLISP:QUICKLOAD QUICKLISP:REGISTER-LOCAL-PROJECTS QUICKLISP:RELEASE QUICKLISP:UNINSTALL QUICKLISP:UPDATE-ALL-DISTS QUICKLISP:UPDATE-CLIENT QUICKLISP:WHERE-IS-SYSTEM) ;;;; THE END ;;;;
2,605
Common Lisp
.lisp
66
36.787879
83
0.649704
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
88bba964caeafa257ed0ae9529125df3f2247fe86c2ea00c069eff4bb151f9bf
4,765
[ -1 ]
4,766
quicklisp.lisp
informatimago_lisp/tools/quicklisp.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: quicklisp.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Quicklisp tools. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2021-05-13 <PJB> Added QUICK-WHERE-FROM and associated functions. ;;;; 2013-12-06 <PJB> Extracted from rc/common.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2013 - 2021 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.QUICKLISP" (:use "COMMON-LISP" "QUICKLISP" "ASDF" "COM.INFORMATIMAGO.TOOLS.ASDF" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING") (:export "PRINT-SYSTEMS" "QUICK-INSTALLED-SYSTEMS" "QUICK-LIST-SYSTEMS" "QUICK-LIST-PROJECTS" "QUICK-APROPOS" "QUICK-UPDATE" "QUICK-CLEAN" "QUICK-INSTALL-ALL" "QUICK-LOAD-ALL" "QUICK-UNINSTALL" "QUICK-WHERE" "QUICK-WHERE-IS" "SYSTEM-WHERE-IS" "QUICK-WHERE-FROM" "SYSTEM-WHERE-FROM" "PROJECT-WHERE-FROM" "QUICK-DELETE" "QUICK-RELOAD" "QUICK-LOCAL-PROJECTS" "QUICK-RESET" "QUICKLOAD/NEW-PACKAGES") (:documentation "Quicklisp quick commands.")) (in-package "COM.INFORMATIMAGO.TOOLS.QUICKLISP") (defun print-systems (systems pattern &key sort) (flet ((name (thing) (cond ((ignore-errors (slot-boundp thing 'ql-dist:name)) (slot-value thing 'ql-dist:name)) ((ignore-errors (slot-boundp thing 'ql-dist:project-name)) (slot-value thing 'ql-dist:project-name))))) (let ((sorted-systems (make-array (length systems) :fill-pointer 0))) (if pattern (let ((spattern (string pattern))) (dolist (system systems) (when (search spattern (name system) :test (function char-equal)) (vector-push system sorted-systems)))) (progn (setf (fill-pointer sorted-systems) (length systems)) (replace sorted-systems systems))) (map nil (function print) (if sort (sort sorted-systems (function string<) :key (function name)) sorted-systems)) (terpri))) (values)) (defun quick-installed-systems (&optional pattern) "Print the system installed by quicklisp." (print-systems (ql-dist:installed-releases (ql-dist:dist "quicklisp")) pattern :sort t)) (defun quick-list-systems (&optional pattern) "List the quicklisp systems. If the string designator PATTERN is given, then only the systems containing it in their name are listed." (print-systems (ql-dist:provided-systems t) pattern :sort t)) (defun quick-list-projects (&optional pattern) "List the quicklisp projects (releases). If the string designator PATTERN is given, then only the projects containing it in their name are listed." (print-systems (ql-dist:provided-releases t) pattern :sort t)) (defun quick-apropos (pattern) "Search the quicklisp system matching the pattern and print them." ;; For now, we just list the systems: (print-systems (ql-dist:provided-systems t) pattern :sort t)) (defun quick-update () "Updates the quicklisp client, and all the system distributions." (ql:update-client) (ql:update-all-dists) (update-project-dir :force t)) (defun quick-clean () "Clean the quicklisp system distributions." #+#.(cl:if (cl:find-symbol "CLEAN" "QL-DIST") '(:and) '(:or)) (map nil 'ql-dist:clean (ql-dist:enabled-dists)) #-#.(cl:if (cl:find-symbol "CLEAN" "QL-DIST") '(:and) '(:or)) (error "QL-DIST:CLEAN is not available.")) (defun quick-install-all (&key verbose) "Installs all the quicklisp systems, skipping over the errors." (map nil (lambda (system) (handler-case (progn (when verbose (format *trace-output* "~&~A~%" system)) (ql-dist:ensure-installed system)) (error (err) (format *trace-output* "~&~A ~A~%" system err)))) (ql-dist:provided-systems t))) (defun quick-load-all (&key verbose) "Loads all the quicklisp systems, skipping over the errors." (map nil (lambda (system) (handler-case (ql:quickload (ql-dist:name system) :verbose verbose) (error (err) (format *trace-output* "~&~A ~A~%" system err)))) (ql-dist:provided-systems t))) (defun quick-uninstall (system &rest systems) "Uninstall the given systems releases from the quicklisp installation." (map 'list (lambda (system) (ql-dist:uninstall (ql-dist:release (string-downcase system)))) (cons system systems))) (defun quick-where-is (system &rest systems) "Says where the given systems are." #+#.(cl:if (cl:find-symbol "WHERE-IS-SYSTEM" "QUICKLISP-CLIENT") '(:and) '(:or)) (map 'list (lambda (system) (ql:where-is-system (string-downcase system))) (cons system systems)) #-#.(cl:if (cl:find-symbol "WHERE-IS-SYSTEM" "QUICKLISP-CLIENT") '(:and) '(:or)) (error "QUICKLISP-CLIENT:WHERE-IS-SYSTEM is not available.")) (defun quick-where (system &rest systems) "Says where the given systems are." (apply (function quick-where-is) system systems)) (defun quick-delete (system &rest systems) "Delete the ASDF systems so they'll be reloaded." (map 'list (lambda (system) (asdf:clear-system system)) (cons system systems))) (defun quick-reload (system &rest systems) "Delete and reload the ASDF systems." (map 'list (lambda (system) ;; (asdf-delete-system system) (format *trace-output* "~&See also M-x slime-load-system RET~%") (force-output *trace-output*) (asdf:load-system system) (ql:quickload system)) (cons system systems))) (defun quick-local-projects () "Rebuilds the local projects system index." (ql:register-local-projects)) (defun quick-reset () "Rebuilds the local projects system index." (quick-local-projects)) (defun quickload/new-packages (systems &rest args &key &allow-other-keys) "Performs quickload, and return the list of the new packages." (let ((old-ps (mapcar (function package-name) (list-all-packages)))) (apply (function ql:quickload) systems args) (let ((new-ps (mapcar (function package-name) (list-all-packages)))) (sort (set-difference new-ps old-ps :test (function string=)) (function string<))))) (defconstant +one-month+ (* 30 24 60 60 )) (defvar *projects-dir* nil) (defun update-project-dir (&key force) (symbol-macrolet ((timestamp (sexp-file-contents (merge-pathnames "timestamp" *projects-dir*) :if-does-not-exist 0))) (macrolet ((run-command-reporting-error (label command) (let ((vout (gensym)) (verr (gensym)) (vstat (gensym))) `(multiple-value-bind (,vout ,verr ,vstat) (uiop:run-program ,command :ignore-error-status t :force-shell t :output 'string :error-output 'string) (unless (zerop ,vstat) (error "~A exited with status ~D:~%~A~%~A~%" ,label ,vstat ,vout ,verr)))))) (let* ((cache-dir (merge-pathnames ".cache/" (user-homedir-pathname) nil)) (project-dir (merge-pathnames "quicklisp-projects/" cache-dir nil)) (probe (merge-pathnames "README.md" project-dir nil))) (setf *projects-dir* project-dir) (unless (probe-file probe) (ensure-directories-exist probe) (run-command-reporting-error "git cloning quicklisp-project" (format nil "cd ~S && git clone [email protected]:quicklisp/quicklisp-projects.git" (namestring cache-dir))) (setf timestamp (get-universal-time)))) (when (or force (< timestamp (- (get-universal-time) +one-month+))) (run-command-reporting-error "git pulling quicklisp-project" (format nil "cd ~S && git pull" (namestring *projects-dir*))) (setf timestamp (get-universal-time)))))) (defun project-where-from (pname) "Return the contents of the source.txt file of the project PNAME in quicklisp-projects." (update-project-dir) (split-string (string-trim #(#\newline) (text-file-contents (merge-pathnames (make-pathname :directory (list :relative "projects" pname) :name "source" :type "txt" :version nil) *projects-dir*) :if-does-not-exist nil)) " " t)) (defun system-where-is (system) "Return the path where the SYSTEM is stored (where the asd file is found)." #+#.(cl:if (cl:find-symbol "WHERE-IS-SYSTEM" "QUICKLISP-CLIENT") '(:and) '(:or)) (ql:where-is-system system) #-#.(cl:if (cl:find-symbol "WHERE-IS-SYSTEM" "QUICKLISP-CLIENT") '(:and) '(:or)) nil) (defun system-where-from (system) "Return a list indicating where the project in the release that provided the SYSTEM originated from. This is the contents of the source.txt file of the project in quicklisp-projects." (let ((local-systems (ql:list-local-systems)) (sname (asdf-system-name (asdf:find-system system)))) (if (member sname local-systems :test (function string=)) (list :system sname :distribution :local :directory (system-where-is sname) :where-from nil #|TODO: we could look in the directory if there's a .git and show-remotes |#) (let* ((system (ql-dist:find-system sname)) (release (ql-dist:release system))) (if release (let* ((distribution (ql-dist:dist system)) (dname (ql-dist:name distribution)) (pname (and release (ql-dist:project-name release))) (wfrom (cond ((null pname) '()) ((string= dname "quicklisp") (project-where-from pname)) (t '())))) (list :system sname :distribution dname :directory (system-where-is sname) :where-from wfrom)) (list :system sname :distribution nil :directory (system-where-is sname) :where-from '())))))) (defun quick-where-from (system &rest systems) "Says where the systems are from." (dolist (sys (cons system systems)) (print (system-where-from sys))) (terpri) (values)) ;;;; THE END ;;;;
12,270
Common Lisp
.lisp
257
38.081712
116
0.589399
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9e2618b0b78dbaf0f7e878f10e39713b65a02552a36e75a9a7aaa4d7b7411f1d
4,766
[ -1 ]
4,767
pathname-test.lisp
informatimago_lisp/tools/pathname-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: pathname-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test pathname.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.PATHNAME.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.PATHNAME") (:shadowing-import-from "COM.INFORMATIMAGO.TOOLS.PATHNAME" "MAKE-PATHNAME" "USER-HOMEDIR-PATHNAME" "TRANSLATE-LOGICAL-PATHNAME") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.PATHNAME.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,950
Common Lisp
.lisp
48
37.416667
83
0.596842
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2994983937060380fbaa2d6988ee397404f8c0b1699f7d23a5fa76355f9c3638
4,767
[ -1 ]
4,768
undefmethod-test.lisp
informatimago_lisp/tools/undefmethod-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: undefmethod-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test undefmethod. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; GPL3 ;;;; ;;;; Copyright Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.UNDEFMETHOD.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.UNDEFMETHOD") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.UNDEFMETHOD.TEST") (defclass c () ()) (defgeneric m (o)) (define-test test/undefmethod () (eval `(defmethod m ((self c)) 'hi)) (assert-true (find-method (function m) '() '(c) nil)) (eval `(undefmethod m ((self c)) 'hi)) (assert-false (find-method (function m) '() '(c) nil))) (define-test test/all () (test/undefmethod)) ;;;; THE END ;;;;
2,018
Common Lisp
.lisp
51
37.862745
78
0.609781
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
471d26c7959a89554b8c2b50b00f0a03130b0226c15951b1cd36c958d515e64f
4,768
[ -1 ]
4,769
unintern.lisp
informatimago_lisp/tools/unintern.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: unintern.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; XXX ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-04-07 <PJB> Extracted from analysis.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (ql:quickload :com.informatimago.common-lisp.lisp-text) " com.informatimago.common-lisp.lisp-text.source-text uses indifferentiated source-token instances to represents tokens (symbols, numbers, the dot of pairs). This is not practical to analyze the sources. " (defpackage "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.UNINTERN" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.LISP-TEXT.SOURCE-TEXT") (:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.READER" "COPY-READTABLE" "READTABLE-CASE" "SET-DISPATCH-MACRO-CHARACTER") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.READER" "DEFPARSER" "PARSE-TOKEN" "PARSE-DECIMAL-INTEGER-TOKEN" "PARSE-INTEGER-TOKEN" "PARSE-RATIO-TOKEN" "PARSE-FLOAT-1-TOKEN" "PARSE-FLOAT-2-TOKEN") (:export) (:documentation " ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.UNINTERN") (defvar *system-packages* '("COMMON-LISP" "KEYWORD") "List of names of the packages where we intern the symbols with CL:INTERN.") (defparser parse-symbol-token (token) "symbol ::= symbol-name symbol ::= package-marker symbol-name symbol ::= package-marker package-marker symbol-name symbol ::= package-name package-marker symbol-name symbol ::= package-name package-marker package-marker symbol-name symbol-name ::= {alphabetic}+ package-name ::= {alphabetic}+ " (let ((colon (position-if (lambda (traits) (traitp +ct-package-marker+ traits)) (token-traits token)))) (if colon (let* ((double-colon (and (< (1+ colon) (token-length token)) (traitp +ct-package-marker+ (token-char-traits token (1+ colon))))) (pname (subseq (token-text token) 0 colon)) (sname (subseq (token-text token) (+ colon (if double-colon 2 1))))) (when (position-if (lambda (traits) (traitp +ct-package-marker+ traits)) (token-traits token) :start (+ colon (if double-colon 2 1))) (reject t "too many package markers in token ~s" (token-text token))) (when (zerop colon) ;; keywords always exist, so let's intern them before finding them. (setf pname "keyword") (intern sname pname)) ;; the following form thanks to andrew philpot <[email protected]> ;; corrects a bug when reading with double-colon uninterned symbols: (if (find-package pname) (if double-colon (accept 'symbol (intern sname pname)) (multiple-value-bind (sym where) (find-symbol sname pname) (if (eq where :external) (accept 'symbol sym) (accept 'symbol (restart-case (error 'symbol-missing-in-package-error :stream *input-stream* :package-name pname :symbol-name sname) (make-symbol (&rest rest) :report "make the missing symbol in the specified package" (declare (ignore rest)) (intern sname pname))))))) (accept 'symbol (restart-case (error 'symbol-in-missing-package-error :stream *input-stream* :package-name pname :symbol-name sname) (intern-here (&rest rest) :report "intern the symbol in the current package, instead" (declare (ignore rest)) (intern sname)) (return-uninterned (&rest rest) :report "return an uninterned symbol, instead" (declare (ignore rest)) (make-symbol sname)))))) ;; no colon in token, let's just intern the symbol in the current package : (accept 'symbol (intern (token-text token) *package*))))) (defun %parse-token (token) " return: okp ; the parsed lisp object if okp, or an error message if (not okp) " (let ((message nil)) (macrolet ((rom (&body body) "result or message" (if (null body) 'nil (let ((vals (gensym))) `(let ((,vals (multiple-value-list ,(car body)))) ;; (format *trace-output* "~s --> ~s~%" ',(car body) ,vals) (if (first ,vals) (values-list ,vals) (progn (when (second ,vals) (setf message (third ,vals))) (rom ,@(cdr body))))))))) (multiple-value-bind (ok type object) (rom (parse-decimal-integer-token token) (parse-integer-token token) (parse-ratio-token token) (parse-float-1-token token) (parse-float-2-token token) ;; (parse-consing-dot-token token) (parse-symbol-token token)) (declare (ignorable type)) ;; (format *trace-output* "ok = ~s ; type = ~s ; object = ~s~%" ;; ok type object) (values ok (if ok object message)))))) (defparameter *sources* (sort (directory "pw-src/**/*.lisp") (function string<) :key (function namestring))) ;; (with-open-file (source (first *sources*)) ;; (cons (pathname source) ;; (loop ;; :with eof = (gensym "EOF") ;; :for sexp = (com.informatimago.common-lisp.lisp-reader.reader:read source nil eof) ;; :until (eq eof sexp) ;; :collect sexp))) (defvar *ccl-source-readtable* (copy-readtable *source-readtable*)) (defvar *ccl-ffi-readtable* (copy-readtable *source-readtable*)) (setf (readtable-case *ccl-ffi-readtable*) :preserve) (defclass source-ccl-point (source-object dispatch-macro-character-mixin) ((point :initarg :point :accessor source-ccl-point-point))) (defun reader-dispatch-macro-ccl-point (stream sub-char arg) (com.informatimago.common-lisp.lisp-text.source-text::building-reader-dispatch-macro-source-object stream arg sub-char 'source-ccl-point :point (source-read stream t nil t))) (set-dispatch-macro-character #\# #\@ (function reader-dispatch-macro-ccl-point) *ccl-source-readtable*) (defclass source-ccl-ffi (source-object dispatch-macro-character-mixin) ((name :initarg :fname :accessor source-ccl-ffi-name))) (defun ccl-reader-dispatch-macro-ffi (stream sub-char arg) (com.informatimago.common-lisp.lisp-text.source-text::building-reader-dispatch-macro-source-object stream arg sub-char 'source-ccl-ffi :name (let ((*source-readtable* *ccl-ffi-readtable*)) (source-read stream t nil t)))) (set-dispatch-macro-character #\# #\_ (function ccl-reader-dispatch-macro-ffi) *ccl-source-readtable*) (defparameter *contents* (let ((contents '())) (dolist (source *sources* contents) (with-open-file (stream source) (push (cons (pathname source) (loop :for sexp = (source-read stream nil stream) :until (eq sexp stream) :collect sexp)) contents))))) ;;;; THE END ;;;;
9,114
Common Lisp
.lisp
189
37.650794
115
0.564636
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
96b89eeb40671fb9b341c7bd5a0802d9cd162f8cef42363dfa9bc8cce89abb52
4,769
[ -1 ]
4,770
script-test.lisp
informatimago_lisp/tools/script-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: script-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test script.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.SCRIPT.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.SCRIPT") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.SCRIPT.TEST") (define-test test/mapconcat () (loop :for (expression expected) :in '(((mapconcat (lambda (x) (and x (string-downcase x))) '("one" two three nil "five") "-") "one-two-three--five") ((mapconcat (lambda (x) (and x (string-downcase x))) '("one") "-") "one") ((mapconcat (lambda (x) (and x (string-downcase x))) '(nil) "-") "") ((mapconcat (lambda (x) (and x (string-downcase x))) '() "-") "") ((mapconcat (lambda (x) (and x (string-downcase x))) #("one" two three nil "five") "-") "one-two-three--five") ((mapconcat (lambda (x) (and x (string-downcase x))) #("one") "-") "one") ((mapconcat (lambda (x) (and x (string-downcase x))) #(nil) "-") "") ((mapconcat (lambda (x) (and x (string-downcase x))) #() "-") "")) :do (assert-true (equal (eval expression) expected) () "~%Expression: ~S~%Expected: ~S~%Got: ~S~%" expression expected (eval expression)))) (define-test test/all () (test/mapconcat)) ;;;; THE END ;;;;
2,935
Common Lisp
.lisp
66
37.848485
103
0.536126
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
066aa6a7731fc95a5822e44dc171cacc1853561e16c26b992909f4d1ebbfaaf5
4,770
[ -1 ]
4,771
load-asdf.lisp
informatimago_lisp/tools/load-asdf.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: load-asdf.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This file requires or loads ASDF, and ASDF-BINARY-LOCATIONS. ;;;; (With ASDF2, it only configures ASDF with binary locations, ;;;; without the use of an external system ASDF-BINARY-LOCATIONS). ;;;; ;;;; Parameters: ;;;; ;;;; cl-user::*asdf-source* ;;;; ;;;; Should be bound to the path of the asdf.lisp source file. ;;;; ;;;; ;;;; cl-user::*asdf-binary-locations-directory* ;;;; ;;;; Should be bound to the path of the directory of the ;;;; asdf-binary-location system (where the ;;;; asdf-binary-location.asd file lies). ;;;; ;;;; This is not used if ASDF2 is available. ;;;; ;;;; Define these two variables, and load this file. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2010-11-06 <PJB> Extracted from compile-with-asdf.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2010 - 2016 ;;;; ;;;; 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/> ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (defvar *asdf-source* #p"/data/lisp/packages/net/common-lisp/projects/asdf/asdf/asdf.lisp") (defvar *asdf-binary-locations-directory* #p"/data/lisp/packages/net/common-lisp/projects/asdf-binary-locations/asdf-binary-locations/") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; ASDF ;;; (unless (find-package :asdf) (handler-case (require :asdf) (error () (load (compile-file *asdf-source*))))) (defun push-asdf-repository (path) (pushnew path asdf:*central-registry* :test #'equal)) (defun asdf-load (&rest systems) (mapcar (lambda (system) (asdf:operate 'asdf:load-op system)) systems)) (defun asdf-delete-system (&rest systems) (mapc (lambda (system) (remhash (string-downcase system) asdf::*defined-systems*)) systems) (values)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; ASDF-BINARY-LOCATIONS ;;; (defun hostname () (let ((outpath (format nil "/tmp/hostname-~8,'0X.txt" (random #x100000000)))) (asdf:run-shell-command "( hostname --fqdn 2>/dev/null || hostname --long 2>/dev/null || hostname ) > ~A" outpath) (prog1 (with-open-file (hostname outpath) (read-line hostname)) (delete-file outpath)))) (let ((sym (find-symbol "ENABLE-ASDF-BINARY-LOCATIONS-COMPATIBILITY" "ASDF"))) (when (and sym (fboundp sym)) (push :has-asdf-enable-asdf-binary-locations-compatibility *features*))) #+has-asdf-enable-asdf-binary-locations-compatibility (progn (format *trace-output* "enable-asdf-binary-locations-compatibility ~%") (asdf:enable-asdf-binary-locations-compatibility :centralize-lisp-binaries t :default-toplevel-directory (merge-pathnames (format nil ".cache/common-lisp/~A/" (hostname)) (user-homedir-pathname) nil) :include-per-user-information nil :map-all-source-files t :source-to-target-mappings nil)) #-has-asdf-enable-asdf-binary-locations-compatibility (progn (push-asdf-repository *asdf-binary-locations-directory*) (asdf-load :asdf-binary-locations)) #-has-asdf-enable-asdf-binary-locations-compatibility (progn (format *trace-output* "enable-asdf-binary-locations-compatibility ~%") (setf asdf:*centralize-lisp-binaries* t asdf:*include-per-user-information* nil asdf:*default-toplevel-directory* (merge-pathnames (format nil ".cache/common-lisp/~A/" (hostname)) (user-homedir-pathname) nil) asdf:*source-to-target-mappings* '())) ;;;; THE END ;;;;
4,681
Common Lisp
.lisp
114
38.026316
98
0.634505
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7f7d26530f4a51cd2cdcf35e28a767a1d012b5cd91c87bb58bc899556f433e25
4,771
[ -1 ]
4,772
com.informatimago.tools.quicklisp.test.asd
informatimago_lisp/tools/com.informatimago.tools.quicklisp.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.tools.quicklisp.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.tools.quicklisp.test system. ;;;; Tests the com.informatimago.tools.quicklisp system. ;;;; ;;;;USAGE: ;;;; ;;;;AUTHORS: ;;;; <PJB> Pascal J. Bourguignon ;;;;MODIFICATIONS: ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS: ;;;; ;;;;LEGAL: ;;;; ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.tools.quicklisp.test" ;; system attributes: :description "Tests the com.informatimago.tools.quicklisp system." :author "Pascal J. Bourguignon" :maintainer "Pascal J. Bourguignon" :licence "GPL3" ;; component attributes: :version "1.2.0" :properties ((#:author-email . "[email protected]") (#:date . "Winter 2015") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.tools.quicklisp.test/") ((#:albert #:formats) "docbook") ((#:albert #:docbook #:template) . "book") ((#:albert #:docbook #:bgcolor) . "white") ((#:albert #:docbook #:textcolor) . "black")) #+asdf-unicode :encoding #+asdf-unicode :utf-8 :depends-on ("com.informatimago.common-lisp.cesarum" "com.informatimago.tools.quicklisp") :components ((:file "quicklisp-test" :depends-on ()) (:file "asdf-test" :depends-on ())) #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) (let ((*package* (find-package "COM.INFORMATIMAGO.TOOLS.QUICKLISP.TEST"))) (uiop:symbol-call "COM.INFORMATIMAGO.TOOLS.QUICKLISP.TEST" "TEST/ALL")) (let ((*package* (find-package "COM.INFORMATIMAGO.TOOLS.ASDF.TEST"))) (uiop:symbol-call "COM.INFORMATIMAGO.TOOLS.ASDF.TEST" "TEST/ALL")))) ;;;; THE END ;;;;
3,213
Common Lisp
.lisp
70
38.242857
102
0.544094
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9f31e9c5d5ebc5f5ff375da9cca440bad7231c4d7073663e5d6d5f07538ee9c1
4,772
[ -1 ]
4,773
init-asdf.lisp
informatimago_lisp/tools/init-asdf.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: compile-with-asdf.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Register the com.informatimago.common-lisp systems with ASDF. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2010-11-01 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2010 - 2016 ;;;; ;;;; 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/> ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (defvar *asdf-source* (truename (merge-pathnames (make-pathname :name "ASDF" :type "LISP" :case :common) *load-pathname*))) ;; (defvar *asdf-binary-locations-directory* ;; #p"/data/lisp/packages/net/common-lisp/projects/asdf-binary-locations/asdf-binary-locations/") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; ASDF ;;; (unless (find-package :asdf) (handler-case (require :asdf) (error () (load (compile-file *asdf-source*))))) (defun push-asdf-repository (path) (pushnew path asdf:*central-registry* :test #'equal)) (defun asdf-load (&rest systems) (mapcar (lambda (system) (asdf:operate 'asdf:load-op system)) systems)) (defun asdf-delete-system (&rest systems) (mapc (lambda (system) (remhash (string-downcase system) asdf::*defined-systems*)) systems) (values)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; ASDF-BINARY-LOCATIONS ;;; (defun hostname () (let ((outpath (format nil "/tmp/hostname-~8,'0X.txt" (random #x100000000)))) (asdf:run-shell-command "( hostname --fqdn 2>/dev/null || hostname --long 2>/dev/null || hostname ) > ~A" outpath) (prog1 (with-open-file (hostname outpath) (read-line hostname)) (delete-file outpath)))) (let ((sym (find-symbol "ENABLE-ASDF-BINARY-LOCATIONS-COMPATIBILITY" "ASDF"))) (when (and sym (fboundp sym)) (push :has-asdf-enable-asdf-binary-locations-compatibility *features*))) #+has-asdf-enable-asdf-binary-locations-compatibility (progn (format *trace-output* "~&enable-asdf-binary-locations-compatibility ~%") (asdf:enable-asdf-binary-locations-compatibility :centralize-lisp-binaries t :default-toplevel-directory (merge-pathnames (format nil ".cache/common-lisp/~A/" (hostname)) (truename (user-homedir-pathname)) nil) :include-per-user-information nil :map-all-source-files t :source-to-target-mappings nil)) ;; We need (truename (user-homedir-pathname)) because in cmucl (user-homedir-pathname) ;; is a search path, and that cannot be merged... ;; #-has-asdf-enable-asdf-binary-locations-compatibility ;; (progn ;; (push-asdf-repository *asdf-binary-locations-directory*) ;; (asdf-load :asdf-binary-locations)) #-has-asdf-enable-asdf-binary-locations-compatibility (progn (format *trace-output* "~&enable-asdf-binary-locations-compatibility ~%") (setf asdf:*centralize-lisp-binaries* t asdf:*include-per-user-information* nil asdf:*default-toplevel-directory* (merge-pathnames (format nil ".cache/common-lisp/~A/" (hostname)) (truename (user-homedir-pathname)) nil) asdf:*source-to-target-mappings* '())) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Registering com.informatimago.common-lisp systems. ;;; (setf asdf:*central-registry* (append (remove-duplicates (mapcar (lambda (path) (make-pathname :name nil :type nil :version nil :defaults path)) #-abcl (directory "**/*.asd") #+abcl '(#p"/home/pjb/src/git/public/lisp/tools/com.informatimago.tools.make-depends.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/diagram/com.informatimago.common-lisp.diagram.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/html-base/com.informatimago.common-lisp.html-base.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/invoice/com.informatimago.common-lisp.invoice.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/arithmetic/com.informatimago.common-lisp.arithmetic.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/picture/com.informatimago.common-lisp.picture.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/lisp-text/com.informatimago.common-lisp.lisp-text.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/rfc3548/com.informatimago.common-lisp.rfc3548.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/lisp-sexp/com.informatimago.common-lisp.lisp-sexp.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/unix/com.informatimago.common-lisp.unix.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/parser/com.informatimago.common-lisp.parser.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/csv/com.informatimago.common-lisp.csv.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/bank/com.informatimago.common-lisp.bank.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/http/com.informatimago.common-lisp.http.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/lisp-reader/com.informatimago.common-lisp.lisp-reader.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/lisp/com.informatimago.common-lisp.lisp.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/graphviz/com.informatimago.common-lisp.graphviz.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/html-parser/com.informatimago.common-lisp.html-parser.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/ed/com.informatimago.common-lisp.ed.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/rfc2822/com.informatimago.common-lisp.rfc2822.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/html-generator/com.informatimago.common-lisp.html-generator.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/cxx/com.informatimago.common-lisp.cxx.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/interactive/com.informatimago.common-lisp.interactive.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/data-encoding/com.informatimago.common-lisp.data-encoding.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/cesarum/com.informatimago.common-lisp.cesarum.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/regexp/com.informatimago.common-lisp.regexp.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/heap/com.informatimago.common-lisp.heap.asd" #p"/home/pjb/src/git/public/lisp/common-lisp/com.informatimago.common-lisp.asd" #p"/home/pjb/src/git/public/lisp/sbcl/com.informatimago.sbcl.asd" #p"/home/pjb/src/git/public/lisp/susv3/com.informatimago.susv3.asd" #p"/home/pjb/src/git/public/lisp/clisp/com.informatimago.clisp.asd" #p"/home/pjb/src/git/public/lisp/clext/com.informatimago.clext.asd" #p"/home/pjb/src/git/public/lisp/clmisc/com.informatimago.clmisc.asd" #p"/home/pjb/src/git/public/lisp/cl-posix/cliki/cliki.asd" #p"/home/pjb/src/git/public/lisp/cl-posix/cliki/clposixcliki.asd")) :test (function equalp)) asdf:*central-registry*)) ;;;; THE END ;;;;
8,758
Common Lisp
.lisp
146
50.219178
134
0.620212
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9e2972d0ac35cdbc25f40ac450db52b9c5d40833b18eeb441790bac15fbcf913
4,773
[ -1 ]
4,774
summary.lisp
informatimago_lisp/tools/summary.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: summary.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: UNIX ;;;;USER-INTERFACE: UNIX ;;;;DESCRIPTION ;;;; ;;;; This script generates HTML summaries of lisp packages. ;;;; ;;;;USAGE ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Extracted from make-depends.lisp ;;;; 2003-05-04 <PJB> Converted to Common-Lisp from emacs. ;;;; 2002-11-16 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2002 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML")) #-mocl (eval-when (:compile-toplevel :load-toplevel :execute) (com.informatimago.common-lisp.cesarum.package:add-nickname "COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML" "HTML")) (defpackage "COM.INFORMATIMAGO.TOOLS.SUMMARY" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS" "COM.INFORMATIMAGO.TOOLS.SOURCE") (:export "GENERATE-SUMMARY") (:documentation " This script generates HTML summaries of lisp packages. USAGE (generate-summary '(\"read-source\") :repository-url (lambda (path) (format nil \"http://localhost/doc/~A.html\" (translate-logical-pathname path)))) LICENSE AGPL3 Copyright Pascal J. Bourguignon 2002 - 2015 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/> ")) (in-package "COM.INFORMATIMAGO.TOOLS.SUMMARY") (defun generate-summary (sources &key (summary-path #p"SUMMARY.HTML") (character-set "US-ASCII") (source-type "LISP") (verbose nil) (repository-url nil)) "Generates a HTML summary of the sources" (assert (functionp repository-url) (repository-url) "REPOSITORY-URL must be a (function (pathname) string)") (let ((cs (etypecase character-set (character-set character-set) (string (find-character-set character-set)) (symbol (find-character-set (string character-set)))))) (unless cs (error "Cannot find the character set ~A" character-set)) (with-open-file (html summary-path :direction :output :if-does-not-exist :create :if-exists :supersede :external-format (character-set-to-lisp-encoding cs)) (html:with-html-output (html :encoding cs) (html:doctype :transitional (html:comment "-*- coding:~A -*-" (character-set-to-emacs-encoding cs)) (html:html - (html:head - (html:title - (html:pcdata "Summary")) (html:meta (list :http-equiv "Content-Type" :content (format nil "text/html;charset=~A" (character-set-to-mime-encoding cs))))) (html:body - (dolist (source sources) (let* ((path (make-pathname :name (string-downcase source) :type source-type :case :local)) (source-file (get-source-file path)) (header (source-file-header source-file)) (package (or (header-slot header :package) (first (source-file-packages-defined source-file)) ;; for files without a package (eg emacs files) ;; we make a pseudo-package named as the file. (make-instance 'source-package :name (pathname-name path) :nicknames '() :documentation nil :use '() :shadow '() :shadowing-import-from '() :import-from '() :export '() :intern '())))) (when verbose (format *trace-output* ";; Processing ~S~%" source) (format *trace-output* ";; PATH = ~S~%" path) ;;(format *trace-output* ";; HEADER = ~S~%" header) (format *trace-output* ";; PACKAGE = ~S~%" (source-package-name package)) (finish-output *trace-output*)) (unless (header-slot header :noweb) (html:li - (html:tt - (html:b - (html:a (:href (funcall repository-url (com.informatimago.common-lisp.cesarum.package:package-pathname (source-package-name package)))) (html:pcdata "~A" (source-package-name package))))) (html:pre - (dolist (line (header-description header)) (html:cdata "~A~%" line)))))))))))))) ;;;; THE END ;;;;
7,473
Common Lisp
.lisp
148
36.689189
109
0.52839
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9e6bc71435fa5710430eb6866981a2cf8d28c1b6eb5dd7f7a63f3e9370ccf7cc
4,774
[ -1 ]
4,775
loader.lisp
informatimago_lisp/tools/loader.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) #|| (cd #P"~/works/patchwork/") (load "loader.lisp") ||# (pushnew #P"~/works/patchwork/tools/" asdf:*central-registry* :test (function equalp)) (ql:quickload :com.informatimago.check-asdf) (com.informatimago.check-asdf:check-asdf-system-file #P"~/works/patchwork/patchwork/src/mclgui/mclgui.asd") (com.informatimago.check-asdf:check-asdf-system-file #P"~/works/patchwork/patchwork/src/patchwork.asd") #|| (cl:in-package :cl-user) (cd #P"~/works/patchwork/") (pushnew #P"~/works/patchwork/pw-src/" asdf:*central-registry* :test (function equalp)) (defun delete-pw-packages () (loop :while (some 'identity (mapcar (lambda (p) (ignore-errors (delete-package p))) '("C-GET-NOTE-SLOTS" "C-GET-SELECTIONS" "C-LIST-ITEM" "C-LIST-ITEM-H" "C-PATCH-ACCUM" "C-PATCH-BUFFER" "C-PATCH-CHORD-LINE" "C-PATCH-FILE-BUFFER" "C-PATCH-LIST-EDITOR" "C-PW-MIDI-IN" "C-PW-SEND-MIDI-NOTE" "C-PW-TEXT-BOX" "C-PW-TEXT-INPUT" "C-TABLE-WINDOW" "C-TABLE-WINDOW-H" "CLENI" "CLPF-UTIL" "COMBINATORIAL-INTERV" "EPW" "FFI" "LELISP-MACROS" "MIDI" "MIDISHARE" "PATCH-WORK" "PW" "PW-APPLEEVENT" "PW-MACOSX" "PW-STYPE" "SCHEDULER" "QUANTIZING" "USER-ABSTRACTION" "USER-COMP-ABSTR" "USER-SUPPLIED-IN-OUTS"))))) (ql:quickload :patchwork) ||# #|| (cl:in-package :cl-user) (cd #P"~/works/patchwork/tools/") (load "dependency-cycles") (load "asdf-file") (load "read-sources") (com.informatimago.read-sources::analyse-patchwork) (com.informatimago.read-sources::print-objc-class-hierarchy) (cl:in-package "COM.INFORMATIMAGO.ASDF-FILE") (progn ;; (load-asdf-system #P"~/works/patchwork/patchwork/src/mclgui/mclgui.asd") (load-asdf-system #P"~/works/patchwork/pw-src/patchwork.asd") (setf *sorted-files* (topological-sort (hash-table-values *asdf-files*) (function dependencies))) (if (= (length *sorted-files*) (hash-table-count *asdf-files*)) (format t "~&No cycle among files. ~%") (format t "~&The :depends-on relationship between files contains cycles! ~ ~%It should be a tree.~%")) (report-problems (hash-table-values *asdf-files*))) (com.informatimago.read-sources::generate-classes-hierarchy) ||# ;; (sort (mapcar (lambda (p) (namestring (make-pathname :type nil :version nil :defaults (enough-namestring p #P"/home/pjb/works/patchwork/pw-src/")))) *sources*) ;; 'string<) #|| (cl:in-package :cl-user) (cd #P"~/works/patchwork/") (pushnew #P"~/works/patchwork/src/xref/" asdf:*central-registry* :test (function equalp)) (ql:quickload :xref) (load #P"~/works/patchwork/src/xref/reader-setup.lisp") (load #P"~/works/patchwork/analyze.lisp") (cl:in-package :rp-user) (eval-when (:compile-toplevel) (load (compile-file "package-symbols.lisp"))) (eval-when (:execute) (load "package-symbols.lisp")) ;; (list-all-packages) ;; (mapcar (lambda (f) (funcall f :midi)) ;; `(,#'package-symbols ;; ,#'package-external-symbols ;; ,(lambda (p) ;; (set-difference (package-imported-symbols p) ;; (package-external-symbols :cl))))) ;; ;; (nil ;; (#3=MIDI:MIDI-OPEN #2=MIDI:MIDI-WRITE #1=MIDI:MIDI-CLOSE) ;; (MIDI::*PLAYER* MIDI::*PW-REFNUM* MIDI::MIDI-RESET #1# #2# #3#)) ||#
4,390
Common Lisp
.lisp
92
33.815217
162
0.512899
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
789f78fde31910b9e34dd2098c6df3fdf616bf068455b6a624e7928dcf4ac053
4,775
[ -1 ]
4,776
generate.lisp
informatimago_lisp/tools/generate.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (quick-load-all) (defun save-program (name &key init-file main) #+ccl (ccl::save-application name :toplevel-function (when main (lambda () (handler-case (funcall main (rest ccl:*command-line-argument-list*)) (error (err) (finish-output *standard-output*) (finish-output *trace-output*) (format *error-output* "~%~A~%" err) (finish-output *error-output*) (ccl:quit 1))) (finish-output *standard-output*) (finish-output *trace-output*) (finish-output *error-output*) (ccl:quit 0))) :init-file init-file :mode #o755 :prepend-kernel t :error-handler t) #-(or ccl) (error "Not implemented for ~A" (lisp-implementation-type)))
1,608
Common Lisp
.lisp
24
29
112
0.325332
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ffe768197997a4013c1c445636a8f52e2f0f6e097082229a5b25312f291eb4f8
4,776
[ -1 ]
4,777
common-lisp-compile.lisp
informatimago_lisp/tools/common-lisp-compile.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: compile.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Replaces the Makefile. ;;;; ;;;; Usage: (load "compile.lisp") ;;;; ;;;; will compile all outdated files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-08-13 <PJB> Added generation of ASD file and use of ASDF. ;;;; 2004-07-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (defpackage "COM.INFORMATIMAGO.COMMON-LISP.COMPILE" ;; (:use "COMMON-LISP") ;; (:export "MAIN")) ;; (in-package "COM.INFORMATIMAGO.COMMON-LISP.COMPILE") ;;; Not used yet: (defvar *prefix* "/usr/local/") (defvar *module* "common-lisp") (defvar *package-path* "com/informatimago/common-lisp") ;;; ---- (defun logger (ctrl &rest args) (format *trace-output* "~&;;;;~%;;;; ~?~%;;;;~%" ctrl args)) (logger "*** COMPILING COM.INFORMATIMAGO.COMMON-LISP ***") (load "init.lisp") ;; package.lisp is loaded by init.lisp. ;;(package:load-package :com.informatimago.common-lisp.make-depends) (setf package:*package-verbose* nil) ;; Load make-depends dependencies: (defvar *make-depends-dependencies* '(package source-form utility ecma048 list string character-sets ascii stream file html make-depends)) (logger "COMPILE.LISP LOADING DEPENDENCIES") (dolist (file *make-depends-dependencies*) (load (make-pathname :name (string file) :type "LISP" :version nil :case :common :defaults (or *load-pathname* *default-pathname-defaults*)))) #+(or allegro ccl ecl) (load (compile-file #p"PACKAGES:net;sourceforge;cclan;asdf;asdf.lisp")) #-(or allegro ccl ecl) (load (compile-file #p"PACKAGES:NET;SOURCEFORGE;CCLAN;ASDF;ASDF.LISP")) (logger "COMPILE.LISP LOADED DEPENDENCIES") (push (function package:package-system-definition) asdf:*system-definition-search-functions*) (defparameter *sources* '( package source-form ; used by READER and UTILITY, etc. reader ; used by SOURCE-TEXT source-text version script utility ascii ; = iso646-006 (US) ecma048 ; = iso6429 list dll queue array string stream file ;; file uses stream peek-stream scanner parser ;; avl ;; bbtree llrbtree dictionary bset brelation graf graph graph-dot graph-diagram combination pmatch picture memory heap activity message-queue float-binio data-encoding cons-to-ascii tree-to-ascii tree-to-diagram regexp-posix regexp-emacs rfc2822 rfc3548 iso639a iso3166 iso4217 character-sets ; (previously IATA-CHARACTER-SETS) with implementation specific stuff.. html-entities html hquery htrans database parse-html cache ; a generic disk-based cache. aliases passwd group primes tea raiden make-depends cxx ; Simple C++ Parser for call graph analysis. csv ; Coma-Separated-Values files. iban ; Internation Bank Account Number. rib ; Relevés d'Identité Bancaires. invoice ; my personal accounting and invoicing package. browser ; a file browser (and cd/pwd/pushd/popd/ls/cat/more cmds. ed ; a simple editor, for ; common-lisp implementations ; lacking a COMMON-LISP:EDIT function... interactive )) (defparameter *source-type* "lisp") (defun version++ (&optional path) " DO: Increment the version compilation number. The version is persistent, stored in a file named VERSION.DAT in the same directory as *LOAD-PATHNAME*, or at PATH. RETURN: The version as a string \"major.minor.compilation\" " (flet ((read-version (file) (loop :for line = (read-line file nil nil) :for =pos = (when line (position (character "=") line)) :while line :when =pos :collect (list (intern (string-upcase (subseq line 0 =pos)) "KEYWORD") (read-from-string (subseq line (1+ =pos))))))) (let* ((default-path (or *load-pathname* *default-pathname-defaults*)) (version.path (or path (make-pathname :name "VERSION" :type "DAT" :version :newest :defaults default-path))) (version (with-open-file (file version.path :direction :input :if-does-not-exist :error) (read-version file))) (version.major (or (second (assoc :major version)) 0)) (version.minor (or (second (assoc :minor version)) 0)) (version.compilation (1+ (or (second (assoc :compilation version)) 0))) (new-version `((:major ,version.major) (:minor ,version.minor) (:compilation ,version.compilation)))) (with-open-file (file version.path :direction :output :if-does-not-exist :create :if-exists :supersede) (format file "~(~:{~A=~A~%~}~)" new-version)) (values (format nil "~A.~A.~A" version.major version.minor version.compilation) version.major version.minor version.compilation)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Generate the asdf system file, loading the sources. (logger "GENERATING THE ASDF SYSTEM FILE") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends:generate-asd :com.informatimago.common-lisp *sources* *source-type* :version (version++) :implicit-dependencies '("package") :vanillap t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Now, we generate a summary.html page. ;;; (logger "GENERATING THE SUMMARY.HTML") (handler-bind ((warning #'muffle-warning)) (com.informatimago.common-lisp.make-depends:generate-summary *sources* :verbose nil :source-type *source-type* :summary-path "summary.html" :character-set "UTF-8" :repository-url (lambda (pp) (format nil ;; "http://darcs.informatimago.com~ ;; /darcs/public/lisp/~(~A/~A~).lisp" ;; "com/informatimago/~(~A/~A~).lisp" "~(~*~A~).lisp" (car (last (pathname-directory pp))) (pathname-name pp))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Cleanup before asdf:load-op: ;;; we delete the package to let asdf:load-op load them cleanly. ;;; (logger "CLEANING THE LOADED PACKAGES") (defun package-use*-package-p (p q) " RETURN: Whether the package P uses the package Q, or a package that uses the package Q. NOTE: By definition, (PACKAGE-USE*-PACKAGE-P X X) " (setf p (find-package p) q (find-package q)) (loop :with processed = '() :with used = (list p) :while used ;; :do (print (list used processed)) :do (let ((current (pop used))) (if (eq current q) (return-from package-use*-package-p t) (progn (push current processed) (dolist (new (package-use-list current)) (unless (member new processed) (pushnew new used)))))) :finally (return-from package-use*-package-p nil))) (defun topological-sort (nodes lessp) " RETURN: A list of NODES sorted topologically according to the partial order function LESSP. If there are cycles (discounting reflexivity), then the list returned won't contain all the NODES. " (loop :with sorted = '() :with incoming = (map 'vector (lambda (to) (loop :for from :in nodes :when (and (not (eq from to)) (funcall lessp from to)) :sum 1)) nodes) :with q = (loop :for node :in nodes :for inco :across incoming :when (zerop inco) :collect node) :while q :do (let ((n (pop q))) (push n sorted) (loop :for m :in nodes :for i :from 0 :do (when (and (and (not (eq n m)) (funcall lessp n m)) (zerop (decf (aref incoming i)))) (push m q)))) :finally (return (nreverse sorted)))) ;; (defun print-graph (nodes edge-predicate) ;; (flet ((initiale (package) ;; (if (< (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (length (package-name package))) ;; (subseq (package-name package) ;; (length "COM.INFORMATIMAGO.COMMON-LISP.") ;; (1+ (length "COM.INFORMATIMAGO.COMMON-LISP."))) ;; (subseq (package-name package) 0 1)))) ;; (let* ((nodes (coerce nodes 'vector)) ;; (width (ceiling (log (length nodes) 10)))) ;; (loop ;; :for i :from 0 ;; :for node :across nodes ;; :initially (format t "~2%") ;; :do (format t " ~VD: ~A~%" width i node) ;; :finally (format t "~2%")) ;; (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t " ~VD " width "") ;; :do (format t " ~VD" width j) ;; :finally (format t "~%")) ;; (loop ;; :for i :from 0 :below (length nodes) ;; :do (loop ;; :for j :from 0 :below (length nodes) ;; :initially (format t "~A ~VD:" (initiale (aref nodes i)) width i) ;; :do (format t " ~VD" ;; width ;; (if (funcall edge-predicate ;; (aref nodes i) (aref nodes j)) ;; (concatenate 'string ;; (initiale (aref nodes i)) ;; (initiale (aref nodes j))) ;; "")) ;; :finally (format t "~%")) ;; :finally (format t "~%"))))) ;;; With topological-sort, we mustn't use a total order function like this one: ;; (defun package<= (p q) ;; (cond ((eq p q) t) ;; ((package-use*-package-p p q) ;; (assert (not (package-use*-package-p q p)) ;; (p q) "A circle could happen but it should not.") ;; t) ; p<q ;; ((package-use*-package-p q p) nil) ; p>q ;; (t (string<= (package-name p) (package-name q))))) (dolist (p (let* ((nodes (delete-if-not (lambda (p) (let ((prefix "COM.INFORMATIMAGO.COMMON-LISP.")) (and (< (length prefix) (length (package-name p))) (string= prefix (package-name p) :end2 (length prefix))))) (copy-list (list-all-packages)))) (sorted (topological-sort nodes (function package-use*-package-p))) (cyclic (set-difference nodes sorted))) (when cyclic (format t "Cyclic nodes = ~S~%" cyclic)) (nconc cyclic sorted))) (delete-package p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Finally, we compile and load the system ;;; (logger "COMPILING THE ASDF SYSTEM") (setf asdf:*compile-file-warnings-behaviour* :ignore) (let ((*load-verbose* t) (*compile-verbose* t) (asdf::*verbose-out* t)) (asdf:operate 'asdf:load-op :com.informatimago.common-lisp)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
13,720
Common Lisp
.lisp
343
32.35277
94
0.516682
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
686b60f882137d1cccb3d9e8f45e10a457cca035a1632576c77b42aabc5e5665
4,777
[ -1 ]
4,778
dependency-cycles.lisp
informatimago_lisp/tools/dependency-cycles.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: dependency-cycles.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; XXX ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-08-18 <PJB> Corrected find-cycles, corrected export list. ;;;; 2013-09-06 <PJB> Updated for publication. ;;;; 2012-04-06 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2018 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.GRAPH" "COM.INFORMATIMAGO.COMMON-LISP.GRAPHVIZ.GRAPH-DOT" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS" "COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS") (:export "ADJACENCY-LIST" "REACHABLE-LIST" "FIND-CYCLES" "FIND-SHORTEST-PATH" "REPORT-PROBLEMS" "PRINT-CYCLE" "DEPENDENCIES-GRAPH" "GENERATE-DEPENDENCIES-GRAPH") (:documentation " Find cycles in a dependency graph. The graph is defined by a list of nodes and two methods: (ADJACENCY-LIST node) -> list-of-nodes (REACHABLE-LIST node) -> list-of-nodes which is the recursive closure of ADJACENCY-LIST, but provided for efficiency. The function FIND-CYCLES returns a list of cycles in the graph defined by the given list of nodes and the previous methods. (FIND-CYCLES nodes) -> list-of-cycles The function REPORT-PROBLEMS prints a report of the found cycles. (REPORT-PROBLEMS nodes) License: AGPL3 Copyright Pascal J. Bourguignon 2012 - 2018 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/>. ")) (in-package "COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (com.informatimago.clext.character-sets::fill-character-set-emacs-encoding) ;; (com.informatimago.clext.character-sets::fill-character-set-lisp-encoding)) (defparameter *iso-8859-1* (make-external-format (find-character-set "ISO-8859-1") :unix)) (defparameter *utf-8* (make-external-format (find-character-set "UTF-8") :unix)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (defgeneric adjacency-list (object) (:documentation "Return the list of vertices connected to vertex thru a single edge.") (:method ((vertex t)) '())) (defgeneric reachable-list (vertex) (:documentation "Return the list of vertices rechable from vertex.") (:method ((vertex t)) '())) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; dependency graphs should be trees, so we run topological sorts on ;; them. (defun reachable (root successors) " SUCCESSORS: A function of one node returning a list of nodes. RETURN: A list of objects reachable from root traversing SUCCESSORS. " (loop :with reachable = '() :with old = (funcall successors root) :while old :do (let ((current (pop old))) (pushnew current reachable) (dolist (successor (funcall successors current)) (unless (member successor reachable) (pushnew successor old)))) :finally (return reachable))) (defun closest-to-root (nodes ordered-nodes) " RETURN: the node in NODES that is the closest to ROOT according to ordered-nodes " (loop :with closest = (pop nodes) :with minimum = (position closest ordered-nodes) :for node :in nodes :for distance = (position node ordered-nodes) :initially (assert minimum) :when (and distance (< distance minimum)) :do (setf closest node minimum distance) :finally (return (values closest minimum)))) ;; (defun closer-to-root (a b ordered-nodes) ;; (let ((p (position a ordered-nodes)) ;; (q (position b ordered-nodes))) ;; (and p q (< p q)))) (defun find-shortest-path (from to successors) " RETURN: The shortest path of length>0 from FROM to TO if it exists, or NIL. " ;; breadth first search (loop :with processed = '() :for paths = (list (list from)) :then new-paths :for new-paths = (remove-if (lambda (head) (member head processed)) (mapcan (lambda (path) (mapcar (lambda (new-node) (cons new-node path)) (funcall successors (first path)))) paths) :key (function first)) :for shortest-path = (find to new-paths :key (function first)) :do (setf paths (nconc paths new-paths) processed (nconc (delete-duplicates (mapcar (function first) new-paths)) processed)) :until (or shortest-path (endp new-paths)) :finally (return (reverse shortest-path)))) (defun print-cycle (path) (format t "~%There is a cycle going ~%from ~A" (first path)) (dolist (node (rest path)) (format t "~% to ~A" node)) (format t " !!!~%")) (defun set-equal (a b) (and (subsetp a b) (subsetp b a))) (defun find-cycles (objects) (remove-duplicates (remove nil (map 'list (lambda (cycle) (find-shortest-path cycle cycle (function adjacency-list))) (remove-if-not (lambda (x) (member x (reachable-list x))) objects))) :test (function set-equal))) (defun report-problems (objects &key (report *error-output*)) " DO: Find cycles in the graph defined by the nodes in the OBJECTS sequence and the ADJACENCY-LIST and REACHABLE-LIST methods. " (let ((cycles (find-cycles objects))) (when cycles (format report "~&There are ~A cycles in the dependency relationship!~%" (length cycles)) (dolist (path (sort cycles (function string<) :key (function prin1-to-string))) (print-cycle path))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; (defun dependencies-graph (objects) " RETURN: a graph as defined by the nodes in the OBJECTS sequence and the ADJACENCY-LIST an REACHABLE-LIST methods. " (let ((graph (make-instance 'graph-class :edge-class 'directed-edge-class ))) (add-nodes graph objects) (map nil (lambda (from) (dolist (to (adjacency-list from)) (when (find to objects) (add-edge-between-nodes graph from to)))) objects) graph)) (defun generate-dependencies-graph (objects output-dotfile-path) " DO: Generates a GraphViz dot file to draw the dependency-graph defined by the nodes in the OBJECTS sequence and the ADJACENCY-LIST an REACHABLE-LIST methods. " (with-open-file (dot output-dotfile-path :direction :output :if-does-not-exist :create :if-exists :supersede :external-format *iso-8859-1*) (let ((graph (dependencies-graph objects))) (set-property graph :nodesep 3) (set-property graph :ranksep 7) (set-property graph :page "64,48") (set-property graph :ratio :fill) (princ (generate-dot graph) dot)) (values))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; (defun load-dependencies (path files) ;; (with-open-file (stream path :external-format *iso-8859-1*) ;; (loop ;; :for line = (read-line stream nil stream) ;; :for (includep included-file systemp) = (if (eq line stream) ;; '(nil nil nil) ;; (parse-include-line line)) ;; :until (eq line stream) ;; :when includep ;; :collect (or (gethash included-file files) ;; (make-instance 'header-file :path included-file))))) ;; ;; ;; (defparameter *root-path* #p"/home/pjb/src/manager2/trunk/") ;; (defparameter *files* (make-hash-table :test (function equal))) ;; (defparameter *headers* (make-hash-table :test (function equal))) ;; (defparameter *sorted-headers* '()) ;; ;; ;; (defun process-sources (root-path) ;; (let ((header-paths (directory (merge-pathnames "**/*.hxx" root-path nil))) ;; (source-paths (directory (merge-pathnames "**/*.cxx" root-path nil)))) ;; (format t "~A headers; ~A sources~%" (length header-paths) (length source-paths)) ;; ;; (dolist (path source-paths) ;; (setf (gethash path *files*) (make-instance 'source-file :path (namestring path)))) ;; (dolist (path header-paths) ;; (setf (gethash path *headers*) ;; (setf (gethash path *files*) (make-instance 'header-file :path (namestring path)))))) ;; (setf *print-circle* t) ;; (maphash (lambda (path file) ;; (setf (dependencies file) (load-dependencies path *files*))) ;; *files*) ;; (maphash (lambda (path file) ;; (declare (ignore path)) ;; (setf (dependencies-reachable file) (reachable file (function dependencies)))) ;; *files*) ;; (progn (setf *sorted-headers* (topological-sort (hash-table-values *headers*) (function dependencies))) ;; (if (= (length *sorted-headers*) (hash-table-count *headers*)) ;; (format t "~&No #include cycle amongst headers. ~%") ;; (format t "~&The #include relationship between headers contains cycles! It should be a tree.~%")) ;; (report-problems (hash-table-values *headers*))) ;; (progn (setf *sorted-files* (topological-sort (hash-table-values *files*) (function dependencies))) ;; (if (= (length *sorted-files*) (hash-table-count *files*)) ;; (format t "~&No #include cycle amongst sources. ~%") ;; (format t "~&The #include relationship between sources contains cycles! It should be a tree.~%")) ;; (report-problems (hash-table-values *files*)))) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; THE END ;;;;
11,869
Common Lisp
.lisp
260
40.726923
113
0.605434
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f49abd3ac591df9704e420c98ae80595872a6ae82fe75b00eade814b4c662614
4,778
[ -1 ]
4,779
check-asdf-test.lisp
informatimago_lisp/tools/check-asdf-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: check-asdf-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test check-asdf.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.CHECK-ASDF.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.CHECK-ASDF") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.CHECK-ASDF.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,751
Common Lisp
.lisp
44
38.204545
83
0.607625
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ec4c0efebbb7cb017dfcd5f9f903b9b50d58661f848cf7fd83a5ac2607aebaba
4,779
[ -1 ]
4,780
summary-test.lisp
informatimago_lisp/tools/summary-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: summary-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test summary.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.SUMMARY.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.SUMMARY") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.SUMMARY.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,736
Common Lisp
.lisp
44
37.863636
83
0.607101
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f841a59ca2dad28a518f5a7cd0e14cfdb24a03a1294e1e48d40f9689159fc7a5
4,780
[ -1 ]
4,781
asdf-test.lisp
informatimago_lisp/tools/asdf-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: asdf-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test asdf.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.ASDF.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.ASDF") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.ASDF.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,721
Common Lisp
.lisp
44
37.522727
83
0.603582
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
15bd6547d59df8b40d107a44878f66c5907b26d669eced5350d12e1e4536f6e3
4,781
[ -1 ]
4,782
check-asdf.lisp
informatimago_lisp/tools/check-asdf.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: check-asdf.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Check an asdf file for circular dependencies. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-03-25 <PJB> Created. ;;;;BUGS ;;;; ;;;; - remove dependency on script (use uiop instead). ;;;; ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2013 - 2018 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.CHECK-ASDF" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.GRAPH" "COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES") (:import-from "COM.INFORMATIMAGO.TOOLS.SCRIPT" "SHELL") (:export ;; Loading simple ASD files: "LOAD-SIMPLE-ASD-FILE" "ASDF-FILE" "ASDF-FILE-P" "MAKE-ASDF-FILE" "COPY-ASDF-FILE" "ASDF-FILE-PATH" "ASDF-FILE-DEPENDS-ON" "ASDF-FILE-REACHABLE" "SYSTEM-DIRECT-DEPENDENCIES" "SYSTEM-DEPENDS-ON" "SYSTEM-ALL-DEPENDENCIES" ;; Generate dot file from a asdf-file graphs "GENERATE-DOT" "DOT" "ADJACENCY-LIST" "REACHABLE-LIST" "DEPENDENCIES" ;; Check asdf files "CHECK-ASDF-SYSTEM-FILE" "CHECK-ASDF-SYSTEM-DEPENDENCIES") (:documentation " Check an asdf file for circular dependencies. Usage: (com.informatimago.tools.check-asdf:check-asdf-system-file #P\"/some/system.asd\" :report output-stream) License: AGPL3 Copyright Pascal J. Bourguignon 2013 - 2018 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/>. ")) (in-package "COM.INFORMATIMAGO.TOOLS.CHECK-ASDF") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Read Simple ASD Files ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defstruct asdf-file path depends-on reachable) (defmethod print-object ((self asdf-file) stream) (if *print-readably* (format stream "#.(~S ~S ~S)" 'intern-file (asdf-file-path self) '*asdf-files*) (print-unreadable-object (self stream :identity t :type t) (format stream "~S" (asdf-file-path self)))) self) (defun intern-file (path asdf-files) (let ((file (gethash path asdf-files))) (or file (setf (gethash path asdf-files) (make-asdf-file :path path))))) (defvar *asdf-files* (make-hash-table :test (function equal)) "For interactive exploring, we keep a reference to the last loaded asdf files hash-table in this variable.") (defun load-simple-asd-file (path) " RETURN: A hash-table mapping file paths to ASDF-FILE structures. " (setf *asdf-files* (let ((asdf-files (make-hash-table :test (function equal)))) (let ((system (with-open-file (stream path) (read stream)))) (dolist (compo (getf (cddr system) :components)) (when (and (listp compo) (eq :file (first compo))) (let ((file (intern-file (second compo) asdf-files))) (dolist (depend (getf (cddr compo) :depends-on)) (when (stringp depend) (push (intern-file depend asdf-files) (asdf-file-depends-on file)))))))) (maphash (lambda (path file) (declare (ignore path)) (setf (asdf-file-reachable file) (transitive-closure (function asdf-file-depends-on) (asdf-file-depends-on file)))) asdf-files) asdf-files))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Generate dot file from a asdf-file graphs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod adjacency-list ((file asdf-file)) (asdf-file-depends-on file)) (defmethod reachable-list ((file asdf-file)) (asdf-file-reachable file)) (defun dependencies (p q) (member q (asdf-file-reachable p))) (defgeneric generate-dot (object)) (defmethod generate-dot ((file asdf-file)) (let ((style "filled") (color "black") (fillcolor "LightYellow") (label (pathname-name (asdf-file-path file)))) (format nil "~S [ style=~A color=~A fillcolor=~A label=\"~A\" ];~%" (pathname-name (asdf-file-path file)) style color fillcolor label))) (defmethod generate-dot ((edge cons)) (format nil "~S -> ~S [ weight=~D, style=~A, color=~A ];~%" (pathname-name (asdf-file-path (car edge))) (pathname-name (asdf-file-path (cdr edge))) 1 "solid" ; "dotted" "dashed" "bold" "black")) (defmethod generate-dot ((path pathname)) " RETURN: A string containing the dot file data for this graph. " (let ((files (load-simple-asd-file path))) (with-output-to-string (*standard-output*) (format t "digraph ~S~%" (pathname-name path)) (format t "{~%") (format t "rankdir=~A;~%" "TB") (format t "concentrate=~:[false~;true~];~%" t) (mapc 'write-string '( "// attributes of graph:~%" "// page=8,11.4; // page size (NeXTprinter:A4).~%" "// size=30,8; // graph size (please edit to fit).~%" "// rotate=90; // graph orientation (please edit to fit).~%" "// ratio=fill; // fill the size (or compress, auto, aspect/ratio).~%" "nodesep=0.3;~%" "ranksep=0.3;~%" "center=1;~%" "// common attributes of NODES:~%" "node [height=0.2 width=0.5 shape=box fontsize=8 fontname=Times] ;~%")) (maphash (lambda (key file) (declare (ignore key)) (write-string (generate-dot file))) files) (format t "// common attributes of edges:~%edge [style=solid];~%") (maphash (lambda (key file) (declare (ignore key)) (dolist (dependency (asdf-file-depends-on file)) (write-string (generate-dot (cons file dependency))))) files) (format t "}~%")))) ;; (COM.INFORMATIMAGO.TOOLS.ASDF-FILE:generate-dot #P"/Users/pjb/src/public/lisp/tools/com.informatimago.tools.check-asdf.asd") (defun dot (path) (let ((path.dot (make-pathname :defaults path :type "dot")) (path.pdf (make-pathname :defaults path :type "pdf"))) (with-open-file (dot path.dot :direction :output :if-does-not-exist :create :if-exists :supersede) (write-string (generate-dot path) dot)) (shell "/opt/local/bin/dot -Tpdf -o ~S ~S" (#+ccl ccl:native-translated-namestring #-ccl namestring path.pdf) (#+ccl ccl:native-translated-namestring #-ccl namestring path.dot)) (shell "open ~S" (#+ccl ccl:native-translated-namestring #-ccl namestring path.pdf)))) ;; (dot #P"/Users/pjb/src/public/lisp/tools/com.informatimago.tools.check-asdf.asd") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Check asdf files ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *sorted-files* nil) (defun check-asdf-system-file (asd-file &key (report *standard-output*)) (let* ((asdf-files (load-simple-asd-file asd-file)) (sorted-files (topological-sort (hash-table-values asdf-files) (function dependencies)))) (setf *sorted-files* (copy-seq sorted-files)) (if (= (length sorted-files) (hash-table-count asdf-files)) (format report "~&No cycle among files. ~%") (format report "~&The :depends-on relationship between files contains cycles! ~ ~%It should be a tree.~%")) (report-problems (hash-table-values asdf-files) :report report))) ;; Note: we need to cache those dependencies to go faster: (defun system-direct-dependencies (system) (let ((system (asdf:find-system system))) (delete-duplicates (mapcan (lambda (depend) (copy-list (funcall depend system))) '(asdf:system-defsystem-depends-on asdf:system-depends-on asdf:system-weakly-depends-on)) :test (function equal)))) (defun system-depends-on (a b) (member b (system-direct-dependencies a))) (defun system-all-dependencies (system) (com.informatimago.common-lisp.cesarum.utility:transitive-closure (function system-direct-dependencies) (list system))) (defun check-asdf-system-dependencies (system &key (report *standard-output*)) (let* ((all-systems (system-all-dependencies :smart-integrated-sensors.main)) (sorted-systems (topological-sort all-systems (function system-depends-on)))) (if (= (length sorted-systems) (length all-systems)) (format report "~&No cycle among system dependencies.~%") (format report "~&The system dependencies graph of ~S contains cycles! ~ ~%It should be a tree.~%" system)) (report-problems all-systems :report report))) ;;;; THE END ;;;;
10,927
Common Lisp
.lisp
230
40.052174
127
0.589368
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
fb232bf05783d8278301b42ea8b7ce8c7c512c63be38cd9f26626985ffc0ce2b
4,782
[ -1 ]
4,783
reader-macro.lisp
informatimago_lisp/tools/reader-macro.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: reader-macro.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tools to deal with reader macro characters. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-21 <PJB> Renamed all-macro-characters -> list-all-macro-characters. ;;;; changed the tag symbols into keywords. ;;;; 2015-04-03 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.READER-MACRO" (:use "COMMON-LISP") (:export "LIST-ALL-MACRO-CHARACTERS" "LIST-MACRO-CHARACTERS" "REMOVE-ALL-MACRO-CHARACTERS" "PRINT-READTABLE-COMPARISON")) (in-package "COM.INFORMATIMAGO.TOOLS.READER-MACRO") (defun remove-all-macro-characters (readtable) "DO: Removes all the reader macros and dispatching reader macros from the READTABLE. RETURN: READTABLE." (loop :for code :below char-code-limit :for ch = (code-char code) :when (and ch (get-macro-character ch readtable)) :do (set-macro-character ch nil t readtable) (set-syntax-from-char ch #\a readtable)) readtable) (defparameter *standard-macro-characters* "()';\"`,") (defparameter *standard-sharp-subchars* (concatenate 'string #(#\Backspace #\Tab #\Newline #\Linefeed #\Page #\Return #\Space) "#'()*:<=\\\\|+-.AaBbCcOoPpRrSsXx")) (defun list-macro-characters (&key ((:readtable *readtable*) *readtable*) (standard t) (non-standard t)) (remove-if-not (lambda (item) (ecase (first item) (:macro-character (if (find (third item) *standard-macro-characters*) standard non-standard)) (:dispatch-macro-character (if (char= #\# (third item)) (if (find (fourth item) *standard-sharp-subchars*) standard non-standard) non-standard)))) (list-all-macro-characters *readtable*))) (defun list-all-macro-characters (&optional (*readtable* *readtable*)) " RETURN: A list of all the macro and dispatch-macro characters in the readtable. NOTE: We have the same function in the com.informatimago.common-lisp.lisp-reader.reader package, working on com.informatimago.common-lisp.lisp-reader.reader:readtable instead of cl:readtable. " (check-type *readtable* readtable) (loop :with result = '() :for code :below char-code-limit :for ch = (code-char code) :when ch :do (multiple-value-bind (mc nt) (get-macro-character ch) (when mc (if (ignore-errors (progn (get-dispatch-macro-character ch #\a) t)) (loop :for code :below char-code-limit :for sub = (code-char code) :when (and sub (not (and (alpha-char-p sub) (lower-case-p sub))) (get-dispatch-macro-character ch sub)) :do (push (list :dispatch-macro-character nt ch sub #-(and) (format nil "~C~C" ch sub)) result)) (push (list :macro-character nt ch #-(and) (string ch)) result)))) :finally (return (nreverse result)))) (defun print-readtable-comparison (n1 rt1 n2 rt2) (flet ((preprocess (entry rt) (ecase (first entry) (:macro-character (destructuring-bind (terminating ch) (rest entry) (list (string ch) (first entry) terminating (get-macro-character ch rt)))) (:dispatch-macro-character (destructuring-bind (terminating ch sub) (rest entry) (list (format nil "~C~C" ch sub) (first entry) terminating (get-dispatch-macro-character ch sub rt)))))) (report-difference (e1-e2 n1 e1 n2) (when e1-e2 (format t "Reader macro~P in ~S but not in ~S:~%" (cdr e1-e2) n1 n2) (dolist (e e1-e2) (let ((ee1 (assoc (first e) e1 :test (function string=)))) (destructuring-bind (s1 o1 t1 f1) ee1 (declare (ignore t1 f1)) (format t "~A ~S is in ~S but not in ~S.~%" o1 s1 n1 n2))))))) (let* ((e1 (mapcar (lambda (entry) (preprocess entry rt1)) (list-all-macro-characters rt1))) (e2 (mapcar (lambda (entry) (preprocess entry rt2)) (list-all-macro-characters rt2))) (common (intersection e1 e2 :key (function first) :test (function string=))) (e1-e2 (set-difference e1 e2 :key (function first) :test (function string=))) (e2-e1 (set-difference e2 e1 :key (function first) :test (function string=)))) (when common (format t "Reader macro~P in common between ~S and ~S:~%" (cdr common) n1 n2) (dolist (e common) (let ((ee1 (assoc (first e) e1 :test (function string=))) (ee2 (assoc (first e) e2 :test (function string=)))) (destructuring-bind (s1 o1 t1 f1) ee1 (destructuring-bind (s2 o2 t2 f2) ee2 (declare (ignore s2 o2)) (unless (eql t1 t2) (format t "~A ~S is ~:[not-~;~]terminating in ~S but ~:[not-~;~]terminating in ~S.~%" o1 s1 t1 n1 t2 n2)) (unless (eql f1 f2) (format t "~A ~A are not bound to the same function.~%" o1 s1))))))) (report-difference e1-e2 n1 e1 n2) (report-difference e2-e1 n2 e2 n1))) (values)) #-(and) ( ;; (length (all-macro-characters) (map nil 'print (list-all-macro-characters)) (:macro-character nil #\") (:dispatch-macro-character t #\# #\Null) (:dispatch-macro-character t #\# #\Tab) (:dispatch-macro-character t #\# #\Newline) (:dispatch-macro-character t #\# #\Page) (:dispatch-macro-character t #\# #\Return) (:dispatch-macro-character t #\# #\ ) (:dispatch-macro-character t #\# #\#) (:dispatch-macro-character t #\# #\$) (:dispatch-macro-character t #\# #\&) (:dispatch-macro-character t #\# #\') (:dispatch-macro-character t #\# #\() (:dispatch-macro-character t #\# #\)) (:dispatch-macro-character t #\# #\*) (:dispatch-macro-character t #\# #\+) (:dispatch-macro-character t #\# #\-) (:dispatch-macro-character t #\# #\.) (:dispatch-macro-character t #\# #\:) (:dispatch-macro-character t #\# #\<) (:dispatch-macro-character t #\# #\=) (:dispatch-macro-character t #\# #\>) (:dispatch-macro-character t #\# #\A) (:dispatch-macro-character t #\# #\B) (:dispatch-macro-character t #\# #\C) (:dispatch-macro-character t #\# #\O) (:dispatch-macro-character t #\# #\P) (:dispatch-macro-character t #\# #\R) (:dispatch-macro-character t #\# #\S) (:dispatch-macro-character t #\# #\X) (:dispatch-macro-character t #\# #\\) (:dispatch-macro-character t #\# #\_) (:dispatch-macro-character t #\# #\|) (:dispatch-macro-character t #\# #\Latin_Capital_Letter_E_With_Circumflex) (:macro-character nil #\') (:macro-character nil #\() (:macro-character nil #\)) (:macro-character nil #\,) (:macro-character nil #\;) (:macro-character nil #\`) ) ;;;; THE END ;;;;
8,929
Common Lisp
.lisp
187
37.604278
103
0.546517
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f5b529d49c8c0f967c720062113648a183722e0b0b19f15cbacb6bea597137ed
4,783
[ -1 ]
4,784
manifest-test.lisp
informatimago_lisp/tools/manifest-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: manifest-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test manifest.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.MANIFEST.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.TOOLS.MANIFEST") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.TOOLS.MANIFEST.TEST") (define-test test/all () :success) ;;;; THE END ;;;;
1,741
Common Lisp
.lisp
44
37.977273
83
0.60826
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7297ce2e24fca5716399482a9156d27b11e245064b893522c9ede198591d5551
4,784
[ -1 ]
4,785
analyse-patchwork.lisp
informatimago_lisp/tools/analyse-patchwork.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: analyse-patchwork.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Read and analyse the patchwork sources. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-04-09 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "COM.INFORMATIMAGO.COMMON-LISP.PICTURE.TREE-TO-ASCII")) (defpackage "COM.INFORMATIMAGO.TOOLS.ANALYSE-PATCHWORK" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.GRAPH" "COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES" "COM.INFORMATIMAGO.TOOLS.ASDF-FILE") (:export "READ-SOURCES" "*CONTENTS*") (:shadow "CLASS" "CLASS-NAME" "FIND-CLASS")) (in-package "COM.INFORMATIMAGO.TOOLS.ANALYSE-PATCHWORK") (defun safe-find-package (designator) (or (cl:find-package designator) (error "No such package ~S" designator))) (defvar *readtable-preserve*) (defun sharp-underline-dispatch-reader-macro (stream subchar arg) (declare (ignore subchar arg)) (let ((*readtable* *readtable-preserve*) (*package* (safe-find-package "FFI"))) ;; actual would return the name of a FFI function, variable or #define, ;; we just return the preserved symbol, read in the FFI package.. (values (read stream)))) (defun sharp-at-dispatch-reader-macro (stream subchar arg) "#@(x y) reads a Point. We just read a quoted list." (declare (ignore subchar arg)) (destructuring-bind (h v) (read stream) (values (dpb (ldb (byte 16 0) (round v)) (byte 16 16) (ldb (byte 16 0) (round h)))))) (defun sharp-dot-dispatch-reader-macro (stream subchar arg) "#. we read the expression in the host CL." (declare (ignore subchar arg)) (let ((form (cl:read stream))) (if *read-eval* (values (eval form)) (error "Cannot evaluate #.~S when ~S is ~S" form '*read-eval* *read-eval*)))) (defun sharp-i-dispatch-reader-macro (stream char count) (declare (ignore char count)) `(prefix-expr ',(read stream t nil t))) (defun setup () " Configure a com.informatimago.common-lisp.lisp-reader.reader:readtable for reading lisp sources interning packages and symbols in com.informatimago.common-lisp.lisp-reader.package:package and com.informatimago.common-lisp.lisp-reader.package:symbol instead of common-lisp:package and common-lisp:symbol. " (setf *read-eval* t) (let ((rt (copy-readtable nil))) (set-dispatch-macro-character #\# #\_ (function sharp-underline-dispatch-reader-macro) rt) (set-dispatch-macro-character #\# #\$ (function sharp-underline-dispatch-reader-macro) rt) (set-dispatch-macro-character #\# #\@ (function sharp-at-dispatch-reader-macro) rt) (set-dispatch-macro-character #\# #\. (function sharp-dot-dispatch-reader-macro) rt) (set-dispatch-macro-character #\# #\i (function sharp-i-dispatch-reader-macro) rt) (setf *readtable-preserve* (copy-readtable rt)) (setf (readtable-case *readtable-preserve*) :preserve) (setf *readtable* rt))) (defparameter *sorted-files* '()) (defparameter *contents* '()) (defvar *asdf-files* (make-hash-table)) (defun read-sources (&key (system-file #P"patchwork.asd") (base #P"~/works/patchwork/patchwork/src/")) (setup) (LOAD-SIMPLE-ASD-FILE (merge-pathnames system-file base)) (setf *sorted-files* (reverse (topological-sort (hash-table-values *asdf-files*) (function dependencies)))) ;; (defparameter *sources* ;; (sort (directory "/home/pjb/works/patchwork/pw-src/**/*.lisp") ;; (function string<) :key (function namestring))) ;; (setf *sources* ;; (let* ((files '()) ;; (path (merge-pathnames #P"patchwork.asd" base)) ;; (system (with-open-file (stream path) (read stream)))) ;; (dolist (compo (getf (cddr system) :components) (reverse files)) ;; (when (and (listp compo) ;; (eq :file (first compo))) ;; (push (second compo) files))))) (setf *contents* '()) (handler-case (dolist (file *sorted-files*) (let ((*package* *package*) (path (asdf-file-path file))) (push (cons path (with-open-file (stream (merge-pathnames (make-pathname :type "LISP" :case :common) (merge-pathnames path base))) (princ (namestring (truename (pathname stream)))) (terpri) (finish-output) (loop :for sexp = (read stream nil stream) :until (eql stream sexp) :collect sexp :do (when (listp sexp) (case (first sexp) ((defpackage in-package import export use-package) (eval sexp))))))) *contents*))) (error (err) (terpri) (princ err) (terpri))) (values)) (defun find-forms (operator sexp) (cond ((atom sexp) '()) ((eq operator (first sexp)) (list sexp)) (t '()))) (defun find-all-forms (operator) (mapcan (lambda (file) (let ((forms (mapcan (lambda (sexp) (find-forms operator sexp)) (cdr file)))) (if forms (list (cons (car file) forms)) '()))) *contents*)) ;; (read-sources) ;; (find-all-forms 'eval-when) (defstruct class name file superclasses all-superclasses subclasses) ;; (apropos "class-direct-subclasses") (defparameter *classes* (make-hash-table)) (defun find-class (name) (gethash name *classes*)) (defun intern-class (name file superclasses &optional subclasses) (or (gethash name *classes*) (setf (gethash name *classes*) (make-class :name name :file file :superclasses superclasses :subclasses subclasses)))) (defmethod adjacency-list ((class class)) (mapcar (function find-class) (class-superclasses class))) (defmethod reachable-list ((class class)) (or (class-all-superclasses class) (setf (class-all-superclasses class) (compute-closure (function class-superclasses) (class-superclasses class))))) (defun dependencies (p q) (member q (reachable-list p))) (defvar *defclasses* nil) (defvar *classes* nil) (defun classify-classes () (maphash (lambda (name class) (declare (ignore name)) (setf (class-superclasses class) (mapcan (lambda (name) (let ((superclass (find-class name))) (if superclass (list superclass) (format t "~A inherits from ~A that has no defclass form.~%" (class-name class) name)))) (class-superclasses class))) (dolist (super (class-superclasses class)) (push class (class-subclasses super)))) *classes*)) (defun analyse-patchwork () (read-sources :system-file #P"patchwork.asd" :base #P"~/works/patchwork/patchwork/src/") (setf *defclasses* (cons '("root" (defclass root () ())) (find-all-forms 'defclass))) (loop :for (file . classes) :in *defclasses* :initially (setf *classes* (make-hash-table)) :do (loop :for (nil name superclasses) :in classes :for cls = (find-class name) :do (if cls (format t "~A names two classes, one in ~S and one in ~S~%" name file (class-file cls)) (intern-class name file (or superclasses (if (eq 'root name) '() '(root)))))) :finally (classify-classes)) (report-problems (hash-table-values *classes*))) (defvar *tlee* nil) ; for debugging. (defun print-class-hierarchy () (let ((tlee (let ((nodes (make-hash-table))) (labels ((tlee (class) (setf (gethash (class-name class) nodes) (cons (class-name class) (mapcar (function tlee) (class-subclasses class)))))) (dolist (class (topological-sort (hash-table-values *classes*) (function dependencies))) (tlee class))) (or (gethash 'root nodes) (when (cl:find-package "OBJC") (gethash (find-symbol "OBJC-OBJECT" (cl:find-package "OBJC")) nodes)) (when (cl:find-package "NS") (gethash (find-symbol "NS-OBJECT" (cl:find-package "NS")) nodes))))) (*package* (or (cl:find-package :pw) (safe-find-package :cl-user)))) (setf *tlee* tlee) (princ (com.informatimago.common-lisp.picture.tree-to-ascii:tree-to-ascii tlee :boxed t ;; :format-fun ;; :background ;; :to-length ;; :from-length )))) (defun print-class-parents () (dolist (leaf (remove-if (function class-subclasses) (hash-table-values *classes*)) (terpri)) (terpri) (let ((tlee (let ((nodes (make-hash-table))) (labels ((tlee (class) (setf (gethash (class-name class) nodes) (cons (class-name class) (remove '(root) (mapcar (function tlee) (class-superclasses class)) :test (function equal)))))) (tlee leaf)) (gethash (class-name leaf) nodes))) (*package* (or (cl:find-package :pw) (safe-find-package :cl-user)))) (princ (com.informatimago.common-lisp.picture.tree-to-ascii:tree-to-ascii tlee :boxed t ;; :format-fun ;; :background ;; :to-length ;; :from-length ))))) (defun convert-class-tree (clos-class) (when clos-class (let* ((clos-class (if (symbolp clos-class) (cl:find-class clos-class) clos-class)) (superclasses (closer-mop:class-direct-superclasses clos-class)) (subclasses (closer-mop:class-direct-subclasses clos-class))) (intern-class (cl:class-name clos-class) nil (mapcar (function cl:class-name) superclasses) ;; (mapcar (function cl:class-name) subclasses) ) (dolist (subclass subclasses) (convert-class-tree subclass))))) (defun print-objc-class-hierarchy () (setf *classes* (make-hash-table)) #+#.(cl:if (cl:find-package "NS") '(:and) '(:or)) (convert-class-tree 'ns:ns-object) (classify-classes) (print-class-hierarchy)) (defparameter *utf-8* #-clisp :utf-8 #+clisp charset:utf-8) (defun generate-classes-hierarchy () (with-open-file (*standard-output* "classes-hierarchy.txt" :direction :output :if-exists :supersede :if-does-not-exist :create :external-format *utf-8*) (write-line "-*- mode:view; coding:utf-8 -*-") (terpri) (print-class-hierarchy)) (with-open-file (*standard-output* "classes-parents.txt" :direction :output :if-exists :supersede :if-does-not-exist :create :external-format *utf-8*) (write-line "-*- mode:view; coding:utf-8 -*-") (terpri) (print-class-parents)) (values)) ;; (last (topological-sort (hash-table-values *classes*) (function dependencies))) ;; (#1=#S(class :name root :file "root" :superclasses #2=(#1#) :all-superclasses #2#)) ;; (setf *sorted-files* (reverse (topological-sort (hash-table-values *asdf-files*) ;; (function dependencies)))) ;; (first *defclasses*) ;; ("pw-music/boxes/edit/mn-editor-polif" (defclass patch-work::c-patch-polifmn (patch-work::c-patch-application) ((patch-work::chord-line-list :initform nil :initarg :chord-line-list :accessor patch-work::chord-line-list)))) ;; (loop ;; :with externals = '() ;; :for (file . defpacks) :in (find-all-forms 'defpackage) ;; :for importing-defpacks = (remove-if-not ;; (lambda (defpack) ;; (let ((entry (assoc :import-from (cddr defpack)))) ;; (and entry ;; (or (string= "PATCH-WORK" (second entry)) ;; (string= "PW " (second entry)))))) ;; defpacks) ;; :when importing-defpacks ;; :do (progn ;; (print file) ;; (dolist (entry (mapcar (lambda (defpack) ;; (assoc :import-from (cddr defpack))) ;; importing-defpacks)) ;; (alexandria:appendf externals (cddr entry)))) ;; :finally (print `(:export ,@(sort (remove-duplicates externals :test (function string=)) ;; (function string<))))) ;; (read-sources) ;; (find-all-forms 'export) ;; nil ;; (find-all-forms 'import) ;; (("pw-lib/epw-1.0b/import" (import '(patch-work:new-menu patch-work:pw-addmenu)))) ;; nil ;;;; THE END ;;;;
15,180
Common Lisp
.lisp
330
36.454545
225
0.553048
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
acf6e896ecb944f4240fc193e00d11cc720a8cca8ecf5a884a792ec71768fd9a
4,785
[ -1 ]
4,786
try-systems.lisp
informatimago_lisp/tools/try-systems.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: try-systems.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tries to compile all the systems in an environment similar to ;;;; the one used by quicklisp when validating systems. ;;;; ;;;; Report errors. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-08 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.TOOLS.TRY-SYSTEMS" (:use "COMMON-LISP" "SPLIT-SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.TOOLS.ASDF-FILE" "COM.INFORMATIMAGO.TOOLS.SCRIPT") (:export "TRY-SYSTEMS-IN-DIRECTORY" "TRY-SYSTEMS")) (in-package "COM.INFORMATIMAGO.TOOLS.TRY-SYSTEMS") (defmacro in-home (relative-path) `(load-time-value (merge-pathnames ,relative-path (user-homedir-pathname) nil))) (defvar *reports-directory* (in-home #P"try-system-reports/") "Pathname of the directory where to store reports.") (defvar *asdf* ;; We cannot use quicklisp/asdf.lisp since it's too old an asdf. ;; (in-home #P"quicklisp/asdf.lisp") (let ((dir #.(or *compile-file-truename* *load-truename* #P"./"))) (merge-pathnames (make-pathname :name "asdf" :type "lisp" :version nil :defaults dir) dir nil)) "Pathname of the asdf.lisp source file.") (defvar *releases-file* (in-home #P"quicklisp/dists/quicklisp/releases.txt") "The quicklisp files listing all the releases.") (defvar *local-projects-directory* (in-home #P"quicklisp/local-projects/") "The quicklisp files listing all the releases.") (defvar *software-directory* (in-home #P"quicklisp/dists/quicklisp/software/") "The directory where the quicklisp systems are stored.") (defun directory-of (pathname) (make-pathname :name nil :type nil :version nil :defaults pathname)) (defun find-asd-systems-in-directory (root-directory) (mapcar (lambda (asd-file-pathname) (cons (directory-of asd-file-pathname) (asd-systems-in-asd-file asd-file-pathname))) (find-asd-files root-directory))) (defun quicklisp-registry () "Returns a list of all the directories where there's a ASD file managed by quicklisp." (let ((paths '())) (flet ((process-files (files) (dolist (asdf files) (push (directory-of asdf) paths)))) (dolist (line (remove-if (lambda (line) (or (zerop (length line)) (char= #\# (aref line 0)))) (string-list-text-file-contents *releases-file*))) (destructuring-bind (dir &rest files) (nthcdr 5 (split-sequence #\space line :remove-empty-subseqs t)) (let ((base (merge-pathnames (make-pathname :directory (list :relative dir) :defaults *software-directory*) *software-directory* nil))) (process-files (mapcar (lambda (asdf) (merge-pathnames asdf base nil)) files))))) (process-files (directory (merge-pathnames (make-pathname :directory '(:relative :wild-inferiors) :name :wild :type "asd" :case :local :defaults *local-projects-directory*) *local-projects-directory* nil)))) (remove-duplicates paths :test (function equalp)))) (defun run (date system operation lisp &rest arguments) (let* ((report-dir (merge-pathnames (make-pathname :directory (list :relative date) :defaults *reports-directory*) *reports-directory* nil)) (output-file (make-pathname :name (format nil "~A-~A-~A" date operation system) :type "output" :case :local :defaults report-dir)) (error-file (make-pathname :type "error" :case :local :defaults output-file))) (ensure-directories-exist error-file) (ignore-errors (progn (format *trace-output* "~A~%" output-file) (force-output *trace-output*) (uiop:run-program (mapconcat (function shell-quote-argument) (cons lisp arguments) " ") :input nil :output output-file :error-output error-file :if-output-exists :supersede :if-error-output-exists :supersede) :success)))) (defun date () "Return the current date in YYYYMMDD format." (multiple-value-bind (se mi ho da mo ye) (decode-universal-time (get-universal-time) 0) (declare (ignore se mi ho)) (format nil "~4,'0D~2,'0D~2,'0D" ye mo da))) (defun try-systems-in-directory (root-directory &key (asdf *asdf*) ((:reports-directory *reports-directory*) *reports-directory*)) (setf (uiop:getenv "LC_CTYPE") "en_US.UTF-8") (loop :with results := '() :with date := (date) :with registry := (merge-pathnames (make-pathname :name "registry" :type "lisp" :case :local :directory (list :relative date) :defaults *reports-directory*) *reports-directory* nil) :for (asd-directory . systems) :in (find-asd-systems-in-directory root-directory) :initially (ensure-directories-exist registry) (with-open-file (src registry :direction :output :if-does-not-exist :create :if-exists :supersede) (let ((*print-pretty* t) (*print-readably* t)) (format src "(setf *print-right-margin* 160)~%") (format src "(setf asdf:*central-registry* '~S)~%" (quicklisp-registry)))) :do (loop :for asd-system :in systems :for success := (run date asd-system "load" "sbcl" "--noinform" "--no-userinit" "--non-interactive" "--load" (namestring asdf) "--load" (namestring registry) ;; We cannot use prin1-to-string in case we don't have the same asdf version. "--eval" (format nil "(let ((asdf:*compile-file-warnings-behaviour* :warn) (asdf:*compile-file-failure-behaviour* :error)) (asdf:oos 'asdf:load-op ~S))" asd-system)) :do (push (list success asd-directory asd-system) results)) :finally (loop :for (success nil asd-system) :in results :when (and success (not (test-system-p `(defsystem ,asd-system)))) :do (run date asd-system "test" "sbcl" "--noinform" "--no-userinit" "--non-interactive" "--load" (namestring asdf) "--load" (namestring registry) ;; We cannot use prin1-to-string in case we don't have the same asdf version. "--eval" (format nil "(let ((asdf:*compile-file-warnings-behaviour* :warn) (asdf:*compile-file-failure-behaviour* :error)) (asdf:oos 'asdf:test-op ~S))" asd-system))))) ;; asdf:*compile-file-warnings-behaviour* ;; asdf:*compile-file-errors-behaviour* ;; control the handling of any such events. ;; The valid values for these variables are :error, :warn, and :ignore. #-(and) (run "sbcl" "--noinform" "--no-userinit" "--non-interactive" "--load" (namestring (merge-pathnames "quicklisp/asdf.lisp" (user-homedir-pathname) nil)) "--eval" (prin1-to-string `(push ,asd-directory asdf:*central-registry*)) "--eval" (prin1-to-string `(asdf:oos 'asdf:load-op ,asd-system))) #-(and) (let ((*package* (load-time-value (find-package "KEYWORD")))) (format t "~2%;; Usage:~2%~S~2%" '(try-systems-in-directory #P"~/src/public/lisp/"))) (defun try-systems () (try-systems-in-directory #P"~/src/public/lisp/")) ;;;; THE END ;;;;
9,980
Common Lisp
.lisp
193
38.471503
198
0.539076
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
13b1adddabe740fdbcfb143be6095efdadc01b7f03edf57dcd6a71643420f456
4,786
[ -1 ]
4,787
generate-make-print-vars.lisp
informatimago_lisp/tools/make/generate-make-print-vars.lisp
(in-package "COMMON-LISP-USER") ;;; -------------------------------------------------------------------- ;;; Load the generator (load (make-pathname :name "generate" :type "lisp" :version nil :defaults (or *load-pathname* #P"./"))) ;;; -------------------------------------------------------------------- ;;; generate the program ;;; (defparameter *source-directory* (make-pathname :name nil :type nil :version nil :defaults (or *load-pathname* (truename (first (directory #P"./*.lisp")))))) (defparameter *asdf-directories* (mapcar (lambda (path) (make-pathname :name nil :type nil :version nil :defaults path)) (append (directory (merge-pathnames "**/*.asd" *source-directory* nil)) (list *source-directory*)))) (defparameter *release-directory* #P"HOME:bin;" "Where the executable will be stored." ) (generate-program :program-name "make-print-vars" :main-function "COM.INFORMATIMAGO.TOOLS.MAKEFILE.PRINT-VARS:MAIN" :system-name "make-print-vars" :system-list '() :init-file nil ;; "~/.make-print-vars.lisp" :version "1.0.0" :copyright (format nil "Copyright Pascal J. Bourguignon 2023 - 2023~%License: AGPL3") :source-directory *source-directory* :asdf-directories *asdf-directories* :release-directory *release-directory*)
1,562
Common Lisp
.lisp
24
50.333333
125
0.512402
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
68685f89bf7e9063f6aa398c958c16a74df85224c70cc77032613eb5d1657b8f
4,787
[ -1 ]
4,788
make-parser.lisp
informatimago_lisp/tools/make/make-parser.lisp
(defstruct floc filename lineno offset) (defstruct ebuffer buffer current-line-pos next-line-pos stream floc) (defstruct vmodifiers assign define underfine override private export) (deftype make-word-type () '(member :bogus :eol :static :variable :colon :dcolon :semicolon :varassign :ampcolon :ampdcolon)) (defstruct conditionals if-cmds allocated ignoring seen-else) (defvar *conditionals* (make-conditionals)) (defvar *default-include-directories* '()) (defvar *include-directories* '()) (defvar *max-incl-len* 0) (defvar *reading-file* nil "Current floc") (defvar *read-files* nil "goaldep") (defconstant *command-prefix* " " "TAB") (defun trim-starting-spaces (string) (left-trim-string string #(#\space #\tab #\page #\vt))) (defun parse-makefile (ebuf set-default) (let (collapsed commands commands-started (commands-index 0) targets-started ignoring in-ignored-define no-targets also-make-targets filenames depstr (nlines 0) two-colon (prefix *command-prefix*) pattern pattern-percent fstart (fi (make-floc))) (flet ((record-waiting-files () (when filenames (setf (floc-lineno fi) targets-started (floc-offset fi) 0) (record-files filenames also-make-targets pattern pattern-percen destr commands-started commands-index commands two-colon prefix fi) (setf filenames nil)) (setf commands-index 0 no-targets nil pattern nil also-make-targets nil))) (setf pattern-precen nil commands-started t targets-started t fstart (ebuffer->flock ebuf) (floc-filename fi) (floc-filename (ebuffer-floc ebuf))) ;; Loop over lines in the file. ;; The strategy is to accumulate target names in FILENAMES, dependencies ;; in DEPS and commands in COMMANDS. These are used to define a rule ;; when the start of the next rule (or eof) is encountered. ;; ;; When you see a "continue" in the loop below, that means we are moving on ;; to the next line. If you see record_waiting_files(), then the statement ;; we are parsing also finishes the previous rule. (loop :named parse :do (block continue (flet ((next () (next))) (let ((linelen 0) line (wlen 0) p p2 (vmod (make-vmodifiers))) ;; At the top of this loop, we are starting a brand new line. ;; Grab the next line to be evaluated (incf (floc-lineno ebuf) nlines) (setf nlines (readlines ebuf)) ;; If there is nothing left to eval, we're done. (when (minusp nlines) (return-from parse)) (setf line (ebuffer-buffer ebuf)) ;; Note: in CL we don't need to check the UTF-8 BOM, since ;; it's done by the stream external-format coding. ;; If this line is empty, skip it. (when (zerop (length line)) (next)) (setf linelen (length line)) ;; Check for a shell command line first. ;; If it is not one, we can stop treating cmd_prefix specially. (when (char= command-prefix (aref line 0)) ;; Ignore the commands in a rule with no targets. (when no-targets (next)) (when filenames (when ignoring ;; Yep, this is a shell command, and we don't care. (next)) (when (null commands) (setf commands-started (floc-lineno (ebuffer-floc ebuf)))) ;; Append this command line to the line being accumulated. ;; Skip the initial command prefix character. (push (subseq line 1) commands) (next))) ;; This line is not a shell command line. Don't worry about whitespace. ;; Get more space if we need it; we don't need to preserve the current ;; contents of the buffer. (setf collapsed line) (setf collapsed (collapse-continuations collapsed)) (setf collapsed (remove-comments collapsed)) (setf collapsed (trim-starting-spaces collapsed)) ;; See if this is a variable assignment. We need to do this early, to ;; allow variables with names like 'ifdef', 'export', 'private', etc. (setf p (parse-variable-assignment collapsed 0 vmod)) (when (vmodifiers-assign vmod) (let (v (origin (if (vmodifiers-override vmod) :override :file))) ;; If we're ignoring then we're done now. (when ignoring (when (vmodifiers-define vmod) (setf in-ignored-define t)) (next)) ;; Variable assignment ends the previous rule. (record-waiting-files) (when (vmodifiers-undefine vmod) (do-undefine p origin ebuf) (next)) (if (vmodifiers-define vmod) (setf v (do-define p origin ebuf)) (setf v (try-variable-definition fstart p origin 0))) (assert v) (unless (eq :default (vmodifiers-export vmod)) (setf (variable-export v) (vmodifier-export vmod))) (when (vmodifiers-preivate vmod) (setf variable-private-var v) t) ;; This line has been dealt with. (next))) ;; If this line is completely empty, ignore it. (when (zerop (length p)) (next)) (multiple-value-setq (token p2) (end-of-token p)) (setf p2 (trim-starting-spaces p2)) ;; If we're in an ignored define, skip this line (but maybe get out). (when in-ignored-define ;; See if this is an endef line (plus optional comment). (if (and (string= "endef" token) (stop-set p2 '(or map-comment map-nul))) (setf in-ignored-define nil)) (next)) ;; Check for conditional state changes. (let ((i (conditional-line p token fstart))) (case i ((-2)) ((-1) (error "invalid syntax in conditional ~S" fstart)) (otherwise (setf ignoring i) (next)))) ;; Nothing to see here... move along. (when ignoring (next)) ;; Manage the "export" keyword used outside of variable assignment ;; as well as "unexport". (let ((exporting (string= "export" token))) (when (or exporting (string= "unexport" token)) ;; Export/unexport ends the previous rule. (record-waiting-files) ;; (un)export by itself causes everything to be (un)exported. (if (zerop (length p2)) (setf export-all-variables exporting) (let (l cp ap) ;; Expand the line so we can use indirect and constructed ;; variable names in an (un)export command. (setf cp (allocated-variable-expand p2)) (loop :for p :in (split-tokens cp) (let ((v (lookup-variable p))) (unless v (setf v (define-variable-global p "" :file 0 fstart))) (setf (variable-export v) (if exporting :export :noexport)))))) (next))) ;; Handle the special syntax for vpath. (when (string= "vpath" token) (let (cp (vpath nil)) ;; vpath ends the previous rule. (record-waiting-files) (setf cp (variable-expand p2)) (let ((tokens (split-tokens cp))) (when tokens (setf vpat (pop tokens))) (construct-vpah-list vpath tokens))) (next)) )))))))
9,416
Common Lisp
.lisp
210
28.014286
99
0.484829
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f88dc8df33e0fbf7a9bc92e48fb19f9adc6b1103fa7ed40ad7c17b7761ceecff
4,788
[ -1 ]
4,789
make-print-vars.lisp
informatimago_lisp/tools/make/make-print-vars.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: make-dump-makefile-vars.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Extracts the variable names from variable definitions from a makefile, ;;;; and prints a rule to print the value of each variable. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2023-04-24 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2023 - 2023 ;;;; ;;;; 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/>. ;;;;************************************************************************** (defpackage "COM.INFORMATIMAGO.TOOLS.MAKEFILE.PRINT-VARS" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM" "COM.INFORMATIMAGO.COMMON-LISP.TOOLS.MAKE") (:export "MAIN")) (in-package "COM.INFORMATIMAGO.TOOLS.MAKEFILE.PRINT-VARS") (defun split-tokens (line rest-of-lines) ;; TODO: use a proper Makefile token parser!!! (loop :with eof := (length line) :with start := 0 :with end := 0 :while (< end eof) :collect (loop :with state := :in-token :until (eql state :got-token) :do (let ((ch (aref line end))) (cond ((find ch "!\"%&'()*,-./0123456789;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~") (incf end)) ((char= ch #\\) (incf end 2)) ((char= ch #\$) (incf end) (cond ((<= eof end) (setf state :got-token)) ((char= (aref line end) #\$) (incf end) (setf state :got-token)) ((char= (aref line end) #\() (incf end) (loop :while (and (<= eof end) rest-of-lines) :do (setf line (concatenate 'string line (pop rest-of-lines)) eof (length line))) (when (<= eof end) (error "EOF in $(…) expression~%~S" line)) (loop :while (char/= (aref line end) #\)) :do (incf end) :finally (if (< end eof) (progn (incf end) (setf state :got-token)) ))) (t (incf end)))) ((find ch "+?") ; += ?= (cond ((<= eof (1+ end)) (incf end) (setf state :got-token)) ((char= (aref line (1+ end)) #\=) (when (= start end) (incf end 2)) (setf state :got-token)) (t (incf end)))) ((char= ch #\:) ; : or := (cond ((<= eof (1+ end)) (incf end)) ((char= (aref line (1+ end)) #\=) (when (= start end) (incf end 2))) (t (when (= start end) (incf end)))) (setf state :got-token)) ((char= ch #\=) (when (= start end) (incf end)) (setf state :got-token)) ((find ch #(#\space #\tab)) (if (< start end) (setf state :got-token) (loop :while (and (< end eof) (find (aref line end) #(#\space #\tab))) :do (incf end) :finally (setf start end)))) ((char= ch #\#) ;; if # is at the start of a token, ;; then it's a comment to the end of the line ;; else it's a constituent character. (if (= start end) (setf end eof) (incf end))) (t (error "Invalid character in makefile: ~C (~D)~%~S" ch (char-code ch) line)))) :do (when (<= eof end) (setf state :got-token)) :finally (return (values (prog1 (subseq line start end) (setf start end)) rest-of-lines))))) (defun join-continuation-lines (lines) (loop :with new-lines := '() :with big-line := '() :for line :in lines :if (and (plusp (length line)) (char= #\\ (aref line (1- (length line))))) :do (push (subseq line 0 (1- (length line))) big-line) (push " " big-line) :else :do (if big-line (progn (push line big-line) (push (format nil "~{~A~}" (nreverse big-line)) new-lines) (setf big-line '())) (push line new-lines)) :end :finally (return (nreverse new-lines)))) (defun process-makefile (lines handler) (let ((lines (join-continuation-lines lines))) (loop :while lines :do (let ((line (pop lines))) (unless (prefixp "#" line) (let ((tokens (split-tokens line))) (cond ((null tokens)) ((string= "define" (first tokens)) (funcall handler :define (cons line (loop :for line := (pop lines) :collect line :until (prefixp "endef" line))))) ((member ":" (rest tokens) :test (function string=)) (funcall handler :rule (cons line (loop :for line := (pop lines) :collect line :while (or (prefixp "#" line) (prefixp " " line) (prefixp " " line)))))) ((member (elt tokens 1) '(":=" "=" "+=" "?=") :test (function string=)) (funcall handler :variable tokens)) (t (error "Unexpected Makefile line: ~S~%~S" line tokens)))))))) (values)) (defun extract-variables-from-makefile (lines) (let ((variables '()) (i 0) (last-line nil)) (process-makefile lines (lambda (kind lines) ;; (print (list kind lines)) (incf i) (setf last-line (first lines)) (when (zerop (mod i 100000)) (format *trace-output* "# ~D: ~A~%" i last-line) (finish-output *trace-output*)) (when (eq kind :variable) (push (string-trim " " (subseq (first lines) 0 (or (search ":=" (first lines)) (search "=" (first lines)) 0))) variables)))) (sort variables (lambda (a b) (let ((ap (position #\. a)) (bp (position #\. b))) (if (and ap bp) (let ((ra (subseq a ap)) (rb (subseq b bp))) (if (string= ra rb) (string< a b) (string< ra rb))) (string< a b))))))) (defun quoted (string) (with-output-to-string (*standard-output*) (princ "'") (loop :for ch :across string :do (case ch ((#\\ #\') (princ "\\") (princ ch)) (otherwise (princ ch)))) (princ "'"))) (defun regexp-quoted (string) (with-output-to-string (*standard-output*) (loop :for ch :across string :do (case ch ((#\[ #\( #\. #\\ #\? #\+ #\^ #\$) (princ "\\") (princ ch)) (otherwise (princ ch)))))) (defun generate-print-vars-rule (variables output) (format output "# -*- mode:makefile -*-~%") (format output "vars:~%~:{ @printf '%s = %s\\n' ~A \"$(~A)\"~%~}~%" (mapcar (lambda (var) (list (quoted var) var)) variables))) (defun generate-variable-mangling (variables output) (format output "# -*- mode:sed -*-~%") (format output "~:{s/\\<~A\\>/~A/g~%~}" (mapcar (lambda (var) (list (regexp-quoted var) (gentemp "V"))) variables))) (defun usage (pname) (format t "~A usage:~%" pname) (format t " ~A -h|--help~%" pname) (format t " ~A -h|--help~%" pname) (format t " ~A [-m|--mangle] $path_to_makefile > $path_to_makefile-vars_include~%" pname) (format t " ~A [-m|--mangle] < $path_to_makefile > $path_to_makefile-vars_include~%" pname)) (defconstant +ex-ok+ 0) (defconstant +ex-usage+ 64) (defconstant +ex-oserr+ 71) (defun main (pname &rest arguments) (handler-case (let ((action (function generate-print-vars-rule))) ;; check options: (cond ((or (member "-h" arguments :test (function string=)) (member "--help" arguments :test (function string=))) (usage pname) (return-from main +ex-ok+)) ((or (string= "-m" (first arguments)) (string= "--mangle" (first arguments))) (pop arguments) (setf action (function generate-variable-mangling)))) ;; check remaining unknown options: (when (find-if (lambda (argument) (prefixp "-" argument)) arguments) (error "Invalid argument: ~A" (find-if (lambda (argument) (prefixp "-" argument)) arguments)) (return-from main +EX-USAGE+)) ;; perform action: (funcall action (extract-variables-from-makefile (cond ((endp arguments) (stream-to-string-list *standard-input*)) ((endp (rest arguments)) (let ((makefile-namestring (first arguments))) (string-list-text-file-contents makefile-namestring))) (t (error "Too many arguments.")))) *standard-output*)) (CCL::SIMPLE-STREAM-ERROR (err) (format *error-output* "ERROR: ~A~%" err) (finish-output *error-output*) (return-from main +ex-oserr+)) (error (err) (print (type-of err) *error-output*) (format *error-output* "ERROR: ~A~%" err) (finish-output *error-output*) (return-from main +ex-usage+))) +ex-ok+) ;; #-testing ;; (ccl:quit (apply (function main) ;; (first (uiop:raw-command-line-arguments)) ;; (uiop:command-line-arguments)))
12,760
Common Lisp
.lisp
287
28.101045
125
0.420447
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
131703c156e1fb71d28c4e3318bc6f4d83e0f1c25b442e9da2607be322502d36
4,789
[ -1 ]
4,790
parser.lisp
informatimago_lisp/tools/make/parser.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: parser.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A parser for GNU makefiles ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2023-04-20 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2023 - 2023 ;;;; ;;;; 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/>. ;;;;************************************************************************** (in-package "COM.INFORMATIMAGO.TOOLS.MAKE.PARSER") ;;;--------------------------------------------------------------------- (defgeneric parse-makefile (makefile &key &allow-other-keys)) ;;;--------------------------------------------------------------------- (defstruct floc filename lineno offset) (defstruct ebuffer (buffer "") stream floc) (defstruct vmodifiers assign define underfine override private export) (deftype make-word-type () '(member :bogus :eol :static :variable :colon :dcolon :semicolon :varassign :ampcolon :ampdcolon)) (defstruct conditionals if-cmds allocated ignoring seen-else) (defvar *conditionals* (make-conditionals)) (defvar *default-include-directories* '()) (defvar *include-directories* '()) (defvar *max-incl-len* 0) (defvar *reading-file* nil "Current floc") (defvar *read-files* nil "goaldep") (defconstant *command-prefix* " " "TAB") (defun readline (ebuf) ;; Note: readstring is implemented with with-input-from-string in (parse-makefile (string)) (loop :with nlines := 0 :for line := (read-line (ebuffer-stream ebuf) nil nil) :while line :do ;; This only happens when the first thing on the line is a ;; '\0'. It is a pretty hopeless case, but (wonder of ;; wonders) Athena lossage strikes again! (xmkmf puts NULs in ;; its makefiles.) There is nothing really to be done; we ;; synthesize a newline so the following line doesn't appear ;; to be part of this line. (when (find #\null line) (warn "NUL character seen; rest of line ignored") (setf line (subseq line 0 (position #\null line)))) ;; We got a newline, so add one to the count of lines. (incf nlines) ;; Check to see if the line was really ended with CRLF; if so ignore ;; the CR. #-(or windows dos emx) (setf line (delete #\return line)) (let ((blen (length line))) (setf line (string-right-trim "\\" line)) (setf (ebuffer-buffer ebuf) (if (oddp (- blen (length line))) (if (ebuffer-buffer ebuf) (concatenate 'string (ebuffer-buffer ebuf) line) line) line))) :finally ;; /* If we found some lines, return how many. ;; If we didn't, but we did find _something_, that indicates we read the last ;; line of a file with no final newline; return 1. ;; If we read nothing, we're at EOF; return -1. */ (return (cond ((plusp nlines) (values nlines line)) ((ebuffer-buffer ebuf) (values 1 line)) (t (values -1 nil)))))) (defun test/readline () (assert (equal (multiple-value-list (with-input-from-string (makefile " NAME = make-print-vars TEST_MAKEFILE ?= /build/pbourguignon/work/build.devel/.makedump all:$(NAME) $(NAME) --help \ && $(NAME) --mangle $(TEST_MAKEFILE) > m.sed \ && $(NAME) $(TEST_MAKEFILE) > $(TEST_MAKEFILE)-vars $(NAME):$(NAME).lisp ccl < generate-exe.lisp >$(NAME).log 2>$(NAME).err || ( cat $(NAME).err ; exit 200 ) clean: -rm -f *.lx64fsl -rm -f *.out *.err -rm -f system-index.txt ") (let ((ebuf (make-ebuffer :stream makefile :floc (make-floc :filename "/mem/string/makefile" :lineno 1 :offset 0)))) (values (readline ebuf) (ebuffer-buffer ebuf))))) '(1 "NAME = make-print-vars"))) :success) ;; Note: we don't want to hardwire with #+ those values, ;; to be able to read foreign files (cross tools) (defconstant +MAP-NUL+ #x0001) (defconstant +MAP-BLANK+ #x0002) (defconstant +MAP-NEWLINE+ #x0004) (defconstant +MAP-COMMENT+ #x0008) (defconstant +MAP-SEMI+ #x0010) (defconstant +MAP-EQUALS+ #x0020) (defconstant +MAP-COLON+ #x0040) (defconstant +MAP-VARSEP+ #x0080) (defconstant +MAP-PIPE+ #x0100) (defconstant +MAP-DOT+ #x0200) (defconstant +MAP-COMMA+ #x0400) (defconstant +MAP-USERFUNC+ #x2000) (defconstant +MAP-VARIABLE+ #x4000) (defconstant +MAP-DIRSEP+ #x8000) #+vms (defconstant +MAP-VMSCOMMA+ +MAP-COMMA+) #-vms (defconstant +MAP-VMSCOMMA+ #x0000) (defconstant +MAP-SPACE+ (logior +MAP-BLANK+ +MAP-NEWLINE+)) #+(and dos (not cygwin)) (defconstant +PATH-SEPARATOR-CHAR+ #\;) #+(and dos (not cygwin)) (defconstant +MAP-PATHSEP+ +MAP-SEMI+) #+unix (defconstant +PATH-SEPARATOR-CHAR+ #\:) #+unix (defconstant +MAP-PATHSEP+ +MAP-COLON+) ;; (defconstant +PATH-SEPARATOR-CHAR+ #\;) ;; (defconstant +MAP-PATHSEP+ +MAP-SEMI+) ;; ;; (defconstant +PATH-SEPARATOR-CHAR+ #\,) ;; (defconstant +MAP-PATHSEP+ +MAP-COMMA+) (defvar *whitespaces* #(#\space #\tab #\page #\vt #\newline #\linefeed #\return)) (defun whitespacep (ch) (find ch *whitespaces*)) (defun trim-starting-spaces (string) (string-left-trim *whitespaces* string)) (defparameter *stopchar-map* (let ((map (make-array 128 :element-type 'fixnum :initial-element 0)) (maxcode 127)) (flet ((enter (ch flag) (assert (<= (char-code ch) maxcode)) (setf (aref map (char-code ch)) flag))) (enter #\Null +MAP-NUL+) (enter #\# +map-comment+) (enter #\; +map-semi+) (enter #\= +map-equals+) (enter #\: +map-colon+) (enter #\| +map-pipe+) (enter #\. (logior +map-dot+ +map-userfunc+)) (enter #\( +map-varsep+) (enter #\{ +map-varsep+) (enter #\} +map-varsep+) (enter #\) +map-varsep+) (enter #\$ +map-variable+) (enter #\_ +map-userfunc+) (enter #\- +map-userfunc+) (enter #\space +map-blank+) (enter #\tab +map-blank+) (enter #\/ +map-dirsep+) #+vms (enter #\: +map-dirsep+) #+vms (enter #\] +map-dirsep+) #+vms (enter #\> +map-dirsep+) #+dos (enter #\\ +map-dirsep+)) (loop :for i :from 1 :to maxcode :do (cond ((and (whitespacep (code-char i)) (zerop (logand (aref map i) +map-blank+))) (setf (aref map i) (logior (aref map i) +map-newline+))) ((alphanumericp (code-char i)) (setf (aref map i) (logior (aref map i) +map-userfunc+))))) map)) (declaim (inline any-set stop-set isblank isspace isdirsep has-drivespec end-of-token map-stopchar)) (defun map-stopchar (ch) (let ((code (char-code ch))) (if (<= (length *stopchar-map*) code) 0 (aref *stopchar-map* code)))) (defun any-set (a b) (not (zerop (logand a b)))) (defun stop-set (ch mask) (any-set (map-stopchar ch) mask)) (defun isblank (ch) (stop-set ch +map-blank+)) (defun isspace (ch) (stop-set ch +map-space+)) (defun isdirsep (ch) (stop-set ch +map-dirsep+)) (defun has-drivespec (ch) (stop-set ch +map-dirsep+)) (defun end-of-token (ch) (stop-set ch (logior +map-space+ +map-nul+))) (defun split-tokens (source) ;; char* find_next_token(const char** ptr,size_t* lengthpr); ;; find-if = NEXT_TOKEN() (loop :with end := 0 :with eos := (length source) :for start := (or (position-if (lambda (ch) (not (isspace ch))) source) eos) :then (or (position-if (lambda (ch) (not (isspace ch))) source :start end) eos) :while (< start eos) :do (setf end (or (position-if (function end-of-token) source :start start) eos)) :collect (subseq source start end))) ;; (defconstant +PARSEFS-NONE+ #x0000) ;; (defconstant +PARSEFS-NOSTRIP+ #x0001) ;; (defconstant +PARSEFS-NOAR+ #x0002) ;; (defconstant +PARSEFS-NOGLOB+ #x0004) ;; (defconstant +PARSEFS-EXISTS+ #x0008) ;; (defconstant +PARSEFS-NOCACHE+ #x0010) ;; (defconstant +PARSEFS-ONEWORD+ #x0020) ;; (defconstant +PARSEFS-WAIT+ #x0040) (deftype flag () '(member :nostrip :noar :noglob :exists :nocache :oneword :wait)) (defun find-map-unquote (source start stopmap) ;; Search STRING for an unquoted STOPMAP. ;; Backslashes quote elements from STOPMAP and backslash. ;; Quoting backslashes are removed from STRING by compacting it into itself. ;; Returns a pointer to the first unquoted STOPCHAR if there is one, or nil if ;; there are none. ;; ;; If MAP_VARIABLE is set, then the complete contents of variable references ;; are skipped, even if they contain STOPMAP characters. ;; Returns: the token text and the end position in source. (setf stopmap (logior stopmap +map-nul+)) (let* ((eos (length source)) (end start)) ;; NOTE: current implementation in make (4.+) read.c says that $() ;; has higher priority than \x : ;; - the code tests for $ before testing for a previous \ ;; - the result is that: ;; c=n ;; s=\$(c) ;; reads as s=\n (after $(c) expansion) (loop :do (setf end (or (position-if (lambda (ch) (stop-set ch stopmap)) source :start end) eos)) :while (< end eos) ;; If we stopped due to a variable reference, skip over its contents. :do (cond ((char= #\$ (aref source end)) (incf end) (when (< end eos) (let ((openparen (aref source end))) (case openparen ((#\( #\{) (let ((closeparen (if (char= #\( openparen) #\) #\})) (pcount 1)) (incf end) (loop :while (and (< end eos) (plusp pcount)) :do (cond ((char= (aref source end) openparen) (incf pcount)) ((char= (aref source end) closeparen) (decf pcount))) (incf end)))))) ;; Skipped the variable reference: look for STOPCHARS again. )) ((and (< start end) (char= (aref source (1- end)) #\\)) ;; Search for more backslashes. (let ((i (- end 2))) (loop :while (and (<= start i) (char= (aref source i) #\\)) :do (decf i)) (incf i) (multiple-value-bind (backslash-count escape-count) (truncate (- end i) 2) (replace source source :start2 start :end2 (- end backslash-count) :start1 (+ start backslash-count)) (incf start backslash-count) (when (zerop escape-count) ;; All the backslashes quoted each other; the STOPCHAR was ;; unquoted. (return-from find-map-unquote (values end (subseq source start end))))) ;; The STOPCHAR was quoted by a backslash. Look for another. (incf end))) (t (return-from find-map-unquote (values end (subseq source start end)))))) (values end nil))) (defun test/find-map-unquote () (assert (equal (multiple-value-list (find-map-unquote "foo bar baz" 4 +MAP-BLANK+)) '(7 "bar"))) (assert (equal (multiple-value-list (find-map-unquote "foo bar" 4 +MAP-BLANK+)) '(7 nil))) ;; reads $(…): (assert (equal (multiple-value-list (find-map-unquote "foo bar$(baz and,quux) bozo" 4 +MAP-BLANK+)) '(12 "bar$(baz"))) (assert (equal (multiple-value-list (find-map-unquote "foo bar$(baz and,quux) bozo" 4 (logior +MAP-BLANK+ +map-variable+))) '(22 "bar$(baz and,quux)"))) (assert (equal (multiple-value-list (find-map-unquote "foo bar\\\\$(baz and,quux) bozo" 4 (logior +MAP-BLANK+ +map-variable+))) '(24 "bar\\\\$(baz and,quux)"))) (assert (equal (multiple-value-list (find-map-unquote "foo bar\\$(baz and,quux) bozo" 4 (logior +MAP-BLANK+ +map-variable+))) '(23 "bar\\$(baz and,quux)"))) ;; reads \\x: (assert (equal (multiple-value-list (find-map-unquote "foo bar\\quux bozo" 4 (logior +MAP-BLANK+ +map-variable+))) '(12 "bar\\quux"))) (assert (equal (multiple-value-list (find-map-unquote "foo bar\\\\quux bozo" 4 (logior +MAP-BLANK+ +map-variable+))) '(13 "bar\\\\quux"))) (assert (equal (multiple-value-list (find-map-unquote "foo bar\\ quux bozo" 4 (logior +MAP-BLANK+ +map-variable+))) '(13 "bar\\ quux"))) (assert (equal (multiple-value-list (find-map-unquote "foo bar\\\\ quux bozo" 4 (logior +MAP-BLANK+ +map-variable+))) '(9 "bar\\"))) :success) (defun parse-file-seq (source stopmap prefix flags) " PREFIX: added to each parsed file. STOPMAP: an integer mask of +MAP-…+ FLAGS: a list of RETURN: a list of namestrings. " (let ((findmap (logior stopmap +map-vmscomma+ +map-nul+)) (found-wait nil) (gl (make-glob))) (unless (member :oneword flags) (setf findmap (logior findmap +map-blank+))) (setf stopmap (logior stopmap +map-nul+)) ; Always stop on NUL. (unless (member :noglob flags) (dir-setup-glob gl)) ;; Skip whitespace; at the end of the string or STOPCHAR we're done. (loop :with end := 0 :with eos := (length source) :for start := (or (position-if (lambda (ch) (not (isspace ch))) source) eos) :then (or (position-if (lambda (ch) (not (isspace ch))) source :start end) eos) :while (or (< start eos) (stop-set (aref source start) stopmap)) :do (setf end (find-map-unquote source start findmap)) (setf end (or (position-if (function end-of-token) source :start end) eos)) :collect (subseq source start end)) (loop :for ) )) (defvar *command-prefix* nil "NIL => Commands start with a TAB; otherwise they start with that string.") (defmethod parse-makefile ((ebuf ebuffer) &key set-default &allow-other-keys) (let (collapsed commands commands-started (commands-index 0) targets-started ignoring in-ignored-define no-targets also-make-targets filenames depstr (nlines 0) two-colon (prefix *command-prefix*) pattern pattern-percent fstart (fi (make-floc)) token) (flet ((record-waiting-files () (when filenames (setf (floc-lineno fi) targets-started (floc-offset fi) 0) (record-files filenames also-make-targets pattern pattern-percent depstr commands-started commands-index commands two-colon prefix fi) (setf filenames nil)) (setf commands-index 0 no-targets nil pattern nil also-make-targets nil))) (setf pattern-percent nil commands-started t targets-started t fstart (ebuffer-floc ebuf) (floc-filename fi) (floc-filename (ebuffer-floc ebuf))) ;; Loop over lines in the file. ;; The strategy is to accumulate target names in FILENAMES, dependencies ;; in DEPS and commands in COMMANDS. These are used to define a rule ;; when the start of the next rule (or eof) is encountered. ;; ;; When you see a "continue" in the loop below, that means we are moving on ;; to the next line. If you see record_waiting_files(), then the statement ;; we are parsing also finishes the previous rule. (loop :named parse :do (block continue (flet ((next () (return-from continue))) (let ((linelen 0) line (wlen 0) p p2 (vmod (make-vmodifiers))) ;; At the top of this loop, we are starting a brand new line. ;; Grab the next line to be evaluated (incf (floc-lineno ebuf) nlines) (setf nlines (readline ebuf)) ;; If there is nothing left to eval, we're done. (when (minusp nlines) (return-from parse)) (setf line (ebuffer-buffer ebuf)) ;; Note: in CL we don't need to check the UTF-8 BOM, since ;; it's done by the stream external-format coding. ;; If this line is empty, skip it. (when (zerop (length line)) (next)) (setf linelen (length line)) ;; Check for a shell command line first. ;; If it is not one, we can stop treating cmd_prefix specially. (when (char= *command-prefix* (aref line 0)) ;; Ignore the commands in a rule with no targets. (when no-targets (next)) (when filenames (when ignoring ;; Yep, this is a shell command, and we don't care. (next)) (when (null commands) (setf commands-started (floc-lineno (ebuffer-floc ebuf)))) ;; Append this command line to the line being accumulated. ;; Skip the initial command prefix character. (push (subseq line 1) commands) (next))) ;; This line is not a shell command line. Don't worry about whitespace. ;; Get more space if we need it; we don't need to preserve the current ;; contents of the buffer. (setf collapsed line) (setf collapsed (collapse-continuations collapsed)) (setf collapsed (remove-comments collapsed)) (setf collapsed (trim-starting-spaces collapsed)) ;; See if this is a variable assignment. We need to do this early, to ;; allow variables with names like 'ifdef', 'export', 'private', etc. (setf p (parse-variable-assignment collapsed 0 vmod)) (when (vmodifiers-assign vmod) (let (v (origin (if (vmodifiers-override vmod) :override :file))) ;; If we're ignoring then we're done now. (when ignoring (when (vmodifiers-define vmod) (setf in-ignored-define t)) (next)) ;; Variable assignment ends the previous rule. (record-waiting-files) (when (vmodifiers-undefine vmod) (do-undefine p origin ebuf) (next)) (if (vmodifiers-define vmod) (setf v (do-define p origin ebuf)) (setf v (try-variable-definition fstart p origin 0))) (assert v) (unless (eq :default (vmodifiers-export vmod)) (setf (variable-export v) (vmodifier-export vmod))) (when (vmodifiers-preivate vmod) (setf (variable-private-var v) t)) ;; This line has been dealt with. (next))) ;; If this line is completely empty, ignore it. (when (zerop (length p)) (next)) (multiple-value-setq (token p2) (end-of-token p)) (setf p2 (trim-starting-spaces p2)) ;; If we're in an ignored define, skip this line (but maybe get out). (when in-ignored-define ;; See if this is an endef line (plus optional comment). (if (and (string= "endef" token) (stop-set p2 '(or map-comment map-nul))) (setf in-ignored-define nil)) (next)) ;; Check for conditional state changes. (let ((i (conditional-line p token fstart))) (case i ((-2)) ((-1) (error "invalid syntax in conditional ~S" fstart)) (otherwise (setf ignoring i) (next)))) ;; Nothing to see here... move along. (when ignoring (next)) ;; Manage the "export" keyword used outside of variable assignment ;; as well as "unexport". (let ((exporting (string= "export" token))) (when (or exporting (string= "unexport" token)) ;; Export/unexport ends the previous rule. (record-waiting-files) ;; (un)export by itself causes everything to be (un)exported. (if (zerop (length p2)) (setf export-all-variables exporting) (let (l cp ap) ;; Expand the line so we can use indirect and constructed ;; variable names in an (un)export command. (setf cp (allocated-variable-expand p2)) (loop :for p :in (split-tokens cp) (let ((v (lookup-variable p))) (unless v (setf v (define-variable-global p "" :file 0 fstart))) (setf (variable-export v) (if exporting :export :noexport)))))) (next))) ;; Handle the special syntax for vpath. (when (string= "vpath" token) (let (cp (vpath nil)) ;; vpath ends the previous rule. (record-waiting-files) (setf cp (variable-expand p2)) (let ((tokens (split-tokens cp))) (when tokens (setf vpath (pop tokens))) (construct-vpath-list vpath tokens))) (next)) ;; Handle include and variants. (when (or (string= "include" token) (string= "-include" token) (string= "sinclude" token)) ;; We have found an 'include' line specifying a nested ;; makefile to be read at this point. */ (let (save new-conditionals files (noerror (char/= #\i (aref token 0)))) ;; Include ends the previous rule. (record-waiting-files) (setf p (allocated-variable-expand p2)) ;; If no filenames, it's a no-op. (unless p (next)) ;; Parse the list of file names. Don't expand archive references! (setf files (parse-file-seq p)) ) (next)) ;; Handle the special syntax for define. (when (string= "define" token) (let (cp (name nil) (value nil)) ;; define ends the previous rule. (record-waiting-files) (setf cp (allocated-variable-expand p2)) (setf cp (trim-starting-spaces cp)) (setf name (pop (split-tokens cp))) (setf value (trim-starting-spaces cp)) (define-variable-global name value :file 0 fstart)) (next)) ))))))) ;;;--------------------------------------------------------------------- (defmethod parse-makefile ((makefile pathname) &key &allow-other-keys) (with-open-file (input makefile) (parse-makefile input))) (defmethod parse-makefile ((makefile-contents string) &key &allow-other-keys) (with-input-from-string (input makefile-contents) (parse-makefile input))) (defmethod parse-makefile ((makefile stream) &key &allow-other-keys) (let ((ebuf (make-ebuffer :stream makefile :floc (make-floc :filename (namestring (pathname makefile)) :lineno 1 :offset 0)))) (parse-makefile ebuf))) ;;;--------------------------------------------------------------------- (defun test/all () (test/find-map-unquote) (test/readline)) (test/all)
27,142
Common Lisp
.lisp
608
32.348684
99
0.512706
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a16b3312d85a7a2e78a0c060f2eaaea2a1c3c1de051570bdbb319168d92192ac
4,790
[ -1 ]
4,791
generate.lisp
informatimago_lisp/tools/make/generate.lisp
(in-package "COMMON-LISP-USER") ;; Remove used package from CL-USER to avoid conflicts. ;; Note: this doesn't remove directly imported symbols. (mapc (lambda (package) (unuse-package package "COMMON-LISP-USER")) (set-difference (copy-seq (package-use-list "COMMON-LISP-USER")) (delete nil (list ;; A list of all the "CL" packages possible: (find-package "COMMON-LISP"))))) ;;; -------------------------------------------------------------------- ;;; Utilities ;;; (defun say (format-control &rest arguments) (format t "~&;;; ~?~%" format-control arguments) (finish-output)) (defun runtime-function (name) (read-from-string name)) (defun runtime-symbol (name) (read-from-string name)) (defun runtime-value (name) (symbol-value (read-from-string name))) (defun (setf runtime-value) (new-value name) (setf (symbol-value (read-from-string name)) new-value)) (defun load-quicklisp () (say "Loading quicklisp.") (load #P"~/quicklisp/setup.lisp") (setf (runtime-value "QUICKLISP-CLIENT:*QUICKLOAD-VERBOSE*") t)) (defun configure-asdf-directories (directories &key append) (if (member :asdf3 *features*) (funcall (runtime-function "ASDF:INITIALIZE-SOURCE-REGISTRY") `(:source-registry :ignore-inherited-configuration ,@(mapcar (lambda (dir) `(:directory ,dir)) (remove-duplicates directories :test (function equalp))) ,@(when append `(:default-registry)))) (setf (runtime-value "ASDF:*CENTRAL-REGISTRY*") (remove-duplicates (if append (append directories (runtime-value "ASDF:*CENTRAL-REGISTRY*")) directories) :test (function equalp))))) (defun not-implemented-yet (what) (error "~S is not implemented yet on ~A, please provide a patch!" what (lisp-implementation-type))) #-(and) (defun program-path () (let* ((argv (ext:argv)) (largv (length argv)) (args ext:*args*) (largs (length args)) (index (- largv largs 1)) (path (and (<= 0 index largv) (elt argv index)))) (cond (path path) ((and *load-truename* (string/= (file-namestring *load-truename*) "script.lisp")) (namestring *load-truename*)) (t *default-program-name*)))) (defun argv () #+ccl ccl:*command-line-argument-list* #+clisp (cons (elt (ext:argv) 0) ext:*args*) #+ecl (si::command-args) #+sbcl sb-ext:*posix-argv* #-(or ccl clisp ecl sbcl) (not-implemented-yet 'exit)) (defun exit (status) #+ccl (ccl:quit status) #+clisp (ext:quit status) #+ecl (ext:quit status) #+sbcl (sb-ext:exit :code status) #-(or ccl clisp ecl sbcl) (not-implemented-yet 'exit)) (defun make-toplevel-function (main-function-name init-file) (let ((form `(lambda () (handler-case (progn ,@(when init-file `((load ,init-file :if-does-not-exist nil))) (apply (read-from-string ,main-function-name) #+ecl (si::command-args) #-ecl (argv))) (error (err) (ignore-errors (finish-output *standard-output*)) (ignore-errors (finish-output *trace-output*)) (ignore-errors (format *error-output* "~%~A~%" err) (finish-output *error-output*)) #+ecl (ext:quit 1) #-ecl (exit 1))) (ignore-errors (finish-output *standard-output*)) (ignore-errors (finish-output *trace-output*)) #+ecl (ext:quit 0) #-ecl (exit 0)))) #+ecl (list form) #-ecl (coerce form 'function))) (defun system-cl-source-files (system) (let ((system (funcall (runtime-function "ASDF:FIND-SYSTEM") system))) (remove-duplicates (append (mapcar (runtime-function "ASDF:COMPONENT-PATHNAME") (remove-if-not (lambda (component) (typep component (runtime-symbol "ASDF:CL-SOURCE-FILE"))) (funcall (runtime-function "ASDF:COMPONENT-CHILDREN") system))) (mapcan (function system-cl-source-files) (delete-duplicates (mapcan (lambda (depend) (copy-list (funcall (runtime-function depend) system))) '("ASDF:SYSTEM-DEFSYSTEM-DEPENDS-ON" "ASDF:SYSTEM-DEPENDS-ON" "ASDF:SYSTEM-WEAKLY-DEPENDS-ON")) :test (function equal)))) :test (function equal)))) (defun system-object-files (system) (let ((system (funcall (runtime-function "ASDF:FIND-SYSTEM") system))) (remove-duplicates (append (mapcan (lambda (component) (copy-list (funcall (runtime-function "ASDF:OUTPUT-FILES") (runtime-symbol "ASDF:COMPILE-OP") component))) (funcall (runtime-function "ASDF:COMPONENT-CHILDREN") system)) (mapcan (function system-object-files) (delete-duplicates (mapcan (lambda (depend) (copy-list (funcall (runtime-function depend) system))) '("ASDF:SYSTEM-DEFSYSTEM-DEPENDS-ON" "ASDF:SYSTEM-DEPENDS-ON" "ASDF:SYSTEM-WEAKLY-DEPENDS-ON")) :test (function equal)))) :test (function equal)))) (defun slurp-stream (stream) (with-output-to-string (*standard-output*) (loop :for line := (read-line stream nil) :while line :do (write-line line)))) #+ecl (defun pre-compile-with-quicklisp (program-name main-function system-name system-list source-directory asdf-directories release-directory init-file version copyright) (declare (ignorable program-name main-function system-name system-list source-directory asdf-directories release-directory init-file version copyright)) (say "Quickloading ~S" (cons system-name system-list)) (multiple-value-bind (output status) (ext:run-program (first (argv)) (list "--norc" "--load" "generate.lisp" "--eval" (prin1-to-string `(progn (require 'cmp) (load-quicklisp) (configure-asdf-directories ',asdf-directories) (funcall (runtime-function "QL:QUICKLOAD") ',(cons system-name system-list))))) :input nil :output :stream :wait t) (unless (zerop status) (write-string (slurp-stream output))) (say " status ~S" status))) (defun generate-program (&key program-name main-function system-name system-list source-directory asdf-directories release-directory init-file version copyright) (declare (ignorable release-directory init-file system-name system-list version copyright source-directory)) #+ecl (pre-compile-with-quicklisp program-name main-function system-name system-list source-directory asdf-directories release-directory init-file version copyright) #-ecl (load-quicklisp) #+ecl (progn (require 'cmp) (say "Requiring ASDF") (require 'asdf)) (configure-asdf-directories asdf-directories) #-ecl (progn (say "Quickloading system ~A" system-name) (funcall (runtime-function "QL:QUICKLOAD") system-name) (when system-list (say "Quickloading systems ~A" system-list) (funcall (runtime-function "QL:QUICKLOAD") system-list))) (say "Generating program ~A" (merge-pathnames program-name release-directory)) #+ccl (progn ;; This doesn't return. (ccl::save-application (merge-pathnames program-name release-directory nil) :toplevel-function (make-toplevel-function main-function nil) :init-file init-file :mode #o755 :prepend-kernel t :error-handler t)) #+clisp (progn (ext::saveinitmem (merge-pathnames program-name release-directory nil) :executable t :norc t :quiet t :verbose t :script t :documentation (format nil "~A version ~A~%~A~%" program-name version copyright) :start-package (find-package "COMMON-LISP-USER") ;; locked-packages ;; :keep-global-handlers :init-function (make-toplevel-function main-function init-file)) (ext:quit 0)) #+ecl (progn #-(and) (load "hw.asd") #-(and) (asdf:oos 'asdf:program-op system-name) (funcall (runtime-function "ASDF:MAKE-BUILD") system-name :type :program :monolithic t :ld-flags '() :prologue-code "" :epilogue-code (make-toplevel-function main-function init-file) :move-here release-directory) #-(and) (progn (c:build-program (merge-pathnames program-name release-directory nil) :lisp-files (system-object-files system-name) :ld-flags '() :prologue-code "" :epilogue-code (make-toplevel-function main-function init-file)) (rename-file (make-pathname :directory (append (pathname-directory (uiop/configuration::compute-user-cache)) (rest (pathname-directory source-directory))) :name (string-downcase system-name) :type nil) (merge-pathnames program-name release-directory nil))) (ext:quit 0)) #+sbcl (sb-ext:save-lisp-and-die program-name :executable t :compression 9 :toplevel (make-toplevel-function main-function init-file)) #-(or ccl clisp ecl sbcl) (not-implemented-yet 'generate-program)) ;;;; THE END ;;;;
10,886
Common Lisp
.lisp
221
34.538462
142
0.537471
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
eadb82025b6b4b5f3038bc7a4c1eb06d0df442125300e771febc1275d876c467
4,791
[ -1 ]
4,792
com.informatimago.clisp.asd
informatimago_lisp/clisp/com.informatimago.clisp.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.clisp.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.clisp library. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2010-10-31 <PJB> Created this .asd file. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2010 - 2016 ;;;; ;;;; 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/ ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) #+clisp (when (find-package "LINUX") (pushnew :linux *features*))) #-clisp (asdf:defsystem "com.informatimago.clisp" :description "Informatimago Common Lisp Clisp Specific Packages" :long-description "There's nothing here for non-clisp implementations." :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :license "AGPL3" :version "1.4.0" #+asdf-unicode :encoding #+asdf-unicode :utf-8 :depends-on () :components ()) #+clisp (asdf:defsystem "com.informatimago.clisp" ;; system attributes: :description "Informatimago Common Lisp Clisp Specific Packages" :long-description " Various packages using clisp specific features (some of them could or should be made into implementation independant packages). " :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.4.0" :properties ((#:author-email . "[email protected]") (#:date . "Spring 2014") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.clmisc/") ((#:albert #:formats) . ("docbook")) ((#:albert #:docbook #:template) . "book") ((#:albert #:docbook #:bgcolor) . "white") ((#:albert #:docbook #:textcolor) . "black")) #+asdf-unicode :encoding #+asdf-unicode :utf-8 :depends-on ("com.informatimago.common-lisp.cesarum") :components ((:file "syslog") (:file "disk") ;; (:file "objc") (:file "string") (:file "fifo-stream") (:file "iotask") (:file "rfc1413" :depends-on ("iotask")) ;; :shared-object is not known of asdf, but is defined by clg-tools... ;; (:shared-object "libraw-memory" ;; :components ((:c-source-file "raw-memory-lib")) ;; :depends-on ()) ;; (:file "raw-memory" :depends-on ("libraw-memory")) #+linux (:file "susv3") #+linux (:file "susv3-mc3" :depends-on ("susv3")) #+linux (:file "susv3-xsi" :depends-on ("susv3")) #+linux (:file "script" :depends-on ("string")) #+linux (:file "shell") #+linux (:file "xterm" :depends-on ("susv3")) #+linux (:file "make-volumes" :depends-on ("susv3"))) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.clisp.test")))) (eval-when (:compile-toplevel :load-toplevel :execute) #+(and clisp (not linux)) (warn "System ~A is incomplete without the LINUX package." :com.informatimago.clisp) #-clisp (warn "System ~A is useless on ~A" :com.informatimago.clisp (lisp-implementation-type))) ;;;; THE END ;;;;
4,399
Common Lisp
.lisp
94
41.297872
98
0.589851
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2f681ad52a98b8eeef9e77a7e17c5c5a48204ba97bf636eca66994aedae1f5cb
4,792
[ -1 ]
4,793
clisp-ffi-howto.txt
informatimago_lisp/clisp/clisp-ffi-howto.txt
From: Hoehle, Joerg-Cyril <Joerg-Cyril.Hoehle <at> t-systems.com> Subject: FFI howto: variable length arrays (long) Newsgroups: gmane.lisp.clisp.general Date: Wed, 05 Mar 2003 16:04:26 +0100 Dear reader, [Sam: this text will hopefully answer questions regarding FOREIGN-VALUE et al.] the text below assumes some familiarity with the CLISP FFI declarations and reading of prior FFI cookbook texts of mine (i.e. sent on 12th of February 2002 to this list). How to deal with variable length (unknown at compile time) arrays with the CLISP FFI? The aforementioned cookbook part already contains an example for gethostname. It was relatively easy, since the maximal array length (MAXHOSTNAMELEN: 256) is a system-wide constant. There's a well-known variable length case everybody knows about: C-STRING. You may not have recognized that C-ARRAY-PTR is a generalization of C-STRING to any other type: (C-ARRAY-PTR CHARACTER) is equivalent to C-STRING - except for efficiency. Yet that is still not enough to handle typical needs. I'll use zlib's compress function as an example throughout this document. Its declaration is: int compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); However that does not tell enough for a FFI definition. The documentation defines: "sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer." Now this is all we need to know about compress. Here is what I dream of: (def-lib-call-out zlib-compress [eventually library] (:name "compress") (:arguments (dest (ffi:c-ptr (ffi:c-array ffi:uint8 is_len(destlen))) :out :guard (zerop return)) (destlen ffi:ulong :in-out) (source (ffi:c-ptr (ffi:c-array ffi:uint8 is_len(sourcelen)))) (sourcelen ffi:ulong)) (:return-type ffi:int)) Well, the CLISP FFI does not support this kind of declaration. We need to do it by hand. We will need a Lisp wrapper around the foreign function. I'll distinguish input from output (or :in-out) cases and start with :in parameter declarations. Part 1: input parameters (:IN) source is a typical :in parameter. It's a variable length array, and its length is passed as an extra argument. If, in our application, we're going to compress strings only, then the above declaration could be changed to (c-ptr (c-array character is_len(sourcelen))) -- at least in what I dream of. But in such cases, I'd rather just use C-STRING. The difference is a terminating NUL (0) character that the FFI will supply automatically. The callee (zlib) will not even see it, since it is not allowed to read more than sourcelen characters. The equivalent declaration for bytes instead of a string is: (C-ARRAY-PTR UINT8) (def-lib-call-out zlib-compress [eventually library] (:name "compress") (:arguments (dest ... :out #|:guard (zerop return)|#) (destlen ulong :in-out) (source (c-array-ptr uint8)) (sourcelen ulong)) (:return-type ffi:int)) (defun my-compress (sourcebytes) "Accepts an array of bytes and returns a vector of its compressed contents." (let ((sourcelen (length sourcebytes))) (multiple-value-bind (status actual) (zlib-compress <destlen> bytes sourcelen) ...))) Several people have inquired whether CLISP would stop at a 0 byte occurring within sourcebytes. The answer is no. From the Lisp point of view, a whole array is passed trough the interface. Contents don't matter, therefore the length is not limited by an eventual (POSITION 0 sourcebytes). Summary: Do waste a terminating 0 byte (or int, or NULL pointer) by using C-STRING or (C-ARRAY-PTR x) when applicable. This has much less overhead and easier to read than the variable length support that we cannot circumvent for output parameters. However, C-STRING or C-ARRAY-PTR are not useable in call cases. We then have to use a technique as developed below for the :OUT (or :in-out) case. Part 2: output parameters (:OUT or :IN-OUT) compress' dest is a typical output parameter. One solution path would be to construct a FFI definition at run-time, when we know the actual source and dest buffer length. We would need to weight the time needed to build, parse and compile such a definition vs. the gain from being able to use an exact array type declaration comprising the size. (defun my-compress (source) (let* ((sourcelen (length source)) (destlen (+ 12 (ceiling (* sourcelen 1.05))))) (funcall (foreign-address-function ; not yet in CLISP #'zlib-compress `(c-function ... (dest (C-ARRAY CHARACTER ,destlen) :out) (destlen (C-PTR ulong) :in-out) (source (C-ARRAY CHARACTER ,sourcelen)) (sourcelen ulong))) destlen source sourcelen))) This is one way to go, which in the case of compress is not enough, because only part of the dest buffer is filled in, as returned in <destlen> on output. We could use SUBSEQ on the result of the call to zlib-compress, but that would be some waste of storage. Instead, let us allocate the destination buffer on the stack, using FFI:WITH-FOREIGN-OBJECT. This is faster and makes more sense than using malloc() (via FFI:SIMPLE-CALLOC or FFI:DEEP-MALLOC) and UNWIND-PROTECT. We must then pass a C-POINTER (a FOREIGN-ADDRESS object) to this buffer to the foreign function. (def-lib-call-out zlib-compress [eventually library] (:name "compress") (:arguments (dest C-POINTER :IN #|:guard (zerop return)|#) (destlen ulong :in-out) (source (c-array-ptr uint8)) (sourcelen ulong)) (:return-type ffi:int)) Note how the former :OUT declaration for dest now turns into an :IN declaration. That's why C doesn't know about :in or :out, as opposed to other languages. All it sees is pointers. (defun my-compress (sourcebytes) "Accepts an array of bytes and returns a vector of its compressed contents." (let* ((sourcelen (length source)) (destlen (+ 12 (ceiling (* sourcelen 1.05))))) (WITH-FOREIGN-OBJECT (dest 'uint8 :count destlen) (multiple-value-bind (status actual) (zlib-compress (FOREIGN-ADDRESS dest) destlen sourcebytes sourcelen) (if (zerop status) ...))))) Actually, I haven't yet implemented the :COUNT extension to WITH-FOREIGN-OBJECT (so far it's only available with SIMPLE-CALLOC and DEEP-MALLOC). Let's use an equivalent (but less efficient) form instead: (WITH-FOREIGN-OBJECT (dest `(c-array uint8 ,destlen)) Note how I passed (FOREIGN-ADDRESS dest) instead of `dest' to the foreign function. The reason is that WITH-FOREIGN-OBJECT creates an object of type FOREIGN-VARIABLE, which one can understand as encapsulating a FOREIGN-ADDRESS object together with a foreign type. I'm thinking about submitting a patch to src/foreign.d which would made this call superfluous: a C-POINTER declaration would be satisfied by either untyped FOREIGN-ADDRESS (as by now) or typed FOREIGN-VARIABLE objects. What did we achieve so far? We managed to pass to the foreign function a buffer exactly as large as needed, along with its size. The foreign function will fill part of it, and we need to extract the results. The dest buffer is only filled when the function was successful: (if (zerop status) (subseq (FOREIGN-VALUE dest) 0 actual) (error ...)) The code above dereferences the whole buffer, then takes out the part that was actually filled in, allocating and copying another sequence. We shall do without it. The CLISP FFI contains macros to operate on what is called foreign places. In the future, it will export their lower-level functional counterparts which operate on FOREIGN-VARIABLE objects, as obtained by e.g. with-foreign-object. These functions shall have a trailing * in their name, e.g. ELEMENT* instead of ELEMENT, etc. (It's undecided whether I should rename FOREIGN-VALUE to FOREIGN-VALUE* for coherence, or only rename in case of name duplication -- please tell me). Remember the foreign type of dest: (C-ARRAY UINT8 <destlen>) What we want is a shorter array. Let's use CAST*, like any C programmer. (foreign-value (CAST* dest `(C-ARRAY UINT8 ,actual))) ; broken Using CAST* here does not work, though, because CLISP insists on keeping the size of the foreign structure constant when casting. So we are going to use OFFSET* instead, which lets us conceptually overlay an address or memory range with another structure. (if (zerop status) (foreign-value (FFI:OFFSET* dest 0 `(C-ARRAY UINT8 ,actual))) to be compared with the original form: (subseq (FOREIGN-VALUE dest) 0 actual) Joining all steps, the complete example becomes: (defun my-compress (sourcebytes) "Accepts an array of bytes and returns a vector of its compressed contents." (let* ((sourcelen (length source)) (destlen (+ 12 (ceiling (* sourcelen 1.05))))) (WITH-FOREIGN-OBJECT (dest 'uint8 :count destlen) (multiple-value-bind (status actual) (zlib-compress (FOREIGN-ADDRESS dest) destlen sourcebytes sourcelen) (if (zerop status) (FOREIGN-VALUE (OFFSET* dest 0 `(C-ARRAY UINT8 ,actual))) (error "zlib::compress error code ~D" status)))))) However, as of CLISP-2.30, these names with the trailing star are not yet exported from the package FFI. They're named FFI::%CAST instead, which is not engaging. Instead of using these, I'll show how to write equivalent code using what CLISP calls foreign places. A foreign place is a concept similar to that of a generalized variable. Instead of using with-foreign-object, we shall write WITH-C-VAR. The code looks almost the same. (WITH-C-VAR (dest `(c-array uint8 ,destlen)) (multiple-value-bind (status destbytes actual) (zlib-compress (C-VAR-ADDRESS dest) destlen sourcebytes sourcelen) (if (zerop status) (subseq dest 0 actual) (error "zlib::compress error code ~D" status)))) `Dest' now denotes a foreign place. From a technical point of this means no more than there is a SYMBOL-MACROLET which wraps its uses into a FOREIGN-VALUE form. Therefore, evaluating (reading) `dest' dereferences the foreign memory's contents. Setting it (using SETQ or SETF) writes to foreign memory. The address of this foreign places can be obtained with C-VAR-ADDRESS -- FOREIGN-ADDRESS would not work. So one saves typing FOREIGN-VALUE. What else is there about it? On the positive side, it combines nicely with Lisp. Foreign structures can be used smoothly. And it works with old CLISPs (OFFSET has been there since day one of the CLISP FFI). Please compare the resulting code with the above. (defun my-compress (sourcebytes) "Accepts an array of bytes and returns a vector of its compressed contents." (let* ((sourcelen (length source)) (destlen (+ 12 (ceiling (* sourcelen 1.05))))) (WITH-C-VAR (dest 'uint8 :count destlen) (multiple-value-bind (status actual) (zlib-compress (C-VAR-ADDRESS dest) destlen sourcebytes sourcelen) (if (zerop status) (OFFSET dest 0 `(c-array uint8 ,actual)) (error "zlib::compress error code ~D" status)))))) On the negative side, I find the automated dereferencing dangerous, since the programmer must be careful about each of its appearances: usually only within other FFI forms like SLOT, ELEMENT, CAST, OFFSET. In particular, it should not be passed to another function: this passes the dereferenced value, not a reference to foreign memory! As an example, consider returning from a function the buffer and its size: (values dest (length dest)) ;BROKEN This code reads the foreign buffer twice and builds two Lisp vectors out of it!. One should have used instead: (values dest (SIZEOF dest)) or (let ((dest dest)) (values dest (length dest))) Let ((dest dest)) is a little bit obfuscated: the Lisp variable could (or should) have been renamed instead, giving: (let ((dest-as-Lisp-vector dest)) (values dest-as-Lisp-vector (length dest-as-Lisp-vector))) Furthermore, using FOREIGN-VARIABLE objects instead of foreign places feels closer to programming with references or proxies (or objects?) as when using Java, Python or C++ etc. Last but not least: an object of type FOREIGN-VARIABLE can be stored anywhere and passed to a function, like every other object. Foreign places cannot. It's natural for the functions SIMPLE-CALLOC and DEEP-MALLOC to return such objects. I've been considering adding a WITH-FOREIGN-PLACE macro: it would define a foreign place out of a foreign-variable (or foreign address) object. This would be useful in those portions of code which access slots of the foreign structure. (WITH-FOREIGN-PLACE (place (gethash key table (DEEP-MALLOC ...))) (element place 0)) WITH-C-VAR now appears as a combination of it and of WITH-FOREIGN-OBJECT: (with-foreign-object (-var- type [initform]) (WITH-FOREIGN-PLACE (place -var-) ...body)) (defmacro WITH-FOREIGN-PLACE ((place foreign-variable) &body body) (let ((fv (gensym (symbol-name place)))) `(let ((,fv ,foreign-variable)) (symbol-macrolet ((,place (FOREIGN-VALUE ,fv))) , <at> body)))) Lifting the 1:1 encoding restriction on strings Western people tend to forget about it, but custom:*DEFAULT-FOREIGN-ENCODING* comes into play every time C-STRING or CHARACTER declarations are involved. How to deal with e.g. UTF-8, UTF-16, Japaneese or Corean encodings? One trivial - yet successful - solution path would be to use a composition of known elements: (defun compress-string-to-bytes (string encoding &key (start 0) (end nil)) (my-compress (ext:convert-string-to-bytes string encoding :start start :end end))) We shall investigate another solution. It involves WITH-FOREIGN-STRING. This form is specialized in allocating strings on the execution stack and accepts encoding, start and end arguments. WITH-FOREIGN-STRING yields a FOREIGN-ADDRESS object (not a foreign variable as with-foreign-object) that we shall pass as the source to the foreign function. We thus need another FFI declaration: (def-lib-call-out zlib-compress [eventually library] (:name "compress") (:arguments (dest C-POINTER :in #|:guard (zerop return)|#) (destlen ulong :in-out) (source C-POINTER) (sourcelen ulong)) (:return-type ffi:int) (:language :stdc)) The WITH-FOREIGN-STRING macro takes a program body and binds three variables to a FOREIGN-ADDRESS object pointing to the converted string, its original length in elements (modulo the NULL-TERMINATED-P key) and its length in bytes. I designed it not to use a FOREIGN-VARIABLE object because: 1. most uses would be to pass its address to a foreign function anyway, 2. more importantly, its unclear what the proper foreign type should be. One may think that for fixed-with encodings like e.g. UTF-16, it should result in (C-ARRAY UINT16 <element-count>) but that would imply that the programmer might not be in control of the type since the actual encoding may be defined by the user. Therefore, only (C-ARRAY UINT8 <sourcelen>) seems to make sense. But wouldn't (C-ARRAY-MAX UINT8 <sourcelen>) not be more appropriate? So I decided to stick with an untyped address. Should you have a need to access individual characters, then you can "cast" it to a foreign variable object of the type that you need using FOREIGN-ADDRESS-VARIABLE (not yet in CLISP). (FOREIGN-ADDRESS-VARIABLE dest `(c-array uint8 ,sourcelen)) I'm thinking about using the already existing CAST macro or CAST* function for this purpose. Then you can use typical accessors on it: (ELEMENT* (foreign-address-variable dest `(c-array uint 8 ,sourcelen)) 0) would extract the first byte (if length allows). Nevertheless, the code below invokes FOREIGN-ADDRESS on dest, just so to feel safe should I eve change my mind. Given a FOREIGN-ADDRESS object, it's in effect an identity function. (defun compress-string-to-bytes (string encoding &key (start 0) (end nil)) "Return a vector of compressed bytes from STRING, according to ENCODING" (WITH-FOREIGN-STRING (source element-count sourcelen string :null-terminated-p nil :encoding encoding :start start :end end) (declare (ignore element-count)) (let ((destlen (+ 12 (ceiling (* sourcelen 1.05))))) (with-c-var (dest 'uint8 :count destlen) (multiple-value-bind (status actual) (zlib-compress (c-var-address dest) destlen (FOREIGN-ADDRESS source) sourcelen) (if (zerop status) (offset dest 0 `(c-array uint8 ,actual)) (error "zlib::compress error code ~D" status))))))) Efficiency considerations I did not perform actual measurements, yet with the current API, it is quite probable that using SUBSEQ is faster than using CAST or OFFSET etc. The reason is that in the latter case, a lot is happening at run-time in CLISP: 1. create a (c-array uint8 <actual> list using backquote 2. transform it into the internal type representation 3. construct a FOREIGN-VARIABLE with this type 4. dereference memory using FOREIGN-VALUE It therefore becomes questionable whether the advantage of dereferencing only <actual> bytes instead of the whole <destlen> number of bytes and not creating an extra vector is worth our effort! It appears that what stands in our way towards performance is the extra level of abstraction introduced by the CLISP FFI. What we see is some kind of interpretation overhead. I'm not speaking about a byte-code interpreter, but about an interpreter specialized on manipulating foreign variable descriptions and interpreting forms like OFFSET, ELEMENT, SLOT etc. With a Lisp-to-native code compiler like CMUCL, clever compiler optimizations and a good FFI API, this run-time overhead could be avoided. W.r.t. to the API, a small problem here is the use of backquote, which means that the compiler would have to figure out that the backquoted list only serves to build an external type description for a variable length array. It should be easier to express and understand this, for both the programmer and the compiler: that's why I introduced the :count keyword to the memory allocating functions. It's easier to optimize (DEEP-MALLOC 'uint8 :count (foo x)) than (DEEP-MALLOC `(c-array uint8 ,(foo x))) By contrast, the Amiga-CLISP AFFI has no such interpretation level. The API that it provides is the equivalent of machine level: the work that in all cases must be done is memory transfer, the rest is overhead. Therefore, the AFFI only contains 4 functions. A lot can be implemented on top of these. There is one function for foreign function call and three for memory transfer: MEM-READ, MEM-WRITE and MEM-WRITE-VECTOR. Using AFFI, we would have written: (let ((result (MAKE-ARRAY actual :element-type '(unsigned-byte 8)))) (MEM-READ (foreign-address dest) result)) It would have been really fast, with the least possible overhead, but the programmer would have to write the code in an imperative style, which to the compiler theory purist (like me) appears like applying partial evaluation or compiler optimization techniques by hand, which s/he considers a shame. Yet working with the AFFI does not let one feel stranger than working with C, or with any of the other Lisp's FFIs. It's working with a lot of low-level stuff like buffer allocation, correct buffer size etc. which declarative style (like CLISP's DEF-CALL-OUT) tends to avoid. Yet when DEF-CALL-OUT is not enough and a wrapper is needed, using CLISP's DEREF, WITH-FOREIGN-OBJECT etc. does not feel like programming at a highler level than using other FFIs. Compared to these, the overhead of all the intermediate FOREIGN-VARIABLE objects and steps is too high IMHO. IMHO, an API which produces code which will be order of magnitudes slower than its C counterpart will rightly be the target of criticisms. Declarative style wins Remember what I said I dream of? (def-lib-call-out zlib-compress [eventually library] (:name "compress") (:arguments (dest (ffi:c-ptr (ffi:c-array ffi:uint8 is_len(destlen))) :out :guard (zerop return)) (destlen ffi:ulong :in-out) (source (ffi:c-ptr (ffi:c-array ffi:uint8 is_len(sourcelen)))) (sourcelen ffi:ulong)) (:return-type ffi:int)) Isn't that much simpler than all this cumbersome and error-prone low-level handling with buffers, memory, arrays, their sizes, etc.? CLISP's declarative DEF-CALL-OUT already manages to provide a FFI definition for many many foreign functions. I believe something like the above is likely to provide 80% of the remaining needs. Feel free to investigate defining such a form. If you do, consider making it powerful enough to handle Postgres' string quoting function: http://cert.uni-stuttgart.de/doc/postgresql/escape/ size_t PQescapeString (char *to, const char *from, size_t length); "The from points to the first character of the string which is to be escaped, and the length parameter counts the number of characters in this string (a terminating NUL character is neither necessary nor counted). to shall point to a buffer which is able to hold at least one more character than twice the value of length, otherwise the behavior is undefined. A call to PQescapeString writes an escaped version of the from string to the to buffer, replacing special characters so that they cannot cause any harm, and adding a terminating NUL character. PQescapeString returns the number of characters written to to, not including the terminating NUL character. Behavior is undefined when the to and from strings overlap." One may argue that its parameter usage is badly designed, if not braindead. The difficulty I see here in finding a way to declaratively express the required interface is that the size of the to buffer and the number of useful bytes come from to different places (1+ (* length 2)) vs. the return value, as opposed to compress' destlen :in-out parameter. Writing wrappers by hand on a case by case basis maybe error-prone, but it is straightforward. It doesn't require much brain. Summary o By all means, use C-STRING or (C-ARRAY-PTR type) whereever possible. o Foreign places provide a somewhat elegant, at least compact, however inefficient way of working on foreign structures. o The required DEF-CALL-OUT parameter declarations depend on the wrapper. There's no "one declaration for all uses" as in C. o A worthwhile approach instead of writing ad hoc code which every time loooks similar (with-foreign-object etc.) would be to provide a DEF-VARLEN-CALL-OUT macro which would encapsulate all this with-foreign-object, foreign-value, subseq etc. code. (def-lib-call-out zlib-compress [eventually library] (:name "compress") (:arguments (dest C-POINTER :in #|:guard (zerop return)|#) (destlen ulong :in-out) (source (c-array-ptr uint8)) (sourcelen ulong)) (:return-type ffi:int) (:language :stdc)) (defun my-compress (sourcebytes) "Accepts an array of bytes and returns a vector of its compressed contents." (let* ((sourcelen (length source)) (destlen (+ 12 (ceiling (* sourcelen 1.05))))) (WITH-C-VAR (dest uint8 :count destlen)) (multiple-value-bind (status actual) (zlib-compress (C-VAR-ADDRESS dest) destlen sourcebytes sourcelen) (if (zerop status) (OFFSET dest 0 `(C-ARRAY UINT8 ,actual)) (error "zlib::compress error code ~D" status)))))) Things not (yet) in CLISP: o DEF-CALL-VAR-OUT macro for variable length arrays o :count extension to WITH-FOREIGN-OBJECT and WITH-C-VAR o rename OFFSET* SLOT* ELEMENT* etc. instead of %OFFSET %SLOT o exporting FOREIGN-VALUE and OFFSET* etc. from FFI o export and document FFI:PARSE-C-TYPE and its converse o FOREIGN-ADDRESS-FUNCTION (so far only part of my dynload patch) o dynamic library call out (dynload patch to be completed) o FOREIGN-ADDRESS-VARIABLE (if not reusing CAST) o possibly make CALL-OUT code accept FOREIGN-VARIABLE objects where type C-POINTER is expected (so far only FOREIGN-ADDRESS) o WITH-FOREIGN-PLACE macro o compile-time or load-time inlining of constant PARSE-C-TYPE use as in (deep-malloc 'uint8 :size (foo x)) or with-foreign-object ... o ... I appreciate comments, Jörg Höhle. ------------------------------------------------------- This SF.net email is sponsored by: Etnus, makers of TotalView, The debugger for complex code. Debugging C/C++ programs can leave you feeling lost and disoriented. TotalView can help you find your way. Available on major UNIX and Linux platforms. Try it free. www.etnus.com Gmane From: Hoehle, Joerg-Cyril <Joerg-Cyril.Hoehle <at> t-systems.com> Subject: FFI: variable size values (was FFI crash: what am I missing?!) Newsgroups: gmane.lisp.clisp.general Date: Tue, 05 Aug 2003 10:50:27 +0200 Hi, Sam wrote: >> >what is the correct idiom for the C "unknown type array"? >> >E.g., suppose >> > int* foo(); >> >will return the array of integers of size N, where N is the return >> >value of another function >> > int foo_size(); >> >how do I express foo() and foo_size() in CLISP FFI? >> >Suppose >> > int foo (int *size, int**arr); >> >returns status and puts the length of the array into `size' and the >> >pointer of the array into `arr'. >> >what is the correct CLISP FFI idiom? See answers below >what if, as in the first example, the size is returned by a _different_ >function?! That's why I said "the latter case" fits my (unwritten) macro. The former does not fit the one declaration per function" model, since the "transaction" (I name is so) is distributed across two calls. >> Explicit management using WITH-FOREIGN-OBJECT and friends is >> involved. >any cast requires equal memory size. I wrote in the past on the OFFSET solution. It looks like you have forgot about my article "FFI howto: variable length arrays (long)" from 5th of March 2003. http://sourceforge.net/mailarchive/forum.php?thread_id=1784502&forum_id=6767 http://sourceforge.net/mailarchive/forum.php?thread_id=1788500&forum_id=6767 >is a C wrapper the only solution? Not at all. Sometimes I recommend C wrappers to create an interface that better suits Lisp, but it is not strictly necessary. You can use the FFI to call any function and retrieve its results, writing Lisp code (be it less efficient because of run-time parsing (FFI:parse-c-type) and conversions (ffi:cast)). But see my below comment on the regexp case. >> A longer answer may follow tomorrow, I need to go home now. >biting my nails off :-) I hope you can still type in the following: The first foo You didn't say whether foo_size() has to be called before or after foo(). I'll call it afterwards, for similarity with the regexp module, where the number of the group positions can be read off a slot of the structure. BTW, the current CLISP regexp module arbitrarily limits the return to 10 group positions ("num-matches"), because it does not consider the re_nsub slot out off the regex_t structure. This is a case where I'd recommend a little C wrapper code to make interfacing easier. I very much prefer this over duplicating the regex_t structure in Lisp via (FFI:C-STRUCT <many slots>). I don't want to have to maintain this by hand, whereas the C wrapper would always stay in sync with the C regex.h header by mere recompilation. (def-call-out %foo1 (:name "foo") (:return-type c-pointer) (:language :stdc)) (defun foo1 () (let ((ptr (%foo1))) (when ptr ;; c-pointer type will return NIL for NULL in the near future (with-c-var (array 'c-pointer ptr) (cast array `(c-ptr (c-array sint ,(foo-size)))))))) The second foo I take it that foo2 allocates the buffer it returns via arr . Who must free it? Also you don't say whether it's :in-out or :out, so I take :out only. However it's common for the buffer to be supplied by the caller, with a maximum size provided by the size argument as an :in-out parameter. The C declaration you supply doesn't tell the difference, and the below code covers the other case. Here's what the macro call might like (def-call-var-out foo2 (:name "foo") (:arguments (size (c-ptr uint) :out) (arr (c-ptr (c-ptr (c-array sint size))) :out [:malloc-free])) (:guard (zerop return)) (:return-type int) (:language :stdc)) BTW, I recommend using unsigned types even though C people usually just use "int" (new-wave C people say "size_t"). E.g. size obviously should be unsigned. Here's what you do without the charming macro: (def-call-out %foo2 (:name "foo") (:arguments (size (c-ptr uint) :out) (arr (c-ptr c-pointer) :out)) (:return-type int) (:language :stdc)) (defun foo2 () (multiple-value-bind (status size array-ptr) (%foo2) (if (zerop status) (with-c-var (arr 'c-pointer array-ptr) (cast arr `(c-ptr (c-array sint ,size)))) ;; the macro would return (values status [size array]) (error "Call failed with status ~D" status)))) This costs a PARSE-C-TYPE for every call for both foo1 and foo2. My MEM-READ proposal could avoid that in some cases, depending on the type (so far only built-in-arrays of CLISP, i.e. uint8/16/32, but not sint8/16/32 are supported). (defun foo2 () (multiple-value-bind (status size array-ptr) (%foo2) (if (zerop status) (let ((vec (make-array size :element-type '(unsigned-byte 32)))) (mem-read array-ptr vec)) (error "Call failed with status ~D" status)))) (defun foo1 () (let ((ptr (%foo1))) (when ptr ;; c-pointer type will return NIL for NULL in the near future (let ((vec (make-array (foo-size) :element-type '(unsigned-byte 32)))) (mem-read ptr vec))))) My FOREIGN-VARIABLE constructor (design not yet finished) would allow to avoid WITH-C-VAR, but would still require PARSE-C-TYPE at run-time, allowing code similar to: (defun foo1 () (let ((ptr (%foo1))) (when ptr ;; c-pointer type will return NIL for NULL in the near future (foreign-value (foreign-address-variable ptr `(C-ARRAY SINT ,(foo-size))))))) or maybe I'll require an explicit call (foreign-address-variable ptr (parse-c-type `(C-ARRAY SINT ,(foo-size)))) It's a constructor after all, not a macro-level keep-typing-short sort of thing. Regards, Jorg Hohle. ------------------------------------------------------- This SF.Net email sponsored by: Free pre-built ASP.NET sites including Data Reports, E-commerce, Portals, and Forums are available now. Download today and enter to win an XBOX or Visual Studio .NET. http://aspnet.click-url.com/go/psa00100003ave/direct;at.aspnet_072303_01/01
30,772
Common Lisp
.lisp
574
50.585366
119
0.751105
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8a6fc3c33953e075b184f3870efb2edc0814af9c109063682bbceb7ec74faa8b
4,793
[ -1 ]
4,794
uffi.lisp
informatimago_lisp/clisp/uffi.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: uffi.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: clisp ;;;;USER-INTERFACE: NONE ;;;;NOWEB: T ;;;;DESCRIPTION ;;;; ;;;; This API is obsolete. See: CFFI. ;;;; ;;;; This is a UFFI layer over the clisp native FFI. ;;;; ;;;; ;;;; Programs running on CLISP may set CUSTOM:*FOREING-ENCODING* ;;;; and this will be honored in the conversion of strings between ;;;; Lisp and C by the underlying FFI. ;;;; ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;; <KMR> Kevin M. Rosenberg ;;;;MODIFICATIONS ;;;; 2004-07-29 <PJB> Implemented LOAD-FOREIGN-LIBRARY, FIND-FOREIGN-LIBRARY. ;;;; 2003-06-03 <PJB> Created. ;;;; Some code taken from Kevin M. Rosenberg's UFFI 1.2.15. ;;;;BUGS ;;;; Not tested yet. ;;;; ;;;; FIND-FOREIGN-LIBRARY can't do its work portably for the ill definition ;;;; of COMMON-LISP:DIRECTORY. Only a unix implementation is provided. ;;;; ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.UFFI" (:nicknames "UFFI") (:documentation " This package implements over clisp native FFI the UFFI API as defined in 'UFFI Reference Guide' by Kevin M. Rosenberg, Heart Hospital of New Mexico. The version of the UFFI implemented here is uffi-1.2.15. URL: <http://uffi.b9.com/manual/book1.html> URL: <http://uffi.b9.com/> LEGAL: Copyright Pascal J. Bourguignon 2003 - 2004 This package is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ") (:use "COMMON-LISP") ;; actually: FROM COMMON-LISP IMPORT ALL; ;; really: USE FFI,CUSTOM,EXT; (:export ;; immediate types "DEF-TYPE" "DEF-CONSTANT" ;; Don't use it! "DEF-FOREIGN-TYPE" "NULL-CHAR-P" ;; aggregate types "DEF-ENUM" "DEF-STRUCT" "GET-SLOT-VALUE" "GET-SLOT-POINTER" "DEF-ARRAY-POINTER" "DEREF-ARRAY" "DEF-UNION" ;; objects "ALLOCATE-FOREIGN-OBJECT" "FREE-FOREIGN-OBJECT" "WITH-FOREIGN-OBJECT" "WITH-FOREIGN-OBJECTS" "SIZE-OF-FOREIGN-TYPE" "POINTER-ADDRESS" "DEREF-POINTER" "ENSURE-CHAR-CHARACTER" "ENSURE-CHAR-INTEGER" "NULL-POINTER-P" "MAKE-NULL-POINTER" "+NULL-CSTRING-POINTER"+ "CHAR-ARRAY-TO-POINTER" ;; string functions "CONVERT-FROM-CSTRING" "CONVERT-TO-CSTRING" "FREE-CSTRING" "WITH-CSTRING" "WITH-CSTRINGS" "CONVERT-FROM-FOREIGN-STRING" "CONVERT-TO-FOREIGN-STRING" "ALLOCATE-FOREIGN-STRING" "WITH-FOREIGN-STRING" ;; function call "DEF-FUNCTION" ;; Libraries "FIND-FOREIGN-LIBRARY" "LOAD-FOREIGN-LIBRARY" "DEFAULT-FOREIGN-LIBRARY-TYPE" ;; OS "RUN-SHELL-COMMAND" ;; This is not used anywhere by UFFI: what's the use? ;; Don't use it: if you need such a function, use a POSIX or an OS API, ;; not a UFFI. )) ;;COM.INFORMATIMAGO.CLISP.UFFI (in-package "COM.INFORMATIMAGO.CLISP.UFFI") (provide :uffi) ;; Some client code use REQUIRE! Can you imagine that? ;; In general functions defined with UFFI (DEF-FUNCTION) do not convert ;; between Lisp objects and C objects. This is to be done by the client ;; code. ;; FFI provides for specification of the external language, with :C (K&C), ;; :STDC (ANSI C) or :STDC-STDCALL (ANSI C with stdcall). ;; UFFI does not. ;; UFFI does not allow the definition of a C variable (extern). ;; FFI does, with def-c-var. ;; However, we could play C tricks to get a UFFI pointer to a C variable. ;; (Is there any other such variable than errno?) ;; In FFI, c-type as defined with def-c-type are symbols used as key in ;; an internal hash table where c-type objects are stored. ;; (uffi:def-type the-struct-type-def the-struct-type) ;; (let ((a-foreign-struct (allocate-foreign-object 'the-struct-type))) ;; (declare 'the-struct-type-def a-foreign-struct) ;; (get-slot-value a-foreign-struct 'the-struct-type 'field-name)) ;; There's no UFFI type to specify function types. ;; UFFI:DEF-FUNCTION corresponds to FFI:DEF-CALL-OUT ;; There's none corresponding to FFI:DEF-CALL-IN ;; UFFI has only :IN arguments. ;; FFI has also :INOUT and :OUT arguments. ;; We'll use :ALLOCATION :NONE and :IN arguments, and manage our own buffers. ;; FFI: ;; Passing FFI:C-STRUCT, FFI:C-UNION, FFI:C-ARRAY, FFI:C-ARRAY-MAX values ;; as arguments (not via pointers) is only possible to the extent the C ;; compiler supports it. Most C compilers do it right, but some C ;; compilers (such as gcc on hppa) have problems with this. ;; UFFI: The values must be converted between Lisp types and C types by the ;; client code. ;; FFI: The values are converted automatically between Lisp and C, depending ;; on the FFI-C-TYPE-TO-CL-TYPE table and specifications of C types. ;; ;; Therefore: UFFI :CSTRING are implemented as CL:STRING ;; UFFI :CENUM are implemented as CL:INTEGER ;; UFFI :CSTRUCT are implemented as CL:DEFSTRUCT ;; UFFI :CARRAY are implemented as CL:ARRAY ? ;; (* TYPE) ;; (ENUM (FIELD VALUE)...) ;; (STRUCT (FIELD TYPE)...) ;; (UNION (FIELD TYPE)...) ;; (* (ARRAY TYPE)) ;; :struct-pointer ;; :pointer-self ;; ;; immediate types ;; "DEF-TYPE" --> LISP DEFTYPE WITH CONVERSION TO :CL ;; ;; "DEF-FOREIGN-TYPE" --> C typedef type name; ;; --> DEF-C-TYPE ;; ;; "NULL-CHAR-P" ;; ;; ;; aggregate types ;; "DEF-ENUM" --> C typedef enum {...} name; ;; --> DEF-C-ENUM DEFTYPE ;; ;; "DEF-STRUCT" --> C typedef struct name {...} name; ;; --> DEF-C-STRUCT ;; ;; "GET-SLOT-VALUE" ;; "GET-SLOT-POINTER" ;; "DEF-ARRAY-POINTER" --> C typedef type* name; ;; --> DEF-C-TYPE ;; ;; "DEREF-ARRAY" ;; ;; "DEF-UNION" --> C typedef union {...} name; ;; --> DEF-C-TYPE ;; ;; ;; ;; objects ;; "ALLOCATE-FOREIGN-OBJECT" ;; "FREE-FOREIGN-OBJECT" ;; "WITH-FOREIGN-OBJECT" --> FFI:WITH-FOREIGN-OBJECT ;; "WITH-FOREIGN-OBJECTS" ;; "SIZE-OF-FOREIGN-TYPE" ;; "POINTER-ADDRESS" ;; "DEREF-POINTER" ;; "ENSURE-CHAR-CHARACTER" ;; "ENSURE-CHAR-INTEGER" ;; "NULL-POINTER-P" ;; "MAKE-NULL-POINTER" ;; "+NULL-CSTRING-POINTER"+ ;; "CHAR-ARRAY-TO-POINTER" ;; ;; ;; string functions ;; "CONVERT-FROM-CSTRING" ;; "CONVERT-TO-CSTRING" ;; "FREE-CSTRING" ;; "WITH-CSTRING" ;; "WITH-CSTRINGS" ;; "CONVERT-FROM-FOREIGN-STRING" ;; "CONVERT-TO-FOREIGN-STRING" --> (FFI:C-ARRAY-MAX FFI:UCHAR SIZE) ;; "ALLOCATE-FOREIGN-STRING" --> (FFI:C-ARRAY-MAX FFI:UCHAR SIZE) ;; OR --> (FFI:C-ARRAY-MAX FFI:CHAR SIZE) ;; "WITH-FOREIGN-STRING" --> FFI:WITH-FOREIGN-OBJECT ;; Because of (:struct name) and (:struct-pointer name) we must keep ;; a separate list of structure names (even if def-struct creates both ;; a typedef and a struct). ;; ;; Because of :pointer-self, when we convert a struct, we must keep the ;; current structure name at hand. ;; ;; We should check that a structure does not contain a (:struct self) ;; if not encapsulated into a (* ). ;;; FFI-C-TYPE-TO-CL-TYPE ;;; (BOOLEAN . BOOLEAN) ;;; (CHARACTER . CHARACTER) ;;; (FFI:SHORT . INTEGER) ;;; (FFI:USHORT . INTEGER) ;;; (FFI:INT . INTEGER) ;;; (FFI:UINT . INTEGER) ;;; (FFI:LONG . INTEGER) ;;; (FFI:ULONG . INTEGER) ;;; (SINGLE-FLOAT . SINGLE-FLOAT) ;;; (DOUBLE-FLOAT . DOUBLE-FLOAT) (defstruct (type-conv (:type list) (:conc-name nil)) uffi-type ffi-type cl-type) (defconstant +type-conversion-list+ '( ;; :UFFI :FFI :CL (:char ffi:character character) (:unsigned-char ffi:character character) (:byte ffi:sint8 (signed-byte 8)) (:unsigned-byte ffi:uint8 (unsigned-byte 9)) (:short ffi:sint16 (signed-byte 16)) (:unsigned-short ffi:uint16 (unsigned-byte 16)) (:int ffi:sint32 (signed-byte 32)) (:unsigned-int ffi:uint32 (unsigned-byte 32)) (:long ffi:sint32 (signed-byte 32)) (:unsigned-long ffi:uint32 (unsigned-byte 32)) (:float single-float single-float) (:double double-float double-float) (:cstring ffi:c-pointer string) (:pointer-void ffi:c-pointer t) (:void nil nil) ;;; ;;; (:ENUM FFI:INT INTEGER) ;;; ((:STRUCT name) FFI:C-STRUCT STRUCTURE) ;;; ((:STRUCT-POINTER name) (FFI:C-PTR-NULL FFI:C-STRUCT) STRUCTURE) ;;; ;; FOR LISP TYPE: WE BUILD A DEFSTRUCT ;;; (:UNION FFI:C-UNION UNION) ;;; ;; FOR LISP TYPE: FFI CONSIDER IT TO BE OF THE TYPE OF THE FIRST FIELD. ;;; ((:ARRAY TYPE) (FFI:C-ARRAY-PTR TYPE) (ARRAY :ELEMENT-TYPE TYPE)) ;;; ) "A LIST OF: (UFFI-TYPE FFI-TYPE CL-TYPE)" ) ;;+TYPE-CONVERSION-LIST+ (defvar +type-conversion-hash+ (let ((table (make-hash-table :size 23))) (dolist (record +type-conversion-list+) (setf (gethash (uffi-type record) table) record)) table) "A hash uffi-type --> (uffi-type ffi-type cl-type)." ) ;;+TYPE-CONVERSION-HASH+ (declaim (inline get-type-conversion-record)) (defun get-type-conversion-record (uffi-type) " PRIVATE RETURN: THE RECORD FROM +TYPE-CONVERSION-HASH+ CORRESPONDING TO UFFI-TYPE, OR NIL IF NONE EXISTS. " (gethash uffi-type +type-conversion-hash+) ) ;;GET-TYPE-CONVERSION-RECORD (defvar *foreign-types-hash* (make-hash-table :size 23) "A HASH TABLE OF THE NAMED FOREIGN TYPES: NAME --> UFFI-TYPE." ) ;;*FOREIGN-TYPES-HASH* (defvar *foreign-structs-hash* (make-hash-table :size 23) "A HASH TABLE OF THE NAMED FOREIGN STRUCTS: NAME --> UFFI-STRUCT-TYPE." ) ;;*FOREIGN-STRUCTS-HASH* ;;; PRIMITIVE-UFFI-TYPE ;;; :POINTER-SELF ;;; (:STRUCT-POINTER STRUCT-NAME) ;;; (:STRUCT STRUCT-NAME) ;;; (:STRUCT STRUCT-NAME (FNAME FTYPE)...) ;;; 'TYPE ;;; ;;; (:UNION UNION-NAME (FNAME FTYPE)...) ;;; (:ARRAY-PTR TYPE) ;;; (:ARRAY TYPE SIZE) (defun clean-uffi-type (uffi-type &optional current-struct) " PRIVATE DO: REPLACE :POINTER-SELF BY (* (:STRUCT CURRENT-STRUCT),) (:STRUCT-POINTER NAME) BY (* (:STRUCT NAME)), AND CHECK THAT A STRUCTURE EXISTS FOR (:STRUCT NAME). REPLACE (* :UNSIGNED-CHAR) and (* :CHAR) BY :CSTRING, SINCE IT SEEMS UFFI CLIENT CODE ERRONEOUSLY USE (* :UNSIGNED-CHAR) INSTEAD OF :CSTRING... RETURN: A CLEANED UFFI-TYPE. TODO: CHECK OF (STRUCT X (FIELD (STRUCT X))). " (if (atom uffi-type) (if (eq uffi-type :pointer-self) (if current-struct `(* (:struct ,current-struct)) (error "FOUND :POINTER-SELF OUT OF A STRUCTURE.")) uffi-type) (case (first uffi-type) (:struct-pointer (unless (= 2 (length uffi-type)) (error "INVALID UFFI TYPE: ~S." uffi-type)) `(* ,(clean-uffi-type (second uffi-type)))) (:struct (cond ((= 2 (length uffi-type)) (unless (gethash (second uffi-type) *foreign-structs-hash*) (error "UNKNOWN STRUCT TYPE: ~S." uffi-type)) uffi-type) ((< 2 (length uffi-type)) (let ((struct-name (second uffi-type))) (unless (symbolp struct-name) (error "EXPECTED A SYMBOL AS STRUCT NAME INSTEAD OF ~S." struct-name)) `(:struct ,struct-name ,@(mapcar (lambda (field) (let ((name (first field)) (type (second field))) (unless (= 2 (length field)) (error "INVALID STRUCT FIELD ~S." field)) (list name (clean-uffi-type type struct-name)))) (cddr uffi-type))))) (t (error "INVALID STRUCT TYPE: ~S." uffi-type)))) (common-lisp:quote (clean-uffi-type (second uffi-type) current-struct)) (:union (unless (< 2 (length uffi-type)) (error "MISSING FIELDS IN UNION TYPE ~S." uffi-type)) `(:union ,(second uffi-type) ,@(mapcar (lambda (field) (let ((name (first field)) (type (second field))) (unless (= 2 (length field)) (error "INVALID UNION FIELD ~S." field)) (list name (clean-uffi-type type current-struct)))) (cddr uffi-type)))) (:array-ptr (unless (= 2 (length uffi-type)) (error "INVALID ARRAY-PTR TYPE: ~S." uffi-type)) `(:array-ptr ,(clean-uffi-type (second uffi-type) current-struct))) (:array (unless (= 3 (length uffi-type)) (error "INVALID ARRAY TYPE: ~S." uffi-type)) (let ((size (third uffi-type))) (unless (and (integerp size) (< 0 size)) (error "INVALID ARRAY SIZE: ~S." size)) `(:array ,(clean-uffi-type (second uffi-type) current-struct) ,size))) (* (unless (= 2 (length uffi-type)) (error "INVALID POINTER TYPE: ~S." uffi-type)) `(* ,(clean-uffi-type (second uffi-type)))) ;;(if (member (second uffi-type) '(:unsigned-char :char)) ;;'FFI:C-POINTER (otherwise (error "INVALID TYPE: ~S." uffi-type)))) ) ;;CLEAN-UFFI-TYPE (defun convert-from-uffi-type (uffi-type context) " PRIVATE DO: Converts from a uffi type to an implementation specific type. UFFI-TYPE: A UFFI TYPE. CONTEXT: :FFI OR :CL RETURN: A FFI TYPE (C-TYPE), OR A COMMON-LISP TYPE, DEPENDING ON THE CONTEXT. " (unless (or (eq context :ffi) (eq context :cl)) (error "UNEXPECTED CONTEXT ~S, SHOULD BE EITHER :FFI OR :CL." context)) (if (atom uffi-type) (let ((record (get-type-conversion-record uffi-type))) (if record ;; primitive types (if (eq context :ffi) (ffi-type record) (cl-type record)) ;; named types (let ((type (gethash uffi-type *foreign-types-hash*))) (if type (convert-from-uffi-type type context) (error "UNKNOWN UFFI TYPE ~S." uffi-type))))) (let ((sub-type (first uffi-type))) (case sub-type (:struct (let ((name (second uffi-type)) (fields (mapcar (lambda (field) (let ((name (first field)) (type (second field))) (list name (convert-from-uffi-type type context)))) (cddr uffi-type)))) ;; TODO: SEE GENERATION OF (:STRUCT NAME) ;; VS. GENERATION OF: (:STRUCT NAME (FIELD TYPE)...) (if (null fields) (let ((type (gethash name *foreign-structs-hash*))) (if type (if (eq context :ffi) `(ffi:c-struct ,name) name) ;; (CONVERT-FROM-UFFI-TYPE TYPE CONTEXT) (error "UNKNOWN UFFI STRUCTURE ~S." name))) (if (eq context :ffi) `(ffi:c-struct ,name ,@fields) `(defstruct ,name ,@fields))))) (:union (if (eq context :ffi) `(:c-union ,@(mapcar (lambda (field) (let ((name (first field)) (type (second field))) (list name (convert-from-uffi-type type context)))) (cddr uffi-type))) `(convert-from-uffi-type (second (second uffi-type)) context))) (:array-ptr (let ((element-type (convert-from-uffi-type (second uffi-type) context))) (if (eq context :ffi) `(ffi:c-array-ptr ,element-type) `(array ,element-type *)))) (:array (let ((element-type (convert-from-uffi-type (second uffi-type) context)) (array-size (cddr uffi-type))) (if (eq context :ffi) `(ffi:c-array ,element-type ,array-size) `(array ,element-type (,array-size))))) (* (if (eq context :ffi) `(ffi:c-ptr ,(convert-from-uffi-type (second uffi-type) :ffi)) ;;'FFI:C-POINTER (error "I don't know what a ~S is in Lisp."))) (otherwise (error "INVALID TYPE ~S." uffi-type))))) ) ;;CONVERT-FROM-UFFI-TYPE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; I. Declarations ;; ;;;;;;;;;;;;;;;;;;;;; (defmacro def-type (name type) " DO: Defines a Common Lisp type based on a UFFI type. NAME: A symbol naming the type TYPE: A form that is evaluated that specifies the UFFI type. IMPLEMENTATION: For now, we generate `(DEFTYPE ,NAME T). URL: <http://uffi.b9.com/manual/def-type.html> URL: <http://www.lisp.org/HyperSpec/Body/mac_deftype.html> " (setf type (clean-uffi-type type)) `(deftype ,name t ,(convert-from-uffi-type type :cl))) ;;DEF-TYPE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; II. Primitive Types ;; ;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def-constant (name value &key (export nil)) " DO: This is a thin wrapper around defconstant. It evaluates at compile-time and optionally exports the symbol from the package. NAME: A symbol that will be bound to the value. VALUE: An evaluated form that is bound the the name. EXPORT: EXPORT <=> The name is exported from the current package. The default is NIL NOTE: I would not advise using this macro, since it does not allow to attach a documentation string! URL: <http://uffi.b9.com/manual/def-constant.html> URL: <http://www.lisp.org/HyperSpec/Body/mac_defconstant.html> URL: <http://www.lisp.org/HyperSpec/Body/fun_export.html> " `(eval-when (:compile-toplevel :load-toplevel :execute) (defconstant ,name ,value) ,(when export (list 'export `(quote ,name))) ',name) ) ;;DEF-CONSTANT (defmacro def-foreign-type (name type) " DO: Defines a new foreign type. NAME: A symbol naming the new foreign type. VALUE: A form that is not evaluated that defines the new foreign type. URL: <http://uffi.b9.com/manual/def-foreign-type.html> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let* ((name name) (uffi-type (clean-uffi-type type name)) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ',name *foreign-types-hash*) ',uffi-type) (ffi:def-c-type ,name ,ffi-type)))) ;;DEF-FOREIGN-TYPE (defmacro null-char-p (val) " DO: Tests if a character or integer is NULL. This abstracts the difference in implementations where some return a character and some return an integer when dereferencing a C character pointer. CHAR: A character or integer. RETURN: A boolean flag indicating if char is a NULL value. URL: <http://uffi.b9.com/manual/null-char-p.html> " `(let ((val ,val)) (if (characterp val) (zerop (char-code val)) (zerop val))) ) ;;NULL-CHAR-P (defun make-constant-name (enum-name separator-string constant-id) " PRIVATE DO: Builds an enum constant name. " (intern (with-standard-io-syntax (format nil "~A~A~A" enum-name separator-string constant-id)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; III. Aggregate Types ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def-enum (name constants &key (separator-string "#")) " DO: Declares a C enumeration. It generates constants with integer values for the elements of the enumeration. The symbols for the these constant values are created by the concatenation of the enumeration name, separator-string, and field symbol. Also creates a foreign type with the name name of type :int. NAME: A symbol that names the enumeration. CONSTANTS: A list of enum constants definitions. Each definition can be a symbol or a list of two elements. Symbols get assigned a value of the current counter which starts at 0 and increments by 1 for each subsequent symbol. It the constants definition is a list, the first position is the symbol and the second position is the value to assign the the symbol. The current counter gets set to 1+ this value. SEPARATOR-STRING: A string that governs the creation of constants. The default is \"#\". IMPLEMENTATION: We generate both a DEF-C-TYPE for the NAME and a DEF-C-ENUM for the constants. URL: <http://uffi.b9.com/manual/def-enum.html> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-enum> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let ((c-constants (mapcar (lambda (constant) (cond ((symbolp constant) (list (make-constant-name name separator-string constant)) ) ((and (consp constant) (= 2 (length constant)) (integerp (cadr constant))) (list (make-constant-name name separator-string (car constant)) (cadr constant))) (t (error "INVALID ENUM CONSTANT SYNTAX: ~S." constant)))) constants))) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ,name *foreign-types-hash*) :int) (ffi:def-c-type ,name ,(convert-from-uffi-type :int :ffi)) (ffi:def-c-enum ,name ,@c-constants))) ) ;;DEF-ENUM (defmacro def-struct (name &rest fields) " DO: Declares a structure. A special type is available as a slot in the field. It is a pointer that points to an instance of the parent structure. It's type is :pointer-self. NAME: A symbol that names the structure. FIELDS: A variable number of field definitions. Each definition is a list consisting of a symbol naming the field followed by its foreign type. IMPLEMENTATION: Generates a DEF-C-STRUCT which defines both a foreign C type and a Common-Lisp STRUCTURE-CLASS. URL: <http://uffi.b9.com/manual/def-struct.html> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-struct> " (let* ((name name) (uffi-type (clean-uffi-type `(:struct ,name ,@fields) name)) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ',name *foreign-types-hash*) (setf (gethash ',name *foreign-structs-hash*) ',uffi-type)) (ffi:def-c-struct ,@(cdr ffi-type)))) ) ;;DEF-STRUCT ;; ,(CONVERT-FROM-UFFI-TYPE TYPE :CL) ;; (COM.INFORMATIMAGO.CLISP.UFFI::CLEAN-UFFI-TYPE '(* :unsigned-char) 'struct-name) ;; (setf name 'ldap-error fields '((e_code :int) (e_reason (* :unsigned-char)))) (defmacro get-slot-value (obj type field) " DO: Accesses a slot value from a structure. OBJ: A pointer to foreign structure. TYPE: A name of the foreign structure type. FIELD: A name of the desired field in foreign structure. RETURN: The value of the field in the structure. SEE ALSO: GET-SLOT-POINTER URL: <http://uffi.b9.com/manual/get-slot-value.html> URL: <http://clisp.sourceforge.net/impnotes.html#slot> " (when (and (listp type) (eq 'quote (car type))) (setf type (second type))) ;; TODO: CHECK CONVERT TYPE. `(ffi:slot (ffi:deref (ffi:cast (ffi:foreign-value ,obj) (* ,type))) ,field)) ;;GET-SLOT-VALUE (defmacro get-slot-pointer (obj type field) " DO: Accesses a slot value from a structure. OBJ: A pointer to foreign structure. TYPE: A name of the foreign structure type. FIELD: A name of the desired field in foreign structure. RETURN: The value of the field in the structure: A POINTER. NOTE: This is similar to GET-SLOT-VALUE. It is used when the value of a slot is a pointer type. SEE ALSO: GET-SLOT-VALUE URL: <http://uffi.b9.com/manual/get-slot-pointer.html> URL: <http://clisp.sourceforge.net/impnotes.html#slot> " ;; NO DIFFERENCE TO ACCESS POINTER FIELD THAN TO ACCESS VALUE FIELDS. `(get-slot-value ,obj ,type ,field) ) ;;GET-SLOT-POINTER (defmacro def-array-pointer (name type) " DO: Defines a type that is a pointer to an array of type. NAME: A name of the new foreign type. TYPE: The foreign type of the array elements. URL: <http://uffi.b9.com/manual/def-array-pointer.html> URL: <http://clisp.sourceforge.net/impnotes.html#c-array-ptr> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let* ((name name) (uffi-type (clean-uffi-type `(:array-ptr ,type))) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ,name *foreign-types-hash*) ,uffi-type) (ffi:def-c-type ,name ,ffi-type))) ) ;;DEF-ARRAY-POINTER (defmacro def-union (name &rest fields) " NAME: A name of the new union type. FIELDS: A list of fields of the union. DO: Defines a foreign union type. URL: <http://uffi.b9.com/manual/def-union.html> URL: <http://clisp.sourceforge.net/impnotes.html#c-union> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let* ((name name) (uffi-type (clean-uffi-type `(:union ,name ,@fields))) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ,name *foreign-types-hash*) ,uffi-type) (ffi:def-c-type ,name ,ffi-type))) ) ;;DEF-UNION ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; IV. Objects ;; ;;;;;;;;;;;;;;;;; (ffi:def-call-out malloc (:name "malloc") (:arguments (size ffi:uint32 :in)) (:return-type ffi:c-pointer) (:language :stdc) (:library "/lib/libc.so.6")) (ffi:def-call-out free (:name "free") (:arguments (ptr ffi:c-pointer :in)) (:return-type nil) (:language :stdc) (:library "/lib/libc.so.6")) (defmacro allocate-foreign-object (type &optional (size 1)) " DO: Allocates an instance of a foreign object. TYPE: The type of foreign object to allocate. This parameter is evaluated. SIZE: An optional size parameter that is evaluated. If specified, allocates and returns an array of type that is size members long. This parameter is evaluated. RETURN: A pointer to the foreign object. URL: <http://uffi.b9.com/manual/allocate-foreign-object.html> URL: IMPLEMENTATION: " ;; TODO: CHECK IF TYPE IS CONTANT AND THE.N CHECK AND CONVERT ;; IT AT COMPILE TIME. `(ffi:allocate-shallow (convert-from-uffi-type (clean-uffi-type ,type) :ffi) :count ,size)) ;;ALLOCATE-FOREIGN-OBJECT (defmacro free-foreign-object (ptr) " DO: Frees the memory used by the allocation of a foreign object. PTR: A pointer to the allocated foreign object to free. URL: <http://uffi.b9.com/manual/free-foreign-object.html> URL: IMPLEMENTATION: " `(ffi:foreign-free ,ptr) ) ;;FREE-FOREIGN-OBJECT (defmacro with-foreign-object ((var type) &body body) " DO: This function wraps the allocation, binding, and destruction of a foreign object. On CMUCL and Lispworks platforms the object is stack allocated for efficiency. Benchmarks show that AllegroCL performs much better with static allocation. VAR: The variable name to bind. TYPE: The type of foreign object to allocate. This parameter is evaluated. RETURN: The result of evaluating the body. URL: <http://uffi.b9.com/manual/with-foreign-object.html> URL: " `(let ((,var (allocate-foreign-object ,type))) (unwind-protect (progn ,@body) (free-foreign-object ,var))) ) ;;WITH-FOREIGN-OBJECT (defmacro size-of-foreign-type (type) " FTYPE: A foreign type specifier. This parameter is evaluated. RETURN: The number of data bytes used by a foreign object type. This does not include any Lisp storage overhead. URL: <http://uffi.b9.com/manual/size-of-foreign-type.html> URL: <http://clisp.sourceforge.net/impnotes.html#sizeof> " `(ffi:sizeof (convert-from-uffi-type (clean-uffi-type ,type) :ffi)) ) ;;SIZE-OF-FOREIGN-TYPE (defmacro pointer-address (ptr) " PTR: A pointer to a foreign object. RETURN: An integer representing the pointer's address. URL: <http://uffi.b9.com/manual/pointer-address.html> URL: <http://clisp.sourceforge.net/impnotes.html#c-var-addr> " `(let ((ptr ,ptr)) (declare (type 'ffi:foreign-address ptr)) (ffi::foreign-address-unsigned ptr)) ) ;;POINTER-ADDRESS (defmacro deref-pointer (ptr type) " PTR: A pointer to a foreign object. TYPE: A foreign type of the object being pointed to. RETURN: The value of the object where the pointer points. URL: <http://uffi.b9.com/manual/deref-pointer.html> URL: <http://clisp.sourceforge.net/impnotes.html#deref> NOTE: This is an accessor and can be used with SETF . " `(ffi:deref (ffi:cast (ffi:foreign-value ,ptr) (convert-from-uffi-type (clean-uffi-type (list '* ,type)) :ffi) )) ) ;;DEREF-POINTER (defmacro ensure-char-character (object) " DO: Ensures that an object obtained by dereferencing a :CHAR pointer is a character. OBJECT: Either a character or a integer specifying a character code. RETURN: A character. URL: <http://uffi.b9.com/manual/ensure-char-character.html> URL: " `(let ((object ,object)) (if (characterp object) object (code-char object))) ) ;;ENSURE-CHAR-CHARACTER (defmacro ensure-char-integer (object) " DO: Ensures that an object obtained by dereferencing a :CHAR pointer is an integer. OBJECT: Either a character or a integer specifying a character code. RETURN: An integer. URL: <http://uffi.b9.com/manual/ensure-char-integer.html> URL: " `(let ((object ,object)) (if (characterp object) (char-code object) object)) ) ;;ENSURE-CHAR-INTEGER (defmacro make-null-pointer (type) " DO: Creates a NULL pointer of a specified type. TYPE: A type of object to which the pointer refers. RETURN: The NULL pointer of type TYPE. URL: <http://uffi.b9.com/manual/make-null-pointer.html> URL: " (declare (ignore type)) (ffi::unsigned-foreign-address 0) ;; `(FFI:CAST (ffi:foreign-value (FFI::UNSIGNED-FOREIGN-ADDRESS 0)) ;; (CONVERT-FROM-UFFI-TYPE ;; (CLEAN-UFFI-TYPE (LIST '* ,TYPE)) :FFI)) ) ;;MAKE-NULL-POINTER (defmacro null-pointer-p (ptr) " DO: Tests if a pointer is has a NULL value. PTR: A foreign object pointer. RETURN: Whether ptr is NULL. URL: <http://uffi.b9.com/manual/null-pointer-p.html> URL: <http://clisp.sourceforge.net/impnotes.html#fa-null> " `(ffi:foreign-address-null ,ptr) ) ;;NULL-POINTER-P (defconstant +null-cstring-pointer+ (ffi::unsigned-foreign-address 0) ;;(FFI:CAST (ffi:foreign-value (FFI::UNSIGNED-FOREIGN-ADDRESS 0)) ;; (CONVERT-FROM-UFFI-TYPE (CLEAN-UFFI-TYPE :CSTRING) :FFI)) "A NULL cstring pointer. This can be used for testing if a cstring returned by a function is NULL. URL: <http://uffi.b9.com/manual/null-cstring-pointer.html> " ) ;;+NULL-CSTRING-POINTER+ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; V. Strings ;; ;;;;;;;;;;;;;;;; (defmacro convert-from-cstring (cstring) " CSTRING: A cstring. RETURN: A Lisp string. DO: Converts a Lisp string to a cstring. This is most often used when processing the results of a foreign function that returns a cstring. URL: <http://uffi.b9.com/manual/convert-from-cstring.html> " `,cstring ) ;;CONVERT-FROM-CSTRING (defmacro convert-to-cstring (string) " STRING: A Lisp string. RETURN: A cstring. DO: Converts a Lisp string to a cstring. The cstring should be freed with free-cstring. URL: <http://uffi.b9.com/manual/convert-to-cstring.html> " `,string ) ;;CONVERT-TO-CSTRING (defmacro free-cstring (cstring) " CSTRING: A cstring. DO: Frees any memory possibly allocated by convert-to-cstring. On some implementions, a cstring is just the Lisp string itself. " (declare (ignore cstring)) ;; NOP ) ;;FREE-CSTRING (defmacro with-cstring ((cstring string) &body body) " CSTRING: A symbol naming the cstring to be created. STRING: A Lisp string that will be translated to a cstring. BODY: The body of where the CSTRING will be bound. DO: Binds a symbol to a cstring created from conversion of a string. Automatically frees the cstring. URL: <http://uffi.b9.com/manual/with-cstring.html> " ;; `(let ((,cstring (convert-to-cstring ,string))) ;; (unwind-protect ;; (progn ,@body) ;; (free-cstring ,cstring))) `(let ((,cstring ,string)) ,@body) ) ;;WITH-CSTRING (defun foreign-string-length (foreign-string) (do ((len 0 (1+ len))) ((= 0 (ffi:element (ffi:foreign-value foreign-string) len)) len))) ;;foreign-string-length (defun convert-from-foreign-string (foreign-string &key length (null-terminated-p t)) " DO: Builds a Lisp string from a foreign string. Can translate ASCII and binary strings. FOREIGN-STRING: A foreign string. LENGTH: The length of the foreign string to convert. The default is the length of the string until a NULL character is reached. NULL-TERMINATED-P: A boolean flag with a default value of T. When true, the string is converted until the first NULL character is reached. RETURN: A Lisp string. URL: <http://uffi.b9.com/manual/convert-from-foreign-string.html> URL: <http://clisp.sourceforge.net/impnotes.html#encoding> " (let ((byte-vector (make-array (list (if (or null-terminated-p (null length)) (foreign-string-length foreign-string) length)) :element-type '(unsigned-byte 8))) (foreign-type `(ffi:c-array ffi:uchar ,(list length)))) (declare (ignore foreign-type)) ; TODO! (dotimes (i (length byte-vector)) (setf (aref byte-vector i) (ffi:element (ffi:foreign-value foreign-string) i))) (ext:convert-string-from-bytes byte-vector custom:*foreign-encoding*) )) ;;CONVERT-FROM-FOREIGN-STRING (defun convert-to-foreign-string (string) " STRING: A Lisp string. RETURN: A foreign string. DO: Converts a Lisp string to a foreign string. Memory should be freed with free-foreign-object. URL: <http://uffi.b9.com/manual/convert-to-foreign-string.html> " (let* ((byte-vector (ext:convert-string-to-bytes string custom:*foreign-encoding*)) (result (allocate-foreign-string (1+ (length byte-vector)))) (foreign-type `(ffi:c-array ffi:uchar ,(list (1+ (length byte-vector)))))) (declare (ignore foreign-type)) ; TODO! (dotimes (i (length byte-vector)) (setf (ffi:element (ffi:foreign-value result) i) (aref byte-vector i))) (setf (ffi:element (ffi:foreign-value result) (length byte-vector)) 0) result)) ;;CONVERT-TO-FOREIGN-STRING (defun allocate-foreign-string (size &key (unsigned t)) " SIZE: The size of the space to be allocated in bytes. UNSIGNED: A boolean flag with a default value of T. When true, marks the pointer as an :UNSIGNED-CHAR. RETURN: A foreign string which has undefined contents. DO: Allocates space for a foreign string. Memory should be freed with free-foreign-object. URL: <http://uffi.b9.com/manual/allocate-foreign-string.html> " (allocate-foreign-object (if unsigned ':unsigned-char ':char) size) ) ;;ALLOCATE-FOREIGN-STRING ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; VI. Functions & Libraries ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *modules-to-library-map* (make-hash-table :test (function equal)) "Maps module names to library paths.") (defmacro def-function (name args &key module returning) " DO: Declares a foreign function. NAME: A string or list specifying the function name. If it is a string, that names the foreign function. A Lisp name is created by translating #\_ to #\- and by converting to upper-case in case-insensitive Lisp implementations. If it is a list, the first item is a string specifying the foreign function name and the second it is a symbol stating the Lisp name. ARGS: A list of argument declarations. If NIL, indicates that the function does not take any arguments. MODULE: A string specifying which module (or library) that the foreign function resides. (Required by Lispworks) RETURNING: A declaration specifying the result type of the foreign function. :VOID indicates that this function does not return any value. URL: <http://uffi.b9.com/manual/def-function.html> NOTE: All Common-Lisp implementations are 'case-insensitive'. <http://www.lisp.org/HyperSpec/Body/sec_2-1-1-2.html> " (let (l-name c-name) (if (stringp name) (setq c-name name l-name (intern (string-upcase (substitute (character "-") (character "_") name)))) (setq c-name (first name) l-name (second name))) `(ffi:def-call-out ,l-name (:name ,c-name) ,@(when args `((:arguments ,@(mapcar (lambda (arg) `(,(first arg) ,(convert-from-uffi-type (clean-uffi-type (second arg)) :ffi) :in)) args)))) ,@(when returning `((:return-type ,(convert-from-uffi-type (clean-uffi-type returning) :ffi)))) ,@(when module (let ((library (gethash module *modules-to-library-map*))) `((:library ,(or library module))))) (:language :stdc)))) ;;DEF-FUNCTION (defun load-foreign-library (filename &key module supporting-libraries) " DO: Loads a foreign library. Applies a module name to functions within the library. Ensures that a library is only loaded once during a session. FILENAME: A string or pathname specifying the library location in the filesystem. At least one implementation (Lispworks) can not accept a logical pathname. MODULE: A string designating the name of the module to apply to functions in this library. (Required for Lispworks) SUPPORTING-LIBRARIES: A list of strings naming the libraries required to link the foreign library. (Required by CMUCL) RETURN: A boolean flag, T if the library was able to be loaded successfully or if the library has been previously loaded, otherwise NIL. URL: <http://uffi.b9.com/manual/load-foreign-library.html> IMPLEMENTATION: Loading the library is defered to the first function call. Here we just register the mapping between the MODULE and the FILENAME. TODO: Should we explicitely load the SUPPORTING-LIBRARIES too? " (declare (ignore supporting-libraries)) (when module (setf (gethash module *modules-to-library-map*) (namestring filename))) t) ;;LOAD-FOREIGN-LIBRARY (defun split-string (string &optional (separators " ")) " NOTE: current implementation only accepts as separators a string containing literal characters. " (unless (simple-string-p string) (setq string (copy-seq string))) (unless (simple-string-p separators) (setq separators (copy-seq separators))) (let ((chunks '()) (position 0) (nextpos 0) (strlen (length string)) ) (declare (type simple-string string separators)) (loop while (< position strlen) do (loop while (and (< nextpos strlen) (not (position (char string nextpos) separators))) do (setq nextpos (1+ nextpos)) ) ;;loop (push (subseq string position nextpos) chunks) (setq position (1+ nextpos)) (setq nextpos position) ) ;;loop (nreverse chunks) )) ;;SPLIT-STRING (defun find-foreign-library (names directories &key drive-letters types verbose) " NAMES: A string or list of strings containing the base name of the library file. DIRECTORIES: A string or list of strings containing the directory the library file. DRIVE-LETTERS: A string or list of strings containing the drive letters for the library file. TYPES: A string or list of strings containing the file type of the library file. Default is NIL. If NIL, will use a default type based on the currently running implementation. VERBOSE: This is an extension from the UFFI specification. Prints a line on *trace-output* for each path considered. RETURN: The path of the first found file, or NIL if the library file was not found. DO: Finds a foreign library by searching through a number of possible locations. URL: <http://uffi.b9.com/manual/find-foreign-library.html> IMPLEMENTATION: You'd better leave it up to the system to find the library! This implementation can't locate libc because on linux, there's no link named libc.so and this API doesn't allow for a version number (anyway, library versions such as in libc.so.6.0.1 have nothing to do with COMMON-LISP version that are actually file versions and mere integers). Some people believe the can pass with impunity strings containing dots as types. But that's not so. " (flet ((ensure-list (item) (if (listp item) item (list item)))) (setf names (ensure-list names)) (setf directories (ensure-list directories)) (setf drive-letters (ensure-list drive-letters)) (setf types (ensure-list types)) (setf names (mapcan (lambda (name) (if (or (<= (length name) 3) (string/= "lib" name :end2 3)) (list name (concatenate 'string "lib" name)) (list name))) names)) (setf types (or (delete-if (lambda (item) (not (every (function alphanumericp) item))) types) '("so"))) (setf drive-letters (or drive-letters '(nil))) (when verbose (format *trace-output* "Directories = ~S~%" directories) (format *trace-output* "Types = ~S~%" types) (format *trace-output* "Names = ~S~%" names) (format *trace-output* "Drive-letters = ~S~%" drive-letters)) (dolist (dir directories) (dolist (type types) (dolist (name names) (dolist (device drive-letters) (let ((path (make-pathname :device device :directory ((lambda (items) (if (char= (character "/") (char dir 0)) (cons :absolute (cdr items)) (cons :relative items))) (split-string dir "/")) :name name :type type))) (when verbose (format *trace-output* "; Considering ~S~%" path)) (when (probe-file path) (return-from find-foreign-library path)))))) nil))) ;;FIND-FOREIGN-LIBRARY ;;;; THE END ;;;;
49,972
Common Lisp
.lisp
1,112
37.490108
83
0.569219
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b7d9d63da7217a8962455bafb5c4b553bb40c36129f1dff6caa27058e18bddb8
4,794
[ -1 ]
4,795
rfc1413.lisp
informatimago_lisp/clisp/rfc1413.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: rfc1413.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Implements an IDENT protocol client. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-08-31 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2005 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "SOCKET" "REGEXP" "COM.INFORMATIMAGO.CLISP.IOTASK")) (defpackage "COM.INFORMATIMAGO.CLISP.RFC1413" (:nicknames "COM.INFORMATIMAGO.CLISP.IDENT" "IDENT-CLIENT" "RFC1413") (:documentation "Implements a ident protocol client.") (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS") (:export "CHARSET-MAP" "GET-PORT-FOR-SERVICE" "BINARY-STREAM-LISTEN" "IDENT-PARSE-RESPONSE" "IDENT-FORMAT-REQUEST" "BATCH-REQUEST-IDENTS" "REQUEST-IDENT" "BATCH-REQUEST-IDENTS/IOTASK" "REQUEST-IDENT/IOTASK")) ;; TODO: get-port-for-service should move to a generic socket utility package. (in-package "COM.INFORMATIMAGO.CLISP.RFC1413") (defconstant +connection-timeout+ 60) ; TODO: check RFC about this timeout. (defconstant +wait-response-timeout+ 30) (defun xor (a b) (or (and a (not b)) (and (not a) b))) (defun get-real-time () (/ (coerce (get-internal-real-time) 'double-float) internal-time-units-per-second)) ;; (defparameter +charset-path+ ;; #P"PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;IANA-CHARACTER-SETS.DATA") ;; (defparameter *charset-map* nil) ;; ;; ;; (defun charset-map () ;; "Builds and returns the charset-map, which maps character set names ;; to clisp charsets" ;; (or *charset-map* ;; (progn ;; (setf *charset-map* (make-hash-table :test (function equalp))) ;; (dolist (cs (read-character-sets +charset-path+)) ;; (let ((charsets ;; (mapcan ;; (lambda (name) ;; ;; map some character set names to charset names. ;; (multiple-value-bind (all utf bl) ;; (regexp:match "^UTF-\\(.*\\)\\([BL]\\)E$" name) ;; (when all ;; (setf name (format nil ;; "UNICODE-~A-~:[LITTLE~;BIG~]-ENDIAN" ;; (regexp:match-string name utf) ;; (string-equal ;; (regexp:match-string name bl) ;; "B"))))) ;; ;; find the character set name in the charset package ;; (let ((charset (find-symbol (string-upcase name) :charset))) ;; (if charset ;; (list charset) ;; (loop ; not found: try with a prefix. ;; with u = (string-upcase name) ;; for l from (length u) downto 3 ;; for n = (subseq u 0 l) ;; for c = (find-symbol n :charset) ;; do (when c (return (list c))) ;; finally (return nil))))) ;; cs))) ;; ;; (print `(,cs --> ,charsets)) ;; (cond ;; ((null charsets)) ; forget it ;; ((null (cdr charsets)) ; map all to the one ;; (dolist (name cs) ;; (setf (gethash name *charset-map*) (first charsets)))) ;; (t ; oops! map each to its own or the first ;; (warn "One IANA character set maps to more than one ~ ;; clisp CHARSET: ~S --> ~S" cs charsets) ;; (dolist (name cs) ;; (setf (gethash name *charset-map*) ;; (or (find-symbol (string-upcase name) :charset) ;; (first charsets)))))))) ;; *charset-map*))) ;; ;; ;; (DEFUN get-charset (name) ;; (gethash name (charset-map))) (defun get-port-for-service (service) #+ #. (cl:if (cl:ignore-errors (cl:find-symbol "SERVICE" "POSIX")) '(and) '(or)) (posix:service-port (posix:service service)) #- #. (cl:if (cl:ignore-errors (cl:find-symbol "SERVICE" "POSIX")) '(and) '(or)) (multiple-value-bind (name aliases port protocol) (socket:socket-service-port service) (declare (ignore name aliases protocol)) port)) (defun binary-stream-listen (stream) (case (socket:socket-status stream 0) ((:input :io) t) (otherwise nil))) (defun read-line-in-buffer (stream buffer) "Read byte sequence into the buffer, adjusting the fill-pointer. When CR-LF is read, return the position of the eoln If the buffer becomes full before the CR-LF is read, then signal an error." ;; KEEP Synchronized with RECYCLE-LINE-BUFFER (loop while (binary-stream-listen stream) do (vector-push (read-byte stream) buffer)) (let ((eoln (search #(13 10) buffer))) ;; (print `(:eoln ,eoln :buffer ,buffer)) (cond (eoln (decf (fill-pointer buffer) 2)) ((<= (array-dimension buffer 0) (fill-pointer buffer)) ; no eoln (error "ident server sent a line too long.")) (t nil)))) (defun recycle-line-buffer (buffer) "Moves the bytes following the first eoln to the beginning of the buffer." ;; KEEP Synchronized with READ-LINE-IN-BUFFER ;; The current version doesn't read more than CR LF, ;; so we don't have anything to do. (setf (fill-pointer buffer) 0)) (defparameter +ch.cr+ (code-char 13)) (defparameter +ch.lf+ (code-char 10)) (defparameter +ch.comma+ (character ",")) (defparameter +comma+ 44 "ASCII CODE for COMMA") (defparameter +colon+ 58 "ASCII CODE for COLON") (defun ident-parse-response (buffer) (flet ((split-subparts (part process) (loop with subparts = '() for start = 0 then (1+ comma) for comma = (position +ch.comma+ part :start start) do (push (funcall process (string-trim " " (subseq part start comma))) subparts) while comma finally (return (nreverse subparts))))) (loop with parts = '() for start = 0 then (1+ colon) for colon = (position +colon+ buffer :start start) for count from 1 do (push (cons start colon) parts) while (and colon (< count 3)) finally (setf colon (or (and colon (1+ colon)) (length buffer))) (let ((str (ext:convert-string-from-bytes buffer charset:ascii :end colon))) (setf parts (mapcar (lambda (se process) (split-subparts (subseq str (car se) (cdr se)) process)) parts (list (function identity) (lambda (name) (intern name :keyword)) (function parse-integer)))) (let ((cs (find-character-set (or (second (first parts)) "ASCII")))) (push (if cs (ext:convert-string-from-bytes buffer (cs-lisp-encoding cs) :start colon) (subseq buffer colon)) parts)) (return (nreverse parts)))))) #|| (defparameter ex0 (ext:convert-string-to-bytes "6195, 23 : ERROR : NO-USER" charset:ascii)) (defparameter ex1 (ext:convert-string-to-bytes "6193, 23 : USERID : UNIX :stjohns" charset:ascii)) (defparameter ex2 (ext:convert-string-to-bytes "6193, 23 : USERID : UNIX,ISO-8859-1 :stétienne" charset:iso-8859-1)) (defparameter ex3 (ext:convert-string-to-bytes "6193, 23 : USERID : UNIX,ISO-8859-5 :Распутин" charset:iso-8859-5)) (mapcar (function IDENT-PARSE-RESPONSE) (list ex0 ex1 ex2 ex3)) ||# (defun ident-format-request (request) (destructuring-bind (remote-port local-port) request (ext:convert-string-to-bytes (format nil "~A, ~A~C~C" remote-port local-port +ch.cr+ +ch.lf+) charset:ascii))) (defun batch-request-idents (remote-host port-couples) " RETURN: a list of responses from REMOTE-HOST ident server: for each port-couple ((remote-port local-port) (:USERID) (opsys [charset]) user-id) or: ((remote-port local-port) (:ERROR) (error-type)) or: ((remote-port local-port) (:TIMEOUT)) " (unless port-couples (return-from batch-request-idents nil)) (let ((remote (socket:socket-connect (get-port-for-service "ident") remote-host :element-type '(unsigned-byte 8) :buffered nil))) ;; No :timeout to get error when connection is refused. (unwind-protect (loop with inbuf = (make-array '(1024) :element-type '(unsigned-byte 8) :initial-element 0 :fill-pointer 0) with state = :sending with start-wait = 0.0 with results = '() with to-send = port-couples with to-receive = port-couples do #+(or) (print `(:state ,state :start-wait ,start-wait :results ,results :to-send ,to-send :to-receive ,to-receive)) (case (socket:socket-status remote +wait-response-timeout+) ((nil) (cond ((eq state :sending) (setf state :waiting start-wait (get-real-time))) ((<= +wait-response-timeout+ (- (get-real-time) start-wait)) ;; time-out (return-from batch-request-idents (dolist (request to-receive (nreverse results)) (push (list (pop to-receive) '(:timeout)) results))))) (sleep 0.05)) ((:input :io) ; something to read (when (read-line-in-buffer remote inbuf) (let ((result (ident-parse-response inbuf))) (unless (equal (car to-receive) (car result)) (warn "Desynchronization ~S --> ~S" (car to-receive) result)) (pop to-receive) (push result results)) (unless to-receive (setf state :waiting)) (recycle-line-buffer inbuf))) ((:output) (cond (to-send (setf state :sending) (write-sequence (ident-format-request (pop to-send)) remote) (finish-output remote)) ((and (eq state :waiting) (<= +wait-response-timeout+ (- (get-real-time) start-wait))) ;; time-out (return-from batch-request-idents (dolist (request to-receive (nreverse results)) (push (list (pop to-receive) '(:timeout)) results)))) (to-receive (when (eq state :sending) (setf state :waiting start-wait (get-real-time)))) (t (return-from batch-request-idents (nreverse results))))) (otherwise ; eof or error (return-from batch-request-idents (nreverse results))))) (close remote)))) (defun request-ident (&key remote-host remote-port local-port socket) " NOTE: Specify either (remote-host remote-port local-port) or socket. RETURN: ((remote-port local-port) (:USERID) (opsys [charset]) user-id) or: ((remote-port local-port) (:ERROR) (error-type)) or: ((remote-port local-port) (:TIMEOUT)) " (assert (xor (and remote-host remote-port local-port) socket) (remote-host remote-port local-port socket) "Either the three remote-host, remote-port and local port, or socket must be specified.") (when socket (let (local-host) (multiple-value-setq (remote-host remote-port) (socket:socket-stream-peer socket t)) (multiple-value-setq (local-host local-port) (socket:socket-stream-local socket t)))) (first (batch-request-idents remote-host (list (list remote-port local-port))))) #|| (ext:shell "netstat -tnp") (request-ident :remote-host "62.93.174.78" :remote-port 22 :local-port 32793) ||# (defun batch-request-idents/iotask (continuation remote-host port-couples) " DO: Connects to the remote host and schedules a iotask to process the ident protocol, and returns immediately. IOTASK-POLL must be called periodically. When the responses are received, calls continuation with the list of responses from REMOTE-HOST ident server: for each port-couple ((remote-port local-port) (:USERID) (opsys [charset]) user-id) or: ((remote-port local-port) (:ERROR) (error-type)) or: ((remote-port local-port) (:TIMEOUT)) " (unless port-couples (return-from batch-request-idents/iotask (funcall continuation nil))) (let ((remote (socket:socket-connect (get-port-for-service "ident") remote-host :element-type '(unsigned-byte 8) :buffered nil)) ;; No :timeout to get error when connection is refused. (inbuf (make-array '(1024) :element-type '(unsigned-byte 8) :initial-element 0 :fill-pointer 0)) (state :sending) (start-wait 0.0) (results '()) (to-send port-couples) (to-receive port-couples)) (flet ((task (task status) (flet ((done (result) (close remote) (com.informatimago.clisp.iotask:iotask-dequeue task) (funcall continuation result) (return-from task))) ;;(unwind-protect #+(or) (print `(:state ,state :start-wait ,start-wait :results ,results :to-send ,to-send :to-receive ,to-receive)) (case status ((:timeout) (done (dolist (request to-receive (nreverse results)) (push (list (pop to-receive) '(:timeout)) results)))) ((:input :io) ; something to read (when (read-line-in-buffer remote inbuf) (let ((result (ident-parse-response inbuf))) (unless (equal (car to-receive) (car result)) (warn "Desynchronization ~S --> ~S" (car to-receive) result)) (pop to-receive) (push result results)) (unless to-receive (setf state :waiting)) (recycle-line-buffer inbuf))) ((:output) (cond (to-send (setf state :sending) (write-sequence (ident-format-request (pop to-send)) remote) (finish-output remote)) ((and (eq state :waiting) (<= +wait-response-timeout+ (- (get-real-time) start-wait))) ;; time-out (done (dolist (request to-receive (nreverse results)) (push (list (pop to-receive) '(:timeout)) results)))) (to-receive (when (eq state :sending) (setf state :waiting start-wait (get-real-time)))) (t (done (nreverse results))))) (otherwise ; eof or error (done (nreverse results))))))) (com.informatimago.clisp.iotask:iotask-enqueue-stream remote (function task) :name "BATCH-REQUEST-IDENTS/IOTASK" :alarm-time +wait-response-timeout+)))) (defun request-ident/iotask (continuation &key remote-host remote-port local-port socket) " NOTE: Specify either (remote-host remote-port local-port) or socket. DO: Connects to the remote host and schedules a iotask to process the ident protocol, and returns immediately. IOTASK-POLL must be called periodically. When the response is received, calls continuation with ((remote-port local-port) (:USERID) (opsys [charset]) user-id) or: ((remote-port local-port) (:ERROR) (error-type)) or: ((remote-port local-port) (:TIMEOUT)) " (assert (xor (and remote-host remote-port local-port) socket) (remote-host remote-port local-port socket) "Either the three remote-host, remote-port and local port, or socket must be specified.") (when socket (let (local-host) (multiple-value-setq (remote-host remote-port) (socket:socket-stream-peer socket t)) (multiple-value-setq (local-host local-port) (socket:socket-stream-local socket t)))) (batch-request-idents/iotask remote-host (list (list remote-port local-port)) (lambda (results) (funcall continuation (first results))))) ;;;; THE END ;;;;
18,881
Common Lisp
.lisp
404
36.80198
99
0.537977
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
21bd1fb99d7393bb6d6459decce393a550c95f486962b967923275d94cecc39f
4,795
[ -1 ]
4,796
raw-memory.lisp
informatimago_lisp/clisp/raw-memory.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: raw-memory.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Peek and Poke. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-11-30 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (eval-when (:compile-toplevel :load-toplevel :execute) (require "linux")) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "LINUX")) (defpackage "COM.INFORMATIMAGO.CLISP.RAW-MEMORY" (:documentation "Peek and Poke.") (:use "COMMON-LISP" "FFI") (:shadowing-import-from "FFI" "SIN") (:export "*LIBRARY*" "PEEK" "POKE" "DUMP" "WITH-SIGSEG-HANDLER" ;; The following are low-level function, not protected by signal handler. ;; Install you own! "PEEK-UINT8" "PEEK-SINT8" "POKE-UINT8" "POKE-SINT8" "PEEK-UINT16" "PEEK-SINT16" "POKE-UINT16" "POKE-SINT16" "PEEK-UINT32" "PEEK-SINT32" "POKE-UINT32" "POKE-SINT32" "PEEK-UINT64" "PEEK-SINT64" "POKE-UINT64" "POKE-SINT64")) (in-package "COM.INFORMATIMAGO.CLISP.RAW-MEMORY") (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *library* "/usr/local/lib/libraw-memory.so" "The namestring of the pathname to the raw-memory library file.")) (defun install-signal-handler (signum handler) (let ((oldhan (linux:|set-signal-handler| signum handler)) (sigset (second (multiple-value-list (linux:|sigaddset| (second (multiple-value-list (linux:|sigemptyset|))) signum))))) (linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| sigset) (values signum oldhan sigset))) (defun restore-signal-handler (signum oldhan sigset) (linux:|set-signal-handler| signum oldhan) (linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| sigset)) (defmacro with-signal-handler (signum handler &body body) (let ((voldhan (gensym)) (vsignum (gensym)) (vsigset (gensym))) `(let* ((,vsignum ,signum) (,voldhan (linux:|set-signal-handler| ,vsignum ,handler)) (,vsigset (second (multiple-value-list (linux:|sigaddset| (second (multiple-value-list (linux:|sigemptyset|))) ,vsignum))))) (linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| ,vsigset) (unwind-protect (progn ,@body) (linux:|set-signal-handler| ,vsignum ,voldhan) (linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| ,vsigset))))) (defmacro with-sigseg-handler (&body body) `(with-signal-handler linux:|SIGSEGV| (lambda (signum) (declare (ignore signum)) (error "Got Segment Violation Signal while accessing raw memory")) ,@body)) ;; Scalar: (defmacro generate-peek-and-poke () (loop with code = '() for size in '(8 16 32) ;; peek and poke of 64-bit don't work. for c-peek-name = (format nil "peek~D" size) for c-poke-name = (format nil "poke~D" size) do (loop for type in '(uint sint) for l-peek-name = (intern (with-standard-io-syntax (format nil"PEEK-~A~D" type size)) "COM.INFORMATIMAGO.CLISP.RAW-MEMORY") for l-poke-name = (intern (with-standard-io-syntax (format nil"POKE-~A~D" type size)) "COM.INFORMATIMAGO.CLISP.RAW-MEMORY") for l-type = (intern (with-standard-io-syntax (format nil"~A~D" type size)) "FFI") do (push `(ffi:def-call-out ,l-peek-name (:name ,c-peek-name) (:arguments (address ffi:ulong)) (:return-type ,l-type) (:library *library*) (:language :stdc)) code) (push `(ffi:def-call-out ,l-poke-name (:name ,c-poke-name) (:arguments (address ffi:ulong) (value ,l-type)) (:return-type nil) (:library *library*) (:language :stdc)) code)) finally (return `(progn ,@ code)))) (eval-when (:load-toplevel :execute) (generate-peek-and-poke)) (defun peek-uint64 (address) (dpb (peek-uint32 (+ 4 address)) (byte 32 32) (peek-uint32 address))) (defun peek-sint64 (address) (dpb (peek-uint32 (+ 4 address)) (byte 32 32) (peek-uint32 address))) (defun poke-uint64 (address object) (poke-uint32 address (ldb (byte 32 0) object)) (poke-uint32 (+ 4 address) (ldb (byte 32 32) object))) (defun poke-sint64 (address object) (poke-uint32 address (ldb (byte 32 0) object)) (poke-uint32 (+ 4 address) (ldb (byte 32 32) object))) (defun get-function (type peek-or-poke) (case peek-or-poke ((:peek) (when (atom type) (error "Can't peek this type ~S" type)) (case (first type) ((unsigned-byte) (case (second type) ((8) (values (function peek-uint8 ) 1)) ((16) (values (function peek-uint16) 2)) ((32) (values (function peek-uint32) 4)) ((64) (values (function peek-uint64) 8)) (otherwise (error "Can't peek this type ~S" type)))) ((signed-byte) (case (second type) ((8) (values (function peek-sint8 ) 1)) ((16) (values (function peek-sint16) 2)) ((32) (values (function peek-sint32) 4)) ((64) (values (function peek-sint64) 8)) (otherwise (error "Can't peek this type ~S" type)))) (otherwise (error "Can't peek this type ~S" type)))) ((:poke) (when (atom type) (error "Can't poke this type ~S" type)) (case (first type) ((unsigned-byte) (case (second type) ((8) (values (function poke-uint8 ) 1)) ((16) (values (function poke-uint16) 2)) ((32) (values (function poke-uint32) 4)) ((64) (values (function poke-uint64) 8)) (otherwise (error "Can't poke this type ~S" type)))) ((signed-byte) (case (second type) ((8) (values (function poke-sint8 ) 1)) ((16) (values (function poke-sint16) 2)) ((32) (values (function poke-sint32) 4)) ((64) (values (function poke-sint64) 8)) (otherwise (error "Can't poke this type ~S" type)))) (otherwise (error "Can't poke this type ~S" type)))) (otherwise (error "PEEK-OR-POKE must be either :PEEK or :POKE, not ~S" peek-or-poke)))) ;; type: simtype | comtype. ;; simtype: ;; (unsigned-byte 8) ;; (signed-byte 8) ;; (unsigned-byte 16) ;; (signed-byte 16) ;; (unsigned-byte 32) ;; (signed-byte 32) ;; (unsigned-byte 64) ;; (signed-byte 64) ;; single-float ; not implemented yet. ;; double-float ; not implemented yet. ;; comtype: ;; (array simtype size) ;; (vector simtype size) (defun peek (address type) (with-signal-handler linux:|SIGSEGV| (lambda (signum) (declare (ignore signum)) (error "Got Segment Violation Signal while peeking ~8,'0X" address)) (if (and (listp type) (or (eq (first type) 'array) (eq (first type) 'vector))) (multiple-value-bind (peek incr) (get-function (second type) :peek) (do ((data (make-array (list (third type)) :element-type (second type) :initial-element 0)) (address address (+ address incr)) (i 0 (1+ i))) ((>= i (third type)) data) (setf (aref data i) (funcall peek address)))) (funcall (get-function type :peek) address)))) ;;peek (defun poke (address type value) (with-signal-handler linux:|SIGSEGV| (lambda (signum) (declare (ignore signum)) (error "Got Segment Violation Signal while poking ~8,'0X" address)) (if (and (listp type) (or (eq (first type) 'array) (eq (first type) 'vector))) (multiple-value-bind (poke incr) (get-function (second type) :poke) (do ((address address (+ address incr)) (i 0 (1+ i))) ((>= i (third type)) (values)) (funcall poke address (aref value i)))) (funcall (get-function type :poke) address value)))) ;;poke (defun dump (address type &optional (stream t) (margin "")) (with-signal-handler linux:|SIGSEGV| (lambda (signum) (declare (ignore signum)) (error "Got Segment Violation Signal while peeking ~8,'0X" address)) (if (and (listp type) (or (eq (first type) 'array) (eq (first type) 'vector))) (multiple-value-bind (peek incr) (get-function (second type) :peek) (do ((address address (+ address incr)) (i 0 (1+ i))) ((>= i (third type)) (format stream "~&") (values)) (when (zerop (mod i (/ 16 incr))) (format stream "~&~A~8,'0X: " margin (+ address i))) (format stream "~V,'0X " (* 2 incr) (funcall peek address)))) (multiple-value-bind (peek incr) (get-function type :peek) (format stream "~&~A~8,'0X: ~V,'0X ~&" margin address (* 2 incr) (funcall peek address)))))) ;; (in-package "COMMON-LISP-USER") ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (unless (find-package "LINUX") ;; (warn "Package LINUX is not available. Signal handling is disabled.") ;; (defpackage "LINUX" ;; (:use "COMMON-LISP") ;; (:export "set-signal-handler" "sigaddset" "sigemptyset" ;; "sigprocmask-set-n-save" "SIG_UNBLOCK" "SIGSEGV")) ;; (in-package "LINUX") ;; (defmacro null-op (name) ;; `(defmacro ,name (&rest args) (declare (ignore args)) nil)) ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (null-op |set-signal-handler|) ;; (null-op |sigaddset|) ;; (null-op |sigemptyset|) ;; (null-op |sigprocmask-set-n-save|) ;; (defparameter |SIG_UNBLOCK| 0) ;; (defparameter |SIGSEGV| 0)))) ;; ;; (in-package "COMMON-LISP-USER") ;;;; THE END ;;;;
11,405
Common Lisp
.lisp
259
36.316602
83
0.570927
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6d44a2632be358e0a5756854771c14c2c1686431150c60b8daa6f37c47ecd57a
4,796
[ -1 ]
4,797
disk.lisp
informatimago_lisp/clisp/disk.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: disk.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: clisp ;;;;USER-INTERFACE: clisp ;;;;DESCRIPTION ;;;; ;;;; This package exports disk management functions, ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2010-06-27 <PJB> Removed string constant +TAB+. ;;;; 2003-10-21 <PJB> Added du. ;;;; 2002-01-09 <PJB> Moved in df from tar-backup. ;;;; 2002-10-?? <PJB> Creation. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2002 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.DISK" (:documentation "This package exports disk management functions. Copyright Pascal J. Bourguignon 2002 - 2003 This package is provided under the GNU General Public License. See the source file for details.") (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY") (:export "VOLINFO" "VOLINFO-PATH" "VOLINFO-FS-TYPE" "VOLINFO-SIZE" "VOLINFO-USED" "VOLINFO-AVAILABLE" "VOLINFO-MOUNT-POINT" "DF" "DU" )) (in-package "COM.INFORMATIMAGO.CLISP.DISK") (defun old-df () " RETURN: A list of sublists each containing: (device size used available mount-point) " (mapcar (lambda (line) (split-string line " ")) (stream-to-string-list (ext:run-shell-command "/bin/df -T|postodax|/bin/awk '/Available/{next;}{print $1,$2,$3,$4,$5,$7;}'" :output :stream)))) (defstruct volinfo (path "" :type string) (fs-type "" :type string) (size 0 :type number) (used 0 :type number) (available 0 :type number) (mount-point "" :type string) ) ;;VOLINFO (defun df (&optional path) " RETURN: A list of volinfo structures. " (unless path (setq path "")) (mapcar (lambda (line) (let ((data (split-string line " \\+"))) (make-volinfo :path (nth 0 data) :fs-type (nth 1 data) :size (* 1024 (read-from-string (nth 2 data))) :used (* 1024 (read-from-string (nth 3 data))) :available (* 1024 (read-from-string (nth 4 data))) :mount-point (nth 5 data)))) (stream-to-string-list (ext:run-shell-command (format nil "df -k -T ~A|postodax|/bin/awk '/Available/{next;}{print $1,$2,$3,$4,$5,$7;}'" path) :output :stream)))) (defun du (&optional (path (ext:cd))) " RETURN: The Disk Usage of the given PATH (or the current directory). It's given as the underlying du command gives it, either in blocks of 1KB or of 512 B. " (values (read-from-string (caar (mapcar (lambda (line) (split-string line #.(string (code-char 9)))) (stream-to-string-list (ext:run-program "du" :arguments (list "-s" path) :output :stream))))))) ;;;; THE END ;;;;
4,033
Common Lisp
.lisp
105
33.828571
88
0.596375
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1646be3bc7944f876f1d126d8961844efd61a702181d7389202b460fbd2e2689
4,797
[ -1 ]
4,798
mysql.lisp
informatimago_lisp/clisp/mysql.lisp
;;;; -*- coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: mysql.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; MySQL FFI. ;;;; This package exports mysql functions. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2006-04-21 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2006 - 2016 ;;;; ;;;; 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/> ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.MYSQL" (:documentation "This package exports mysql functions. Copyright Pascal J. Bourguignon 2006 - 2006 This package is provided under the GNU General Public License. See the source file for details.") (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY") (:export )) (in-package "COM.INFORMATIMAGO.CLISP.MYSQL") (defconstant +library+ #+unix "/usr/lib/libmysqlclient.so" #-unix (error "Where is the mysqlclient library?")) (ffi:def-c-type my-bool ffi:char) (ffi:def-c-type gptr (ffi:c-pointer ffi:char)) (ffi:def-c-type my-socket ffi:int) (defconstant +name-len+ 64 "Field/table name length") (defconstant +hostname-length+ 60) (defconstant +username-length+ 16) (defconstant +server-version-length 60) (defconstant +local-host+ "localhost") (defconstant +local-host-namedpipe+ ".") (defenum enum-server-command +com-sleep+ +com-quit+ +com-init-db+ +com-query+ +com-field-list+ +com-create-db+ +com-drop-db+ +com-refresh+ +com-shutdown+ +com-statistics+ +com-process-info+ +com-connect+ +com-process-kill+ +com-debug+ +com-ping+ +com-time+ +com-delayed-insert+ +com-change-user+ +com-binlog-dump+ +com-table-dump+ +com-connect-out+) (defconstant +not-null-flag+ 1 "Field can't be NULL") (defconstant +pri-key-flag+ 2 "Field is part of a primary key") (defconstant +unique-key-flag+ 4 "Field is part of a unique key") (defconstant +multiple-key-flag+ 8 "Field is part of a key") (defconstant +blob-flag+ 16 "Field is a blob") (defconstant +unsigned-flag+ 32 "Field is unsigned") (defconstant +zerofill-flag+ 64 "Field is zerofill") (defconstant +binary-flag+ 128 "") ;; The following are only sent to new clients (defconstant +enum-flag+ 256 "field is an enum") (defconstant +auto-increment-flag+ 512 "field is a autoincrement field") (defconstant +timestamp-flag+ 1024 "Field is a timestamp") (defconstant +set-flag+ 2048 "field is a set") (defconstant +num-flag+ 32768 "Field is num (for clients)") (defconstant +part-key-flag+ 16384 "Intern; Part of some key") (defconstant +group-flag+ 32768 "Intern: Group field") (defconstant +unique-flag+ 65536 "Intern: Used by sql-yacc") (defconstant +refresh-grant+ 1 "Refresh grant tables") (defconstant +refresh-log+ 2 "Start on new log file") (defconstant +refresh-tables+ 4 "close all tables") (defconstant +refresh-hosts+ 8 "Flush host cache") (defconstant +refresh-status+ 16 "Flush status variables") (defconstant +refresh-threads+ 32 "Flush thread cache") (defconstant +refresh-slave+ 64 "Reset master info and restart slave thread") (defconstant +refresh-master+ 128 "Remove all bin logs in the index and truncate the index") ;; The following can't be set with mysql-refresh() (defconstant +refresh-read-lock+ 16384 "Lock tables for read") (defconstant +refresh-fast+ 32768 "Intern flag") (defconstant +client-long-password+ 1 "new more secure passwords") (defconstant +client-found-rows+ 2 "Found instead of affected rows") (defconstant +client-long-flag+ 4 "Get all column flags") (defconstant +client-connect-with-db+ 8 "One can specify db on connect") (defconstant +client-no-schema+ 16 "Don't allow database.table.column") (defconstant +client-compress+ 32 "Can use compression protocol") (defconstant +client-odbc+ 64 "Odbc client") (defconstant +client-local-files+ 128 "Can use LOAD DATA LOCAL") (defconstant +client-ignore-space+ 256 "Ignore spaces before '('") (defconstant +client-change-user+ 512 "Support the mysql-change-user()") (defconstant +client-interactive+ 1024 "This is an interactive client") (defconstant +client-ssl+ 2048 "Switch to SSL after handshake") (defconstant +client-ignore-sigpipe+ 4096 "IGNORE sigpipes") (defconstant +client-transactions+ 8192 "Client knows about transactions") (defconstant +server-status-in-trans+ 1 "Transaction has started") (defconstant +server-status-autocommit+ 2 "Server in auto-commit mode") (defconstant +mysql-errmsg-size+ 200) (defconstant +net-read-timeout+ 30 "Timeout on read") (defconstant +net-write-timeout+ 60 "Timeout on write") (defconstant +net-wait-timeout+ (* 8 60 60) "Wait for new query") (defconstant +max-char-width+ 255 "Max length for a CHAR colum") (defconstant +max-blob-width+ 8192 "Default width for blob") (ffi:def-c-type net (vio ffi:c-pointer) (fd my-socket) ; For Perl DBI/dbd (fcntl ffi:int) (buff ffi:c-pointer) (buff-end ffi:c-pointer) (write-pos ffi:c-pointer) (read-pos ffi:c-pointer) (last-error (ffi:c-array-max ffi:char +mysql-errmsg-size+)) (last-errno ffi:uint) (max-packet ffi:uint) (timeout ffi:uint) (pkt-nr ffi:uint) (error ffi:uchar) (return-errno my-bool) (compress my-bool) (no-send-ok my-bool) ; needed if we are doing several ;; queries in one command ( as in LOAD TABLE ... FROM MASTER ), ;; and do not want to confuse the client with OK at the wrong time. (remain-in-buf ffi:ulong) (length ffi:ulong) (buf-length ffi:ulong) (where-b ffi:ulong) (return-status (ffi:c-ptr-null ffi:uint)) (reading-or-writing ffi:uchar) (save-char ffi:char)) (defconstant +packet-error+ #xffffffff) (defenum enum-field-types +field-type-decimal+ +field-type-tiny+ +field-type-short+ +field-type-long+ +field-type-float+ +field-type-double+ +field-type-null+ +field-type-timestamp+ +field-type-longlong+ +field-type-int24+ +field-type-date+ +field-type-time+ +field-type-datetime+ +field-type-year+ +field-type-newdate+ (+field-type-enum+ 247) (+field-type-set+ 248) (+field-type-tiny-blob+ 249) (+field-type-medium-blob+ 250) (+field-type-long-blob+ 251) (+field-type-blob+ 252) (+field-type-var-string+ 253) (+field-type-string+ 254)) (defconstant +field-type-char+ +field-type-tiny+ "For compability") (defconstant +field-type-interval+ +field-type-enum+ "For compability") (ffi:def-c-var max-allowed-packet (:name "max_allowed_packet") (:type ffi:ulong) (:library #.+library+)) (ffi:def-c-var net-buffer-length (:name "net_buffer_length") (:type ffi:ulong) (:library #.+library+)) (defun net-new-transaction (net) (setf (ffi:slot net 'pkt-nr) 0)) (ffi:def-call-out my-net-init (:name "my_net_init") (:arguments (net (ffi:c-pointer net)) (vio ffi:c-pointer)) (:result-type ffi:int) (:library #.+library+)) (ffi:def-call-out net-end (:name "net_end") (:arguments (net (ffi:c-pointer net))) (:result-type nil) (:library #.+library+)) (ffi:def-call-out net-clear (:name "net_clear") (:arguments (net (ffi:c-pointer net))) (:result-type nil) (:library #.+library+)) (ffi:def-call-out net-flush (:name "net_flush") (:arguments (net (ffi:c-pointer net))) (:result-type nil) (:library #.+library+)) (ffi:def-call-out my-net-write (:name "my_net_write") (:arguments (net (ffi:c-pointer net)) (packet (ffi:array ffi:uchar) :in) (len ffi:ulong)) (:result-type ffi:int) (:library #.+library+)) (ffi:def-call-out net-write (:name "net_write") (:arguments (net (ffi:c-pointer net)) (command ffi:uchar) (packet (ffi:array ffi:uchar) :in) (len ffi:ulong)) (:result-type ffi:int) (:library #.+library+)) (ffi:def-call-out net-real-write (:name "net_real_write") (:arguments (net (ffi:c-pointer net)) (packet (ffi:array ffi:uchar) :in) (len ffi:ulong)) (:result-type ffi:int) (:library #.+library+)) (ffi:def-call-out my-net-read (:name "my_net_read") (:arguments (net (ffi:c-pointer net))) (:result-type ffi:uint) (:library #.+library+)) (ffi:def-c-type rand-struct (seed1 ffi:ulong) (seed2 ffi:ulong) (max-value ffi:ulong) (max-value-dbl ffi:double)) ;; The following is for user defined functions (defenum item-result +string-result+ +real-result+ +int-result+) (ffi:def-c-type udf-args (arg-count ffi:uint) ; Number of arguments (arg-type (ffi:c-array-ptr item-result)) ; Pointer to item-results (args (ffi:c-array-ptr ffi:c-string)) ; Pointer to argument (lengths (ffi:c-array-ptr ffi:ulong)) ; Length of string arguments (maybe-null (ffi:c-array-ptr ffi:char))) ; Set to 1 for all maybe-null args ;; This holds information about the result (ffi:def-c-type udf-init (maybe-null my-bool) ; 1 iff function can return NULL (decimals ffi:uint) ; for real functions (max-length ffi:uint) ; For string functions (ptr ffi:c-pointer) ; free pointer for function data (const-item my-bool)) ; 0 if result is independent of arguments ;; Constants when using compression (defconstant +net-header-size+ 4 "standard header size") (defconstant +comp-header-size+ 3 "compression header extra size") ;; Prototypes to password functions (ffi:def-call-out random-init (:name "randominit") (:arguments (rs (ffi:c-ptr rand-struct)) (seed1 ffi:ulong) (seed2 ffi:ulong)) (:result-type nil) (:library #.+library+)) (ffi:def-call-out rnd (:name "rnd") (:arguments (rs (ffi:c-ptr rand-struct))) (:result-type ffi:double-float) (:library #.+library+)) (ffi:def-call-out make-scrambled-password (:name "make_scrambled_password") (:arguments (to ffi:c-string :out) (password ffi:c-string :in)) (:result-type nil) (:library #.+library+)) (ffi:def-call-out get-salt-from-password (:name "get_salt_from_password") (:arguments (res ffi:ulong :out) (password ffi:c-string :in)) (:result-type nil) (:library #.+library+)) #| void make-password-from-salt(char *to, unsigned long *hash-res) ; char *scramble(char *to,const char *message,const char *password, my-bool old-ver) ; my-bool check-scramble(const char *, const char *message, unsigned long *salt,my-bool old-ver) ; char *get-tty-password(char *opt-message) ; void hash-password(unsigned long *result, const char *password) ; /* Some other useful functions */ void my-init(void) ; void load-defaults(const char *conf-file, const char **groups, int *argc, char ***argv) ; my-bool my-thread-init(void) ; void my-thread-end(void) ; (defconstant +NULL-LENGTH+ #xffffffff "For net-store-length") ;; Version numbers for protocol & mysqld (defconstant +PROTOCOL_VERSION+ 10) (defconstant +MYSQL_SERVER_VERSION+ "3.23.55") (defconstant +MYSQL_SERVER_SUFFIX+ "") (defconstant +FRM_VER+ 6) (defconstant +MYSQL_VERSION_ID+ 32355) (defconstant +MYSQL_PORT+ 3306) (defconstant +MYSQL_UNIX_ADDR+ "/var/lib/mysql/mysql.sock") (defconstant +MYSQL_CONFIG_NAME+ "my") ;; mysqld compile time options (defconstant +MYSQL_CHARSET+ "latin1") (ffi:def-c-var mysql-port ffi:uint) (ffi:def-c-var mysql-unix-port ffi:c-string) #define IS-PRI-KEY(n) ((n) & PRI-KEY-FLAG) #define IS-NOT-NULL(n) ((n) & NOT-NULL-FLAG) #define IS-BLOB(n) ((n) & BLOB-FLAG) #define IS-NUM(t) ((t) <= FIELD-TYPE-INT24 || (t) == FIELD-TYPE-YEAR) #define IS-NUM-FIELD(f) ((f)->flags & NUM-FLAG) #define INTERNAL-NUM-FIELD(f) (((f)->type <= FIELD-TYPE-INT24 && ((f)->type != FIELD-TYPE-TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == FIELD-TYPE-YEAR) typedef struct st-mysql-field { char *name ; /* Name of column */ char *table ; /* Table of column if column was a field */ char *def ; /* Default value (set by mysql-list-fields) */ enum enum-field-types type ; /* Type of field. Se mysql-com.h for types */ unsigned int length ; /* Width of column */ unsigned int max-length ; /* Max width of selected set */ unsigned int flags ; /* Div flags */ unsigned int decimals ; /* Number of decimals in field */ } MYSQL-FIELD ; typedef char **MYSQL-ROW ; /* return data as array of strings */ typedef unsigned int MYSQL-FIELD-OFFSET; /* offset to current field */ #if defined(NO-CLIENT-LONG-LONG) typedef unsigned long my-ulonglong ; #elif defined (--WIN--) typedef unsigned --int64 my-ulonglong ; #else typedef unsigned long long my-ulonglong ; #endif #define MYSQL-COUNT-ERROR (~(my-ulonglong) 0) typedef struct st-mysql-rows { struct st-mysql-rows *next ; /* list of rows */ MYSQL-ROW data ; } MYSQL-ROWS ; typedef MYSQL-ROWS *MYSQL-ROW-OFFSET ; /* offset to current row */ typedef struct st-mysql-data { my-ulonglong rows ; unsigned int fields ; MYSQL-ROWS *data ; MEM-ROOT alloc ; } MYSQL-DATA ; struct st-mysql-options { unsigned int connect-timeout,client-flag; my-bool compress,named-pipe ; unsigned int port ; char *host,*init-command,*user,*password,*unix-socket,*db ; char *my-cnf-file,*my-cnf-group, *charset-dir, *charset-name ; my-bool use-ssl ; /* if to use SSL or not */ char *ssl-key ; /* PEM key file */ char *ssl-cert ; /* PEM cert file */ char *ssl-ca ; /* PEM CA file */ char *ssl-capath ; /* PEM directory of CA-s? */ } ; enum mysql-option { MYSQL-OPT-CONNECT-TIMEOUT, MYSQL-OPT-COMPRESS, MYSQL-OPT-NAMED-PIPE, MYSQL-INIT-COMMAND, MYSQL-READ-DEFAULT-FILE, MYSQL-READ-DEFAULT-GROUP, MYSQL-SET-CHARSET-DIR, MYSQL-SET-CHARSET-NAME, MYSQL-OPT-LOCAL-INFILE} ; enum mysql-status { MYSQL-STATUS-READY,MYSQL-STATUS-GET-RESULT, MYSQL-STATUS-USE-RESULT} ; typedef struct st-mysql { NET net ; /* Communication parameters */ gptr connector-fd ; /* ConnectorFd for SSL */ char *host,*user,*passwd,*unix-socket,*server-version,*host-info, *info,*db ; unsigned int port,client-flag,server-capabilities ; unsigned int protocol-version ; unsigned int field-count ; unsigned int server-status ; unsigned long thread-id ; /* Id for connection in server */ my-ulonglong affected-rows ; my-ulonglong insert-id ; /* id if insert on table with NEXTNR */ my-ulonglong extra-info ; /* Used by mysqlshow */ unsigned long packet-length ; enum mysql-status status ; MYSQL-FIELD *fields ; MEM-ROOT field-alloc ; my-bool free-me ; /* If free in mysql-close */ my-bool reconnect ; /* set to 1 if automatic reconnect */ struct st-mysql-options options ; char scramble-buff[9] ; struct charset-info-st *charset ; unsigned int server-language ; } MYSQL ; typedef struct st-mysql-res { my-ulonglong row-count ; unsigned int field-count, current-field ; MYSQL-FIELD *fields ; MYSQL-DATA *data ; MYSQL-ROWS *data-cursor ; MEM-ROOT field-alloc ; MYSQL-ROW row ; /* If unbuffered read */ MYSQL-ROW current-row ; /* buffer to current row */ unsigned long *lengths ; /* column lengths of current row */ MYSQL *handle ; /* for unbuffered reads */ my-bool eof ; /* Used my mysql-fetch-row */ } MYSQL-RES ; /* Functions to get information from the MYSQL and MYSQL-RES structures */ /* Should definitely be used if one uses shared libraries */ my-ulonglong STDCALL mysql-num-rows(MYSQL-RES *res) ; unsigned int STDCALL mysql-num-fields(MYSQL-RES *res) ; my-bool STDCALL mysql-eof(MYSQL-RES *res) ; MYSQL-FIELD *STDCALL mysql-fetch-field-direct(MYSQL-RES *res, unsigned int fieldnr) ; MYSQL-FIELD * STDCALL mysql-fetch-fields(MYSQL-RES *res) ; MYSQL-ROWS * STDCALL mysql-row-tell(MYSQL-RES *res) ; unsigned int STDCALL mysql-field-tell(MYSQL-RES *res) ; unsigned int STDCALL mysql-field-count(MYSQL *mysql) ; my-ulonglong STDCALL mysql-affected-rows(MYSQL *mysql) ; my-ulonglong STDCALL mysql-insert-id(MYSQL *mysql) ; unsigned int STDCALL mysql-errno(MYSQL *mysql) ; char * STDCALL mysql-error(MYSQL *mysql) ; char * STDCALL mysql-info(MYSQL *mysql) ; unsigned long STDCALL mysql-thread-id(MYSQL *mysql) ; const char * STDCALL mysql-character-set-name(MYSQL *mysql) ; MYSQL * STDCALL mysql-init(MYSQL *mysql) ; #ifdef HAVE-OPENSSL int STDCALL mysql-ssl-set(MYSQL *mysql, const char *key, const char *cert, const char *ca, const char *capath) ; char * STDCALL mysql-ssl-cipher(MYSQL *mysql) ; int STDCALL mysql-ssl-clear(MYSQL *mysql) ; #endif /* HAVE-OPENSSL */ MYSQL * STDCALL mysql-connect(MYSQL *mysql, const char *host, const char *user, const char *passwd) ; my-bool STDCALL mysql-change-user(MYSQL *mysql, const char *user, const char *passwd, const char *db) ; #if MYSQL-VERSION-ID >= 32200 MYSQL * STDCALL mysql-real-connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix-socket, unsigned int clientflag) ; #else MYSQL * STDCALL mysql-real-connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, unsigned int port, const char *unix-socket, unsigned int clientflag) ; #endif void STDCALL mysql-close(MYSQL *sock) ; int STDCALL mysql-select-db(MYSQL *mysql, const char *db) ; int STDCALL mysql-query(MYSQL *mysql, const char *q) ; int STDCALL mysql-send-query(MYSQL *mysql, const char *q, unsigned int length) ; int STDCALL mysql-read-query-result(MYSQL *mysql) ; int STDCALL mysql-real-query(MYSQL *mysql, const char *q, unsigned int length) ; int STDCALL mysql-create-db(MYSQL *mysql, const char *DB) ; int STDCALL mysql-drop-db(MYSQL *mysql, const char *DB) ; int STDCALL mysql-shutdown(MYSQL *mysql) ; int STDCALL mysql-dump-debug-info(MYSQL *mysql) ; int STDCALL mysql-refresh(MYSQL *mysql, unsigned int refresh-options) ; int STDCALL mysql-kill(MYSQL *mysql,unsigned long pid) ; int STDCALL mysql-ping(MYSQL *mysql) ; char * STDCALL mysql-stat(MYSQL *mysql) ; char * STDCALL mysql-get-server-info(MYSQL *mysql) ; char * STDCALL mysql-get-client-info(void) ; char * STDCALL mysql-get-host-info(MYSQL *mysql) ; unsigned int STDCALL mysql-get-proto-info(MYSQL *mysql) ; MYSQL-RES * STDCALL mysql-list-dbs(MYSQL *mysql,const char *wild) ; MYSQL-RES * STDCALL mysql-list-tables(MYSQL *mysql,const char *wild) ; MYSQL-RES * STDCALL mysql-list-fields(MYSQL *mysql, const char *table, const char *wild) ; MYSQL-RES * STDCALL mysql-list-processes(MYSQL *mysql) ; MYSQL-RES * STDCALL mysql-store-result(MYSQL *mysql) ; MYSQL-RES * STDCALL mysql-use-result(MYSQL *mysql) ; int STDCALL mysql-options(MYSQL *mysql,enum mysql-option option, const char *arg) ; void STDCALL mysql-free-result(MYSQL-RES *result) ; void STDCALL mysql-data-seek(MYSQL-RES *result, my-ulonglong offset) ; MYSQL-ROW-OFFSET STDCALL mysql-row-seek(MYSQL-RES *result, MYSQL-ROW-OFFSET) ; MYSQL-FIELD-OFFSET STDCALL mysql-field-seek(MYSQL-RES *result, MYSQL-FIELD-OFFSET offset) ; MYSQL-ROW STDCALL mysql-fetch-row(MYSQL-RES *result) ; unsigned long * STDCALL mysql-fetch-lengths(MYSQL-RES *result) ; MYSQL-FIELD * STDCALL mysql-fetch-field(MYSQL-RES *result) ; unsigned long STDCALL mysql-escape-string(char *to,const char *from, unsigned long from-length) ; unsigned long STDCALL mysql-real-escape-string(MYSQL *mysql, char *to,const char *from, unsigned long length) ; void STDCALL mysql-debug(const char *debug) ; char * STDCALL mysql-odbc-escape-string(MYSQL *mysql, char *to, unsigned long to-length, const char *from, unsigned long from-length, void *param, char * (*extend-buffer) (void *, char *to, unsigned long *length)) ; void STDCALL myodbc-remove-escape(MYSQL *mysql,char *name) ; unsigned int STDCALL mysql-thread-safe(void) ; #define mysql-reload(mysql) mysql-refresh((mysql),REFRESH-GRANT) |# ;;;; THE END ;;;;
24,548
Common Lisp
.lisp
500
43.714
175
0.589202
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5313c7ecd7139bb208a6288f0e868f6442d9bd71e101cd33ea4f41a077527ba9
4,798
[ -1 ]
4,799
uffi-test.lisp
informatimago_lisp/clisp/uffi-test.lisp
;;;; -*- coding:utf-8 -*- (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ffi:def-call-out string-in (:name "uffi_test_string_in") (:arguments (value ffi:c-string)) (:return-type nil) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) (ffi:def-call-out string-out (:name "uffi_test_string_out") (:arguments (value ffi:c-pointer :in) (max-length ffi:uint32 :in)) (:return-type nil) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) (defun foreign-string-length (foreign-string) (do ((len 0 (1+ len))) ((= 0 (ffi:element (ffi:foreign-value foreign-string) len)) len))) ;;foreign-string-length (defun convert-from-foreign-string (foreign-string &key length (null-terminated-p t)) " DO: Builds a Lisp string from a foreign string. Can translate ASCII and binary strings. FOREIGN-STRING: A foreign string. LENGTH: The length of the foreign string to convert. The default is the length of the string until a NULL character is reached. NULL-TERMINATED-P: A boolean flag with a default value of T. When true, the string is converted until the first NULL character is reached. RETURN: A Lisp string. URL: <http://uffi.b9.com/manual/convert-from-foreign-string.html> URL: <http://clisp.sourceforge.net/impnotes.html#encoding> " (let ((byte-vector (make-array (list (if (or null-terminated-p (null length)) (foreign-string-length foreign-string) length)) :element-type '(unsigned-byte 8))) (foreign-type `(ffi:c-array ffi:uchar ,(list length)))) (dotimes (i (length byte-vector)) (setf (aref byte-vector i) (ffi:element (ffi:foreign-value foreign-string) i))) (ext:convert-string-from-bytes byte-vector custom:*foreign-encoding*) )) ;;CONVERT-FROM-FOREIGN-STRING (defun h-string-out (max-length) (ffi:with-foreign-object (result `(ffi:c-array ffi:uchar ,(1+ max-length))) (string-out result max-length) (convert-from-foreign-string result))) ;;h-string-out (ffi:def-call-out string-result (:name "uffi_test_string_result") (:return-type ffi:c-string) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ffi:def-call-out sint32-in (:name "uffi_test_sint32_in") (:arguments (value ffi:sint32)) (:return-type nil) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) (ffi:def-call-out sint32-out (:name "uffi_test_sint32_out") (:arguments (value (ffi:c-ptr ffi:sint32) :out)) (:return-type nil) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) (ffi:def-call-out sint32-result (:name "uffi_test_sint32_result") (:return-type ffi:sint32) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) uffi ffi-arg ffi-ret ==================== ============================ ============================ :sint32 ffi:sint32 ffi:sint32 (* :sint32) (ffi:c-ptr ffi:sint32) (ffi:c-ptr ffi:sint32) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ffi:def-c-struct record-t (character ffi:character) (number ffi:int) (single-float ffi:single-float) (small-string (ffi:c-array ffi:character 16)) (big-string ffi:c-string)) ;;(ffi:c-array-ptr ffi:character) --> (simple-vector size) (ffi:def-call-out record-in (:name "uffi_test_record_in") (:arguments (value (ffi:c-ptr record-t))) (:return-type nil) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) (ffi:def-call-out record-out (:name "uffi_test_record_out") (:arguments (value ffi:c-pointer)) (:return-type nil) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) (defun h-record-out () (ffi:with-foreign-object (result 'record-t) (record-out (ffi:foreign-address result)) (make-record-t :character (ffi:slot (ffi:foreign-value result) 'character) :number (ffi:slot (ffi:foreign-value result) 'number) :single-float (ffi:slot (ffi:foreign-value result) 'single-float) :small-string (ffi:slot (ffi:foreign-value result) 'small-string) :big-string (ffi:slot (ffi:foreign-value result) 'big-string)))) ;;h-record-out (ffi:def-call-out record-result (:name "uffi_test_record_result") (:return-type (ffi:c-ptr record-t)) (:language :stdc) (:library "/home/pascal/src/common/clisp/uffi-test.so")) ;;;; THE END ;;;;
5,018
Common Lisp
.lisp
115
38.147826
84
0.600411
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b2bf0cfe66dfd26cb4653f99f0fa69f2512eb7fa23041a4bd5ab8a82d2b89058
4,799
[ -1 ]
4,800
susv3-mc3.lisp
informatimago_lisp/clisp/susv3-mc3.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: susv3-mc3.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; An implementation of SUSV3-MC3 for clisp. ;;;; ;;;; Implemented: ;;;; mmap/munmap ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-11-29 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "FFI" "LINUX")) (eval-when (:compile-toplevel :load-toplevel :execute) (require "linux")) (defpackage "COM.INFORMATIMAGO.CLISP.SUSV3-MC3" (:use "COMMON-LISP" "COM.INFORMATIMAGO.CLISP.SUSV3") (:export "PROT-NONE" "PROT-READ" "PROT-WRITE" "PROT-EXEC" "MAP-SHARED" "MAP-PRIVATE" "MAP-FIXED" "MAP-FILE" "MAP-ANONYMOUS" "MAP-GROWSDOWN" "MAP-DENYWRITE" "MAP-EXECUTABLE" "MAP-LOCKED" "MAP-NORESERVE" "MAP-FAILED" "MMAP" "MUNMAP") (:documentation " An implementation of SUSV3-MC3 for clisp. Implemented: mmap/munmap Copyright Pascal J. Bourguignon 2004 - 2004 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. ")) (in-package "COM.INFORMATIMAGO.CLISP.SUSV3-MC3") (eval-when (:compile-toplevel :load-toplevel :execute) ;; TODO: Actually, we should include the features only if it's proven to exist on the current system. At run-time. (pushnew :susv3 *features*) (pushnew :susv3-mc3 *features*)) (ffi:default-foreign-library "libc.so.6") (defconstant prot-none 0 "Page can not be accessed.") (defconstant prot-read 1 "Page can be read.") (defconstant prot-write 2 "Page can be written.") (defconstant prot-exec 4 "Page can be executed.") (defconstant map-shared #x01 "Share changes. ") (defconstant map-private #x02 "Changes are private. ") (defconstant map-fixed #x10 "Interpret addr exactly. ") (defconstant map-file 0) (defconstant map-anonymous #x20 "Don't use a file. ") (defconstant map-growsdown #x0100 "Stack-like segment. ") (defconstant map-denywrite #x0800 "ETXTBSY") (defconstant map-executable #x1000 "Mark it as an executable. ") (defconstant map-locked #x2000 "Lock the mapping. ") (defconstant map-noreserve #x4000 "Don't check for reservations. ") (defconstant map-failed #xffffffff) ; -1 (ffi:def-c-type pointer ffi:ulong) (ffi:def-call-out mmap (:name "mmap") (:arguments (start pointer) (size ffi:size_t) (prot ffi:int) (flags ffi:int) (fd ffi:int) (offset linux:|off_t|)) (:return-type pointer) (:language :stdc)) (ffi:def-call-out munmap (:name "munmap") (:arguments (start pointer) (size ffi:size_t)) (:return-type pointer) (:language :stdc)) ;;;; THE END ;;;;
4,040
Common Lisp
.lisp
95
40.094737
116
0.658854
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
55eed343ed11063d646e1ca12c22682e2832844f95c45fa58aa5ff3d7791b656
4,800
[ -1 ]
4,801
iotask.lisp
informatimago_lisp/clisp/iotask.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: iotask.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Encapsulates clisp socket-status. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-08-31 <PJB> Created. ;;;;BUGS ;;;;TODO merge with pollio? ;;;; ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2005 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.IOTASK" (:documentation "This package exports a sheduler encapsulating clisp SOCKET:SOCKET-STATUS which itself encapsulate select(2)/poll(2). Copyright Pascal J. Bourguignon 2005 - 2005 This package is provided under the GNU General Public License. See the source file for details.") (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ECMA048" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST") (:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ECMA048" "ED") (:export "IOTASK" "IOTASK-ENQUEUE" "IOTASK-ENQUEUE-STREAM" "IOTASK-DEQUEUE" "IOTASK-POLL" "IOTASK-SCHEDULE" "MAKE-BUFFERED-DISCIPLINE" "MAKE-KEYBOARD-DISCIPLINE")) (in-package "COM.INFORMATIMAGO.CLISP.IOTASK") (defclass iotask () ((stream :accessor iotask-stream :initarg :stream) (process-event :accessor iotask-process-event :initarg :process-event) (name :accessor iotask-name :initarg :name) (stdin :accessor iotask-stdin :initarg :stdin :initform *standard-input*) (stdout :accessor iotask-stdout :initarg :stdout :initform *standard-output*) (stderr :accessor iotask-stderr :initarg :stderr :initform *error-output*) (query :accessor iotask-query :initarg :query :initform *query-io*) (alarm-time :accessor iotask-alarm-time :initarg :alarm-time :documentation "The next run-time an :alarm event should be posted. (in INTERNAL-TIME-UNITS-PER-SECOND units)") (alarm-period :accessor iotask-alarm-period :initarg :alarm-period :documentation "The period run-time an :alarm event should be posted. (in INTERNAL-TIME-UNITS-PER-SECOND units)"))) (defclass iotask-wait () ()) (defclass iotask-no-wait () ()) (defmethod initialize-instance ((task iotask) &rest args) (declare (ignore args)) (call-next-method) (handler-case (socket:socket-status (iotask-stream task) 0) (error () (change-class task 'iotask-no-wait)) (:no-error (s n) (declare (ignore s n)) (change-class task 'iotask-wait))) task) (defvar *iotasks* '() "List of IOTASK instances that are scheduled in the pool loop.") (defvar *iotask-wait* '() "Sublist of *iotask* which can be handled by socket:socket-wait.") (defvar *iotask-no-wait* '() "Sublist of *iotask* which cannot be handled by socket:socket-wait.") ;; INVARIANT: ;; (assert (null (intersection *iotask-wait* *iotask-no-wait*))) ;; (assert (set-equal *iotasks* (union *iotask-wait* *iotask-no-wait*))) (defun iotask-enqueue (task) (push task *iotasks*) (handler-case (socket:socket-status (iotask-stream task) 0) (error () (push task *iotask-no-wait*)) (:no-error (s n) (declare (ignore s n)) (push task *iotask-wait*)))) (defun iotask-enqueue-stream (stream process-event &key name alarm-time alarm-period) (iotask-enqueue (make-instance 'iotask :stream stream :stdin stream :stdout stream :stderr stream :query stream :process-event process-event :name name :alarm-time alarm-time :alarm-period alarm-period))) (defun iotask-dequeue (task) (setf *iotasks* (delete task *iotasks*)) (setf *iotask-wait* (delete task *iotask-wait*)) (setf *iotask-no-wait* (delete task *iotask-no-wait*))) (defun iotask-poll (&optional (timeout 0.0)) ;; TODO: implement the :alarm event. (map nil (lambda (task status) (when status (let ((*standard-input* (iotask-stdin task)) (*standard-output* (iotask-stdout task)) (*error-output* (iotask-stderr task)) (*query-io* (iotask-query task))) (funcall (iotask-process-event task) task status)))) *iotask-no-wait* (mapcar (lambda (task) (let ((stream (iotask-stream task))) (cond ((input-stream-p stream) (cond ((listen stream) :input) ((output-stream-p stream) :output) (t nil))) ((output-stream-p stream) :output) (t nil)))) *iotask-no-wait*)) (map nil (lambda (task status) (when status (let ((*standard-input* (iotask-stdin task)) (*standard-output* (iotask-stdout task)) (*error-output* (iotask-stderr task)) (*query-io* (iotask-query task))) (funcall (iotask-process-event task) task status)))) *iotask-wait* (socket:socket-status (mapcar (function iotask-stream) *iotask-wait*) timeout))) (defun iotask-schedule () (loop while *iotasks* do (iotask-poll 1.0))) (defun make-buffered-discipline (process-input) "process-input discipline to be used on buffered input streams." (lambda (task event) (when (member event '(:input :error)) (funcall process-input task (read-line (iotask-stream task)))))) (defun make-keyboard-discipline (process-input) "process-input discipline to be used on clisp *keyboard-input*: buffer up a line before forwarding to process-input." (let ((buffer (make-array '(128) :element-type 'character :fill-pointer 0 :adjustable t))) (lambda (task event) (when (eq :input event) (let* ((ich (read-char (iotask-stream task))) (ch (system::input-character-char ich))) (cond ((null ch)) ((= (char-code ch) com.informatimago.common-lisp.cesarum.ecma048:cr) (terpri) (finish-output) (funcall process-input task (subseq buffer 0 (fill-pointer buffer))) (setf (fill-pointer buffer) 0)) ((or (= (char-code ch) com.informatimago.common-lisp.cesarum.ecma048:bs) (= (char-code ch) com.informatimago.common-lisp.cesarum.ecma048::del)) (when (< 0 (fill-pointer buffer)) (princ (code-char com.informatimago.common-lisp.cesarum.ecma048:bs)) (princ " ") (princ (code-char com.informatimago.common-lisp.cesarum.ecma048:bs)) (finish-output) (decf (fill-pointer buffer)))) (t (princ ch) (finish-output) (vector-push ch buffer)))))))) ;;;; THE END ;;;;
8,393
Common Lisp
.lisp
181
38.165746
87
0.589521
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1008e0a60a803f16c8a153dc3fb6ae182d44e4c313703a3ecef417fcdc33b96b
4,801
[ -1 ]
4,802
objc.lisp
informatimago_lisp/clisp/objc.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: objc.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;NOWEB: T ;;;;DESCRIPTION ;;;; ;;;; An objc API FFI interface. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2003-05-30 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.OBJC" (:documentation "This module exports a reader macro for Objective-C messaging.") (:use "COMMON-LISP") (:export )) ;; [object met:arg hod:arg:arg:arg] ;; start ::= objc-expression . ;; objc-expression ::= '[' message { '.' message } ['.'] ']' ;; lisp-expression ::= '(' sexp {sexp} ')' . ;; message ::= object method-and-arg . ;; method-and-arg ::= named-method-part argument { method-part argument } . ;; named-method-part ::= name-':' . ;; method-part ::= named-method-part | ':' . ;; argument ::= expression . ;; object ::= expression . ;; expression ::= simple | lisp-expression | objc-expresison . ;; simple ::= identifier . ;; identifier ::= objc-symbol | lisp-symbol ;; | '|'-package-(':'|'::')-symbol-'|' . ;;; /* Basic data types for Objective C. ;;; Copyright (C) 1993, 1995, 1996 Free Software Foundation, Inc. ;;; ;;; This file is part of GNU CC. ;;; ;;; GNU CC 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. ;;; ;;; GNU CC 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 GNU CC; see the file COPYING. If not, write to ;;; the Free Software Foundation, 59 Temple Place - Suite 330, ;;; Boston, MA 02111-1307, USA. */ ;;; ;;; /* As a special exception, if you link this library with files ;;; compiled with GCC to produce an executable, this does not cause ;;; the resulting executable to be covered by the GNU General Public License. ;;; This exception does not however invalidate any other reasons why ;;; the executable file might be covered by the GNU General Public License. */ ;;; ;;; #ifndef __objc_INCLUDE_GNU ;;; #define __objc_INCLUDE_GNU ;;; ;;; #ifdef __cplusplus ;;; extern "C" { ;;; #endif ;;; ;;; #include <stddef.h> ;;; ;;; /* ;;; ** Definition of the boolean type. ;;; */ ;;; #ifdef __vxworks ;;; typedef int BOOL; ;;; #else ;;; typedef unsigned char BOOL; ;;; #endif ;;; #define YES (BOOL)1 ;;; #define NO (BOOL)0 ;;; ;;; /* ;;; ** Definition of a selector. Selectors themselves are not unique, but ;;; ** the sel_id is a unique identifier. ;;; */ ;;; typedef const struct objc_selector ;;; { ;;; void *sel_id; ;;; const char *sel_types; ;;; } *SEL; ;;; ;;; inline static BOOL ;;; sel_eq (SEL s1, SEL s2) ;;; { ;;; if (s1 == 0 || s2 == 0) ;;; return s1 == s2; ;;; else ;;; return s1->sel_id == s2->sel_id; ;;; } ;;; ;;; ;;; /* ;;; ** ObjC uses this typedef for untyped instances. ;;; */ ;;; typedef struct objc_object { ;;; struct objc_class* class_pointer; ;;; } *id; ;;; ;;; /* ;;; ** Definition of method type. When retrieving the implementation of a ;;; ** method, this is type of the pointer returned ;;; */ ;;; typedef id (*IMP)(id, SEL, ...); ;;; ;;; /* ;;; ** More simple types... ;;; */ ;;; #define nil (id)0 /* id of Nil instance */ ;;; #define Nil (Class)0 /* id of Nil class */ ;;; typedef char *STR; /* String alias */ ;;; ;;; /* ;;; ** The compiler generates one of these structures for each class. ;;; ** ;;; ** This structure is the definition for classes. ;;; ** ;;; ** This structure is generated by the compiler in the executable and used by ;;; ** the run-time during normal messaging operations. Therefore some members ;;; ** change type. The compiler generates "char* const" and places a string in ;;; ** the following member variables: super_class. ;;; */ ;;; typedef struct objc_class *MetaClass; ;;; typedef struct objc_class *Class; ;;; struct objc_class { ;;; MetaClass class_pointer; /* Pointer to the class's ;;; meta class. */ ;;; struct objc_class* super_class; /* Pointer to the super ;;; class. NULL for class ;;; Object. */ ;;; const char* name; /* Name of the class. */ ;;; long version; /* Unknown. */ ;;; unsigned long info; /* Bit mask. See class masks ;;; defined above. */ ;;; long instance_size; /* Size in bytes of the class. ;;; The sum of the class ;;; definition and all super ;;; class definitions. */ ;;; struct objc_ivar_list* ivars; /* Pointer to a structure that ;;; describes the instance ;;; variables in the class ;;; definition. NULL indicates ;;; no instance variables. Does ;;; not include super class ;;; variables. */ ;;; struct objc_method_list* methods; /* Linked list of instance ;;; methods defined for the ;;; class. */ ;;; struct sarray * dtable; /* Pointer to instance ;;; method dispatch table. */ ;;; struct objc_class* subclass_list; /* Subclasses */ ;;; struct objc_class* sibling_class; ;;; ;;; struct objc_protocol_list *protocols; /* Protocols conformed to */ ;;; void* gc_object_type; ;;; }; ;;; ;;; #ifndef __OBJC__ ;;; typedef struct objc_protocol { ;;; struct objc_class* class_pointer; ;;; char *protocol_name; ;;; struct objc_protocol_list *protocol_list; ;;; struct objc_method_description_list *instance_methods, *class_methods; ;;; } Protocol; ;;; ;;; #else /* __OBJC__ */ ;;; @class Protocol; ;;; #endif ;;; ;;; typedef void* retval_t; /* return value */ ;;; typedef void(*apply_t)(void); /* function pointer */ ;;; typedef union { ;;; char *arg_ptr; ;;; char arg_regs[sizeof (char*)]; ;;; } *arglist_t; /* argument frame */ ;;; ;;; ;;; IMP objc_msg_lookup(id receiver, SEL op); ;;; ;;; #ifdef __cplusplus ;;; } ;;; #endif ;;; ;;; #endif /* not __objc_INCLUDE_GNU */ ;;;; THE END ;;;;
8,180
Common Lisp
.lisp
215
36.944186
83
0.549956
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
22db110dce71b6ffd6aaec6cee55ba3e372c0235ec15620394d4b6fb9c9c3bf2
4,802
[ -1 ]
4,803
uffi-bsd.lisp
informatimago_lisp/clisp/uffi-bsd.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: uffi.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: clisp ;;;;USER-INTERFACE: NONE ;;;;NOWEB: T ;;;;DESCRIPTION ;;;; ;;;; This API is obsolete. See: CFFI ;;;; ;;;; This is a UFFI layer over the clisp native FFI. ;;;; ;;;; ;;;; Programs running on CLISP may set CUSTOM:*FOREING-ENCODING* ;;;; and this will be honored in the conversion of strings between ;;;; Lisp and C by the underlying FFI. ;;;; ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;; <KMR> Kevin M. Rosenberg ;;;;MODIFICATIONS ;;;; 2004-07-29 <PJB> Implemented LOAD-FOREIGN-LIBRARY, FIND-FOREIGN-LIBRARY. ;;;; 2003-06-03 <PJB> Created. ;;;; Some code taken from Kevin M. Rosenberg's UFFI 1.2.15. ;;;;BUGS ;;;; Not tested yet. ;;;; ;;;; FIND-FOREIGN-LIBRARY can't do its work portably for the ill definition ;;;; of COMMON-LISP:DIRECTORY. Only a unix implementation is provided. ;;;; ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.UFFI" (:nicknames "UFFI") (:documentation " This package implements over clisp native FFI the UFFI API as defined in 'UFFI Reference Guide' by Kevin M. Rosenberg, Heart Hospital of New Mexico. The version of the UFFI implemented here is uffi-1.2.15. URL: <http://uffi.b9.com/manual/book1.html> URL: <http://uffi.b9.com/> LEGAL: Copyright Pascal J. Bourguignon 2003 - 2004 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ") (:use "COMMON-LISP") ;; actually: FROM COMMON-LISP IMPORT ALL; ;; really: USE FFI,CUSTOM,EXT; (:export ;; immediate types "DEF-TYPE" "DEF-CONSTANT" ;; Don't use it! "DEF-FOREIGN-TYPE" "NULL-CHAR-P" ;; aggregate types "DEF-ENUM" "DEF-STRUCT" "GET-SLOT-VALUE" "GET-SLOT-POINTER" "DEF-ARRAY-POINTER" "DEREF-ARRAY" "DEF-UNION" ;; objects "ALLOCATE-FOREIGN-OBJECT" "FREE-FOREIGN-OBJECT" "WITH-FOREIGN-OBJECT" "WITH-FOREIGN-OBJECTS" "SIZE-OF-FOREIGN-TYPE" "POINTER-ADDRESS" "DEREF-POINTER" "ENSURE-CHAR-CHARACTER" "ENSURE-CHAR-INTEGER" "NULL-POINTER-P" "MAKE-NULL-POINTER" "+NULL-CSTRING-POINTER"+ "CHAR-ARRAY-TO-POINTER" ;; string functions "CONVERT-FROM-CSTRING" "CONVERT-TO-CSTRING" "FREE-CSTRING" "WITH-CSTRING" "WITH-CSTRINGS" "CONVERT-FROM-FOREIGN-STRING" "CONVERT-TO-FOREIGN-STRING" "ALLOCATE-FOREIGN-STRING" "WITH-FOREIGN-STRING" ;; function call "DEF-FUNCTION" ;; Libraries "FIND-FOREIGN-LIBRARY" "LOAD-FOREIGN-LIBRARY" "DEFAULT-FOREIGN-LIBRARY-TYPE" ;; OS "RUN-SHELL-COMMAND" ;; This is not used anywhere by UFFI: what's the use? ;; Don't use it: if you need such a function, use a POSIX or an OS API, ;; not a UFFI. )) ;;COM.INFORMATIMAGO.CLISP.UFFI (in-package "COM.INFORMATIMAGO.CLISP.UFFI") (provide :uffi) ;; Some client code use REQUIRE! Can you imagine that? ;; In general functions defined with UFFI (DEF-FUNCTION) do not convert ;; between Lisp objects and C objects. This is to be done by the client ;; code. ;; FFI provides for specification of the external language, with :C (K&C), ;; :STDC (ANSI C) or :STDC-STDCALL (ANSI C with stdcall). ;; UFFI does not. ;; UFFI does not allow the definition of a C variable (extern). ;; FFI does, with def-c-var. ;; However, we could play C tricks to get a UFFI pointer to a C variable. ;; (Is there any other such variable than errno?) ;; In FFI, c-type as defined with def-c-type are symbols used as key in ;; an internal hash table where c-type objects are stored. ;; (uffi:def-type the-struct-type-def the-struct-type) ;; (let ((a-foreign-struct (allocate-foreign-object 'the-struct-type))) ;; (declare 'the-struct-type-def a-foreign-struct) ;; (get-slot-value a-foreign-struct 'the-struct-type 'field-name)) ;; There's no UFFI type to specify function types. ;; UFFI:DEF-FUNCTION corresponds to FFI:DEF-CALL-OUT ;; There's none corresponding to FFI:DEF-CALL-IN ;; UFFI has only :IN arguments. ;; FFI has also :INOUT and :OUT arguments. ;; We'll use :ALLOCATION :NONE and :IN arguments, and manage our own buffers. ;; FFI: ;; Passing FFI:C-STRUCT, FFI:C-UNION, FFI:C-ARRAY, FFI:C-ARRAY-MAX values ;; as arguments (not via pointers) is only possible to the extent the C ;; compiler supports it. Most C compilers do it right, but some C ;; compilers (such as gcc on hppa) have problems with this. ;; UFFI: The values must be converted between Lisp types and C types by the ;; client code. ;; FFI: The values are converted automatically between Lisp and C, depending ;; on the FFI-C-TYPE-TO-CL-TYPE table and specifications of C types. ;; ;; Therefore: UFFI :CSTRING are implemented as CL:STRING ;; UFFI :CENUM are implemented as CL:INTEGER ;; UFFI :CSTRUCT are implemented as CL:DEFSTRUCT ;; UFFI :CARRAY are implemented as CL:ARRAY ? ;; (* TYPE) ;; (ENUM (FIELD VALUE)...) ;; (STRUCT (FIELD TYPE)...) ;; (UNION (FIELD TYPE)...) ;; (* (ARRAY TYPE)) ;; :struct-pointer ;; :pointer-self ;; ;; immediate types ;; "DEF-TYPE" --> LISP DEFTYPE WITH CONVERSION TO :CL ;; ;; "DEF-FOREIGN-TYPE" --> C typedef type name; ;; --> DEF-C-TYPE ;; ;; "NULL-CHAR-P" ;; ;; ;; aggregate types ;; "DEF-ENUM" --> C typedef enum {...} name; ;; --> DEF-C-ENUM DEFTYPE ;; ;; "DEF-STRUCT" --> C typedef struct name {...} name; ;; --> DEF-C-STRUCT ;; ;; "GET-SLOT-VALUE" ;; "GET-SLOT-POINTER" ;; "DEF-ARRAY-POINTER" --> C typedef type* name; ;; --> DEF-C-TYPE ;; ;; "DEREF-ARRAY" ;; ;; "DEF-UNION" --> C typedef union {...} name; ;; --> DEF-C-TYPE ;; ;; ;; ;; objects ;; "ALLOCATE-FOREIGN-OBJECT" ;; "FREE-FOREIGN-OBJECT" ;; "WITH-FOREIGN-OBJECT" --> FFI:WITH-FOREIGN-OBJECT ;; "WITH-FOREIGN-OBJECTS" ;; "SIZE-OF-FOREIGN-TYPE" ;; "POINTER-ADDRESS" ;; "DEREF-POINTER" ;; "ENSURE-CHAR-CHARACTER" ;; "ENSURE-CHAR-INTEGER" ;; "NULL-POINTER-P" ;; "MAKE-NULL-POINTER" ;; "+NULL-CSTRING-POINTER"+ ;; "CHAR-ARRAY-TO-POINTER" ;; ;; ;; string functions ;; "CONVERT-FROM-CSTRING" ;; "CONVERT-TO-CSTRING" ;; "FREE-CSTRING" ;; "WITH-CSTRING" ;; "WITH-CSTRINGS" ;; "CONVERT-FROM-FOREIGN-STRING" ;; "CONVERT-TO-FOREIGN-STRING" --> (FFI:C-ARRAY-MAX FFI:UCHAR SIZE) ;; "ALLOCATE-FOREIGN-STRING" --> (FFI:C-ARRAY-MAX FFI:UCHAR SIZE) ;; OR --> (FFI:C-ARRAY-MAX FFI:CHAR SIZE) ;; "WITH-FOREIGN-STRING" --> FFI:WITH-FOREIGN-OBJECT ;; Because of (:struct name) and (:struct-pointer name) we must keep ;; a separate list of structure names (even if def-struct creates both ;; a typedef and a struct). ;; ;; Because of :pointer-self, when we convert a struct, we must keep the ;; current structure name at hand. ;; ;; We should check that a structure does not contain a (:struct self) ;; if not encapsulated into a (* ). ;;; FFI-C-TYPE-TO-CL-TYPE ;;; (BOOLEAN . BOOLEAN) ;;; (CHARACTER . CHARACTER) ;;; (FFI:SHORT . INTEGER) ;;; (FFI:USHORT . INTEGER) ;;; (FFI:INT . INTEGER) ;;; (FFI:UINT . INTEGER) ;;; (FFI:LONG . INTEGER) ;;; (FFI:ULONG . INTEGER) ;;; (SINGLE-FLOAT . SINGLE-FLOAT) ;;; (DOUBLE-FLOAT . DOUBLE-FLOAT) (defstruct (type-conv (:type list) (:conc-name nil)) uffi-type ffi-type cl-type) (defconstant +type-conversion-list+ '( ;; :UFFI :FFI :CL (:char ffi:character character) (:unsigned-char ffi:character character) (:byte ffi:sint8 (signed-byte 8)) (:unsigned-byte ffi:uint8 (unsigned-byte 9)) (:short ffi:sint16 (signed-byte 16)) (:unsigned-short ffi:uint16 (unsigned-byte 16)) (:int ffi:sint32 (signed-byte 32)) (:unsigned-int ffi:uint32 (unsigned-byte 32)) (:long ffi:sint32 (signed-byte 32)) (:unsigned-long ffi:uint32 (unsigned-byte 32)) (:float single-float single-float) (:double double-float double-float) (:cstring ffi:c-pointer string) (:pointer-void ffi:c-pointer t) (:void nil nil) ;;; ;;; (:ENUM FFI:INT INTEGER) ;;; ((:STRUCT name) FFI:C-STRUCT STRUCTURE) ;;; ((:STRUCT-POINTER name) (FFI:C-PTR-NULL FFI:C-STRUCT) STRUCTURE) ;;; ;; FOR LISP TYPE: WE BUILD A DEFSTRUCT ;;; (:UNION FFI:C-UNION UNION) ;;; ;; FOR LISP TYPE: FFI CONSIDER IT TO BE OF THE TYPE OF THE FIRST FIELD. ;;; ((:ARRAY TYPE) (FFI:C-ARRAY-PTR TYPE) (ARRAY :ELEMENT-TYPE TYPE)) ;;; ) "A LIST OF: (UFFI-TYPE FFI-TYPE CL-TYPE)" ) ;;+TYPE-CONVERSION-LIST+ (defvar +type-conversion-hash+ (let ((table (make-hash-table :size 23))) (dolist (record +type-conversion-list+) (setf (gethash (uffi-type record) table) record)) table) "A hash uffi-type --> (uffi-type ffi-type cl-type)." ) ;;+TYPE-CONVERSION-HASH+ (declaim (inline get-type-conversion-record)) (defun get-type-conversion-record (uffi-type) " PRIVATE RETURN: THE RECORD FROM +TYPE-CONVERSION-HASH+ CORRESPONDING TO UFFI-TYPE, OR NIL IF NONE EXISTS. " (gethash uffi-type +type-conversion-hash+) ) ;;GET-TYPE-CONVERSION-RECORD (defvar *foreign-types-hash* (make-hash-table :size 23) "A HASH TABLE OF THE NAMED FOREIGN TYPES: NAME --> UFFI-TYPE." ) ;;*FOREIGN-TYPES-HASH* (defvar *foreign-structs-hash* (make-hash-table :size 23) "A HASH TABLE OF THE NAMED FOREIGN STRUCTS: NAME --> UFFI-STRUCT-TYPE." ) ;;*FOREIGN-STRUCTS-HASH* ;;; PRIMITIVE-UFFI-TYPE ;;; :POINTER-SELF ;;; (:STRUCT-POINTER STRUCT-NAME) ;;; (:STRUCT STRUCT-NAME) ;;; (:STRUCT STRUCT-NAME (FNAME FTYPE)...) ;;; 'TYPE ;;; ;;; (:UNION UNION-NAME (FNAME FTYPE)...) ;;; (:ARRAY-PTR TYPE) ;;; (:ARRAY TYPE SIZE) (defun clean-uffi-type (uffi-type &optional current-struct) " PRIVATE DO: REPLACE :POINTER-SELF BY (* (:STRUCT CURRENT-STRUCT),) (:STRUCT-POINTER NAME) BY (* (:STRUCT NAME)), AND CHECK THAT A STRUCTURE EXISTS FOR (:STRUCT NAME). REPLACE (* :UNSIGNED-CHAR) and (* :CHAR) BY :CSTRING, SINCE IT SEEMS UFFI CLIENT CODE ERRONEOUSLY USE (* :UNSIGNED-CHAR) INSTEAD OF :CSTRING... RETURN: A CLEANED UFFI-TYPE. TODO: CHECK OF (STRUCT X (FIELD (STRUCT X))). " (if (atom uffi-type) (if (eq uffi-type :pointer-self) (if current-struct `(* (:struct ,current-struct)) (error "FOUND :POINTER-SELF OUT OF A STRUCTURE.")) uffi-type) (case (first uffi-type) (:struct-pointer (unless (= 2 (length uffi-type)) (error "INVALID UFFI TYPE: ~S." uffi-type)) `(* ,(clean-uffi-type (second uffi-type)))) (:struct (cond ((= 2 (length uffi-type)) (unless (gethash (second uffi-type) *foreign-structs-hash*) (error "UNKNOWN STRUCT TYPE: ~S." uffi-type)) uffi-type) ((< 2 (length uffi-type)) (let ((struct-name (second uffi-type))) (unless (symbolp struct-name) (error "EXPECTED A SYMBOL AS STRUCT NAME INSTEAD OF ~S." struct-name)) `(:struct ,struct-name ,@(mapcar (lambda (field) (let ((name (first field)) (type (second field))) (unless (= 2 (length field)) (error "INVALID STRUCT FIELD ~S." field)) (list name (clean-uffi-type type struct-name)))) (cddr uffi-type))))) (t (error "INVALID STRUCT TYPE: ~S." uffi-type)))) (common-lisp:quote (clean-uffi-type (second uffi-type) current-struct)) (:union (unless (< 2 (length uffi-type)) (error "MISSING FIELDS IN UNION TYPE ~S." uffi-type)) `(:union ,(second uffi-type) ,@(mapcar (lambda (field) (let ((name (first field)) (type (second field))) (unless (= 2 (length field)) (error "INVALID UNION FIELD ~S." field)) (list name (clean-uffi-type type current-struct)))) (cddr uffi-type)))) (:array-ptr (unless (= 2 (length uffi-type)) (error "INVALID ARRAY-PTR TYPE: ~S." uffi-type)) `(:array-ptr ,(clean-uffi-type (second uffi-type) current-struct))) (:array (unless (= 3 (length uffi-type)) (error "INVALID ARRAY TYPE: ~S." uffi-type)) (let ((size (third uffi-type))) (unless (and (integerp size) (< 0 size)) (error "INVALID ARRAY SIZE: ~S." size)) `(:array ,(clean-uffi-type (second uffi-type) current-struct) ,size))) (* (unless (= 2 (length uffi-type)) (error "INVALID POINTER TYPE: ~S." uffi-type)) `(* ,(clean-uffi-type (second uffi-type)))) ;;(if (member (second uffi-type) '(:unsigned-char :char)) ;;'FFI:C-POINTER (otherwise (error "INVALID TYPE: ~S." uffi-type)))) ) ;;CLEAN-UFFI-TYPE (defun convert-from-uffi-type (uffi-type context) " PRIVATE DO: Converts from a uffi type to an implementation specific type. UFFI-TYPE: A UFFI TYPE. CONTEXT: :FFI OR :CL RETURN: A FFI TYPE (C-TYPE), OR A COMMON-LISP TYPE, DEPENDING ON THE CONTEXT. " (unless (or (eq context :ffi) (eq context :cl)) (error "UNEXPECTED CONTEXT ~S, SHOULD BE EITHER :FFI OR :CL." context)) (if (atom uffi-type) (let ((record (get-type-conversion-record uffi-type))) (if record ;; primitive types (if (eq context :ffi) (ffi-type record) (cl-type record)) ;; named types (let ((type (gethash uffi-type *foreign-types-hash*))) (if type (convert-from-uffi-type type context) (error "UNKNOWN UFFI TYPE ~S." uffi-type))))) (let ((sub-type (first uffi-type))) (case sub-type (:struct (let ((name (second uffi-type)) (fields (mapcar (lambda (field) (let ((name (first field)) (type (second field))) (list name (convert-from-uffi-type type context)))) (cddr uffi-type)))) ;; TODO: SEE GENERATION OF (:STRUCT NAME) ;; VS. GENERATION OF: (:STRUCT NAME (FIELD TYPE)...) (if (null fields) (let ((type (gethash name *foreign-structs-hash*))) (if type (if (eq context :ffi) `(ffi:c-struct ,name) name) ;; (CONVERT-FROM-UFFI-TYPE TYPE CONTEXT) (error "UNKNOWN UFFI STRUCTURE ~S." name))) (if (eq context :ffi) `(ffi:c-struct ,name ,@fields) `(defstruct ,name ,@fields))))) (:union (if (eq context :ffi) `(:c-union ,@(mapcar (lambda (field) (let ((name (first field)) (type (second field))) (list name (convert-from-uffi-type type context)))) (cddr uffi-type))) `(convert-from-uffi-type (second (second uffi-type)) context))) (:array-ptr (let ((element-type (convert-from-uffi-type (second uffi-type) context))) (if (eq context :ffi) `(ffi:c-array-ptr ,element-type) `(array ,element-type *)))) (:array (let ((element-type (convert-from-uffi-type (second uffi-type) context)) (array-size (cddr uffi-type))) (if (eq context :ffi) `(ffi:c-array ,element-type ,array-size) `(array ,element-type (,array-size))))) (* (if (eq context :ffi) `(ffi:c-ptr ,(convert-from-uffi-type (second uffi-type) :ffi)) ;;'FFI:C-POINTER (error "I don't know what a ~S is in Lisp."))) (otherwise (error "INVALID TYPE ~S." uffi-type))))) ) ;;CONVERT-FROM-UFFI-TYPE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; I. Declarations ;; ;;;;;;;;;;;;;;;;;;;;; (defmacro def-type (name type) " DO: Defines a Common Lisp type based on a UFFI type. NAME: A symbol naming the type TYPE: A form that is evaluated that specifies the UFFI type. IMPLEMENTATION: For now, we generate `(DEFTYPE ,NAME T). URL: <http://uffi.b9.com/manual/def-type.html> URL: <http://www.lisp.org/HyperSpec/Body/mac_deftype.html> " (setf type (clean-uffi-type type)) `(deftype ,name t ,(convert-from-uffi-type type :cl))) ;;DEF-TYPE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; II. Primitive Types ;; ;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def-constant (name value &key (export nil)) " DO: This is a thin wrapper around defconstant. It evaluates at compile-time and optionally exports the symbol from the package. NAME: A symbol that will be bound to the value. VALUE: An evaluated form that is bound the the name. EXPORT: EXPORT <=> The name is exported from the current package. The default is NIL NOTE: I would not advise using this macro, since it does not allow to attach a documentation string! URL: <http://uffi.b9.com/manual/def-constant.html> URL: <http://www.lisp.org/HyperSpec/Body/mac_defconstant.html> URL: <http://www.lisp.org/HyperSpec/Body/fun_export.html> " `(eval-when (:compile-toplevel :load-toplevel :execute) (defconstant ,name ,value) ,(when export (list 'export `(quote ,name))) ',name) ) ;;DEF-CONSTANT (defmacro def-foreign-type (name type) " DO: Defines a new foreign type. NAME: A symbol naming the new foreign type. VALUE: A form that is not evaluated that defines the new foreign type. URL: <http://uffi.b9.com/manual/def-foreign-type.html> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let* ((name name) (uffi-type (clean-uffi-type type name)) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ',name *foreign-types-hash*) ',uffi-type) (ffi:def-c-type ,name ,ffi-type)))) ;;DEF-FOREIGN-TYPE (defmacro null-char-p (val) " DO: Tests if a character or integer is NULL. This abstracts the difference in implementations where some return a character and some return an integer when dereferencing a C character pointer. CHAR: A character or integer. RETURN: A boolean flag indicating if char is a NULL value. URL: <http://uffi.b9.com/manual/null-char-p.html> " `(let ((val ,val)) (if (characterp val) (zerop (char-code val)) (zerop val))) ) ;;NULL-CHAR-P (defun make-constant-name (enum-name separator-string constant-id) " PRIVATE DO: Builds an enum constant name. " (intern (with-standard-io-syntax (format nil "~A~A~A" enum-name separator-string constant-id)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; III. Aggregate Types ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro def-enum (name constants &key (separator-string "#")) " DO: Declares a C enumeration. It generates constants with integer values for the elements of the enumeration. The symbols for the these constant values are created by the concatenation of the enumeration name, separator-string, and field symbol. Also creates a foreign type with the name name of type :int. NAME: A symbol that names the enumeration. CONSTANTS: A list of enum constants definitions. Each definition can be a symbol or a list of two elements. Symbols get assigned a value of the current counter which starts at 0 and increments by 1 for each subsequent symbol. It the constants definition is a list, the first position is the symbol and the second position is the value to assign the the symbol. The current counter gets set to 1+ this value. SEPARATOR-STRING: A string that governs the creation of constants. The default is \"#\". IMPLEMENTATION: We generate both a DEF-C-TYPE for the NAME and a DEF-C-ENUM for the constants. URL: <http://uffi.b9.com/manual/def-enum.html> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-enum> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let ((c-constants (mapcar (lambda (constant) (cond ((symbolp constant) (list (make-constant-name name separator-string constant)) ) ((and (consp constant) (= 2 (length constant)) (integerp (cadr constant))) (list (make-constant-name name separator-string (car constant)) (cadr constant))) (t (error "INVALID ENUM CONSTANT SYNTAX: ~S." constant)))) constants))) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ,name *foreign-types-hash*) :int) (ffi:def-c-type ,name ,(convert-from-uffi-type :int :ffi)) (ffi:def-c-enum ,name ,@c-constants))) ) ;;DEF-ENUM (defmacro def-struct (name &rest fields) " DO: Declares a structure. A special type is available as a slot in the field. It is a pointer that points to an instance of the parent structure. It's type is :pointer-self. NAME: A symbol that names the structure. FIELDS: A variable number of field definitions. Each definition is a list consisting of a symbol naming the field followed by its foreign type. IMPLEMENTATION: Generates a DEF-C-STRUCT which defines both a foreign C type and a Common-Lisp STRUCTURE-CLASS. URL: <http://uffi.b9.com/manual/def-struct.html> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-struct> " (let* ((name name) (uffi-type (clean-uffi-type `(:struct ,name ,@fields) name)) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ',name *foreign-types-hash*) (setf (gethash ',name *foreign-structs-hash*) ',uffi-type)) (ffi:def-c-struct ,@(cdr ffi-type)))) ) ;;DEF-STRUCT ;; ,(CONVERT-FROM-UFFI-TYPE TYPE :CL) ;; (COM.INFORMATIMAGO.CLISP.UFFI::CLEAN-UFFI-TYPE '(* :unsigned-char) 'struct-name) ;; (setf name 'ldap-error fields '((e_code :int) (e_reason (* :unsigned-char)))) (defmacro get-slot-value (obj type field) " DO: Accesses a slot value from a structure. OBJ: A pointer to foreign structure. TYPE: A name of the foreign structure type. FIELD: A name of the desired field in foreign structure. RETURN: The value of the field in the structure. SEE ALSO: GET-SLOT-POINTER URL: <http://uffi.b9.com/manual/get-slot-value.html> URL: <http://clisp.sourceforge.net/impnotes.html#slot> " (when (and (listp type) (eq 'quote (car type))) (setf type (second type))) ;; TODO: CHECK CONVERT TYPE. `(ffi:slot (ffi:deref (ffi:cast (ffi:foreign-value ,obj) (* ,type))) ,field)) ;;GET-SLOT-VALUE (defmacro get-slot-pointer (obj type field) " DO: Accesses a slot value from a structure. OBJ: A pointer to foreign structure. TYPE: A name of the foreign structure type. FIELD: A name of the desired field in foreign structure. RETURN: The value of the field in the structure: A POINTER. NOTE: This is similar to GET-SLOT-VALUE. It is used when the value of a slot is a pointer type. SEE ALSO: GET-SLOT-VALUE URL: <http://uffi.b9.com/manual/get-slot-pointer.html> URL: <http://clisp.sourceforge.net/impnotes.html#slot> " ;; NO DIFFERENCE TO ACCESS POINTER FIELD THAN TO ACCESS VALUE FIELDS. `(get-slot-value ,obj ,type ,field) ) ;;GET-SLOT-POINTER (defmacro def-array-pointer (name type) " DO: Defines a type that is a pointer to an array of type. NAME: A name of the new foreign type. TYPE: The foreign type of the array elements. URL: <http://uffi.b9.com/manual/def-array-pointer.html> URL: <http://clisp.sourceforge.net/impnotes.html#c-array-ptr> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let* ((name name) (uffi-type (clean-uffi-type `(:array-ptr ,type))) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ,name *foreign-types-hash*) ,uffi-type) (ffi:def-c-type ,name ,ffi-type))) ) ;;DEF-ARRAY-POINTER (defmacro def-union (name &rest fields) " NAME: A name of the new union type. FIELDS: A list of fields of the union. DO: Defines a foreign union type. URL: <http://uffi.b9.com/manual/def-union.html> URL: <http://clisp.sourceforge.net/impnotes.html#c-union> URL: <http://clisp.sourceforge.net/impnotes.html#def-c-type> " (let* ((name name) (uffi-type (clean-uffi-type `(:union ,name ,@fields))) (ffi-type (convert-from-uffi-type uffi-type :ffi)) ) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ,name *foreign-types-hash*) ,uffi-type) (ffi:def-c-type ,name ,ffi-type))) ) ;;DEF-UNION ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; IV. Objects ;; ;;;;;;;;;;;;;;;;; (ffi:def-call-out malloc (:name "malloc") (:arguments (size ffi:uint32 :in)) (:return-type ffi:c-pointer) (:language :stdc)) (ffi:def-call-out free (:name "free") (:arguments (ptr ffi:c-pointer :in)) (:return-type nil) (:language :stdc)) (defmacro allocate-foreign-object (type &optional (size 1)) " DO: Allocates an instance of a foreign object. TYPE: The type of foreign object to allocate. This parameter is evaluated. SIZE: An optional size parameter that is evaluated. If specified, allocates and returns an array of type that is size members long. This parameter is evaluated. RETURN: A pointer to the foreign object. URL: <http://uffi.b9.com/manual/allocate-foreign-object.html> URL: IMPLEMENTATION: " ;; TODO: CHECK IF TYPE IS CONTANT AND THE.N CHECK AND CONVERT ;; IT AT COMPILE TIME. `(ffi:allocate-shallow (convert-from-uffi-type (clean-uffi-type ,type) :ffi) :count ,size)) ;;ALLOCATE-FOREIGN-OBJECT (defmacro free-foreign-object (ptr) " DO: Frees the memory used by the allocation of a foreign object. PTR: A pointer to the allocated foreign object to free. URL: <http://uffi.b9.com/manual/free-foreign-object.html> URL: IMPLEMENTATION: " `(ffi:foreign-free ,ptr) ) ;;FREE-FOREIGN-OBJECT (defmacro with-foreign-object ((var type) &body body) " DO: This function wraps the allocation, binding, and destruction of a foreign object. On CMUCL and Lispworks platforms the object is stack allocated for efficiency. Benchmarks show that AllegroCL performs much better with static allocation. VAR: The variable name to bind. TYPE: The type of foreign object to allocate. This parameter is evaluated. RETURN: The result of evaluating the body. URL: <http://uffi.b9.com/manual/with-foreign-object.html> URL: " `(let ((,var (allocate-foreign-object ,type))) (unwind-protect (progn ,@body) (free-foreign-object ,var))) ) ;;WITH-FOREIGN-OBJECT (defmacro size-of-foreign-type (type) " FTYPE: A foreign type specifier. This parameter is evaluated. RETURN: The number of data bytes used by a foreign object type. This does not include any Lisp storage overhead. URL: <http://uffi.b9.com/manual/size-of-foreign-type.html> URL: <http://clisp.sourceforge.net/impnotes.html#sizeof> " `(ffi:sizeof (convert-from-uffi-type (clean-uffi-type ,type) :ffi)) ) ;;SIZE-OF-FOREIGN-TYPE (defmacro pointer-address (ptr) " PTR: A pointer to a foreign object. RETURN: An integer representing the pointer's address. URL: <http://uffi.b9.com/manual/pointer-address.html> URL: <http://clisp.sourceforge.net/impnotes.html#c-var-addr> " `(let ((ptr ,ptr)) (declare (type 'ffi:foreign-address ptr)) (ffi::foreign-address-unsigned ptr)) ) ;;POINTER-ADDRESS (defmacro deref-pointer (ptr type) " PTR: A pointer to a foreign object. TYPE: A foreign type of the object being pointed to. RETURN: The value of the object where the pointer points. URL: <http://uffi.b9.com/manual/deref-pointer.html> URL: <http://clisp.sourceforge.net/impnotes.html#deref> NOTE: This is an accessor and can be used with SETF . " `(ffi:deref (ffi:cast (ffi:foreign-value ,ptr) (convert-from-uffi-type (clean-uffi-type (list '* ,type)) :ffi) )) ) ;;DEREF-POINTER (defmacro ensure-char-character (object) " DO: Ensures that an object obtained by dereferencing a :CHAR pointer is a character. OBJECT: Either a character or a integer specifying a character code. RETURN: A character. URL: <http://uffi.b9.com/manual/ensure-char-character.html> URL: " `(let ((object ,object)) (if (characterp object) object (code-char object))) ) ;;ENSURE-CHAR-CHARACTER (defmacro ensure-char-integer (object) " DO: Ensures that an object obtained by dereferencing a :CHAR pointer is an integer. OBJECT: Either a character or a integer specifying a character code. RETURN: An integer. URL: <http://uffi.b9.com/manual/ensure-char-integer.html> URL: " `(let ((object ,object)) (if (characterp object) (char-code object) object)) ) ;;ENSURE-CHAR-INTEGER (defmacro make-null-pointer (type) " DO: Creates a NULL pointer of a specified type. TYPE: A type of object to which the pointer refers. RETURN: The NULL pointer of type TYPE. URL: <http://uffi.b9.com/manual/make-null-pointer.html> URL: " (declare (ignore type)) (ffi::unsigned-foreign-address 0) ;; `(FFI:CAST (ffi:foreign-value (FFI::UNSIGNED-FOREIGN-ADDRESS 0)) ;; (CONVERT-FROM-UFFI-TYPE ;; (CLEAN-UFFI-TYPE (LIST '* ,TYPE)) :FFI)) ) ;;MAKE-NULL-POINTER (defmacro null-pointer-p (ptr) " DO: Tests if a pointer is has a NULL value. PTR: A foreign object pointer. RETURN: Whether ptr is NULL. URL: <http://uffi.b9.com/manual/null-pointer-p.html> URL: <http://clisp.sourceforge.net/impnotes.html#fa-null> " `(ffi:foreign-address-null ,ptr) ) ;;NULL-POINTER-P (defconstant +null-cstring-pointer+ (ffi::unsigned-foreign-address 0) ;;(FFI:CAST (ffi:foreign-value (FFI::UNSIGNED-FOREIGN-ADDRESS 0)) ;; (CONVERT-FROM-UFFI-TYPE (CLEAN-UFFI-TYPE :CSTRING) :FFI)) "A NULL cstring pointer. This can be used for testing if a cstring returned by a function is NULL. URL: <http://uffi.b9.com/manual/null-cstring-pointer.html> " ) ;;+NULL-CSTRING-POINTER+ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; V. Strings ;; ;;;;;;;;;;;;;;;; (defmacro convert-from-cstring (cstring) " CSTRING: A cstring. RETURN: A Lisp string. DO: Converts a Lisp string to a cstring. This is most often used when processing the results of a foreign function that returns a cstring. URL: <http://uffi.b9.com/manual/convert-from-cstring.html> " `,cstring ) ;;CONVERT-FROM-CSTRING (defmacro convert-to-cstring (string) " STRING: A Lisp string. RETURN: A cstring. DO: Converts a Lisp string to a cstring. The cstring should be freed with free-cstring. URL: <http://uffi.b9.com/manual/convert-to-cstring.html> " `,string ) ;;CONVERT-TO-CSTRING (defmacro free-cstring (cstring) " CSTRING: A cstring. DO: Frees any memory possibly allocated by convert-to-cstring. On some implementions, a cstring is just the Lisp string itself. " (declare (ignore cstring)) ;; NOP ) ;;FREE-CSTRING (defmacro with-cstring ((cstring string) &body body) " CSTRING: A symbol naming the cstring to be created. STRING: A Lisp string that will be translated to a cstring. BODY: The body of where the CSTRING will be bound. DO: Binds a symbol to a cstring created from conversion of a string. Automatically frees the cstring. URL: <http://uffi.b9.com/manual/with-cstring.html> " ;; `(let ((,cstring (convert-to-cstring ,string))) ;; (unwind-protect ;; (progn ,@body) ;; (free-cstring ,cstring))) `(let ((,cstring ,string)) ,@body) ) ;;WITH-CSTRING (defun foreign-string-length (foreign-string) (do ((len 0 (1+ len))) ((= 0 (ffi:element (ffi:foreign-value foreign-string) len)) len))) ;;foreign-string-length (defun convert-from-foreign-string (foreign-string &key length (null-terminated-p t)) " DO: Builds a Lisp string from a foreign string. Can translate ASCII and binary strings. FOREIGN-STRING: A foreign string. LENGTH: The length of the foreign string to convert. The default is the length of the string until a NULL character is reached. NULL-TERMINATED-P: A boolean flag with a default value of T. When true, the string is converted until the first NULL character is reached. RETURN: A Lisp string. URL: <http://uffi.b9.com/manual/convert-from-foreign-string.html> URL: <http://clisp.sourceforge.net/impnotes.html#encoding> " (let ((byte-vector (make-array (list (if (or null-terminated-p (null length)) (foreign-string-length foreign-string) length)) :element-type '(unsigned-byte 8))) (foreign-type `(ffi:c-array ffi:uchar ,(list length)))) (declare (ignore foreign-type)) ; TODO! (dotimes (i (length byte-vector)) (setf (aref byte-vector i) (ffi:element (ffi:foreign-value foreign-string) i))) (ext:convert-string-from-bytes byte-vector custom:*foreign-encoding*) )) ;;CONVERT-FROM-FOREIGN-STRING (defun convert-to-foreign-string (string) " STRING: A Lisp string. RETURN: A foreign string. DO: Converts a Lisp string to a foreign string. Memory should be freed with free-foreign-object. URL: <http://uffi.b9.com/manual/convert-to-foreign-string.html> " (let* ((byte-vector (ext:convert-string-to-bytes string custom:*foreign-encoding*)) (result (allocate-foreign-string (1+ (length byte-vector)))) (foreign-type `(ffi:c-array ffi:uchar ,(list (1+ (length byte-vector)))))) (declare (ignore foreign-type)) ; TODO! (dotimes (i (length byte-vector)) (setf (ffi:element (ffi:foreign-value result) i) (aref byte-vector i))) (setf (ffi:element (ffi:foreign-value result) (length byte-vector)) 0) result)) ;;CONVERT-TO-FOREIGN-STRING (defun allocate-foreign-string (size &key (unsigned t)) " SIZE: The size of the space to be allocated in bytes. UNSIGNED: A boolean flag with a default value of T. When true, marks the pointer as an :UNSIGNED-CHAR. RETURN: A foreign string which has undefined contents. DO: Allocates space for a foreign string. Memory should be freed with free-foreign-object. URL: <http://uffi.b9.com/manual/allocate-foreign-string.html> " (allocate-foreign-object (if unsigned ':unsigned-char ':char) size) ) ;;ALLOCATE-FOREIGN-STRING ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; VI. Functions & Libraries ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *modules-to-library-map* (make-hash-table :test (function equal)) "Maps module names to library paths.") (defmacro def-function (name args &key module returning) " DO: Declares a foreign function. NAME: A string or list specifying the function name. If it is a string, that names the foreign function. A Lisp name is created by translating #\_ to #\- and by converting to upper-case in case-insensitive Lisp implementations. If it is a list, the first item is a string specifying the foreign function name and the second it is a symbol stating the Lisp name. ARGS: A list of argument declarations. If NIL, indicates that the function does not take any arguments. MODULE: A string specifying which module (or library) that the foreign function resides. (Required by Lispworks) RETURNING: A declaration specifying the result type of the foreign function. :VOID indicates that this function does not return any value. URL: <http://uffi.b9.com/manual/def-function.html> NOTE: All Common-Lisp implementations are 'case-insensitive'. <http://www.lisp.org/HyperSpec/Body/sec_2-1-1-2.html> " (let (l-name c-name) (if (stringp name) (setq c-name name l-name (intern (string-upcase (substitute (character "-") (character "_") name)))) (setq c-name (first name) l-name (second name))) `(ffi:def-call-out ,l-name (:name ,c-name) ,@(when args `((:arguments ,@(mapcar (lambda (arg) `(,(first arg) ,(convert-from-uffi-type (clean-uffi-type (second arg)) :ffi) :in)) args)))) ,@(when returning `((:return-type ,(convert-from-uffi-type (clean-uffi-type returning) :ffi)))) ,@(when module (let ((library (gethash module *modules-to-library-map*))) `((:library ,(or library module))))) (:language :stdc)))) ;;DEF-FUNCTION (defun load-foreign-library (filename &key module supporting-libraries) " DO: Loads a foreign library. Applies a module name to functions within the library. Ensures that a library is only loaded once during a session. FILENAME: A string or pathname specifying the library location in the filesystem. At least one implementation (Lispworks) can not accept a logical pathname. MODULE: A string designating the name of the module to apply to functions in this library. (Required for Lispworks) SUPPORTING-LIBRARIES: A list of strings naming the libraries required to link the foreign library. (Required by CMUCL) RETURN: A boolean flag, T if the library was able to be loaded successfully or if the library has been previously loaded, otherwise NIL. URL: <http://uffi.b9.com/manual/load-foreign-library.html> IMPLEMENTATION: Loading the library is defered to the first function call. Here we just register the mapping between the MODULE and the FILENAME. TODO: Should we explicitely load the SUPPORTING-LIBRARIES too? " (declare (ignore supporting-libraries)) (when module (setf (gethash module *modules-to-library-map*) (namestring filename))) t) ;;LOAD-FOREIGN-LIBRARY (defun split-string (string &optional (separators " ")) " NOTE: current implementation only accepts as separators a string containing literal characters. " (unless (simple-string-p string) (setq string (copy-seq string))) (unless (simple-string-p separators) (setq separators (copy-seq separators))) (let ((chunks '()) (position 0) (nextpos 0) (strlen (length string)) ) (declare (type simple-string string separators)) (loop while (< position strlen) do (loop while (and (< nextpos strlen) (not (position (char string nextpos) separators))) do (setq nextpos (1+ nextpos)) ) ;;loop (push (subseq string position nextpos) chunks) (setq position (1+ nextpos)) (setq nextpos position) ) ;;loop (nreverse chunks) )) ;;SPLIT-STRING (defun find-foreign-library (names directories &key drive-letters types verbose) " NAMES: A string or list of strings containing the base name of the library file. DIRECTORIES: A string or list of strings containing the directory the library file. DRIVE-LETTERS: A string or list of strings containing the drive letters for the library file. TYPES: A string or list of strings containing the file type of the library file. Default is NIL. If NIL, will use a default type based on the currently running implementation. VERBOSE: This is an extension from the UFFI specification. Prints a line on *trace-output* for each path considered. RETURN: The path of the first found file, or NIL if the library file was not found. DO: Finds a foreign library by searching through a number of possible locations. URL: <http://uffi.b9.com/manual/find-foreign-library.html> IMPLEMENTATION: You'd better leave it up to the system to find the library! This implementation can't locate libc because on linux, there's no link named libc.so and this API doesn't allow for a version number (anyway, library versions such as in libc.so.6.0.1 have nothing to do with COMMON-LISP version that are actually file versions and mere integers). Some people believe the can pass with impunity strings containing dots as types. But that's not so. " (flet ((ensure-list (item) (if (listp item) item (list item)))) (setf names (ensure-list names)) (setf directories (ensure-list directories)) (setf drive-letters (ensure-list drive-letters)) (setf types (ensure-list types)) (setf names (mapcan (lambda (name) (if (or (<= (length name) 3) (string/= "lib" name :end2 3)) (list name (concatenate 'string "lib" name)) (list name))) names)) (setf types (or (delete-if (lambda (item) (not (every (function alphanumericp) item))) types) '("so"))) (setf drive-letters (or drive-letters '(nil))) (when verbose (format *trace-output* "Directories = ~S~%" directories) (format *trace-output* "Types = ~S~%" types) (format *trace-output* "Names = ~S~%" names) (format *trace-output* "Drive-letters = ~S~%" drive-letters)) (dolist (dir directories) (dolist (type types) (dolist (name names) (dolist (device drive-letters) (let ((path (make-pathname :device device :directory ((lambda (items) (if (char= (character "/") (char dir 0)) (cons :absolute (cdr items)) (cons :relative items))) (split-string dir "/")) :name name :type type))) (when verbose (format *trace-output* "; Considering ~S~%" path)) (when (probe-file path) (return-from find-foreign-library path)))))) nil))) ;;FIND-FOREIGN-LIBRARY ;; Local Variables: ;; eval: (cl-indent 'ffi:with-c-place 1) ;; End: ;;;; uffi.lisp -- -- ;;;;
50,761
Common Lisp
.lisp
1,124
37.704626
83
0.571125
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
850fe1091befbf75fe297953029118e81fd0e697cf099e726732060edb0ffd13
4,803
[ -1 ]
4,804
com.informatimago.clisp.test.asd
informatimago_lisp/clisp/com.informatimago.clisp.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.clisp.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.clisp.test system. ;;;; Tests the com.informatimago.clisp system. ;;;; ;;;;USAGE: ;;;; ;;;;AUTHORS: ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS: ;;;; 2015-02-23 <PJB> Created. ;;;;BUGS: ;;;; ;;;;LEGAL: ;;;; ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/> ;;;; ;;;;*************************************************************************** (in-package "COMMON-LISP-USER") #-clisp (asdf:defsystem "com.informatimago.clisp.test" ;; system attributes: :description "Dummy tests the com.informatimago.clisp system." :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.2.0" :properties ((#:author-email . "[email protected]") (#:date . "Winter 2015") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.clisp.test/") ((#:albert #:formats) "docbook") ((#:albert #:docbook #:template) . "book") ((#:albert #:docbook #:bgcolor) . "white") ((#:albert #:docbook #:textcolor) . "black")) #+asdf-unicode :encoding #+asdf-unicode :utf-8 :depends-on () :components () #+asdf3 :perform #+asdf3 (asdf:test-op (o s) (declare (ignore o s)))) #+clisp (asdf:defsystem "com.informatimago.clisp.test" ;; system attributes: :description "Tests the com.informatimago.clisp system." :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.2.0" :properties ((#:author-email . "[email protected]") (#:date . "Winter 2015") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.clisp.test/") ((#:albert #:formats) "docbook") ((#:albert #:docbook #:template) . "book") ((#:albert #:docbook #:bgcolor) . "white") ((#:albert #:docbook #:textcolor) . "black")) #+asdf-unicode :encoding #+asdf-unicode :utf-8 :depends-on ("com.informatimago.common-lisp.cesarum" "com.informatimago.clisp") :components ((:file "string-test" :depends-on ())) #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) (dolist (p '("COM.INFORMATIMAGO.CLISP.STRING.TEST")) (let ((*package* (find-package p))) (uiop:symbol-call p "TEST/ALL"))))) ;;;; THE END ;;;;
3,928
Common Lisp
.lisp
88
37.852273
93
0.553962
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c16c161d5e36c80d4e6c014fe98fc21fd30c8de555ffea9c481645ecb8cded78
4,804
[ -1 ]
4,805
clisp-ffi.txt
informatimago_lisp/clisp/clisp-ffi.txt
======================================================================== 30.3.  Extensions-2.3. The Foreign Function Call Facility Platform dependent: many UNIX, Win32 platforms only. 30.3.1. Overview 30.3.2. (Foreign) C types 30.3.3. The choice of the C flavor. 30.3.4. Foreign variables 30.3.5. Operations on foreign places 30.3.6. Foreign functions 30.3.7. Argument and result passing conventions 30.3.8. Parameter Mode 30.3.9. Examples A foreign function description is written as a Lisp file, and when compiled it produces a #P".c" file which is then compiled by the C compiler and may be linked together with lisp.a. All symbols relating to the foreign function interface are exported from the package "FFI".. To use them, (USE-PACKAGE "FFI"). Special "FFI". forms may appear anywhere in the Lisp file. 30.3.1.  Overview These are the special "FFI". forms. We have taken a pragmatic approach: the only foreign languages we support for now are C and ANSI C. special "FFI". forms; name is any Lisp SYMBOL; c-name is a STRING. (FFI:DEF-C-TYPE name c-type) This form makes name a shortcut for c-type. Note that c-type may already refer to name. Forward declarations of types are not possible, however. (FFI:DEF-C-VAR name {option}*) This form defines a FFI:FOREIGN-VARIABLE. name is the Lisp name, a regular Lisp SYMBOL. Options for FFI:DEF-C-VAR (:NAME c-name) specifies the name as seen from C, as a string. If not specified, it is derived from the print name of the Lisp name. (:TYPE c-type) specifies the variable's foreign type. (:READ-ONLY BOOLEAN) If this option is specified and non-NIL, it will be impossible to change the variable's value from within Lisp (using SETQ or similar). (:ALLOC ALLOCATION) This option can be either :NONE or :MALLOC-FREE and defaults to :NONE. If it is :MALLOC-FREE, any values of type FFI:C-STRING, FFI:C-PTR, FFI:C-PTR-NULL, FFI:C-ARRAY-PTR within the foreign value are assumed to be pointers to malloc-allocated storage, and when SETQ replaces an old value by a new one, the old storage is freed using free and the new storage allocated using malloc. If it is :NONE, SETQ assumes that the pointers point to good storage (not NULL!) and overwrites the old values by the new ones. This is dangerous (just think of overwriting a string with a longer one or storing some data in a NULL pointer...) and deprecated. (:LIBRARY STRING) Specifies the (optional) dynamic library which contains the variable. (FFI:DEF-CALL-OUT name {option}*) This form defines a named call-out function (a foreign function called from Lisp: control flow temporarily leaves Lisp). Options for FFI:DEF-CALL-OUT (:NAME c-name) Any Lisp function call to #'name is redirected to call the C function c-name. (:ARGUMENTS {(argument c-type [PARAM-MODE [ALLOCATION]])}*) (:RETURN-TYPE c-type [ALLOCATION]) Argument list and return value, see Section  30.3.7, "Argument and result passing conventions". and Section  30.3.8, "Parameter Mode".. (:LANGUAGE language) See Section  30.3.3, "The choice of the C flavor.".. (:BUILT-IN BOOLEAN) When the function is a C built-in, the full prototype will be output (unless suppressed by FFI:*OUTPUT-C-FUNCTIONS*). (:LIBRARY STRING) Specifies the (optional) dynamic library which contains the variable. (FFI:DEF-CALL-IN name {option}*) This form defines a named call-in function (i.e., a Lisp function called from the foreign language: control flow temporary enters Lisp) Options for FFI:DEF-CALL-IN (:NAME c-name) Any C function call to the C function c-name is redirected to call the Common Lisp function #'name. (:ARGUMENTS {(argument c-type [PARAM-MODE [ALLOCATION]])}*) (:RETURN-TYPE c-type [ALLOCATION]) Argument list and return value, see Section  30.3.7, "Argument and result passing conventions". and Section  30.3.8, "Parameter Mode".. (:LANGUAGE language) See Section  30.3.3, "The choice of the C flavor.".. (FFI:DEF-C-CALL-OUT name {option}*) This is equivalent to FFI:DEF-CALL-OUT with :LANGUAGE :STDC. deprecated. (FFI:DEF-C-CALL-IN name {option}*) This is equivalent to FFI:DEF-CALL-IN with :LANGUAGE :STDC. deprecated. (FFI:DEF-C-STRUCT name (symbol c-type)*) This form defines name to be both a STRUCTURE-CLASS and a foreign C type with the given slots. name is a SYMBOL (structure name) or a LIST whose FIRST element is the structure name and the REST is options. Two options are supported at this time: Options for FFI:DEF-C-STRUCT :TYPEDEF means that the name of this structure is a C type defined with typedef elsewhere. :EXTERNAL means that this structure is defined in a #P".c" file that you include with, e.g., (FFI:C-LINES "#include <filename.h>"). These options determine how the struct is written to the #P".c". (FFI:DEF-C-ENUM name {symbol | (symbol [value])}*) This form defines symbols as constants, similarly to the C declaration enum { symbol [= value], ... }; You can use (FFI:ENUM-FROM-VALUE name value) and (FFI:ENUM-TO-VALUE name symbol) to convert between the numeric and symbolic representations (of course, the latter function boils down to SYMBOL-VALUE plus a check that the symbol is indeed a constant defined in the FFI:DEF-C-ENUM name). (FFI:C-LINES format-string {argument}*) This form outputs the string (FORMAT NIL format-string {argument}*) to the C output file. This is a rarely needed low-level facility. (FFI:ELEMENT c-place index1 ... indexn) Array element: If c-place is of foreign type (FFI:C-ARRAY c-type (dim1 ... dimn)) and 0 â%ooeôôÌ index1 < dim1, ..., 0 â%ooeôôÌ indexn < dimn, this will be the place corresponding to (AREF c-place index1 ... indexn) or c-place[index1]...[indexn]. It is a place of type c-type. If c-place is of foreign type (FFI:C-ARRAY-MAX c-type dim) and 0 â%ooeôôÌ index < dim, this will be the place corresponding to (AREF c-place index) or c-place[index]. It is a place of type c-type. (FFI:DEREF c-place) Dereference pointer: If c-place is of foreign type (FFI:C-PTR c-type) or (FFI:C-PTR-NULL c-type), this will be the place the pointer points to. It is a place of type c-type. For (FFI:C-PTR-NULL c-type), the c-place may not be NULL. (FFI:SLOT c-place slot-name) Struct or union component: If c-place is of foreign type (FFI:C-STRUCT class ... (slot-name c-type) ...) or of type (FFI:C-UNION ... (slot-name c-type) ...), this will be of type c-type. (FFI:CAST c-place c-type) Type change: A place denoting the same memory locations as the original c-place, but of type c-type. (FFI:OFFSET c-place offset c-type) Type change and displacement: return a place denoting a memory locations displaced from the original c-place by an offset counted in bytes, with type c-type. This can be used to resize an array, e.g. of c-type (FFI:C-ARRAY uint16 n) via (FFI:OFFSET c-place 0 '(FFI:C-ARRAY uint16 k)). (FFI:C-VAR-ADDRESS c-place) Return the address of c-place as a Lisp object of type FFI:FOREIGN-ADDRESS. This is useful as an argument to foreign functions expecting a parameter of C type FFI:C-POINTER. (FFI:C-VAR-OBJECT c-place) Return the FFI:FOREIGN-VARIABLE object underlying the c-place. This is also an acceptable argument type to a FFI:C-POINTER declaration. (FFI:TYPEOF c-place) returns the c-type corresponding to the c-place. (FFI:SIZEOF c-type) (FFI:SIZEOF c-place) The first form returns the size and alignment of the C type c-type, measured in bytes. The second form returns the size and alignment of the C type of c-place, measured in bytes. (FFI:BITSIZEOF c-type) (FFI:BITSIZEOF c-place) The first form returns the size and alignment of the C type c-type, measured in bits. The second form returns the size and alignment of the C type of c-place, measured in bits. (FFI:FOREIGN-ADDRESS-NULL foreign-entity) This predicate returns T if the foreign-entity refers to the NULL address (and thus foreign-entity should probably not be passed to most foreign functions). (FFI:FOREIGN-ADDRESS-UNSIGNED foreign-entity) (FFI:UNSIGNED-FOREIGN-ADDRESS number) FFI:FOREIGN-ADDRESS-UNSIGNED returns the INTEGER address embodied in the Lisp object of type FFI:FOREIGN-ADDRESS, FFI:FOREIGN-POINTER, FFI:FOREIGN-VARIABLE or FFI:FOREIGN-FUNCTION. FFI:UNSIGNED-FOREIGN-ADDRESS returns a FFI:FOREIGN-ADDRESS object pointing to the given INTEGER address. (FFI:FOREIGN-ADDRESS foreign-entity) FFI:FOREIGN-ADDRESS is both a type name and a selector/constructor function. It is the Lisp object type corresponding to a FFI:C-POINTER external type declaration, e.g. a call-out function with (:RETURN-TYPE FFI:C-POINTER) yields a Lisp object of type FFI:FOREIGN-ADDRESS. The function extracts the object of type FFI:FOREIGN-ADDRESS living within any FFI:FOREIGN-VARIABLE or FFI:FOREIGN-FUNCTION object. If the foreign-entity already is a FFI:FOREIGN-ADDRESS, it returns it. If it is a FFI:FOREIGN-POINTER (e.g. a base foreign library address), it encapsulates it into a FFI:FOREIGN-ADDRESS object, as suitable for use with a FFI:C-POINTER external type declaration. It does not construct addresses out of NUMBERs, FFI:UNSIGNED-FOREIGN-ADDRESS must be used for that purpose. (FFI:VALIDP foreign-entity) (SETF (FFI:VALIDP foreign-entity) value) This predicate returns NIL if the foreign-entity (e.g. the Lisp equivalent of a FFI:C-POINTER) refers to a pointer which is invalid because it comes from a previous Lisp session. It returns T if foreign-entity can be used within the current Lisp process (thus it returns T for all non-foreign arguments). You can invalidate a foreign object using (SETF FFI:VALIDP). You cannot resurrect a zombie, nor can you kill a non-foreign object. (FFI:FOREIGN-POINTER foreign-entity) (SETF (FFI:FOREIGN-POINTER foreign-entity) foreign-pointer) FFI:FOREIGN-POINTER returns the FFI:FOREIGN-POINTER associated with the Lisp object of type FFI:FOREIGN-ADDRESS, FFI:FOREIGN-POINTER, FFI:FOREIGN-VARIABLE or FFI:FOREIGN-FUNCTION. (SETF FFI:FOREIGN-POINTER) changes the FFI:FOREIGN-POINTER associated with the Lisp object of type FFI:FOREIGN-ADDRESS, FFI:FOREIGN-VARIABLE or FFI:FOREIGN-FUNCTION to that of the other entity. When foreign-pointer is :COPY, a fresh FFI:FOREIGN-POINTER is allocated. foreign-entity still points to the same object. This is particularly useful with (SETF FFI:VALIDP). (FFI:WITH-FOREIGN-OBJECT (variable c-type [initarg]) body) (FFI:WITH-C-VAR (variable c-type [initarg]) body) These forms allocate space on the C execution stack, bind respectively a FFI:FOREIGN-VARIABLE object or a local SYMBOL-MACRO to variable and execute body. When initarg is not supplied, they allocate space only for (FFI:SIZEOF c-type) bytes. This space is filled with zeroes. E.g., using a c-type of FFI:C-STRING or even (FFI:C-PTR (FFI:C-ARRAY uint8 32)) (!) both allocate place for a single pointer, initialized to NULL. When initarg is supplied, they allocate space for an arbitrarily complex set of structures rooted in c-type. Therefore, FFI:C-ARRAY-MAX, #() and "" are your friends for creating a pointer to the empty arrays: (with-c-var (v '(c-ptr (c-array-max uint8 32)) #()) (setf (element (deref v) 0) 127) v) c-type is evaluated, making creation of variable sized buffers easy: (with-c-var (fv `(c-array uint8 ,(length my-vector)) my-vector) (print fv)) (FFI:WITH-FOREIGN-STRING (foreign-address char-count byte-count string &KEY encoding null-terminated-p start end) &BODY body) This forms converts a Lisp string according to the encoding, allocating space on the C execution stack. encoding can be any EXT:ENCODING, e.g. CHARSET:UTF-16 or CHARSET:UTF-8, circumventing the usual 1:1 limit imposed on CUSTOM:*FOREIGN-ENCODING*. body is then executed with the three variables foreign-address, char-count and byte-count respectively bound to an untyped FFI:FOREIGN-ADDRESS (as known from the FFI:C-POINTER foreign type specification) pointing to the stack location, the number of CHARACTERs of the Lisp string that were considered and the number of (UNSIGNED-BYTE 8) bytes that were allocated for it on the C stack. When null-terminated-p is true, which is the default, a variable number of zero bytes is appended, depending on the encoding, e.g. 2 for CHARSET:UTF-8, and accounted for in byte-count, and char-count is incremented by one. The FFI:FOREIGN-ADDRESS object bound to foreign-address is invalidated upon the exit from the form. A stupid example (a quite costly interface to mblen): (with-foreign-string (fv elems bytes string :encoding charset:jis... :null-terminated-p nil :end 5) (declare (ignore fv elems)) (format t "This string would take ~D bytes." bytes)) (FFI:PARSE-C-TYPE c-type) (FFI:DEPARSE-C-TYPE c-type-internal) Convert between the external (LIST) and internal (VECTOR) C type representations (used by DESCRIBE). (FFI:ALLOCATE-SHALLOW c-type &KEY :COUNT :READ-ONLY) (FFI:ALLOCATE-DEEP c-type contents &KEY :COUNT :READ-ONLY) (FFI:FOREIGN-FREE foreign-entity &KEY :FULL) (FFI:FOREIGN-ALLOCATE c-type-internal &KEY :INITIAL-CONTENTS :COUNT :READ-ONLY) Macro FFI:ALLOCATE-SHALLOW allocates (FFI:SIZEOF c-type) bytes on the C heap and zeroes them out (like calloc). When :COUNT is supplied, c-type is substituted with (FFI:C-ARRAY c-type count), except when c-type is CHARACTER, in which case (FFI:C-ARRAY-MAX CHARACTER count) is used instead. When :READ-ONLY is supplied, the Lisp side is prevented from modifying the memory contents. This can be used as an indication that some foreign side is going to fill this memory (e.g. via read). Returns a FFI:FOREIGN-VARIABLE object of the actual c-type, whose address part points to the newly allocated memory. FFI:ALLOCATE-DEEP will call C malloc as many times as necessary to build a structure on the C heap of the given c-type, initialized from the given contents. E.g., (FFI:ALLOCATE-DEEP 'FFI:C-STRING "ABCDE") performs 2 allocations: one for a C pointer to a string, another for the contents of that string. This would be useful in conjunction with a char** C type declaration. (FFI:ALLOCATE-SHALLOW 'FFI:C-STRING) allocates room for a single pointer (probably 4 bytes). (FFI:ALLOCATE-DEEP 'CHARACTER "ABCDEF" :count 10) allocates and initializes room for the type (FFI:C-ARRAY-MAX CHARACTER 10), corresponding to char* or, more specifically, char[10] in C. Function FFI:FOREIGN-FREE deallocates memory at the address held by the given foreign-entity. If :FULL is supplied and the argument is of type FFI:FOREIGN-VARIABLE, recursively frees the whole complex stucture pointed to by this variable. If given a FFI:FOREIGN-FUNCTION object that corresponds to a CLISP callback, deallocates it. Callbacks are automatically created each time you pass a Lisp function via the "FFI".. Use (SETF FFI:VALIDP) to disable further references to this address from Lisp. This is currently not done automatically. If the given pointer is already invalid, FFI:FOREIGN-FREE (currently) signals an ERROR. This may change to make it easier to integrate with EXT:FINALIZE. Function FFI:FOREIGN-ALLOCATE is a lower-level interface as it requires an internal C type descriptor as returned by FFI:PARSE-C-TYPE. (FFI:WITH-C-PLACE (variable foreign-entity) body) Create a place out of the given FFI:FOREIGN-VARIABLE object so operations on places (e.g. FFI:CAST, FFI:DEREF, FFI:SLOT etc.) can be used within body. FFI:WITH-C-VAR appears as a composition of FFI:WITH-FOREIGN-OBJECT and FFI:WITH-C-PLACE. Such a place can be used to access memory referenced by a foreign-entity object: (setq foo (allocate-deep '(c-array uint8 3) rgb)) (with-c-place (place foo) (element place 0)) FFI:*OUTPUT-C-FUNCTIONS* FFI:*OUTPUT-C-VARIABLES* CLISP will write the extern declarations for foreign functions (defined with FFI:DEF-CALL-OUT) and foreign variables (defined with FFI:DEF-C-VAR) into the output #P".c" (when the Lisp file is compiled with COMPILE-FILE) unless these variables are NIL. They are NIL by default, so the extern declarations are not written; you are encouraged to use FFI:C-LINES to include the appropriate C headers. Set these variables to non-NIL if the headers are not available or not usable. 30.3.2.  (Foreign) C types Foreign C types are used in the "FFI".. They are not regular Common Lisp types or CLOS classes. A c-type is either a predefined C type or the name of a type defined by FFI:DEF-C-TYPE. the predefined C types (c-type) simple-c-type the simple C types ============ ================== ============== =============== ================ Lisp name Lisp equivalent C equivalent ILU equivalent Comment ============ ================== ============== =============== ================ NIL NIL void as a result type only BOOLEAN BOOLEAN int BOOLEAN CHARACTER CHARACTER char SHORT CHARACTER char INTEGER signed char uchar INTEGER unsigned char short INTEGER short ushort INTEGER unsigned short int INTEGER int uint INTEGER unsigned int long INTEGER long ulong INTEGER unsigned long uint8 (UNSIGNED-BYTE 8) uint8 BYTE sint8 (SIGNED-BYTE 8) sint8 uint16 (UNSIGNED-BYTE 16) uint16 SHORT CARDINAL sint16 (SIGNED-BYTE 16) int16 SHORT INTEGER uint32 (UNSIGNED-BYTE 32) uint32 CARDINAL sint32 (SIGNED-BYTE 32) sint32 INTEGER uint64 (UNSIGNED-BYTE 64) uint64 LONG CARDINAL does not work on all platforms sint64 (SIGNED-BYTE 64) sint64 LONG INTEGER does not work on all platforms SINGLE-FLOAT SINGLE-FLOAT float DOUBLE-FLOAT DOUBLE-FLOAT double ============ ================== ============== =============== ================     FFI:C-POINTER This type corresponds to what C calls void*, an opaque pointer. When used as an argument, NIL is accepted as a FFI:C-POINTER and treated as NULL; when a function wants to return a NULL FFI:C-POINTER, it actually returns NIL. FFI:C-STRING This type corresponds to what C calls char*, a zero-terminated string. Its Lisp equivalent is a string, without the trailing zero character. (FFI:C-STRUCT class (ident1 c-type1) ... (identn c-typen)) This type is equivalent to what C calls struct { c-type1 ident1; ...; c-typen identn; }. Its Lisp equivalent is: if class is VECTOR, a SIMPLE-VECTOR; if class is LIST, a proper list; if class is a symbol naming a structure or CLOS class, an instance of this class, with slots of names ident1, ..., identn. class may also be a CONS of a SYMBOL (as above) and a LIST of FFI:DEF-C-STRUCT options. (FFI:C-UNION (ident1 c-type1) ... (identn c-typen)) This type is equivalent to what C calls union { c-type1 ident1; ...; c-typen identn; }. Conversion to and from Lisp assumes that a value is to be viewed as being of c-type1. (FFI:C-ARRAY c-type dim1) (FFI:C-ARRAY c-type (dim1 ... dimn)) This type is equivalent to what C calls c-type [dim1] ... [dimn]. Note that when an array is passed as an argument to a function in C, it is actually passed as a pointer; you therefore have to write (FFI:C-PTR (FFI:C-ARRAY ...)) for this argument's type. (FFI:C-ARRAY-MAX c-type maxdimension) This type is equivalent to what C calls c-type [maxdimension], an array containing up to maxdimension elements. The array is zero-terminated if it contains less than maxdimension elements. Conversion from Lisp of an array with more than maxdimension elements silently ignores the superfluous elements. (FFI:C-FUNCTION (:ARGUMENTS {(argument a-c-type [PARAM-MODE [ALLOCATION]])}*) (:RETURN-TYPE r-c-type [ALLOCATION]) (:LANGUAGE language)) This type designates a C function that can be called according to the given prototype (r-c-type (*) (a-c-type1, ...)). Conversion between C functions and Lisp functions is transparent, and NULL/NIL is recognized and accepted. (FFI:C-PTR c-type) This type is equivalent to what C calls c-type *: a pointer to a single item of the given c-type. (FFI:C-PTR-NULL c-type) This type is also equivalent to what C calls c-type *: a pointer to a single item of the given c-type, with the exception that C NULL corresponds to Lisp NIL. (FFI:C-ARRAY-PTR c-type) This type is equivalent to what C calls c-type (*)[]: a pointer to a zero-terminated array of items of the given c-type. CUSTOM:*FOREIGN-ENCODING* governs conversion for any c-type involving FFI:C-STRING or CHARACTER (but not char). 30.3.3.  The choice of the C flavor. FFI:C-FUNCTION, FFI:DEF-CALL-IN, FFI:DEF-CALL-OUT take :LANGUAGE argument. The language is either :C (denotes K&R C) or :STDC (denotes ANSI C) or :STDC-STDCALL (denotes ANSI C with the stdcall calling convention). It specifies whether the C function (caller or callee) has been compiled by a K&R C compiler or by an ANSI C compiler, and possibly the calling convention. The default language is set using the macro FFI:DEFAULT-FOREIGN-LANGUAGE. If this macro has not been called in the current compilation unit (usually a file), a warning is issued and :STDC is used for the rest of the unit. 30.3.4.  Foreign variables Foreign variables are variables whose storage is allocated in the foreign language module. They can nevertheless be evaluated and modified through SETQ, just as normal variables can, except that the range of allowed values is limited according to the variable's foreign type. Note that for a foreign variable x the form (EQL x x) is not necessarily true, since every time x is evaluated its foreign value is converted to a fresh Lisp value. Foreign variables are defined using FFI:DEF-C-VAR. 30.3.5.  Operations on foreign places A FFI:FOREIGN-VARIABLE name defined by FFI:DEF-C-VAR, FFI:WITH-C-VAR or FFI:WITH-C-PLACE defines a place, i.e., a form which can also be used as argument to SETF. (An "lvalue" in C terminology.) The following operations are available on foreign places: FFI:ELEMENT, FFI:DEREF, FFI:SLOT, FFI:CAST, FFI:OFFSET, FFI:C-VAR-ADDRESS, FFI:C-VAR-OBJECT, FFI:TYPEOF, FFI:SIZEOF, FFI:BITSIZEOF. 30.3.6.  Foreign functions Foreign functions are functions which are defined in the foreign language. There are named foreign functions (imported via FFI:DEF-CALL-OUT or created via FFI:DEF-CALL-IN) and anonymous foreign functions; they arise through conversion of function pointers. A "call-out" function is a foreign function called from Lisp: control flow temporarily leaves Lisp. A "call-in" function is a Lisp function called from the foreign language: control flow temporary enters Lisp. The following forms define foreign functions: FFI:DEF-CALL-IN, FFI:DEF-CALL-OUT, FFI:DEF-C-CALL-IN, FFI:DEF-C-CALL-OUT. 30.3.7.  Argument and result passing conventions When passed to and from functions, allocation of arguments and results is handled as follows: Values of SIMPLE-C-TYPE, FFI:C-POINTER are passed on the stack, with dynamic extent. The ALLOCATION is effectively ignored. Values of type FFI:C-STRING, FFI:C-PTR, FFI:C-PTR-NULL, FFI:C-ARRAY-PTR need storage. The ALLOCATION specifies the allocation policy: :NONE no storage is allocated. :ALLOCA allocation of storage on the stack, which has dynamic extent. :MALLOC-FREE storage will be allocated via malloc and freed via free. If no ALLOCATION is specified, the default ALLOCATION is :NONE for most types, but :ALLOCA for FFI:C-STRING and FFI:C-PTR and FFI:C-PTR-NULL and FFI:C-ARRAY-PTR and for :OUT arguments. [Subject to change!] The :MALLOC-FREE policy provides the ability to pass arbitrarily nested structs containing pointers pointing to structs ... within a single conversion. For call-out functions: For arguments passed from Lisp to C: If ALLOCATION is :MALLOC-FREE: Lisp allocates the storage using malloc and never deallocates it. The C function is supposed to call free when done with it. If ALLOCATION is :ALLOCA: Lisp allocates the storage on the stack, with dynamic extent. It is freed when the C function returns. If ALLOCATION is :NONE: Lisp assumes that the pointer already points to a valid area of the proper size and puts the result value there. This is dangerous! and deprecated. For results passed from C to Lisp: If ALLOCATION is :MALLOC-FREE: Lisp calls free on it when done. If ALLOCATION is :NONE: Lisp does nothing. For call-in functions: For arguments passed from C to Lisp: If ALLOCATION is :MALLOC-FREE: Lisp calls free on it when done. If ALLOCATION is :ALLOCA or :NONE: Lisp does nothing. For results passed from Lisp to C: If ALLOCATION is :MALLOC-FREE: Lisp allocates the storage using malloc and never deallocates it. The C function is supposed to call free when done with it. If ALLOCATION is :NONE: Lisp assumes that the pointer already points to a valid area of the proper size and puts the result value there. This is dangerous! and deprecated. Warning: Passing FFI:C-STRUCT, FFI:C-UNION, FFI:C-ARRAY, FFI:C-ARRAY-MAX values as arguments (not via pointers) is only possible to the extent the C compiler supports it. Most C compilers do it right, but some C compilers (such as gcc on hppa and Win32) have problems with this. The recommended workaround is to pass pointers; this is fully supported. See also this <[email protected]> message. 30.3.8.  Parameter Mode A function parameter's PARAM-MODE may be :IN (means: read-only): The caller passes information to the callee. :OUT (means: write-only): The callee passes information back to the caller on return. When viewed as a Lisp function, there is no Lisp argument corresponding to this, instead it means an additional return value. :IN-OUT (means: read-write): Information is passed from the caller to the callee and then back to the caller. When viewed as a Lisp function, the :OUT value is returned as an additional multiple value. The default is :IN. [Currently, only :IN is fully implemented. :OUT works only with ALLOCATION = :ALLOCA.] ========================================================================
28,115
Common Lisp
.lisp
523
48.200765
80
0.707129
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ce72bfb83cd86cf2c6377660298c16e68cf2c8ab619b7c861215f2ff92d3dc81
4,805
[ -1 ]
4,806
susv3-xsi.lisp
informatimago_lisp/clisp/susv3-xsi.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: susv3-xsi.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This packages exports SUSV3 XSI functions. ;;;; This is the CLISP specific implementation of the SUSV3 XSI API. ;;;; ;;;; ;;;; The Open Group Base Specifications Issue 6 ;;;; IEEE Std 1003.1, 2003 Edition ;;;; ;;;; http://www.opengroup.org/onlinepubs/007904975/index.html ;;;; ;;;; ;;;; Implemented: ;;;; ftw ;;;; msgget/msgctl/msgsnd/msgrcv ;;;; shmget/shmctl/shmat/shmdt ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-11-29 <PJB> Added IPC. ;;;; 2003-06-18 <PJB> Created (FTW). ;;;;BUGS ;;;; Actually, we should include the features only if it's proven to exist ;;;; on the current system. At run-time. ;;;; ;;;; The type of arguments and results of FFI function should be pure ;;;; Common-Lisp objects. We shouldn't need to do any FFI stuff outside ;;;; of here. ;;;; ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "FFI" "LINUX")) (eval-when (:compile-toplevel :load-toplevel :execute) (require "linux")) (defpackage "COM.INFORMATIMAGO.CLISP.SUSV3-XSI" (:documentation "This packages exports SUSV3 XSI functions. This is the CLISP specific implementation of the SUSV3 XSI API.") (:use "COMMON-LISP" "COM.INFORMATIMAGO.CLISP.SUSV3") (:export ;; FTW "+FTW-F+" "+FTW-D+" "+FTW-DNR+" "+FTW-DP+" "+FTW-NS+" "+FTW-SL+" "+FTW-SLN+" "+FTW-PHYS+" "+FTW-MOUNT+" "+FTW-DEPTH+" "+FTW-CHDIR+" "FTW" "FTW-FILTER" "NFTW-FILTER" "FTW" "+FTW-F+" "+FTW-D+" "+FTW-DNR+" "+FTW-DP+" "+FTW-NS+" "+FTW-SL+" "+FTW-SLN+" ;; IPC: "IPC_CREAT" "IPC_EXCL" "IPC_NOWAIT" "IPC_RMID" "IPC_SET" "IPC_STAT" "IPC_INFO" "IPC_PRIVATE" "IPC_PERM" "FTOK" "MSG_NOERROR" "MSG_EXCEPT" "MSGQNUM_T" "MSGLEN_T" "MSQID_DS" "MSG_STAT" "MSG_INFO" "MSGINFO" "MSGGET" "MSGCTL" "MSGSND" "MSGRCV" "+MAX-MTEXT-SIZE+" "MSGBUF" "MAKE-MSGBUF" "SHM_R" "SHM_W" "SHM_RDONLY" "SHM_RND" "SHM_REMAP" "SHM_LOCK" "SHM_UNLOCK" "GETPAGESIZE" "SHMLBA" "SHM_STAT" "SHM_INFO" "SHM_DEST" "SHM_LOCKED" "SHM_HUGETLB" "SHMID_DS" "SHMGET" "SHMCTL" "SHMAT" "SHMDT" "SEM_UNDO" "GETPID" "GETVAL" "GETALL" "GETNCNT" "GETZCNT" "SETVAL" "SETALL" "SEMMNI" "SEMMSL" "SEMMNS" "SEMOPM" "SEMVMX" "SEMAEM" "SEMID_DS" "SEM_STAT" "SEM_INFO" "SEMINFO" "SEMBUF" "SEMGET" "SEMCTL" "SEMOP" ;; // WARNING // WARNING // WARNING // WARNING // WARNING // WARNING // ;; The following are readers, not accessors!!! ;; // WARNING // WARNING // WARNING // WARNING // WARNING // WARNING // "MSGBUF-MTYPE" "MSGBUF-MTEXT" "IPC_PERMKEY" "IPC_PERMUID" "IPC_PERMGID" "IPC_PERMCUID" "IPC_PERMCGID" "IPC_PERMMODE" "IPC_PERMSEQ" "MSGQID_DS-MSG_PERM" "MSGQID_DS-MSG_STIME" "MSQID_DS-MSG_RTIME" "MSQID_DS-MSG_CTIME" "MSQID_DS-MSG_CBYTES" "MSQID_DS-MSG_QNUM" "MSQID_DS-MSG_QBYTES" "MSQID_DS-MSG_LSPID" "MSQID_DS-MSG_LRPID" "MSGINFO-MSGPOOL" "MSGINFO-MSGMAP" "MSGINFO-MSGMAX" "MSGINFO-MSGMNB" "MSGINFO-MSGMNI" "MSGINFO-MSGSSZ" "MSGINFO-MSGTQL" "MSGINFO-MSGSEG" "SHMID_DS-SHM_PERM" "SHMID_DS-SHM_SEGSZ" "SHMID_DS-SHM_ATIME" "SHMID_DS-SHM_DTIME" "SHMID_DS-SHM_CTIME" "SHMID_DS-SHM_CPID" "SHMID_DS-SHM_LPID" "SHMID_DS-SHM_NATTCH" "SEMID_DS-SEM_PERM" "SEMID_DS-SEM_OTIME" "SEMID_DS-SEM_CTIME" "SEMID_DS-SEM_NSEMS" "SEMINFO-SEMMAP" "SEMINFO-SEMMNI" "SEMINFO-SEMMNS" "SEMINFO-SEMMNU" "SEMINFO-SEMMSL" "SEMINFO-SEMOPM" "SEMINFO-SEMUME" "SEMINFO-SEMUSZ" "SEMINFO-SEMVMX" "SEMINFO-SEMAEM" "SEMBUF-SEM_NUM" "SEMBUF-SEM_OP" "SEMBUF-SEM_FLG" )) (in-package "COM.INFORMATIMAGO.CLISP.SUSV3-XSI") (ffi:default-foreign-library "libc.so.6") (eval-when (:compile-toplevel :load-toplevel :execute) ;; TODO: Actually, we should include the features only if it's proven to exist on the current system. At run-time. (pushnew :susv3-xsi *features*)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; FTW.H ;; ;; NOTE: WE DON'T USE THE LIBC IMPLEMENTATION OF FTW; ;; WE IMPLEMENT IT IN LISP USING SUSV3:DIRENT AND SUSV3:STAT. ;; ANOTHER IMPLEMENTATION COULD USE THE C VERSION (BUT WOULD HAVE ;; TO USE C-TO-LISP CALLBACKS! ;; (defconstant +ftw-f+ 0 "File.") (defconstant +ftw-d+ 1 "Directory.") (defconstant +ftw-dnr+ 2 "Directory without read permission.") (defconstant +ftw-dp+ 3 "Directory with subdirectories visited.") (defconstant +ftw-ns+ 4 "Unknown type; stat() failed.") (defconstant +ftw-sl+ 5 "Symbolic link.") (defconstant +ftw-sln+ 6 "Symbolic link that names a nonexistent file.") (defconstant +ftw-phys+ 1 "Physical walk, does not follow symbolic links. Otherwise, NFTW follows links but does not walk down any path that crosses itself.") (defconstant +ftw-mount+ 2 "The walk does not cross a mount point.") (defconstant +ftw-depth+ 4 "All subdirectories are visited before the directory itself.") (defconstant +ftw-chdir+ 8 "The walk changes to each directory before reading it.") (defstruct ftw (base 0 :type integer) (level 0 :type integer)) (deftype ftw-filter () '(function (simple-string stat integer) integer)) (deftype nftw-filter () '(function (simple-string stat integer ftw) integer)) (declaim (ftype (function (simple-string ftw-filter integer) integer) ftw) (ftype (function (simple-string nftw-filter integer integer) integer) nftw)) ;; ISSUE: SHOULD THE FILTER RETURN NIL/T OR ZEROP/NOT ZEROP? ;; AS DEFINED BY SUSV3, ZEROP/NOT ZEROP ALLOW IT TO RETURN ;; A USEFUL VALUE THRU FTW. ;; ;; ISSUE: SHOULD THE FILTER BE ALLOWED TO RETURN NIL/NOT NULL? ;; THAT WOULD BE EVEN MORE USEFUL! ;; ;; ISSUE: SPECIFY WHAT HAPPENS WHEN A CONDITION OCCURS IN THE FILTER ;; --> THE FILTER IS ONLY UNWIND-PROTECTED. ;; ;; ISSUE: SPECIFY THAT FILTER CAN RECEIVE A NIL STAT RATHER THAN AN ;; UNDEFINED ONE. OR NOT? ;; ;; ISSUE: specify that ftw and nfw must not give "." and ".." to the filter ;; (but only when "." is the starting path). (This is underspecified ;; in SUSv3). (defun ftw (path filter ndirs) " URL: <http://www.opengroup.org/onlinepubs/007904975/functions/ftw.html> " (declare (type (integer 1 #|+OPEN-MAX+|#) ndirs)) (declare (ignore ndirs)) ;; We'll have always only one DIR-STREAM open: we keep the list of ;; subdirectories in memory and process them after having read the directory. (let ((dir-stream (opendir path))) (unwind-protect (do* ((entry (readdir dir-stream) (readdir dir-stream)) (directories '()) subpath stat flag (result 0)) ((or (null entry) (/= 0 result)) directories) (unless (or (string= (dirent-name entry) "..") (string= (dirent-name entry) ".")) (setq subpath (concatenate 'string path "/" (dirent-name entry))) (handler-case (setq stat (lstat subpath)) (t () (setq stat nil))) (cond ((null stat) (setq flag +ftw-ns+)) ((s-isreg (stat-mode stat)) (setq flag +ftw-f+)) ((s-isdir (stat-mode stat)) (push subpath directories) (setq flag +ftw-f+)) ((s-islnk (stat-mode stat)) (handler-case (setq stat (stat subpath) flag +ftw-sl+))) (t () (setq stat nil flag +ftw-sln+))) (setq result (handler-case (funcall filter (dirent-name entry) stat flag) (t () -1))))) (closedir dir-stream)))) (defconstant +ftw-f+ 0 "File.") (defconstant +ftw-d+ 1 "Directory.") (defconstant +ftw-dnr+ 2 "Directory without read permission.") (defconstant +ftw-dp+ 3 "Directory with subdirectories visited.") (defconstant +ftw-ns+ 4 "Unknown type; stat() failed.") (defconstant +ftw-sl+ 5 "Symbolic link.") (defconstant +ftw-sln+ 6 "Symbolic link that names a nonexistent file.") ;; int ftw(const char *,int (*)(const char *,const struct stat *,int),int) ;; int nftw(const char *,int (*)(const char *,const struct stat *, int,struct FTW*),int,int) ;; (DEFUN FIND () ;; (DO* ((DIR-STREAM (OPENDIR "/tmp")) ;; (ENTRY (READDIR DIR-STREAM) (READDIR DIR-STREAM))) ;; ((NULL ENTRY)) ;; (FORMAT T "entry: ~8D ~S~%" (DIRENT-INO ENTRY) (DIRENT-NAME ENTRY)))) ;;---------------------------------------------------------------------- ;; ipc ;;---------------------------------------------------------------------- (defconstant ipc_creat #o01000 "Create key if key does not exist.") (defconstant ipc_excl #o02000 "Fail if key exists.") (defconstant ipc_nowait #o04000 "Return error on wait.") ;; Control commands for `msgctl', `semctl', and `shmctl'. (defconstant ipc_rmid 0 "Remove identifier.") (defconstant ipc_set 1 "Set `ipc_perm' options.") (defconstant ipc_stat 2 "Get `ipc_perm' options.") (defconstant ipc_info 3 "See ipcs.") (defconstant ipc_private 0 "Private key.") (ffi:def-c-struct ipc_perm (key linux:|key_t|) ; Key. (uid linux:|uid_t|) ; Owner's user ID. (gid linux:|gid_t|) ; Owner's group ID. (cuid linux:|uid_t|) ; Creator's user ID. (cgid linux:|gid_t|) ; Creator's group ID. (mode ffi:ushort) ; Read/write permission. (pad1 ffi:ushort) (seq ffi:ushort) ; Sequence number. (pad2 ffi:ushort) (unused1 ffi:ulong) (unused2 ffi:ulong)) (ffi:def-call-out ftok (:name "ftok") (:arguments (pathname ffi:c-string) (proj-id ffi:int)) (:return-type linux:|key_t|) (:language :stdc)) ;;---------------------------------------------------------------------- ;; msg ;;---------------------------------------------------------------------- (defconstant msg_noerror #o010000 "no error if message is too big") (defconstant msg_except #o020000 "recv any msg except of specified type") ;; Types used in the structure definition. (ffi:def-c-type msgqnum_t ffi:ulong) (ffi:def-c-type msglen_t ffi:ulong) ;; Structure of record for one message inside the kernel. ;; The type `struct msg' is opaque. (ffi:def-c-struct msqid_ds (msg_perm ipc_perm) ; structure describing operation permission (msg_stime linux:|time_t|) ; time of last msgsnd command (__unused1 ffi:ulong) (msg_rtime linux:|time_t|) ; time of last msgrcv command (__unused2 ffi:ulong) (msg_ctime linux:|time_t|) ; time of last change (__unused3 ffi:ulong) (msg_cbytes ffi:ulong) ; current number of bytes on queue (msg_qnum msgqnum_t) ; number of messages currently on queue (msg_qbytes msglen_t) ; max number of bytes allowed on queue (msg_lspid linux:|pid_t|) ; pid of last msgsnd() (msg_lrpid linux:|pid_t|) ; pid of last msgrcv() (__unused4 ffi:ulong) (__unused5 ffi:ulong)) ;; ipcs ctl commands (defconstant msg_stat 11) (defconstant msg_info 12) ;; buffer for msgctl calls IPC_INFO, MSG_INFO (ffi:def-c-struct msginfo (msgpool ffi:int) (msgmap ffi:int) (msgmax ffi:int) (msgmnb ffi:int) (msgmni ffi:int) (msgssz ffi:int) (msgtql ffi:int) (msgseg ffi:ushort)) (defstruct msgbuf (mtype 0 :type integer) (mtext #() :type (vector (unsigned-byte 8) *))) (ffi:def-call-out msgget (:name "msgget") (:arguments (key linux:|key_t|) (msgflg ffi:int)) (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out msgctl (:name "msgctl") (:arguments (msqid ffi:int) (cmd ffi:int) (buf pointer)) ;; We cannot use (ffi:c-ptr msqid_ds) because in that case ;; it would not be copied back as output parameter. (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out msgsnd (:name "msgsnd") (:arguments (msqid ffi:int) (msgbuf pointer) (msgsz ffi:size_t) (msgflg ffi:int)) (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out msgrcv (:name "msgrcv") (:arguments (msqid ffi:int) (msgbuf pointer) (msgsz ffi:size_t) (msgtyp ffi:long) (msgflg ffi:int)) (:return-type ffi:ssize_t) (:language :stdc)) ;;---------------------------------------------------------------------- ;; shm ;;---------------------------------------------------------------------- ;; Permission flag for shmget. (defconstant shm_r #o0400 "or S_IRUGO from <linux/stat.h> *") (defconstant shm_w #o0200 "or S_IWUGO from <linux/stat.h> *") ;; Flags for `shmat'. (defconstant shm_rdonly #o010000 "attach read-only else read-write *") (defconstant shm_rnd #o020000 "round attach address to SHMLBA *") (defconstant shm_remap #o040000 "take-over region on attach *") ;; Commands for `shmctl'. (defconstant shm_lock 11 "lock segment (root only) *") (defconstant shm_unlock 12 "unlock segment (root only) *") (ffi:def-call-out getpagesize (:name "getpagesize") (:arguments) (:return-type ffi:int) (:language :stdc)) (defun shmlba () "Segment low boundary address multiple. " (getpagesize)) (ffi:def-c-type shmatt_t ffi:ulong) ;; Type to count number of attaches. (ffi:def-c-struct shmid_ds ;; Data structure describing a set of semaphores. (shm_perm ipc_perm) ; structure describing operation permission (shm_segsz ffi:size_t) ; size of segment in bytes (shm_atime linux:|time_t|) ; time of last shmat() (__unused1 ffi:ulong) ; (shm_dtime linux:|time_t|) ; time of last shmdt() (__unused2 ffi:ulong) ; (shm_ctime linux:|time_t|) ;time of last change by shmctl() (__unused3 ffi:ulong) ; (shm_cpid linux:|pid_t|) ; pid of creator (shm_lpid linux:|pid_t|) ; pid of last shmop (shm_nattch shmatt_t) ; number of current attaches (__unused4 ffi:ulong) ; (__unused5 ffi:ulong)) (ffi:def-c-struct shminfo (shmmax ffi:ulong) (shmmin ffi:ulong) (shmmni ffi:ulong) (shmseg ffi:ulong) (shmall ffi:ulong) (__unused1 ffi:ulong) (__unused2 ffi:ulong) (__unused3 ffi:ulong) (__unused4 ffi:ulong)) (ffi:def-c-struct shm_info (used_ids ffi:int) ; (shm_tot ffi:ulong) ; total allocated shm (shm_rss ffi:ulong) ; total resident shm* (shm_swp ffi:ulong) ; total swapped shm (swap_attempts ffi:ulong) ; (swap_successes ffi:ulong)) (ffi:def-call-out shmget (:name "shmget") ;; Get shared memory segment. (:arguments (key linux:|key_t|) (size ffi:size_t) (shmflg ffi:int)) (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out shmctl (:name "shmctl") ;; Shared memory control operation. (:arguments (shmid ffi:int) (cmd ffi:int) (buf pointer)) (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out shmat (:name "shmat") ;; Attach shared memory segment. (:arguments (shmid ffi:int) (shmaddr pointer) (shmflg ffi:int)) (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out shmdt (:name "shmdt") ;; Detach shared memory segment. (:arguments (shmaddr pointer)) (:return-type ffi:int) (:language :stdc)) ;;---------------------------------------------------------------------- ;; sem ;;---------------------------------------------------------------------- ;; Flags for `semop'. (defconstant sem_undo #x1000 "undo the operation on exit") ;; Commands for `semctl'. (defconstant getpid 11 "get sempid") (defconstant getval 12 "get semval") (defconstant getall 13 "get all semval's") (defconstant getncnt 14 "get semncnt") (defconstant getzcnt 15 "get semzcnt") (defconstant setval 16 "set semval") (defconstant setall 17 "set all semval's") (defconstant semmni 128 "<= IPCMNI max # of semaphore identifiers") (defconstant semmsl 250 "<= 8 000 max num of semaphores per id") (defconstant semmns 32000 #|(* SEMMNI SEMMSL)|# "<= INT_MAX max # of semaphores in system") (defconstant semopm 32 "<= 1 000 max num of ops per semop call") (defconstant semvmx 32767 "<= 32767 semaphore maximum value") (defconstant semaem 32767 #|SEMVMX|# "adjust on exit max value") (ffi:def-c-struct semid_ds ;; Data structure describing a set of semaphores. (sem_perm ipc_perm) ; operation permission struct (sem_otime linux:|time_t|) ; last semop() time (__unused1 ffi:ulong) (sem_ctime linux:|time_t|) ; last time changed by semctl() (__unused2 ffi:ulong) (sem_nsems ffi:ulong) ; number of semaphores in set (__unused3 ffi:ulong) (__unused4 ffi:ulong)) ;; The user should define a union like the following to use it for arguments ;; for `semctl'. ;; ;; union semun ;; { ;; int val; <= value for SETVAL ;; struct semid_ds *buf; <= buffer for IPC_STAT & IPC_SET ;; unsigned short int *array; <= array for GETALL & SETALL ;; struct seminfo *__buf; <= buffer for IPC_INFO ;; }; ;; ;; Previous versions of this file used to define this union but this is ;; incorrect. One can test the macro _SEM_SEMUN_UNDEFINED to see whether ;; one must define the union or not. ;; ipcs ctl cmds (defconstant sem_stat 18) (defconstant sem_info 19) (ffi:def-c-struct seminfo (semmap ffi:int) (semmni ffi:int) (semmns ffi:int) (semmnu ffi:int) (semmsl ffi:int) (semopm ffi:int) (semume ffi:int) (semusz ffi:int) (semvmx ffi:int) (semaem ffi:int)) (ffi:def-c-struct sembuf ;; Structure used for argument to `semop' to describe operations. (sem_num ffi:ushort) ; semaphore number (sem_op ffi:short) ; semaphore operation (sem_flg ffi:short) ; operation flag ) (ffi:def-call-out semget (:name "semget") ;; Get semaphore. (:arguments (key linux:|key_t|) (nsems ffi:int) (semflg ffi:int)) (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out semctl (:name "semctl") ;; Semaphore control operation. (:arguments (semid ffi:int) (semnum ffi:int) (cmt ffi:int) (arg pointer)) (:return-type ffi:int) (:language :stdc)) (ffi:def-call-out semop (:name "semop") ;; Operate on semaphore. (:arguments (semid ffi:int) (sops pointer) (nsops ffi:size_t)) (:return-type ffi:int) (:language :stdc)) ;;;; THE END ;;;;
19,925
Common Lisp
.lisp
455
40.356044
116
0.610506
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1c95c36c68815352f23d48045f63b771e2d8f0e64789cd5c5fb9093f8491a062
4,806
[ -1 ]
4,807
string-test.lisp
informatimago_lisp/clisp/string-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: string-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test string.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-25 <PJB> Extracted from string.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.STRING.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.CLISP.STRING") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.CLISP.STRING.TEST") (defun rris-result (test-case res) "Common-Lisp" (if (or (and (eq :error res) (eq res (car test-case))) (string= (car test-case) res)) (progn (format t "Ok ~50W --> ~W~%" (cdr test-case) res) (progress-success)) (progress-failure-message (cdr test-case) "~& expected ~W~% got ~W~%" (car test-case) res))) (defun rris-test () " Test cases for REPLACE-REGEXP-IN-STRING " (let ((*case-fold-search* t)) (do* ((test-cases ;; We use basic POSIX regexps, so no 're+'. ;; result regexp replac string fix lit sub start '( ("xy" "" "x" "y" t t) ("xyxyxyxy" "" "x" "yyyy" t t) ("" "." "x" "" t t) ("x" "." "x" "y" t t) ("xxxx" "." "x" "yyyy" t t) ("xxxx" "." "x" "yaya" t t) ("good" "a" "bad" "good" t t) ("good" "bad" "good" "bad" t t) ("good rest" "bad" "good" "bad rest" t t) ("rest good" "bad" "good" "rest bad" t t) ("good" "bad" (lambda (x) "good") "bad" t t) ("good rest" "bad" (lambda (x) "good") "bad rest" t t) ("rest good" "bad" (lambda (x) "good") "rest bad" t t) ("test" "r\\(e\\)g" "good" "test" nil nil 2) (:error "r\\(e\\)g" "good" "reg" nil nil 2) ("rgoodg" "r\\(e\\)g" "good" "reg" nil nil 1) ("BOC NEW VALUE hoc" "pattern" "nEW VAlue" "BOC PATTERN hoc") ("BOC nEW VAlue hoc" "pattern" "nEW VAlue" "BOC pattern hoc") ("BOC new value hoc" "pattern" "new value" "BOC pattern hoc") ("BOC NEW VAlue hoc" "pattern" "nEW VAlue" "BOC Pattern hoc") ("BOC New Value hoc" "pattern" "new value" "BOC Pattern hoc") ("BOC nEW VAlue hoc" "pattern" "nEW VAlue" "BOC pATteRN hoc") ("BOC New1value hoc" "pattern" "new1value" "BOC Pattern hoc") ("BOC New-Value hoc" "pattern" "new-value" "BOC Pattern hoc") ("rrrr-www-bb rr-w-bbb" "\\(bb*\\) \\(ww*\\) \\(rr*\\)" "\\3-\\2-\\1" "bb www rrrr bbb w rr") ("\\4-www-bb \\4-w-bbb" "\\(bb*\\) \\(ww*\\) \\(rr*\\)" "\\4-\\2-\\1" "bb www rrrr bbb w rr") (:error "blue" "\\\\b\\l\\&" "blue box and bluetooth") ("\\bblue box and \\bbluetooth" "blue" "\\\\b\\&" "blue box and bluetooth")) (cdr test-cases)) (test-case (car test-cases) (car test-cases)) (tc test-case test-case) (all-ok t)) ((null test-cases) all-ok) (when (listp (nth 2 tc)) (setq tc (copy-seq tc)) (setf (nth 2 tc) (coerce (nth 2 tc) 'function))) (let ((res (handler-case (apply (function replace-regexp-in-string) (cdr tc)) (error () :error))) ) (if (eq :error res) (unless (eq res (car test-case)) (setq all-ok nil)) (unless (string= (car test-case) res) (setq all-ok nil))) (rris-result test-case res))))) ;; (rris-test) ;;; (let ((start 0) (case-sensitive nil) (extended nil) (newline nil) (nosub nil)) ;;; (REGEXP:MATCH "blue" "blue box and bluetooth" ;;; :START START :IGNORE-CASE (NOT CASE-SENSITIVE) ;;; :EXTENDED EXTENDED :NEWLINE NEWLINE :NOSUB NOSUB) ) ;; (replace-regexp-in-string "blue" "\\\\b\\X\\&" "blue box and bluetooth") (define-test test/rris () (rris-test)) (define-test test/all () (test/rris)) ;;;; THE END ;;;;
5,683
Common Lisp
.lisp
118
40.694915
83
0.486856
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
da219109df2afbed29cfc15f3a2861953bc9822814a2a6bda7cf65a7a2d81fb7
4,807
[ -1 ]
4,808
make-volumes.lisp
informatimago_lisp/clisp/make-volumes.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: make-volumes.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;NOWEB: T ;;;;DESCRIPTION ;;;; ;;;; This package exports a function to tally a directory tree ;;;; and make if it 'volumes' of a given maximum size. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2003-06-10 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.MAKE-VOLUMES" (:documentation "This package exports a function to tally a directory tree and make if it 'volumes' of a given maximum size.") (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.CLISP.SUSV3") (:export "MAIN" "MAKE-VOLUMES")) (in-package "COM.INFORMATIMAGO.CLISP.MAKE-VOLUMES") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; TREE ;; (defun deep-copy-tree (tree) " NOTE: COPY-TREE ONLY DUPLICATES THE CONS, NOT THE OBJECTS. THIS IS UNFORTUNATE, BECAUSE WE OFTEN NEED TO DUPLICATE THE OBJECTS (STRINGS, ARRAY) TOO, BECAUSE OF THE MUTABLE/IMMUTABLE PROBLEM. DO: MAKES A COPY OF THE TREE, COPYING THE LEAF OBJECTS TOO. " (cond ((consp tree) (cons (deep-copy-tree (car tree)) (deep-copy-tree (cdr tree)))) ((vectorp tree) (copy-seq tree)) (t tree))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; AN ENUMERATOR IS A FUNCTION THAT RETURNS EACH TIME IT'S CALLED THE ;; NEXT ITEM OF A (POSSIBLY VIRTUAL AND POSSIBLY INFINITE) SEQUENCE AND T. ;; WHEN NO ITEM REMAINS, IT RETURNS (VALUES NIL NIL). ;; ENUMERATORS CAN BE CONCATENATED WITH APPEND-ENUMERATORS. ;; (OF COURSE APPENDING AN ENUMERATOR AFTER AN INFINITE ENUMERATOR WOULD ;; BE USELESS). (defun make-list-enumerator (list) " RETURN: A ENUMERATOR FUNCTION FOR THE LIST. NOTE: THE ENUMERATOR FUNCTION RETURNS IN TURN EACH ELEMENT OF THE LIST AS FIRST VALUE AND A BOOLEAN T UNLESS THE END OF THE LIST IS REACHED AS SECOND VALUE. " (lambda () (multiple-value-prog1 (values (car list) (not (null list))) (setq list (cdr list))))) (defun append-enumerators (&rest enumerators) " RETURN: An enumerator that enumerates all the enumerators in turn. " (lambda () (block :meta-enum (loop (if (null enumerators) (return-from :meta-enum (values nil nil)) (multiple-value-bind (val ind) (funcall (car enumerators)) (if ind (return-from :meta-enum (values val ind)) (pop enumerators)))))))) (defun collect-enumerator (enumerator) (do ((result '()) (done nil)) (done result) (multiple-value-bind (val ind) (funcall enumerator) (if ind (push val result) (setq done t))))) (defun map-enumerator (lambda-expr enumerator) (do ((result '()) (done nil)) (done (nreverse result)) (multiple-value-bind (val ind) (funcall enumerator) (if ind (push (funcall lambda-expr val) result) (setq done t))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; UNIX PATHNAMES (defun basename (unix-path) " UNIX-PATH: A STRING CONTAINING A UNIX PATH. RETURN: THE BASENAME, THAT IS, THE LAST COMPONENT OF THE PATH. TRAILING '/'S ARE REMOVED FIRST. " (do* ((end (do ((end (1- (length unix-path)) (1- end))) ((or (< end 0) (char/= (character "/") (char unix-path end))) (1+ end)))) (start (1- end) (1- start))) ((or (< start 0) (char= (character "/") (char unix-path start))) (subseq unix-path (1+ start) end)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; XSI: (defun unix-fs-node-name (node) ;; --> NAME (declare (ignore node))) (defun unix-fs-node-kind (node) (declare (ignore node))) (defun unix-fs-node-directory-path (node) ;; --> "/DIR/PATH" (declare (ignore node))) (defun unix-fs-node-path (node) ;; --> /DIR/PATH/NAME (declare (ignore node))) (defun logical-pathname-namestring-p (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun parse-logical-pathname-namestring (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun parse-unix-pathname-namestring (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun safe-make-pathname (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun safe-directory (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun make-volumes (root-dir) (let ((root-apath ;; TODO: WHAT IF NOT UNIX? (if (logical-pathname-namestring-p root-dir) (parse-logical-pathname-namestring root-dir) (parse-unix-pathname-namestring root-dir))) pathspec) (when (eq :error root-apath) (error "BAD PATHNAME ~S." root-dir)) (setq pathspec (safe-make-pathname :host (aget root-apath :host) :device (aget root-apath :device) :directory (append (aget root-apath :directory) (list :wild-inferiors)) :name :wild :type :wild :version nil :case :common)) (format t "PATHSPEC=~S~%" pathspec) (safe-directory pathspec))) #|| (LOAD "PACKAGES:COM;INFORMATIMAGO;ENCOURS;MAKE-VOLUMES") (IN-PACKAGE "COM.INFORMATIMAGO.CLISP.MAKE-VOLUMES") (MAKE-VOLUMES "/tmp/") ||# ;;;; THE END ;;;;
7,066
Common Lisp
.lisp
171
35.695906
118
0.585835
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9c400abf40b0fec1fb565faf5d57283495056fd2442bba9d79b7798905838900
4,808
[ -1 ]
4,809
script.lisp
informatimago_lisp/clisp/script.lisp
;;;; -*- coding:utf-8 -*- ;;;;***************************************************************************** ;;;;FILE: script.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: clisp ;;;;USER-INTERFACE: clisp ;;;;DESCRIPTION ;;;; ;;;; This module exports some functions usefull when writting clisp scripts. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2003-01-29 <PJB> Creation. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;***************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "SYS" "EXT")) (defpackage "COM.INFORMATIMAGO.CLISP.SCRIPT" (:documentation "This package exports script functions.") (:use "COMMON-LISP" "COM.INFORMATIMAGO.CLISP.STRING") (:export "INITIALIZE" "PERROR" "PMESSAGE" "PQUERY" "*INITIAL-WORKING-DIRECTORY*" "IS-RUNNING" "*PATH*" "*NAME*" "*ARGUMENTS*" "*TESTING*" "PID" "SHELL" "SHELL-QUOTE-ARGUMENT" "EXECUTE" "MAKE-DIRECTORY" "MAKE-SYMBOLIC-LINK" "COPY-FILE" "EXIT" "EX-OK" "EX--BASE" "EX-USAGE" "EX-DATAERR" "EX-NOINPUT" "EX-NOUSER" "EX-NOHOST" "EX-UNAVAILABLE" "EX-SOFTWARE" "EX-OSERR" "EX-OSFILE" "EX-CANTCREAT" "EX-IOERR" "EX-TEMPFAIL" "EX-PROTOCOL" "EX-NOPERM" "EX-CONFIG" "EX--MAX" )) (in-package "COM.INFORMATIMAGO.CLISP.SCRIPT") ;; egrep '([d]efun' pjb-script.lisp | sed -e 's/(defun/;;/' | sort ;;---------------------------------------------------------------------- (defparameter *initial-working-directory* nil " The path to the initial working directory. BUG: This is the value of (EXT:CD) when INITIALIZE is called. ") (defparameter *path* nil " The *path* of the script. Possibly this is not the absolute *path*, but only a relative *path* from the INITIAL-WORKING-DIRECTORY. BUG: This is the value of *LOAD-PATHNAME* when INITIALIZE is called. ") (defparameter *name* nil " The name of the script. BUG: It's derived from the value of *LOAD-PATHNAME* when INITIALIZE is called. ") (defparameter *arguments* ext:*args* " The list of strings containing the arguments passed to the script. ") (defparameter *testing* nil " Whether we're only testing the script. In this package, this will make END-WITH-STATUS THROW :EXIT instead of exiting. NOTE: This variable can be set by the client script (for example, from a --test option). ") (defun initialize () " DO: Initialize this package. This function MUST be called from the script itself to get the correct PNAME. " (setq *initial-working-directory* (ext:cd) *path* *load-pathname* *name* (file-namestring *load-pathname*) *arguments* (copy-seq ext:*args*))) (defun perror (format-string &rest args) " DO: Writes a message on the error output in the name of the script. " (format *error-output* "~&~A: " *name*) (apply (function format) *error-output* format-string args) (finish-output *error-output*)) (defun pmessage (format-string &rest args) " DO: Writes a message on the standard output in the name of the script. " (format *standard-output* "~&~A: " *name*) (apply (function format) *standard-output* format-string args) (finish-output *standard-output*)) (defun pquery (format-string &rest args) " DO: Writes a message on the query I/O in the name of the script, and read a response line. RETURN: A string containing the response line. " (format *query-io* "~&~A: " *name*) (apply (function format) *query-io* format-string args) (finish-output *query-io*) (read-line *query-io*)) ;; Awfull trick for pjb-script:is-running; put this in ~/.clisprc.lisp ;; (DEFUN EXECUTABLE-READER (A B C) (SYS::UNIX-EXECUTABLE-READER A B C)) ;; (SET-DISPATCH-MACRO-CHARACTER #\# #\! #EXECUTABLE-READER) (defun is-running () " RETURN: Whether we're running as a script. (Otherwise, we're just loading). " (eq (get-dispatch-macro-character #\# #\!) #'sys::unix-executable-reader)) (defun pid () (linux:|getpid|)) (defun shell-quote-argument (argument) " DO: Quote an argument for passing as argument to an inferior shell. RETURN: A string containing the quoted argument. " (do ((i 0 (1+ i)) (ch) (result '())) ((<= (length argument) i) (coerce (nreverse result) 'string)) (setq ch (char argument i)) (unless (or (char= (character "-") ch) (char= (character ".") ch) (char= (character "/") ch) (and (char<= (character "A") ch) (char<= ch (character "Z"))) (and (char<= (character "a") ch) (char<= ch (character "z"))) (and (char<= (character "0") ch) (char<= ch (character "9")))) (push (character "\\") result)) (push ch result))) (defun shell (command) " SEE ALSO: EXECUTE. " (ext:shell command)) (defun execute (&rest command) " RETURN: The status returned by the command. SEE ALSO: SHELL " (ext:run-program (car command) :arguments (cdr command) :input :terminal :output :terminal)) (defun copy-file (file newname &optional ok-if-already-exists keep-time) " IMPLEMENTATION: The optional argument is not implemented. Copy FILE to NEWNAME. Both args must be strings. If NEWNAME names a directory, copy FILE there. Signals a `file-already-exists' error if file NEWNAME already exists, unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil. A number as third arg means request confirmation if NEWNAME already exists. This is what happens in interactive use with M-x. Fourth arg KEEP-TIME non-nil means give the new file the same last-modified time as the old one. (This works on only some systems.) A prefix arg makes KEEP-TIME non-nil. " (declare (ignore ok-if-already-exists keep-time)) (execute "cp" (shell-quote-argument file) (shell-quote-argument newname))) (defun make-symbolic-link (filename linkname &optional ok-if-already-exists) " IMPLEMENTATION: The optional argument is not implemented. Make a symbolic link to FILENAME, named LINKNAME. Both args strings. Signals a `file-already-exists' error if a file LINKNAME already exists unless optional third argument OK-IF-ALREADY-EXISTS is non-nil. A number as third arg means request confirmation if LINKNAME already exists. " (declare (ignore ok-if-already-exists)) (/= 0 (linux:|symlink| filename linkname))) (defun make-directory (*path* &optional (parents nil)) " Create the directory *PATH* and any optionally nonexistent parents dirs. The second (optional) argument PARENTS says whether to create parents directories if they don't exist. " (if parents (ensure-directories-exist (concatenate 'string *path* "/.") :verbose nil) (linux:|mkdir| *path* 511 #| #o777 |# )) (ext:probe-directory (if (char= (char *path* (1- (length *path*))) (character "/")) *path* (concatenate 'string *path* "/")))) ;; From /usr/include/sysexists.h (Linux) (defconstant ex-ok 0 "successful termination") (defconstant ex--base 64 "base value for error messages") (defconstant ex-usage 64 "command line usage error The command was used incorrectly, e.g., with the wrong number of arguments, a bad flag, a bad syntax in a parameter, or whatever.") (defconstant ex-dataerr 65 "data format error The input data was incorrect in some way. This should only be used for user's data & not system files.") (defconstant ex-noinput 66 "cannot open input An input file (not a system file) did not exist or was not readable. This could also include errors like \"No message\" to a mailer (if it cared to catch it).") (defconstant ex-nouser 67 "addressee unknown The user specified did not exist. This might be used for mail addresses or remote logins. ") (defconstant ex-nohost 68 "host name unknown The host specified did not exist. This is used in mail addresses or network requests.") (defconstant ex-unavailable 69 "service unavailable A service is unavailable. This can occur if a support program or file does not exist. This can also be used as a catchall message when something you wanted to do doesn't work, but you don't know why.") (defconstant ex-software 70 "internal software error An internal software error has been detected. This should be limited to non-operating system related errors as possible.") (defconstant ex-oserr 71 "system error (e.g., can't fork) An operating system error has been detected. This is intended to be used for such things as \"cannot fork\", \"cannot create pipe\", or the like. It includes things like getuid returning a user that does not exist in the passwd file.") (defconstant ex-osfile 72 "critical OS file missing Some system file (e.g., /etc/passwd, /etc/utmp, etc.) does not exist, cannot be opened, or has some sort of error (e.g., syntax error).") (defconstant ex-cantcreat 73 "can't create (user) output file A (user specified) output file cannot be created.") (defconstant ex-ioerr 74 "input/output error An error occurred while doing I/O on some file.") (defconstant ex-tempfail 75 "temp failure; user is invited to retry temporary failure, indicating something that is not really an error. In sendmail, this means that a mailer (e.g.) could not create a connection, and the request should be reattempted later.") (defconstant ex-protocol 76 "remote error in protocol the remote system returned something that was \"not possible\" during a protocol exchange.") (defconstant ex-noperm 77 "permission denied You did not have sufficient permission to perform the operation. This is not intended for file system problems, which should use NOINPUT or CANTCREAT, but rather for higher level permissions.") (defconstant ex-config 78 "configuration error") (defconstant ex--max 78 "maximum listed value") (defun exit (&optional (status 0)) " DO: Exit the script. If we are testing, then use throw to jump back to the caller. " (when (is-running) (if *testing* (throw :exit status) (ext:exit status)))) ;; when loading, we don't exit, could we? ;;;; THE END ;;;;
11,470
Common Lisp
.lisp
269
38.836431
83
0.671072
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bafcfe6286e074465c0a49c832757ad32f6acf70f2d6e13e1cdd03c9761f9739
4,809
[ -1 ]
4,810
shell.lisp
informatimago_lisp/clisp/shell.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: shell.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: clisp ;;;;USER-INTERFACE: clisp ;;;;DESCRIPTION ;;;; ;;;; This package export shell primitives (fork, pipe, redirections, exec). ;;;; ;;;;USAGE ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2002-12-10 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2002 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "FFI" "LINUX")) (eval-when (:compile-toplevel :load-toplevel :execute) (require "linux")) (defpackage "COM.INFORMATIMAGO.CLISP.SHELL" (:documentation "This package export shell primitives (fork, pipe, redirections, exec).") (:use "COMMON-LISP") (:export ;; variables: "*TEMPORARY-PATHNAME*" ;; pathname of the temporary directory. ;; macro API: "EXECL" "PIPE-AND-EXEC" "PIPE" "FORK" "WAIT" ;; low-level: "PIPE-AND-EXEC-FUN")) (in-package "COM.INFORMATIMAGO.CLISP.SHELL") (defvar *temporary-pathname* "/tmp" "A path to a temporary directory.") ;;; ;; DEF-C-CALL-OUT is deprecated, use FFI:DEF-CALL-OUT instead ;;; ;; *** - FFI::LOOKUP-FOREIGN-FUNCTION: A foreign function "execv" does not exist ;;; ;;(FFI:DEFAULT-FOREIGN-LANGUAGE :STDC) ;;; ;; From the Solaris 2.5 and the Linux manpage: ;;; ;; execve is the "primitive" syscall. ;;; (FFI:DEF-CALL-OUT EXECVE ;;; (:ARGUMENTS (PATH C-STRING) ;;; (ARGV (C-ARRAY-PTR C-STRING)) ;;; (ENVP (C-ARRAY-PTR C-STRING))) ;;; (:RETURN-TYPE INT) ;;; (:NAME "execve") ;;; (:LANGUAGE :STDC) ;;; );;EXECVE ;;; ;; execv and execvp are based on execve. ;;; (FFI:DEF-CALL-OUT EXECV ;;; (:ARGUMENTS (PATH C-STRING) (ARGV (C-ARRAY-PTR C-STRING))) ;;; (:RETURN-TYPE INT) ;;; (:NAME "execv") ;;; (:LANGUAGE :STDC) ;;; );;EXECV ;;; (FFI:DEF-CALL-OUT EXECVP ;;; (:ARGUMENTS (FILE C-STRING) (ARGV (C-ARRAY-PTR C-STRING))) ;;; (:RETURN-TYPE INT) ;;; (:NAME "execvp") ;;; (:LANGUAGE :STDC) ;;; );;EXECVP ;;; (DEFUN EXECL (PATH &REST ARGS) ;;; " ;;; DO: Execute the program at path, passing the arguments argv. ;;; EXAMPLE: (execl \"/bin/ls\" \"ls\" \"-l\" \"-F\" \"/tmp\") ;;; PRE: (<= 1 (length argv)) ;;; NOTE: Usually doesn't return! ;;; The current process image is replaced by the executed program. ;;; " ;;; (EXECV PATH (APPLY #'VECTOR ARGS)) ;;; );;EXECL (defmacro execl (path &rest argv) " DO: Execute the program at path, passing the arguments argv. EXAMPLE: (execl \"/bin/ls\" \"ls\" \"-l\" \"-F\" \"/tmp\") PRE: (<= 1 (length argv)) NOTE: Doesn't return! The current process image is replaced by the executed program. " (let* ((argc (1- (length argv))) (exec (intern (with-standard-io-syntax (format nil "EXECL~D" argc))))) (if (fboundp exec) `(,exec ,path ,@argv nil) `(progn (ffi:def-call-out ,exec (:language :stdc) (:arguments (path ffi:c-string) ,@(do ((i 0 (1+ i)) (arguments nil (cons (list (intern (with-standard-io-syntax (format nil "ARGV~D" i))) 'ffi:c-string) arguments)) ) ((< argc i) (nreverse arguments))) (null ffi:c-string)) (:return-type ffi:int) (:name "execl")) (,exec ,path ,@argv nil))))) ;; ------------- ;; pipe-and-exec ;; ------------- (defun check-process-list (process-list) "PRIVATE. DO: Checks and evaluates the process-list. RETURN: An evaluated process-list. " (mapcar (lambda (process) (cond ((atom process) (error "Invalid process ~S." process)) ((not (keywordp (car process))) (error "Invalid tag for process ~S." process)) ((eq :begin (cadr process)) process) (t (cons (car process) (mapcar (lambda (item) (if (stringp item) item (format nil "~A" (eval item)))) (cdr process)))))) process-list)) (defun check-process-tag (process-list tag) "PRIVATE. DO: Check the process tag. " (unless (member tag process-list :test (function eq) :key (function car)) (error "Tag ~S is not in the process-list." tag))) (defun check-process-fdes (process-list process-fdes &optional triplet) "PRIVATE. DO: Checks and evaluates the process fdes. RETURN: An evaluated process-fdes. " (when (atom process-fdes) (error "Invalid file descriptor specification ~S (must be a list)." process-fdes)) (let ((tag (car process-fdes))) (check-process-tag process-list tag) (cond ((= 2 (length process-fdes)) (when triplet (error "Invalid file descriptor specification ~S (must have 3 elements)." process-fdes)) (let ((fdes (nth 1 process-fdes))) (unless (integerp fdes) (setq fdes (eval fdes))) (unless (integerp fdes) (error "Invalid file descriptor specification ~S (~S should evaluate to an integer)." process-fdes (nth 1 process-fdes))) (list tag fdes))) ((= 3 (length process-fdes)) (unless triplet (error "Invalid file descriptor specification ~S (must have 2 elements)." process-fdes)) (let ((fdes1 (nth 1 process-fdes)) (fdes2 (nth 2 process-fdes))) (unless (integerp fdes1) (setq fdes1 (eval fdes1))) (unless (integerp fdes1) (error "Invalid file descriptor specification ~S (~S should evaluate to an integer)." process-fdes (nth 1 process-fdes))) (unless (integerp fdes2) (setq fdes2 (eval fdes2))) (unless (integerp fdes2) (error "Invalid file descriptor specification ~S (~S should evaluate to an integer)." process-fdes (nth 2 process-fdes))) (list tag fdes1 fdes2))) (t (error "Invalid file descriptor specification ~S (must have ~D elements)." process-fdes (if triplet 3 2)))))) (defun check-edge-list (process-list edge-list) "PRIVATE. DO: Checks the syntax of the edge-list and evalutes file names and descriptors. Issue error calls. RETURN: A canonized edge-list. EDGE-LIST: specifies the pipe and input or output as: pipe ((process-tag fdes) (process-tag fdes)) --> (pipe (process-tag fdes) (process-tag fdes)) input-file ((file file-name) (process-tag fdes)) --> (input (file file-name) (process-tag fdes)) input-file (file-name (process-tag fdes)) --> (input (file file-name) (process-tag fdes)) input-data ((data data-form) (process-tag fdes)) --> (data data-form (process-tag fdes)) output-file ((process-tag fdes) (file file-name)) --> (output (process-tag fdes) (file file-name)) output-file ((process-tag fdes) file-name) --> (output (process-tag fdes) (file file-name)) append-file ((process-tag fdes) (file file-name :append)) --> (output (process-tag fdes) (file file-name :append)) close-fdes (close (process-tag fdes)...) dup2-fdes (dup2 (process-tag tfdes sfdes)...) " (mapcar (lambda (edge) (cond ((atom edge) (error "An edge must be a list, not ~S." edge)) ;; ------------ ;; a close edge ;; ------------ ((eq :close (car edge)) (cons :close (mapcar (lambda (pf) (check-process-fdes process-list pf nil)) (cdr edge))) ) ;; ----------- ;; a dup2 edge ;; ----------- ((eq :duplicate (car edge)) (cons :duplicate (mapc (lambda (pf) (check-process-fdes process-list pf t)) (cdr edge)))) ((/= 2 (length edge)) (error "Invalid edge ~S (must have two nodes)." edge)) ;; ----------- ;; a data edge ;; ----------- ((and (consp (car edge)) (eq :data (caar edge))) (unless (= 2 (length (car edge))) (error "Invalid data node ~S. Expected (:data form)." (car edge))) (check-process-fdes process-list (cadr edge)) (list :data (cadar edge) (check-process-fdes process-list (cadr edge))) ) ;; ----------------- ;; a file input edge ;; ----------------- ((stringp (car edge)) (list :input (list :file (car edge)) (check-process-fdes process-list (cadr edge))) ) ((and (consp (car edge)) (eq :file (caar edge))) (unless (= 2 (length (car edge))) (error "Invalid input file specification ~S. Expected (:FILE fname)." (car edge))) (let ((fname (cadar edge)) ) (setq fname (if (stringp fname) fname (format nil "~A" (eval fname)))) (list :input (list :file fname) (check-process-fdes process-list (cadr edge))))) ;; ---------------------------- ;; a file output or append edge ;; ---------------------------- ((stringp (cadr edge)) (list :output (check-process-fdes process-list (car edge)) (list :file (cadr edge)))) ((and (consp (cadr edge)) (eq :file (caadr edge))) (unless (or (= 2 (length (cadr edge))) (and (= 3 (length (cadr edge))) (eq :append (nth 2 (cadr edge))))) (error (concatenate 'string "Invalid output file specification ~S. " "Expected (LFILE fname [:APPEND]).") (cadr edge))) (let ((fname (cadar edge)) (append (member :append (cadr edge) :test (function eq))) ) (setq fname (if (stringp fname) fname (format nil "~A" (eval fname)))) (list :output (check-process-fdes process-list (car edge)) (if append (list :file fname :append) (list :file fname))))) ;; ----------- ;; a pipe edge ;; ----------- ((and (consp (nth 0 edge)) (consp (nth 1 edge))) (list :pipe (check-process-fdes process-list (nth 0 edge)) (check-process-fdes process-list (nth 1 edge)))) ;; ----------- ;; other edges ;; ----------- (t (error "Invalid edge ~S." edge)) )) edge-list)) (defun create-datafiles-and-pipes (edge-list) "PRIVATE. " ;; pre-process edge-list: ;; 0. input-data must be evaluated and written to temporary files. ;; 1. create all the pipes ;; ;; (data data-form (process-tag fdes)) ;; --> (data data-fdes data-fpath (process-tag fdes)) ;; mkstemp returns an open file descriptor and the file name. ;; We reopen the file as input only before deleting it. ;; ;; (pipe (process-tag fdes) (process-tag fdes)) ;; --> (pipe in-fdes out-fdes (process-tag fdes) (process-tag fdes)) ;; (mapcar (lambda (edge) (cond ;; ------------------------------- ;; ;; create the temporary file ;; data: mkstemp;open;write;open;unlink;close ((eq :data (car edge)) (multiple-value-bind (fdesc fpath) (linux:|mkstemp| (format nil "~a/lisp-inline-data-XXXXXX" *temporary-pathname*)) (when (< fdesc 0) (error "LINUX:mkstemp reported error errno=~a." linux::|errno|)) ;; fill the temporary file (with-open-file (data fpath :direction :output :if-exists :overwrite :if-does-not-exist :create) (format nil "~A" (nth 1 edge))) (prog1 (list :data (linux:|open| fpath linux:|O_RDONLY| 0) fpath (nth 2 edge)) ;; close and delete the temporary file (we keep an input fd). (delete-file fpath) (linux:|close| fdesc)))) ;; ------------------------------- ;; ;; create the pipe ;; pipe: pipe ((eq :pipe (car edge)) (multiple-value-bind (result fdescs) (linux:|pipe|) (when (/= 0 result) (error "LINUX:pipe returned ~S." result)) (cons :pipe (cons (aref fdescs 0) (cons (aref fdescs 1) (cdr edge)))))) ;; ------------------------------- ;; ;; don't do anything. (t edge))) edge-list)) (defun prepare-fd (process edge-list) "PRIVATE. NOTE: called in the child process `PROCESS'. DO: open files, assign pipe descriptors, close file descriptors, dup2 file descriptors, etc, following edge-list instructions, for the given process. " ;; 3. in each child in the order specified, ;; 3.1. open the file, or ;; 3.2. assign the pipe descriptor, or ;; 3.3. close the file descriptor, or ;; 3.4. dup2 the file decriptor. (let ((tag (car process))) (mapc (lambda (edge) (cond ;; ---------------------------------------- ;; ;; (:data ddes dname (:tag fdes)) ((and (eq :data (car edge)) (eq tag (car (nth 3 edge)) )) (let* ((ddes (nth 1 edge)) (fdes (cadr (nth 3 edge))) ) (when (/= ddes fdes) (linux:|dup2| ddes fdes) (linux:|close| ddes)))) ;; "inline" data file. ;; ---------------------------------------- ;; ;; (:input (file fname) (:tag fdes)) ((and (eq :input (car edge)) (eq (car (nth 2 edge)) tag)) (let* ((fname (cadr (nth 1 edge))) (fdes (cadr (nth 2 edge))) (odes (linux:|open| fname linux:|O_RDONLY| 0)) ) (when (< odes 0) (error "Can't open ~S for reading." fname)) (when (/= odes fdes) (linux:|dup2| odes fdes) (linux:|close| odes)))) ;; input data file ;; ---------------------------------------- ;; ;; (:output (:tag fdes) (file fname [:append])) ((and (eq :output (car edge)) (eq (car (nth 1 edge)) tag)) (let* ((fdes (cadr (nth 1 edge))) (fname (cadr (nth 2 edge))) (append (member :append (nth 2 edge) :test (function eq))) (odes (linux:|open| fname (+ linux:|O_WRONLY| linux:|O_CREAT| (if append linux:|O_APPEND| linux:|O_TRUNC|)) 438)) ) (when (< odes 0) (error "Can't open ~S for writting." fname)) (when (/= odes fdes) (linux:|dup2| odes fdes) (linux:|close| odes)))) ;; output data file ;; ---------------------------------------- ;; ;; (:pipe ifdes ofdes (:tag fdes) (:tag fdes)) output pipe ((and (eq :pipe (car edge)) (eq tag (car (nth 3 edge)))) (let* ((ifdes (nth 1 edge)) (ofdes (nth 2 edge)) (fdes (cadr (nth 3 edge)))) (when (/= ofdes fdes) (linux:|dup2| ofdes fdes) (linux:|close| ifdes) (linux:|close| ofdes)))) ;; output pipe ;; ---------------------------------------- ;; ;; (:pipe ifdes ofdes (:tag fdes) (:tag fdes)) input pipe ((and (eq :pipe (car edge) ) (eq tag (car (nth 4 edge)) )) (let* ((ifdes (nth 1 edge)) (ofdes (nth 2 edge)) (fdes (cadr (nth 4 edge)))) (when (/= ifdes fdes) (linux:|dup2| ifdes fdes) (linux:|close| ifdes) (linux:|close| ofdes)))) ;; input pipe ;; ---------------------------------------- ;; ;; (:close (:tag fdes)...) ((eq :close (car edge)) (mapc (lambda (tag-fdes) (when (eq (car tag-fdes) tag) (linux:|close| (cadr tag-fdes)))) (cdr edge))) ;; ---------------------------------------- ;; ;; (:duplicate (:tag dfdes sfdes)...) ((eq :duplicate (car edge)) (mapc (lambda (tag-d-s) (when (eq (car tag-d-s) tag) (let ((dst (nth 1 tag-d-s)) (src (nth 2 tag-d-s))) (linux:|dup2| src dst) ;; we don't close the src, we leave that to the client. ))) (cdr edge))) ;; ---------------------------------------- ;; (t (error "Unknown edge type ~S." edge)))) edge-list))) (defun pipe-and-exec (process-list edge-list &key wait) " RETURN: NOT UP TO DATE a list of processes (:tag status :begin form...) or (:tag status program arg...) for the processes that could be run, and of the form: (nil :tag :begin form...) or (nil :tag program arg...) for the processes that could not be forked. PROCESS-LIST: each process is specified as a list (:tag :begin form...) or (:tag program arg...). EDGE-LIST: specifies the pipe and input or output as: pipe ((process-tag fdes) (process-tag fdes)) input-file ((:file file-name) (process-tag fdes)) input-file (\"file-name\" (process-tag fdes)) input-data ((:data data-expr) (process-tag fdes)) output-file ((process-tag fdes) (file file-name)) output-file ((process-tag fdes) \"file-name\") append-file ((process-tag fdes) (file file-name :append)) close-fdes (:close (process-tag fdes)...) dup2-fdes (:duplicate (process-tag tfdes sfdes)...) file-name can be an expression only inside a (:file ...) In abreviated form, it must be a string literal. fdes can be expressions. program and arg, as well as data and file-name in the case it's encapsulated into a (file ...) will be evaluated once more (can be forms). Expressions in edge-list or in process-list are evaluated, except the forms in (:tag begin form...) wich are evaluated in the forked child process, and the data-expr in (data data-expr) which is evaluated in the result of this macro (in pipe-and-exec-fun). " ;; 0. input-data must be evaluated and written to temporary files. ;; 1. create all the pipes ;; 2. fork the processes. ;; 3. in each child in the order specified, ;; 3.1. open the file, or ;; 3.2. assign the pipe descriptor, or ;; 3.3. close the file descriptor, or ;; 3.4. dup2 the file decriptor. ;; 4. exec the program or run the lisp form, then exit. ;; 5. in parent, close the pipes ;; 6. in parent, wait for all the children. ;; ;; check the syntax, and evalutate process-list: (setq process-list (check-process-list process-list)) ;; check the syntax, and evaluate edge-list and canonize: (setq edge-list (check-edge-list process-list edge-list)) ;; 0. input-data must be evaluated and written to temporary files. ;; 1. create all the pipes (setq edge-list (create-datafiles-and-pipes edge-list)) ;; 2. fork the processes. (setq process-list (mapcar (lambda (process) (let ((pid (linux:|fork|))) (cond ((< pid 0) ;; --------------------------------------------- error ;; TODO: We should keep the errno along with the process. (list :fork-success nil :fork-errno linux::|errno| :process process)) ((= pid 0) ;; --------------------------------------------- child ;; 3. in each child in the order specified, ;; 3.1. open the file, or ;; 3.2. assign the pipe descriptor, or ;; 3.3. close the file descriptor, or ;; 3.4. dup2 the file decriptor. (let ((status 69)) ;; EX_UNAVAILABLE (unwind-protect (progn (prepare-fd process edge-list) ;; 4. exec the program or run the lisp form, then exit. (if (eq :begin (nth 1 process)) ;; lisp form (setq status (eval (cons 'progn (cddr process)))) ;; program process (eval (cons 'execl (cons (nth 1 process) (cdr process)))) )) ;; no clean up ) (ext:exit status))) (t ;; --------------------------------------------- parent (list :fork-success t :child-pid pid :process process)) ) ;;COND )) ;;LAMBDA process-list)) ;; 5. in parent, close the pipes (mapc (lambda (edge) (cond ((eq :data (car edge)) (linux:|close| (nth 1 edge))) ;; input fd we kept. ((eq :pipe (car edge)) (let* ((p1 (nth 1 edge)) (p2 (nth 2 edge))) (linux:|close| p1) (linux:|close| p2))) ;; pipe open in parent, used by children. )) ;;LAMBDA edge-list) (when wait ;; 6. wait for all the children. (do ((child-count (do* ((processes process-list (cdr processes)) (count 0) ) ((null processes) count) (setq count (if (getf (car processes) :fork-success) (1+ count) count)))) ) ((= 0 child-count)) (multiple-value-bind (pid status) (linux:|wait|) (when (< 0 pid) (let* ((process-place (member pid process-list :key (lambda (process) (getf process :child-pid)))) (process (car process-place))) (when process (setf (getf process :child-status) status) (setf (car process-place) process) (setq child-count (1- child-count)))))))) process-list) (defun pipe (process-list &key wait) (let ((tag-num 0)) (setq process-list (mapcar (lambda (process) (setq tag-num (1+ tag-num)) (cons (intern (with-standard-io-syntax (format nil "PROCESS-~A" tag-num)) (find-package "KEYWORD")) process)) process-list)) (pipe-and-exec process-list (do ((previous (caar process-list) (caar process)) (process (cdr process-list) (cdr process)) (edges nil (cons (list (list previous 1) (list (caar process) 0)) edges))) ((null process) (nreverse edges))) :wait wait))) ;;; ;; pipe ((process-tag fdes) (process-tag fdes)) ;;; ;; input-file ((< file-name) (process-tag fdes)) ;;; ;; input-data ((<< data) (process-tag fdes)) ;;; ;; output-file ((process-tag fdes) (> file-name)) ;;; ;; append-file ((process-tag fdes) (>> file-name)) ;;; ;; close-fdes (- process-tag fdes) ;;; ;; dup2-fdes (= process-tag tfdes sfdes) ;;; ;; pipe ((process-tag fdes) (process-tag fdes)) ;;; ;; input-file ((< file-name) (process-tag fdes)) ;;; ;; input-data ((<< data) (process-tag fdes)) ;;; data: mkstemp;open;write;open;unlink;close ;;; ;; output-file ((process-tag fdes) (> file-name)) ;;; ;; append-file ((process-tag fdes) (>> file-name)) ;;; ;; close-fdes (- process-tag fdes) ;;; ;; dup2-fdes (= process-tag tfdes sfdes) ;;; '( ;;; ((:pass 1) (:gpg 6)) ;;; ((:tar 1) (:gpg 0)) ;;; ((:gpg 1) (> "root-0.tar.bz2.gpg")) ;;; ((< "/dev/null") (:tar 0)) ;;; ((< "/dev/null") (:pass 0)) ;;; ) ;;; ;; pipe (\| (process-tag fdes) (process-tag fdes)) ;;; ;; input-file (< file-name (process-tag fdes)) ;;; ;; input-data (<< data (process-tag fdes)) ;;; ;; output-file (> (process-tag fdes) file-name) ;;; ;; append-file (>> (process-tag fdes) file-name) ;;; ;; close-fdes (- (process-tag fdes)...) ;;; ;; dup2-fdes (= (process-tag tfdes sfdes)...) ;;; '( ;;; (\| (:pass 1) (:gpg 6)) ;;; (<< password (:gpg 6)) ;;; (\| (:tar 1) (:gpg 0)) ;;; (> (:gpg 1) "root-0.tar.bz2.gpg") ;;; (>> (:tar 2) "errors") ;;; (>> (:gpg 2) "errors") ;;; (- (:tar 0) (:pass 0)) ;;; (= (:pass 2 3) (:gpg 2 3)) ;;; ) ;;; ;; pipe ((process-tag fdes) (process-tag fdes)) ;;; ;; input-file (file-name (process-tag fdes)) ;;; ;; input-data ((:data data) (process-tag fdes)) ;;; ;; output-file ((process-tag fdes) file-name) ;;; ;; append-file ((process-tag fdes) file-name :append) ;;; ;; close-fdes (:close (process-tag fdes)...) ;;; ;; dup2-fdes (:duplicate (process-tag tfdes sfdes)...) ;;; '( ;;; ((:pass 1) (:gpg 6)) ;;; ((data password) (:gpg 6)) ;;; ((:tar 1) (:gpg 0)) ;;; ((:gpg 1) "root-0.tar.bz2.gpg") ;;; ((:tar 2) "errors" :append) ;;; ((:gpg 2) "errors" :append) ;;; (close (:tar 0) (:pass 0)) ;;; (dup (:pass 2 3) (:gpg 2 3)) ;;; ) (defun fork (body-fun) " RETURN: pid of child in parent ; never in child (exit with result of body-fun as status). " (let ((pid (linux:|fork|))) (if (= 0 pid) ;; child (let ((result (funcall body-fun))) (ext:exit (cond ((numberp result) (logand 255 result)) ((null result) 1) ((eq t result) 0) (t 0)))) ;; parent pid))) (defun wait (pid) " RETURN: pid;status " (linux:|waitpid| pid 0)) ; options: (LOGIOR LINUX:WNOHANG LINUX:WUNTRACED) ;; epf ::= ( pf redir1 ... redirn ) ;; ;; pf ::= ;; (begin . scheme-code) ; Run scheme-code in a fork. ;; (| pf1 ... pfn) ; Simple pipeline ;; (|+ connect-list pf1 ... pfn) ; Complex pipeline ;; (epf . epf) ; An extended process form. ;; (pgm arg1 ... argn) ; Default: exec the program. ;; ;; pf ::= ;; (begin . common-lisp-code) ; Run common-lisp-code in a fork. ;; (pipe pf1 ... pfn) ; Simple pipeline ;; (pipe+ connect-list pf1 ... pfn) ; Complex pipeline ;; (epf . epf) ; An extended process form. ;; (pgm arg1 ... argn) ; Default: exec the program. ;; ;; connect-list ::= ((from1 from2 ... to) ...) ;; ;; redir ::= ;; (< [fdes] file-name) Open file for read. ;; (> [fdes] file-name) Open file create/truncate. ;; (<< [fdes] object) Use object's printed rep. ;; (>> [fdes] file-name) Open file for append. ;; (= fdes fdes/port) Dup2 ;; (- fdes/port) Close fdes/port. ;; stdports 0,1,2 dup'd from standard ports. ;; For redirection we can implement two cases: ;; - it's an external file redirection, ;; then we open the file and put it in the wanted fdes. ;; the file can be closed once forked. ;; ;; - it's an internal data source or sink (<< [fdes] object), (begin cl-code) ;; then we open a pipe and put it in the wanted fdes. ;; These pipes associated with their stream should then be handled ;; in lisp... (defmacro exec-path (&rest command) (when (/= 1 (length command)) (signal 'wrong-number-of-arguments 'exec-path (length command))) (setq command (mapcar (lambda (item) (cond ((symbolp item) (setq item (symbol-name item)) (let ((utem (string-upcase item))) ;;(SHOW UTEM ITEM) (if (string= utem item) (string-downcase item) item))) (t (format nil "~a" item)))) (car command))) `(ext:run-program ,(car command) :arguments (quote ,(cdr command)) :input :terminal :output :terminal :if-output-exists :overwrite :wait t)) (defmacro exec-epf (&rest epf) (let ((pf (car epf)) (redirections (cdr epf)) ) (declare (ignore pf redirections)) (error "NOT IMPLEMENTED YET") `( ,@(car epf) ))) (defmacro & (&rest epf) `(fork (lambda () (exec-epf ,@epf)))) (defmacro run (&rest epf) `(wait (& ,@epf))) (defmacro or-else (&rest pf-list) (declare (ignore pf-list)) (error "NOT IMPLEMENTED YET")) (defmacro and-then (&rest pf-list) (declare (ignore pf-list)) (error "NOT IMPLEMENTED YET")) ;;;; THE END ;;;;
31,108
Common Lisp
.lisp
738
32.666667
132
0.494683
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2f36397fe6c29d873de3970f89626edcd5a19249d0d38051163e559e5a6d9e02
4,810
[ -1 ]
4,811
syslog.lisp
informatimago_lisp/clisp/syslog.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: syslog.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; FFI to syslog. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-04-19 <PJB> Made use of slave logger processes. ;;;; 2003-08-31 <PJB> Created. ;;;;BUGS ;;;; Not implemented as FFI, we're using the external program logger(1) ;;;; in the mean time. ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.SYSLOG" (:documentation "This module exports unix syslog functions. Since FFI is not always available with clisp, we rather use logger(1).") (:use "COMMON-LISP") (:export "OPENLOG" "SYSLOG" "CLOSELOG" "+LOG-PID+" "+LOG-CONS+" "+LOG-ODELAY+" "+LOG-NDELAY+" "+LOG-NOWAIT+" "+LOG-PERROR+" "+LOG-EMERG+" "+LOG-ALERT+" "+LOG-CRIT+" "+LOG-ERR+" "+LOG-WARNING+" "+LOG-NOTICE+" "+LOG-INFO+" "+LOG-DEBUG+" "+LOG-KERN+" "+LOG-USER+" "+LOG-MAIL+" "+LOG-DAEMON+" "+LOG-AUTH+" "+LOG-SYSLOG+" "+LOG-LPR+" "+LOG-NEWS+" "+LOG-UUCP+" "+LOG-CRON+" "+LOG-AUTHPRIV+" "+LOG-FTP+" "+LOG-LOCAL0+" "+LOG-LOCAL1+" "+LOG-LOCAL2+" "+LOG-LOCAL3+" "+LOG-LOCAL4+" "+LOG-LOCAL5+" "+LOG-LOCAL6+" "+LOG-LOCAL7+")) (in-package "COM.INFORMATIMAGO.CLISP.SYSLOG") ;; options (defconstant +log-pid+ 1 "log the pid with each message ") (defconstant +log-cons+ 2 "log on the console if errors in sending ") (defconstant +log-odelay+ 4 "delay open until first syslog() (default) ") (defconstant +log-ndelay+ 8 "don't delay open ") (defconstant +log-nowait+ 16 "don't wait for console forks: DEPRECATED ") (defconstant +log-perror+ 32 "log to stderr as well ") ;; priorities (defconstant +log-emerg+ 0 "system is unusable ") (defconstant +log-alert+ 1 "action must be taken immediately ") (defconstant +log-crit+ 2 "critical conditions ") (defconstant +log-err+ 3 "error conditions ") (defconstant +log-warning+ 4 "warning conditions ") (defconstant +log-notice+ 5 "normal but significant condition ") (defconstant +log-info+ 6 "informational ") (defconstant +log-debug+ 7 "debug-level messages ") ;; facilities (defconstant +log-kern+ 0 "kernel messages ") (defconstant +log-user+ 8 "random user-level messages ") (defconstant +log-mail+ 16 "mail system ") (defconstant +log-daemon+ 24 "system daemons ") (defconstant +log-auth+ 32 "security/authorization messages ") (defconstant +log-syslog+ 40 "messages generated internally by syslogd ") (defconstant +log-lpr+ 48 "line printer subsystem ") (defconstant +log-news+ 56 "network news subsystem ") (defconstant +log-uucp+ 64 "UUCP subsystem ") (defconstant +log-cron+ 72 "clock daemon ") (defconstant +log-authpriv+ 80 "security/authorization messages (private) ") (defconstant +log-ftp+ 88 "ftp daemon ") (defconstant +log-local0+ 128 "reserved for local use ") (defconstant +log-local1+ 136 "reserved for local use ") (defconstant +log-local2+ 144 "reserved for local use ") (defconstant +log-local3+ 152 "reserved for local use ") (defconstant +log-local4+ 160 "reserved for local use ") (defconstant +log-local5+ 168 "reserved for local use ") (defconstant +log-local6+ 176 "reserved for local use ") (defconstant +log-local7+ 184 "reserved for local use ") (defvar *ident* "clisp") (defvar *facility* +log-local0+) (defvar *log-pid* nil "log the pid with each message ") (defvar *log-cons* nil "log on the console if errors in sending ") (defvar *log-odelay* nil "delay open until first syslog() (default) ") (defvar *log-ndelay* nil "don't delay open ") (defvar *log-nowait* nil "don't wait for console forks: DEPRECATED ") (defvar *log-perror* nil "log to stderr as well ") (defvar *loggers* (make-array '(256) :initial-element nil) "Array of logger streams (opened with ext:run-program).") (defun get-logger (facility priority) " RETURN: A logger for the (facility priority) couple. " (unless (and (integerp facility) (integerp priority) (<= 0 (+ facility priority) 255)) (error "Invalid (facility=~S priority=~S) couple." facility priority)) (let ((logger (aref *loggers* (+ facility priority)))) (unless logger (setf logger (ext:run-program "logger" :arguments (append (when *ident* (list "-t" *ident*)) (when *log-pid* (list "-i")) (when *log-perror* (list "-s")) (list "-p" (format nil "~D" (+ facility priority)))) :input :stream :output nil)) (setf (aref *loggers* (+ facility priority)) logger)) logger)) ;;; (DEF-CALL-OUT OPENLOG ;;; (:NAME "openlog") ;;; (:LANGUAGE :STDC) ;;; (:ARGUMENTS (IDENT C-STRING) (OPTION INT) (FACILITY INT)) ;;; (:RETURN-TYPE NIL));;OPENLOG ;;; ;;; ;;; (DEF-CALL-OUT SYSLOG1 ;;; (:NAME "syslog") ;;; (:LANGUAGE :STDC) ;;; (:ARGUMENTS (PRIORITY INT) (FORMAT C-STRING) (VALUE C-STRING)) ;;; (:RETURN-TYPE NIL));;SYSLOG1 ;;; ;;; ;;; (DEFMACRO SYSLOG (PRIORITY FCTRL &REST ARGUMENTS) ;;; (SYSLOG1 PRIORITY "%s" (APPLY (FUNCTION FORMAT) NIL FCTRL ARGUMENTS)) ;;; );;SYSLOG ;;; ;;; ;;; (DEF-CALL-OUT CLOSELOG ;;; (:NAME "closelog") ;;; (:LANGUAGE :STDC) ;;; (:ARGUMENTS) ;;; (:RETURN-TYPE NIL));;CLOSELOG (defun openlog (ident option facility) (setq *ident* ident *facility* facility *log-pid* (/= 0 (logand option +log-pid+)) *log-cons* (/= 0 (logand option +log-cons+)) *log-odelay* (/= 0 (logand option +log-odelay+)) *log-ndelay* (/= 0 (logand option +log-ndelay+)) *log-nowait* (/= 0 (logand option +log-nowait+)) *log-perror* (/= 0 (logand option +log-perror+))) (values)) (defun old-syslog (priority fctrl &rest arguments) (ext:run-program "logger" :arguments (append (when *log-pid* (list "-i")) (when *log-perror* (list "-s")) (list "-p" (format nil "~D" (+ *facility* priority)) "-t" *ident* "--" (apply (function format) nil fctrl arguments))) :input nil :output nil :wait nil) (values)) (defun newlinep (ch) (member ch '(#\newline #\return #\newline))) (defun syslog (priority fctrl &rest arguments) (let ((logger (get-logger *facility* priority))) (let ((lines (apply (function format) nil fctrl arguments))) (princ lines logger) (unless (newlinep (aref lines (1- (length lines)))) (terpri logger)) (finish-output logger))) (values)) (defun closelog () (setf *loggers* (map 'array (lambda (logger) (when logger (close logger)) nil) *loggers*)) (values)) ;;;; THE END ;;;;
7,933
Common Lisp
.lisp
182
39.631868
83
0.619769
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4a0fa807efbcbcf9f8671e8e51bac1e9859514e9a0e4ccfde68abd6341c011ef
4,811
[ -1 ]
4,812
fifo-stream.lisp
informatimago_lisp/clisp/fifo-stream.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: fifo-stream.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A fifo stream: all input is buffered and restituted as output. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2003-09-11 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.FIFO-STREAM" (:use "COMMON-LISP" "GRAY") (:export "FIFO-STREAM") (:documentation " A fifo stream: all input is buffered and restituted as output. Copyright Pascal J. Bourguignon 2003 - 2003 ")) (in-package "COM.INFORMATIMAGO.CLISP.FIFO-STREAM") (defun make-fifo () ;; (VALUES INPUT-STREAM OUTPUT-STREAM) (values nil nil)) (defconstant +chunk-size+ 4096 "Size of one buffer string.") (defclass fifo-stream (fundamental-input-stream fundamental-output-stream fundamental-character-stream) ((output :initform '() :initarg :output :accessor output :type list :documentation "The head of the FIFO buffer list.") (input :initform '() :initarg :input :accessor input :type list :documentation "The tail of the FIFO buffer list.") ) (:documentation "A fifo stream: all input is buffered and restituted as output.") ) ;;; (string start end closed) ;;; ;;; (and (<= 0 output) ;;; (<= output input) ;;; (<= 0 input) ;;; (<= input (length string))) ;;; ;;; closed <=> don't add input, see next buffer ;;; ;;; We could use the fill-pointer for the input. (defun make-buffer () (list (make-string +chunk-size+) 0 0 nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; general generic functions defined on streams ;;; (defmethod close ((stream fifo-stream) &key ((:abort abort-flag) nil)) ;; clisp-2.49|asdf|quicklisp seem to have a constant declaration on abort. " Closes the stream and flushes any associated buffers. " (declare (ignore abort-flag)) ;; When you define a primary method on this function, do not forget to ;; CALL-NEXT-METHOD. ;; TODO: (SETF (BUFFERS STREAM) 'NIL) (call-next-method)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; generic functions for character input ;;; (defmethod stream-read-char ((stream fifo-stream)) " If a character was pushed back using DEFUN STREAM-UNREAD-CHAR, returns and consumes it. Otherwise returns and consumes the next character from the stream. Returns :EOF if the end-of-stream is reached. " (let ((buffer (car (output stream)))) (if buffer (let* ((str (pop buffer)) (out (pop buffer)) (inp (pop buffer)) (closed (pop buffer))) (cond ((< out inp) (incf (second buffer)) (char str out)) (closed :eof) (t (pop (output stream)) (stream-read-char stream)))) :eof))) (defmethod stream-unread-char ((stream fifo-stream) (char character)) " Pushes char, which must be the last character read from the stream, back onto the front of the stream. " (setf (output stream) (cons (list (make-string 1 :initial-element char) 0 1 t) (output stream))) (unless (input stream) (setf (input stream) (output stream))) nil) (defmethod stream-read-char-no-hang ((stream fifo-stream)) " Returns a character or :EOF, like DEFUN STREAM-READ-CHAR, if that would return immediately. If DEFUN STREAM-READ-CHAR's value is not available immediately, returns NIL instead of waiting. The default method simply calls DEFUN STREAM-READ-CHAR; this is sufficient for streams whose DEFUN STREAM-READ-CHAR method never blocks. " ) (defmethod stream-peek-char ((stream fifo-stream)) " If a character was pushed back using DEFUN STREAM-UNREAD-CHAR, returns it. Otherwise returns the next character from the stream, avoiding any side effects DEFUN STREAM-READ-CHAR would do. Returns :EOF if the end-of-stream is reached. The default method calls DEFUN STREAM-READ-CHAR and DEFUN STREAM-UNREAD-CHAR; this is sufficient for streams whose DEFUN STREAM-READ-CHAR method has no side-effects. " ) (defmethod stream-listen ((stream fifo-stream)) " If a character was pushed back using DEFUN STREAM-UNREAD-CHAR, returns it. Otherwise returns the next character from the stream, if already available. If no character is available immediately, or if end-of-stream is reached, returns NIL. The default method calls DEFUN STREAM-READ-CHAR-NO-HANG and DEFUN STREAM-UNREAD-CHAR; this is sufficient for streams whose DEFUN STREAM-READ-CHAR method has no side-effects. " ) (defmethod stream-read-char-will-hang-p ((stream fifo-stream)) " Returns NIL if DEFUN STREAM-READ-CHAR will return immediately. Otherwise it returns true. The default method calls DEFUN STREAM-READ-CHAR-NO-HANG and DEFUN STREAM-UNREAD-CHAR; this is sufficient for streams whose DEFUN STREAM-READ-CHAR method has no side-effects. This function is a CLISP extension (see EXT:READ-CHAR-WILL-HANG-P). " ) (defmethod stream-read-char-sequence ((stream fifo-stream) sequence &optional (start 0) (end nil)) " Fills the subsequence of sequence specified by :START and :END with characters consecutively read from stream. Returns the index of the first element of sequence that was not updated (= end or < end if the stream reached its end). sequence is an array of characters, i.e. a string. start is a nonnegative integer and default to 0. end is a nonnegative integer or NIL and defaults to NIL, which stands for (LENGTH sequence). The default method repeatedly calls DEFUN STREAM-READ-CHAR; this is always sufficient if speed does not matter. This function is a CLISP extension (see EXT:READ-CHAR-SEQUENCE) " (declare (ignore stream sequence start end)) 0) (defmethod stream-read-line ((stream fifo-stream)) " Reads a line of characters, and return two values: the line (a string, without the terminating #\Newline character), and a boolean value which is true if the line was terminated by end-of-stream instead of #\Newline. The default method repeatedly calls DEFUN STREAM-READ-CHAR; this is always sufficient. " ) (defmethod stream-clear-input ((stream fifo-stream)) " Clears all pending interactive input from the stream, and returns true if some pending input was removed. The default method does nothing and returns NIL; this is sufficient for non-interactive streams. " ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; generic functions for character output ;;; (defmethod stream-write-char ((stream fifo-stream) (char character)) " Writes char. You must define a method for this function. " ) (defmethod stream-line-column ((stream fifo-stream)) " Returns the column number where the next character would be written (0 stands for the first column), or NIL if that is not meaningful for this stream. You must define a method for this function. " ) #||| (DEFMETHOD STREAM-START-LINE-P STREAM) RETURNS TRUE IF THE NEXT CHARACTER WOULD BE WRITTEN AT THE START OF A NEW LINE. THE DEFAULT METHOD CALLS DEFUN STREAM-LINE-COLUMN AND COMPARES ITS RESULT WITH 0; this is sufficient for streams whose DEFUN STREAM-LINE-COLUMN never returns NIL. (DEFMETHOD STREAM-WRITE-CHAR-SEQUENCE STREAM SEQUENCE &OPTIONAL [START [END]]) OUTPUTS THE SUBSEQUENCE OF SEQUENCE SPECIFIED BY :START AND :END TO STREAM. SEQUENCE IS AN ARRAY OF CHARACTERS, I.E. A STRING. START IS A NONNEGATIVE INTEGER AND DEFAULT TO 0. END IS A NONNEGATIVE INTEGER OR NIL AND DEFAULTS TO NIL, WHICH STANDS FOR (LENGTH SEQUENCE). THE DEFAULT METHOD REPEATEDLY CALLS DEFUN STREAM-WRITE-CHAR; this is always sufficient if speed does not matter. THIS FUNCTION IS A CLISP EXTENSION (SEE EXT:WRITE-CHAR-SEQUENCE) (DEFMETHOD STREAM-WRITE-STRING STREAM STRING &OPTIONAL [START [END]]) OUTPUTS THE SUBSEQUENCE OF STRING SPECIFIED BY :START AND :END TO STREAM. RETURNS STRING. STRING IS A STRING. START IS A NONNEGATIVE INTEGER AND DEFAULT TO 0. END IS A NONNEGATIVE INTEGER OR NIL AND DEFAULTS TO NIL, WHICH STANDS FOR (LENGTH STRING). THE DEFAULT METHOD CALLS DEFUN STREAM-WRITE-CHAR-SEQUENCE; this is always sufficient. (DEFMETHOD STREAM-TERPRI STREAM) OUTPUTS A #\NEWLINE CHARACTER. THE DEFAULT METHOD CALLS DEFUN STREAM-WRITE-CHAR; this is always sufficient. (DEFMETHOD STREAM-FRESH-LINE STREAM) POSSIBLY OUTPUTS A #\NEWLINE CHARACTER, SO AS TO ENSURE THAT THE NEXT CHARACTER WOULD BE WRITTEN AT THE START OF A NEW LINE. RETURNS TRUE IF IT DID OUTPUT A #\NEWLINE CHARACTER. THE DEFAULT METHOD CALLS DEFUN STREAM-START-LINE-P AND THEN DEFUN STREAM-TERPRI IF NECESSARY ; this is always sufficient. (DEFMETHOD STREAM-FINISH-OUTPUT STREAM) ENSURES THAT ANY BUFFERED OUTPUT HAS REACHED ITS DESTINATION, AND THEN RETURNS. THE DEFAULT METHOD DOES NOTHING. (DEFMETHOD STREAM-FORCE-OUTPUT STREAM) BRINGS ANY BUFFERED OUTPUT ON ITS WAY TOWARDS ITS DESTINATION, AND RETURNS WITHOUT WAITING UNTIL IT HAS REACHED ITS DESTINATION. THE DEFAULT METHOD DOES NOTHING. (DEFMETHOD STREAM-CLEAR-OUTPUT STREAM) ATTEMPTS TO DISCARD ANY BUFFERED OUTPUT WHICH HAS NOT YET REACHED ITS DESTINATION. THE DEFAULT METHOD DOES NOTHING. (DEFMETHOD STREAM-ADVANCE-TO-COLUMN STREAM COLUMN) ENSURES THAT THE NEXT CHARACTER WILL BE WRITTEN AT COLUMN AT LEAST. THE DEFAULT METHOD OUTPUTS AN APPROPRIATE AMOUNT OF SPACE CHARACTERS ; this is sufficient for non-proportional output. |||# ;;;; THE END ;;;;
10,713
Common Lisp
.lisp
239
41.669456
237
0.707732
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a981698f847193066acb2e8c397a5169018360f8648bf233333bde895f898697
4,812
[ -1 ]
4,814
string.lisp
informatimago_lisp/clisp/string.lisp
;;;; -*- coding:utf-8 -*- ;;;;***************************************************************************** ;;;;FILE: string.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: clisp ;;;;USER-INTERFACE: clisp ;;;;DESCRIPTION ;;;; ;;;; This module exports string functions. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2003-01-30 <PJB> Creation. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2003 - 2016 ;;;; ;;;; 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/> ;;;;***************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.CLISP.STRING" (:documentation "This module exports string functions.") (:use "COMMON-LISP" #+clisp "REGEXP" #-clisp "CL-PPCRE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING") (:export "SPLIT-STRING" "UNSPLIT-STRING" "STRING-MATCH" "STRING-TO-NUMBER" "CAPITALIZATION" "*CASE-FOLD-SEARCH*" "REPLACE-REGEXP-IN-STRING" "SUBSTRING")) (in-package "COM.INFORMATIMAGO.CLISP.STRING") ;; We have our own implementation of SPLIT-STRING using REGEXP, ;; specific to CLISP. (defparameter split-string-default-separators (format nil "[ ~C~C~C~C~C]\\+" (code-char 9) (code-char 10) (code-char 11) (code-char 12) (code-char 13)) "The default separators for split-string (HT, LF, VT, FF, CR, SP)") (defun split-string (string &optional separators) " NOTE: This implementation uses he REGEXP package. " (unless separators (setq separators split-string-default-separators)) (let ((result (regexp:regexp-split separators string))) (if (string= "" (car result)) (setq result (cdr result))) (if (string= "" (car (last result))) (setq result (nbutlast result))) result)) ;; But we inherit UNSPLIT-STRING from COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING. (defun string-match (regexp string &key (start 0) (end nil) (case-sensitive nil) (extended nil) (newline nil) (nosub nil)) "An alias for REGEXP:MATCH." (regexp:match regexp string :start start :end end :ignore-case (not case-sensitive) :extended extended :newline newline :nosub nosub)) (defvar *case-fold-search* nil "Whether searches and matches should ignore case. Used by: REPLACE-REGEXP-IN-STRING. ") ;;; CAPITALIZATION: ;;; ;;; 0 NIL ;;; 1 T ;;; ;;; 0 Upcase ;;; 1 Lowcase ;;; 2 Nocase ;;; 3 Special ;;; ;;; STATE: (BOW,U/L/N/S) ;;; Initial state: (NIL SP) ;;; ;;; ((NIL UP) UP) --> (NIL UP) NOT NO-2C-WORD ;;; ((NIL UP) LO) --> (NIL LO) NOT NO-2C-WORD NOT ALL-UPCASE ;;; ((NIL UP) NO) --> (NIL NO) NOT NO-2C-WORD ;;; ((NIL UP) SP) --> (NIL SP) ;;; ((NIL LO) UP) --> (NIL UP) NOT NO-2C-WORD NOT ALL-LOCASE NOT ALL-CAPITA ;;; ((NIL LO) LO) --> (NIL LO) NOT NO-2C-WORD ;;; ((NIL LO) NO) --> (NIL NO) NOT NO-2C-WORD ;;; ((NIL LO) SP) --> (NIL SP) ;;; ((NIL NO) UP) --> (NIL UP) NOT NO-2C-WORD ;;; ((NIL NO) LO) --> (NIL LO) NOT NO-2C-WORD ;;; ((NIL NO) NO) --> (NIL NO) NOT NO-2C-WORD ;;; ((NIL NO) SP) --> (NIL SP) ;;; ((NIL SP) UP) --> ( T UP) NOT ALL-LOCASE ;;; ((NIL SP) LO) --> ( T LO) NOT ALL-UPCASE NOT ALL-CAPITA ;;; ((NIL SP) NO) --> ( T NO) ;;; ((NIL SP) SP) --> (NIL SP) ;;; (( T UP) UP) --> (NIL UP) NOT NO-2C-WORD NOT ALL-LOCASE NOT ALL-CAPITA ;;; (( T UP) LO) --> (NIL LO) NOT NO-2C-WORD NOT ALL-UPCASE ;;; (( T UP) NO) --> (NIL NO) NOT NO-2C-WORD ;;; (( T UP) SP) --> (NIL SP) ;;; (( T LO) UP) --> (NIL UP) NOT NO-2C-WORD NOT ALL-LOCASE ;;; (( T LO) LO) --> (NIL LO) NOT NO-2C-WORD NOT ALL-UPCASE ;;; (( T LO) NO) --> (NIL NO) NOT NO-2C-WORD ;;; (( T LO) SP) --> (NIL SP) ;;; (( T NO) UP) --> (NIL UP) NOT NO-2C-WORD NOT ALL-LOCASE NOT ALL-CAPITA ;;; (( T NO) LO) --> (NIL LO) NOT NO-2C-WORD NOT ALL-UPCASE ;;; (( T NO) NO) --> (NIL NO) NOT NO-2C-WORD ;;; (( T NO) SP) --> (NIL SP) ;;; ( T SP) is impossible. (defparameter +capitalization-transitions+ (make-array '(2 4 4) :initial-contents '((( (0 0 3) (0 1 3 0) (0 2 3) (0 3) ) ( (0 0 3 1 2) (0 1 3) (0 2 3) (0 3) ) ( (0 0 3) (0 1 3) (0 2 3) (0 3) ) ( (1 0 1) (1 1 0 2) (1 2) (0 3) )) (( (0 0 3 1 2) (0 1 3 0) (0 2 3) (0 3) ) ( (0 0 3 1) (0 1 3 0) (0 2 3) (0 3) ) ( (0 0 3 1 2) (0 1 3 0) (0 2 3) (0 3) ) ( (0 0) ;; impossible state (0 1) (0 2) (0 3) ))))) (defun capitalization (string) " RETURN: :LOWER :UPPER :CAPITALIZED or :WHATEVER " (let ((all-upcase 0) (all-locase 1) (all-capita 2) (no-2c-word 3) (result (make-array '(4) :initial-element t)) (state (cons 0 3)) ) (map nil (lambda (ch) (let ((new-state (aref +capitalization-transitions+ (car state) (cdr state) (cond ((not (alpha-char-p ch)) 3) ((upper-case-p ch) 0) ((lower-case-p ch) 1) (t 2))))) (setf (car state) (pop new-state)) (setf (cdr state) (pop new-state)) (mapc (lambda (sym) (setf (aref result sym) nil)) new-state) )) string) (cond ((aref result no-2c-word) :whatever) ((aref result all-upcase) :upper) ((aref result all-locase) :lower) ((aref result all-capita) :capitalized) (t :whatever)))) (defun emacs-bugged-string-capitalize (string) " The string-capitalized that emacs implements in its replace-regexp-in-string which is not even its capitalize (which is correct)! Namely, it seems to touch only the first character of each word. " (do ((result (copy-seq string)) (i 0 (1+ i)) (sp t) (ch) ) ((<= (length result) i) result) (setq ch (char result i)) (if sp (when (alpha-char-p ch) (setf (char result i) (char-upcase ch)) (setq sp nil)) (when (not (alphanumericp ch)) (setq sp t))))) (defun replace-regexp-in-string (regexp rep string &optional (fixedcase nil) (literal nil) (subexp 0) (start 0) &key (case-sensitive (not *case-fold-search*)) (extended nil) (newline nil) (nosub nil)) " NOTE: emacs regexps are a mix between POSIX basic regexps and POSIX extended regexps. By default we'll use basic POSIX regexps, to keep '\\(...\\)' at the cost of the '+' repetition. The key parameters are passed to REGEXP:MATCH if specific behavior is needed. (We're not entirely compatible with emacs, but it's emacs which is wrong and we'll have to use another regexp package in emacs). Replace all matches for REGEXP with REP in STRING. Return a new string containing the replacements. Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the arguments with the same names of function `replace-match'. If START is non-nil, start replacements at that index in STRING. REP is either a string used as the NEWTEXT arg of `replace-match' or a function. If it is a function it is applied to each match to generate the replacement passed to `replace-match'; the match-data at this point are such that match 0 is the function's argument. When REP is a function it's passed the while match 0, even if SUBEXP is not 0. To replace only the first match (if any), make REGEXP match up to \' and replace a sub-expression, e.g. (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1) => \" bar foo\" If second arg FIXEDCASE is non-nil, do not alter case of replacement text. Otherwise maybe capitalize the whole text, or maybe just word initials, based on the replaced text. If the replaced text has only capital letters and has at least one multiletter word, convert NEWTEXT to all caps. Otherwise if all words are capitalized in the replaced text, capitalize each word in NEWTEXT. If third arg LITERAL is non-nil, insert NEWTEXT literally. Otherwise treat `\' as special: `\&' in NEWTEXT means substitute original matched text. `\N' means substitute what matched the Nth `\(...\)'. If Nth parens didn't match, substitute nothing. `\\' means insert one `\'. Case conversion does not apply to these substitutions. FIXEDCASE and LITERAL are optional arguments. The optional fifth argument SUBEXP specifies a subexpression ; it says to replace just that subexpression with NEWTEXT, rather than replacing the entire matched text. This is, in a vague sense, the inverse of using `\N' in NEWTEXT ; `\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts NEWTEXT in place of subexp N. This is useful only after a regular expression search or match, since only regular expressions have distinguished subexpressions. " ;;; REP function(\0) --> NEWTEXT ;;; REP string --> NEWTEXT ;;; ;;; FIXEDCASE T identity ;;; FIXEDCASE NIL replaced text capitalization -> replacement ;;; ;;; LITERAL T identity ;;; LITERAL NIL substitute \&, \N, \\ and \x. ;;; ;;; SUBEXP N replaces only \N instead of \0 (do ((done nil) (pieces '()) (pos 0) (replacement) (replaced-match) (matches)) (done (progn (push (subseq string pos) pieces) (apply (function concatenate) 'string (nreverse pieces)))) (setq matches (multiple-value-list (regexp:match regexp string :start start :ignore-case (not case-sensitive) :extended extended :newline newline :nosub nosub))) (if (and matches (car matches)) (progn ;; -1- Find the replacement: (setq replacement (if (functionp rep) (funcall rep (regexp:match-string string (car matches))) rep)) ;; -2- Process FIXEDCASE (when (or (< subexp 0) (<= (length matches) subexp)) (error "Argument out of range SUBEXP=~A." subexp)) (setq replaced-match (nth subexp matches)) (unless fixedcase (let ((cap (capitalization (regexp:match-string string replaced-match))) ) (setq replacement (funcall (cond ((eq cap :upper) (function string-upcase)) ((eq cap :lower) (function identity)) ;; That's what emacs does... ((eq cap :capitalized) (function emacs-bugged-string-capitalize)) (t (function identity))) replacement)))) ;; -3- Process LITERAL (unless literal ;; substitute \&, \N and \\. (setq replacement (replace-regexp-in-string "\\\\\\(.\\)" (lambda (substr) (cond ((char= (char substr 1) (character "&")) (regexp:match-string string (car matches)) ) ((digit-char-p (char substr 1)) (let ((n (parse-integer substr :start 1))) (if (<= (length matches) n) substr ;; How coherent emacs is! (regexp:match-string string (nth n matches)))) ) ((char= (character "\\") (char substr 1)) (subseq substr 1) ) (t (error "Invalid use of '\\' in replacement text ~W." substr) ))) replacement t t)) ) ;; -4- Replace. (push (subseq string pos (regexp:match-start (nth subexp matches))) pieces) (push replacement pieces) (setq start (if (= 0 (length regexp)) (1+ start) (regexp:match-end (car matches)))) (setq pos (regexp:match-end (nth subexp matches))) (setq done (<= (length string) start)) ) (progn (setq done t) )))) (defun string-to-number (string &key (base 10) (start 0) (end nil)) " DO: Converts the string to a number. RETURN: A number. " ;; PARSE-INTEGER is for integers... (let ((result (with-input-from-string (stream string :start start :end end) (let ((*read-base* base)) (read stream))))) (unless (numberp result) (error "Expected a number, not ~S." result)) result)) ;;;; THE END ;;;;
14,496
Common Lisp
.lisp
352
32.119318
83
0.534988
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
694b9a9036a0376fc70b186687fe62600f9d1924fcd8714ca6b7d15432138cde
4,814
[ -1 ]
4,815
init.lisp
informatimago_lisp/clisp/init.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: init.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Initialization for clisp packages. ;;;; ;;;; This files remove some specificities from the lisp environment ;;;; (to make it more Common-Lisp), ;;;; loads the package COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PACKAGE, ;;;; and add logical pathname translations to help find the other packages. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-01-20 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 2016 ;;;; ;;;; 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/> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (setq *load-verbose* nil) ;; clean the imported packages: (mapc (lambda (used) (unuse-package used "COMMON-LISP-USER")) (remove (find-package "COMMON-LISP") (copy-seq (package-use-list "COMMON-LISP-USER")))) (progn (defvar *directories* '()) (defun get-directory (key &optional (subpath "")) (unless *directories* (with-open-file (dirs (make-pathname :name "DIRECTORIES" :type "TXT" :version nil :case :common :defaults (user-homedir-pathname))) (loop :for k = (read dirs nil dirs) :until (eq k dirs) :do (push (string-trim " " (read-line dirs)) *directories*) :do (push (intern (substitute #\- #\_ (string k)) "KEYWORD") *directories*)))) (unless (getf *directories* key) (error "~S: No directory keyed ~S" 'get-directory key)) (merge-pathnames subpath (getf *directories* key) nil))) #+clisp (when (string= (lisp-implementation-version) "2.33.83" :end1 (min (length (lisp-implementation-version)) 7)) (ext:without-package-lock ("COMMON-LISP") (let ((oldload (function cl:load))) (fmakunbound 'cl:load) (defun cl:load (filespec &key (verbose *load-verbose*) (print *load-print*) (if-does-not-exist t) (external-format :default)) (handler-case (funcall oldload filespec :verbose verbose :print print :if-does-not-exist if-does-not-exist :external-format external-format) (system::simple-parse-error () (funcall oldload (translate-logical-pathname filespec) :verbose verbose :print print :if-does-not-exist if-does-not-exist :external-format external-format))))))) ;; COM.INFORMATIMAGO.CLISP packages depend on themselves, from ;; the current directory, and on COM.INFORMATIMAGO.COMMON-LISP ;; packages from the repository. ;; (SETF (logical-pathname-translations "PACKAGES") nil) ;; ;; (HANDLER-CASE (LOAD (get-directory :share-lisp "packages/com/informatimago/common-lisp/package")) ;; (T () (LOAD (get-directory :share-lisp "packages/com/informatimago/common-lisp/package.lisp")))) (setf (logical-pathname-translations "PACKAGES") nil (logical-pathname-translations "PACKAGES") (list (list "PACKAGES:**;*" (get-directory :share-lisp "packages/**/*")) (list "PACKAGES:**;*.*" (get-directory :share-lisp "packages/**/*.*")) (list "PACKAGES:**;*.*.*" (get-directory :share-lisp "packages/**/*.*.*")))) (handler-case (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE") (t () (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE.LISP"))) ;; Import DEFINE-PACKAGE, and add translations: (import 'package:define-package) (package:add-translations (list "PACKAGES:COM;INFORMATIMAGO;CLISP;**;*.*.*" "**/*.*.*")) ;; (make-pathname ;; :directory (append (pathname-directory *DEFAULT-PATHNAME-DEFAULTS*) ;; '(:wild-inferiors)) ;; :name :wild :type :wild :version :wild))) ;;;; init.lisp -- -- ;;;;
5,083
Common Lisp
.lisp
107
41.11215
107
0.588022
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d9f0abcb33df67c40526d27e21155fcd05bb3b1bdf5fe878ab92572099663a08
4,815
[ -1 ]
4,816
editor.lisp
informatimago_lisp/editor/editor.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: editor.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A screen editor. clispmacs ;;;; ;;;; About emacs in CL: ;;;; http://clocc.cvs.sourceforge.net/clocc/clocc/src/cllib/elisp.lisp?view=markup ;;;; http://common-lisp.net/viewvc/phemlock/phemlock/src/elisp/hemlock-shims.lisp?revision=1.1.1.1&view=markup&sortby=author&pathrev=HEAD ;;;; http://www.emacswiki.org/emacs/EmacsCommonLisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2014-04-30 <PJB> Corrected a couple of little bugs. Added BUGS entries. ;;;; 2007-09-11 <PJB> Added the language feature, and some docstrings. ;;;; 2006-07-10 <PJB> Created. ;;;;BUGS ;;;; - When entering the mini-buffer (prompt-window?), the status ;;;; line above disappears. ;;;; - implement multi-windows (C-x 2, C-x 3, C-x 1) ;;;; - redisplay: we can see the cursor moving over the terminal ;;;; - redisplay: implement minimal updating. ;;;; - implement pathname and buffer-name completion. ;;;; - doesn't take into account changes of terminal size (SIGWINCH). ;;;; - doesn't handle TAB completion (or at least ignore TAB). ;;;; - breaking into the debugger (eg. on C-x C-e) is not handled in the editor, ;;;; and some restart may exit from the editor. ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2006 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.EDITOR") (defvar *debug-on-error* nil "Non-nil means enter debugger if a unhandled error is signaled.") (defvar *debug-on-quit* nil "Non-nil means enter debugger if a unhandled quit is signaled (C-g, for example).") (defvar *debug-on-message* nil "If non-nil, debug if a message matching this regexp is displayed.") (defvar *log* nil "Debugging stream.") (defvar *frame-list* '() "The list of frames.") (defvar *current-frame* nil "The current frame.") (defvar *buffer-list* '() "The list of buffers") (defvar *current-window* nil "The current window.") (defvar *scratch-buffer-default-contents* ";; This buffer is for notes you don't want to save, and for Lisp evaluation. ;; If you want to create a file, visit that file with C-x C-f, ;; then enter the text in that file's own buffer. " "The default contents for the *scratch* buffer.") (defvar *last-command-char* nil "Last input event that was part of a command.") (defvar *this-command* nil "The command now being executed. The command can set this variable; whatever is put here will be in `last-command' during the following command.") (defvar *last-command* nil "The last command executed. Normally a symbol with a function definition, but can be whatever was found in the keymap, or whatever the variable `this-command' was set to by that command. The value `mode-exit' is special; it means that the previous command read an event that told it to exit, and it did so and unread that event. In other words, the present command is the event that made the previous command exit. The value `kill-region' is special; it means that the previous command was a kill command.") (defvar *prefix-arg* nil "The value of the prefix argument for the next editing command. It may be a number, or the symbol `-' for just a minus sign as arg, or a list whose car is a number for just one or more C-u's or nil if no argument has been specified. You cannot examine this variable to find the argument for this command since it has been set to nil by the time you can look. Instead, you should use the variable `current-prefix-arg', although normally commands can get this prefix argument with (interactive \"P\").") (defvar *current-prefix-arg* nil "The value of the prefix argument for this editing command. It may be a number, or the symbol `-' for just a minus sign as arg, or a list whose car is a number for just one or more C-u's or nil if no argument has been specified. This is what `(interactive \"P\")' returns.") (defvar *kill-whole-line* nil "*If non-nil, `kill-line' with no arg at beg of line kills the whole line.") (defvar *yank* nil) #-mocl (declaim (ftype function message)) (defun error (datum &rest arguments) (cond (*debug-on-error* (apply (function cl:error) datum arguments)) ((stringp datum) (message datum)) (t (message "~A" (apply (function format) datum arguments))))) (defmacro with-current-window (window &body body) `(let ((*current-window* ,window)) ,@body)) (defun read-something (prompt other-args validatef postf) (loop :for something = (apply (function read-from-minibuffer) prompt other-args) :then (apply (function read-from-minibuffer) prompt :initial-contents something other-args) :do (if (funcall validatef something) (return (funcall postf something)) (with-current-window (frame-mini-window *current-frame*) (insert " [No match]") ;; TODO: Replace this sleep with an interuptible wait! (redisplay) (sleep 1))))) (defun read-number-from-minibuffer (prompt) (read-something prompt nil (lambda (something) (with-input-from-string (*standard-output* something) (let* ((*read-eval* nil)) (numberp (read))))) (lambda (something) (with-input-from-string (*standard-output* something) (let* ((*read-eval* nil)) (read)))))) (defun nsubseq (sequence start &optional (end nil)) "Same as CL:SUBSEQ, but with vectors, use a displaced array instead of copying the vector." (if (vectorp sequence) (if (and (zerop start) (or (null end) (= end (length sequence)))) sequence (make-array (- (if end (min end (length sequence)) (length sequence)) start) :element-type (array-element-type sequence) :displaced-to sequence :displaced-index-offset start)) (subseq sequence start end))) (defmacro in-order (start end) `(unless (< ,start ,end) (rotatef ,start ,end))) (defun interactive-item (item) (loop :for start :from 0 :for prompt = (nsubseq item (1+ start)) :while (and (< start (length item)) (or (char= #\* (aref item start)) (char= #\@ (aref item start)))) :do (when (char= #\* (aref item start)) (when (buffer-read-only-p (current-buffer)) (error "Buffer is read-only ~S" (current-buffer)))) :finally (return (when (< start (length item)) (case (aref item start) ((#\a) ; read a function name (read-something prompt nil (lambda (name) (fboundp (find-symbol (string-upcase name)))) (compose (function find-symbol) (function string-upcase)))) ((#\b) ; read an existing buffer (read-something prompt nil (function get-buffer) (function identity))) ((#\B) ; read a buffer name (read-from-minibuffer prompt)) ((#\c) ; read a character - no input method #\a ) ((#\C) ; read a command name (read-something prompt nil (lambda (name) (and (fboundp (find-symbol (string-upcase name))) (interactivep (find-symbol (string-upcase name))))) (compose (function find-symbol) (function string-upcase)))) ((#\d) ; value of point as number - no i/o (point)) ((#\D) ; Directory name. (read-something prompt nil (lambda (name) #+clisp (ext:probe-directory name) #-clisp (progn (warn "How to probe for directory ~S in ~S" name (lisp-implementation-type)) t)) (function identity))) ((#\e) ; Parametrized event (i.e., one that's a list) that invoked this command. If used more than once, the Nth `e' returns the Nth parameterized event. This skips events that are integers or symbols. ) ((#\f) ; Existing file name. (read-something prompt nil (function probe-file) (function identity))) ((#\F) ; Possibly nonexistent file name. (read-something prompt nil (function pathname) (function identity))) ((#\G) ; Possibly nonexistent file name, defaulting to just directory name. (read-something prompt nil (function pathname) (function identity))) ((#\i) ; Ignored, i.e. always nil. Does not do I/O. nil) ((#\k) ; Key sequence (downcase the last event if needed to get a definition). ) ((#\K) ; Key sequence to be redefined (do not downcase the last event). ) ((#\m) ; Value of mark as number. Does not do I/O. (mark)) ((#\M) ; Any string. Inherits the current input method. (read-from-minibuffer prompt)) ((#\n) ; Number read using minibuffer. (read-number-from-minibuffer prompt)) ((#\N) ; Raw prefix arg, or if none, do like code `n'. (or *current-prefix-arg* (read-number-from-minibuffer prompt))) ((#\p) ; Prefix arg converted to number. Does not do I/O. (cond ((null *current-prefix-arg*) 1) ((integerp *current-prefix-arg*) *current-prefix-arg*) ((listp *current-prefix-arg*) (first *current-prefix-arg*)) ((eq '- *current-prefix-arg*) -1) (t 0))) ((#\P) ; Prefix arg in raw form. Does not do I/O. *current-prefix-arg*) ((#\r) ; Region: point and mark as 2 numeric args, smallest first. Does no I/O. (let ((start (point)) (end (or (mark) (point)))) (in-order start end) (list start end))) ((#\s) ; Any string. Does not inherit the current input method. (read-from-minibuffer prompt)) ((#\S) ; Any symbol. (read-something prompt nil (constantly t) (compose (function intern) (function string-upcase)))) ((#\U) ; Mouse up event discarded by a previous k or K argument. nil) ((#\v) ; Variable name: symbol that is user-variable-p. ) ((#\x) ; Lisp expression read but not evaluated. (read-something prompt nil (lambda (something) ;; TODO: more sophisticated test (EOS). (handler-case (progn (read-from-string something) t) (cl:error () nil))) (function read-from-string))) ((#\X) ; Lisp expression read and evaluated. (read-something prompt nil (lambda (something) ;; TODO: more sophisticated test (EOS). (handler-case (progn (read-from-string something) t) (cl:error () nil))) (lambda (something) (eval (read-from-string something))))) ((#\z) ; Coding system. ) ((#\Z) ; Coding system, nil if no prefix arg. ) (otherwise (error "Bad interactive specifier ~S" (aref item start)))))))) (defun call-interactively (fun) (let ((interspec (second (interactivep fun)))) (apply fun (cond ((null interspec) '()) ((stringp interspec) (mapcar (function interactive-item) (split-sequence #\newline interspec))) (t (eval interspec)))))) ;;;--------------------------------------------------------------------- ;;; Keymaps ;;;--------------------------------------------------------------------- (defparameter *special-keys* '( :F1 :f2 :F3 :f4 :f5 :f6 :f7 :f8 :f9 :f10 :f11 :F12 :INSERT :DELETE :HOME :END :CENTER :PGUP :PGDN :LEFT :RIGHT :UP :DOWN)) (defstruct (keymap (:constructor %make-keymap) (:conc-name %keymap-) (:predicate keymapp)) table) (defun make-keymap () "Returns a new empty keymap." (let ((keymap (%make-keymap :table (make-hash-table :test (function equal))))) (keymap-bind-key keymap '(:control #\g) 'keyboard-quit) keymap)) (defun keymap-map (function keymap) "Calls FUNCTION with each (KEY BINDING) couples in the KEYMAP." (maphash function (%keymap-table keymap))) (defun keymap-copy (keymap &key shallow) "Returns a copy of the KEYMAP. If SHALLOW is true, then subkeymaps are not copied too." (let ((copy (make-keymap))) (keymap-map (lambda (key binding) (keymap-bind-key copy key (if (and (not shallow) (keymapp binding)) (keymap-copy binding) binding))) keymap) copy)) (defun keymap-bind-key (keymap key binding) "Binds a KEY to a BINDING in the KEYMAP. KEY: must be either a character, one of the *SPECIAL-KEYS*, or a list ([:control] [:meta] KEY) BINDING: must be either a symbol (naming a command), a command function, or another keymap." (setf (gethash key (%keymap-table keymap)) binding)) (defun keymap-binding (keymap &rest keys) "Returns the binding for the KEYS, and the remaining keys." (let ((binding (if (atom (first keys)) (or (gethash (first keys) (%keymap-table keymap)) (gethash (list (first keys)) (%keymap-table keymap))) (gethash (first keys) (%keymap-table keymap))))) (if (and (keymapp binding) (rest keys)) (apply (function keymap-binding) binding (rest keys)) (values binding (rest keys))))) (defparameter *default-keymap* (let ((def-map (make-keymap)) (c-x-map (make-keymap)) (c-h-map (make-keymap)) (fn-map (make-keymap))) (loop ;; Note: all printable iso-8859-1 characters, which is a subset ;; of unicode between 32 and 255, excluding control codes. ;; This may ensure only base-char are used. :for key :across #.(concatenate 'string " !\"#$%&'()*+,-./0123456789:;<=>?" "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" "`abcdefghijklmnopqrstuvwxyz{|}~" " ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿" "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞß" "àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ") :do (keymap-bind-key def-map key 'self-insert-command)) (keymap-bind-key def-map #\return 'new-line) (keymap-bind-key def-map #\newline 'new-line) (keymap-bind-key def-map #\tab 'self-insert-command) (keymap-bind-key def-map #\Rubout 'delete-backward-char) (keymap-bind-key def-map '(:control #\d) 'delete-char) (loop :for key :across "0123456789" :do (keymap-bind-key def-map (list :meta key) 'digit-argument)) (keymap-bind-key def-map '(:meta #\-) 'negative-argument) (keymap-bind-key def-map '(:meta #\x) 'execute-extended-command) (keymap-bind-key def-map '(:meta #\:) 'eval-expression) (keymap-bind-key def-map '(:control #\@) 'set-mark) (keymap-bind-key def-map '(:control #\-) 'negative-argument) (keymap-bind-key def-map '(:control #\u) 'universal-argument) (keymap-bind-key def-map '(:control #\l) 'redisplay) (keymap-bind-key def-map '(:control #\a) 'beginning-of-line) (keymap-bind-key def-map '(:control #\e) 'end-of-line) (keymap-bind-key def-map '(:control #\f) 'forward-char) (keymap-bind-key def-map '(:control #\b) 'backward-char) (keymap-bind-key def-map '(:control #\n) 'next-line) (keymap-bind-key def-map '(:control #\p) 'previous-line) (keymap-bind-key def-map '(:control #\k) 'kill-line) (keymap-bind-key def-map '(:control #\u) 'universal-argument) (keymap-bind-key def-map '(:control #\y) 'yank) (keymap-bind-key def-map '(:control :meta #\f) 'forward-sexp) (keymap-bind-key def-map '(:control :meta #\b) 'backward-sexp) (keymap-bind-key def-map '(:control :meta #\k) 'kill-sexp) (keymap-bind-key def-map '(:control #\v) 'scroll-up) (keymap-bind-key def-map '(:meta #\v) 'scroll-down) (keymap-bind-key def-map '(:control #\h) c-h-map) (keymap-bind-key c-h-map '#\h 'view-hello-file) (keymap-bind-key c-h-map '(:control #\h) 'help-for-help) (keymap-bind-key c-h-map '#\f 'describe-function) (keymap-bind-key c-h-map '#\v 'describe-variable) (keymap-bind-key c-h-map '#\k 'describe-key) (keymap-bind-key c-h-map '#\w 'where-is) (keymap-bind-key def-map '(:control #\x) c-x-map) (keymap-bind-key c-x-map '#\b 'switch-to-buffer) (keymap-bind-key c-x-map '#\f 'find-file) (keymap-bind-key c-x-map '#\k 'kill-buffer) (keymap-bind-key c-x-map '(:control #\s) 'save-buffer) (keymap-bind-key c-x-map '(:control #\b) 'list-buffers) (keymap-bind-key c-x-map '(:control #\c) 'editor-quit) (keymap-bind-key c-x-map '(:control #\d) 'my-debug) (keymap-bind-key c-x-map #\D 'cl-debugger) (keymap-bind-key c-x-map '(:control #\e) 'eval-last-sexp) (keymap-bind-key c-x-map '(:control #\f) 'find-file) (keymap-bind-key def-map '(:control :meta #\[) fn-map) ; temporary kludge (keymap-bind-key def-map '(:meta #\[) fn-map) (keymap-bind-key fn-map '#\A 'previous-line) (keymap-bind-key fn-map '#\B 'next-line) (keymap-bind-key fn-map '#\C 'forward-char) (keymap-bind-key fn-map '#\D 'backward-char) (keymap-bind-key fn-map '#\c 'previous-line) ; ?? (keymap-bind-key fn-map '#\e 'forward-char) ; ?? (keymap-bind-key fn-map '#\d 'backward-char) ; ?? def-map)) (defvar *keymap* nil) #-clisp (defun make-xterm-io-stream (&key display geometry) (error "(~S ~S ~S) Not implemented on ~A" 'make-xterm-io-stream display geometry (lisp-implementation-type))) (defvar *old-terminal-io*) (defun cl-debugger () (declare (interactive)) (let* ((io (make-xterm-io-stream :geometry "100x24+0+0")) (*old-terminal-io* *terminal-io*) (*debug-io* io) (*terminal-io* io)) (unwind-protect (invoke-debugger (make-condition 'simple-error :format-control "Debugger invoked interactively")) (close io)))) ;;;--------------------------------------------------------------------- ;;; Help commands ;;;--------------------------------------------------------------------- (defun view-hello-file () (declare (interactive)) (switch-to-buffer (get-buffer-create "*Hello*")) (erase-buffer) (insert "Hello!~%") (insert "Salut!~%") (insert "¡Hola!~%")) (defun help-for-help () (declare (interactive)) (switch-to-buffer (get-buffer-create "*Help*")) (erase-buffer) (insert " You have typed C-h, the help character. Type a Help option: (Use SPC or DEL to scroll through this text. Type q to exit the Help command.) a PATTERN Show commands whose name matches the PATTERN (a list of words or a regexp). See also the `apropos' command. b Display all key bindings. c KEYS Display the command name run by the given key sequence. C CODING Describe the given coding system, or RET for current ones. d PATTERN Show a list of functions, variables, and other items whose documentation matches the PATTERN (a list of words or a regexp). e Go to the *Messages* buffer which logs echo-area messages. f FUNCTION Display documentation for the given function. F COMMAND Show the on-line manual's section that describes the command. g Display information about the GNU project. h Display the HELLO file which illustrates various scripts. i Start the Info documentation reader: read on-line manuals. I METHOD Describe a specific input method, or RET for current. k KEYS Display the full documentation for the key sequence. K KEYS Show the on-line manual's section for the command bound to KEYS. l Show last 300 input keystrokes (lossage). L LANG-ENV Describes a specific language environment, or RET for current. m Display documentation of current minor modes and current major mode, including their special commands. n Display news of recent Emacs changes. p TOPIC Find packages matching a given topic keyword. r Display the Emacs manual in Info mode. s Display contents of current syntax table, plus explanations. S SYMBOL Show the section for the given symbol in the on-line manual for the programming language used in this buffer. t Start the Emacs learn-by-doing tutorial. v VARIABLE Display the given variable's documentation and value. w COMMAND Display which keystrokes invoke the given command (where-is). . Display any available local help at point in the echo area. C-a Information about Emacs. C-c Emacs copying permission (GNU General Public License). C-d Instructions for debugging GNU Emacs. C-e External packages and information about Emacs. C-f Emacs FAQ. C-m How to order printed Emacs manuals. C-n News of recent Emacs changes. C-o Emacs ordering and distribution information. C-p Info about known Emacs problems. C-t Emacs TODO list. C-w Information on absence of warranty for GNU Emacs. ")) (defun where-is (cname) (declare (interactive "CWhere is command: ")) (switch-to-buffer (get-buffer-create "*Help*")) (erase-buffer) (insert "~S is a command~%" cname)) (defun describe-function (fname) (declare (interactive "aDescribe Function: ")) (switch-to-buffer (get-buffer-create "*Help*")) (erase-buffer) (insert "~S is a function~%" fname)) (defun describe-variable (vname) (declare (interactive "vDescribe Variable: ")) (switch-to-buffer (get-buffer-create "*Help*")) (erase-buffer) (insert "~S is a variable~%" vname)) (defun describe-key (kname) (declare (interactive "kDescribe Key: ")) (switch-to-buffer (get-buffer-create "*Help*")) (erase-buffer) (insert "~S is a key sequence~%" kname)) ;;;--------------------------------------------------------------------- ;;; Files ;;;--------------------------------------------------------------------- (defclass file () ((pathname :initarg :pathname :accessor file-pathname))) (defgeneric file-name (file)) (defgeneric file-contents (file)) (defgeneric (setf file-contents) (new-contents file)) (defmethod file-name ((self file)) (file-namestring (file-pathname self))) (defmethod (setf file-contents) (new-contents (self file)) (ensure-directories-exist (file-pathname self)) (with-open-file (out (file-pathname self) :direction :output :external-format :default :if-does-not-exist :create :if-exists :supersede) (write-sequence new-contents out))) (defmethod file-contents ((self file)) (with-open-file (in (file-pathname self) :direction :input :external-format :default :if-does-not-exist nil) (if in (let* ((busize (or (ignore-errors (file-length in)) 4096)) (eltype (stream-element-type in)) (initel (if (subtypep eltype 'integer) 0 #\Space)) (buffer (make-array busize :element-type eltype :initial-element initel :adjustable t :fill-pointer t)) (start 0) (max-extend 65536)) (loop (let ((end (read-sequence buffer in :start start))) (when (< end busize) ;; we got eof, or have read enough (setf (fill-pointer buffer) end) (return-from file-contents (copy-seq buffer))) ;; no eof; extend the buffer (setf busize (if (<= (* 2 busize) max-extend) (* 2 busize) (+ busize max-extend)) start end)) (adjust-array buffer busize :initial-element initel :fill-pointer t))) ""))) ;;;--------------------------------------------------------------------- ;;; Buffers ;;;--------------------------------------------------------------------- (defun compose (f &rest others) (if (null others) f (lambda (x) (funcall f (funcall (apply (function compose) others) x))))) ;; (defun buffer-list () ;; (mapcar (function window-buffer) ;; (apply (function append) ;; (mapcar(function frame-window-list) *frame-list*)))) (defmacro with-buffer (buffer &body body) `(with-current-window (make-instance 'context :buffer (get-buffer ,buffer)) (unwind-protect (progn ,@body) (marker-delete (context-point *current-window*)) (when (context-mark *current-window*) (marker-delete (context-mark *current-window*)))))) ;; [window]-1--------1-[context]-*------/-1-[buffer]-1--------*-[marker] ;; | | | ;; 2+ +-0/1----------------------------------2-+ ;; | ;; +-----------1-[frame] ;; BUFFERS contains the text and can edit it (insert/delete). ;; A BUFFER can have MARKERS. ;; A BUFFER can be saved to or loaded from a FILE. ;; MARKERS are positions in the text of a BUFFER that move along when ;; text is inserted or deleted before the MARKER position. ;; A MARKER has a gravity toward the begin or the end of the BUFFER, ;; which is taken into account when the insertion or deletion involves ;; exactly the position of the MARKER. ;; Editing CONTEXTs held the current editing point and the mark, both ;; MARKERs of the BUFFER of the CONTEXT. ;; WINDOWS display part of the contents of a BUFFER, thru an editing ;; CONTEXT. ;; We need these three objects to allow the following features: ;; - When there are several WINDOWS open on the same BUFFER, each ;; WINDOW show a different point position and editing thru the ;; different WINDOWS happens at the different point in the BUFFER. ;; - A WINDOW can display different BUFFERs at different times ;; (SWITCH-TO-BUFFER). ;; - When a BUFFER is not visible in any WINDOW, it keeps a CONTEXT ;; that shows again when we switch back to it in a WINDOW. ;; (note: GNUemacs saves only one CONTEXT). ;; FRAMES are terminals or GUI windows. ;; They may display several editor WINDOWS. ;; There is usually a mini-window at the bottom of the frame ;; that shows the contents of the mini-buffer. (defclass buffer () ((name :accessor buffer-name :initarg :name) (lines :accessor buffer-lines :type dll) (markers :accessor buffer-markers :initform '()) (mark :accessor buffer-saved-mark :initarg :mark :initform nil :documentation "Saved mark in the buffer.") (point :accessor buffer-saved-point :initarg :point :initform nil :documentation "Saved insertion point in the buffer.") (read-only-p :accessor buffer-read-only-p :initform nil) (changed-p :accessor buffer-changed-p :initform nil) (file :accessor buffer-file :initform nil))) (defclass marker () ((buffer :accessor marker-buffer :initarg :buffer :accessor marker-valid-p) (point :accessor marker-point :initarg :point) (gravity :accessor marker-gravity :initarg :gravity :initform :end :type (member :begin :end)))) (defclass frame () ((title :accessor frame-title :initarg :title :initform "") (window-list :accessor frame-window-list :initform '()) (mini-window :accessor frame-mini-window) (mini-buffer :accessor frame-mini-buffer) (prompt-window :accessor frame-prompt-window) (prompt-buffer :accessor frame-prompt-buffer) (width :accessor frame-width :initarg :width) (height :accessor frame-height :initarg :height) (screen :accessor frame-screen :initarg :screen))) (defgeneric context-buffer (window)) (defgeneric context-point (window)) (defgeneric context-mark (window)) (defgeneric context-save (window)) (defgeneric (setf context-point) (value window)) (defgeneric (setf context-mark) (value window)) (defclass context () ((buffer :accessor context-buffer :initarg :buffer) (mark :accessor context-mark :initarg :mark :initform nil :documentation "Mark in the buffer.") (point :accessor context-point :initarg :point :initform nil :documentation "Insertion point in the buffer.") (edited-p :accessor context-edited-p :initform nil))) (defclass window () ((frame :accessor window-frame :initarg :frame) (context :accessor window-context :initarg :context :initform nil) (top :accessor window-top :initarg :top) (left :accessor window-left :initarg :left) (height :accessor window-height :initarg :height) (width :accessor window-width :initarg :width) (changed-p :accessor window-changed-p :initform nil) (top-row :accessor window-top-row :initform 0 :documentation "Number of the line displayed on the top row of the window.") (name :accessor window-name :initarg :name))) (defclass window-with-status-bar (window) () (:documentation "This is a normal window, which displays a status bar at the bottom. Normally, only the bottom-most window, displaying the mini-buffer is a plain window without a status bar.")) (defgeneric window-bottom (window)) (defgeneric window-right (window)) (defgeneric window-visible-line-count (self)) (defgeneric window-visible-line-count (self)) (defgeneric window-move-cursor-to (self &key line column)) (defmethod window-bottom ((self window)) (+ (window-top self) (window-height self))) (defmethod window-right ((self window)) (+ (window-left self) (window-width self))) (defmethod window-visible-line-count ((self window)) (window-height self)) (defmethod window-visible-line-count ((self window-with-status-bar)) (1- (window-height self))) (defmethod window-move-cursor-to ((self window) &key (line 0) (column 0)) (let ((frame (window-frame self))) (format *log* "move cursor to x:~A, y:~A~%" (+ (window-left self) column) (+ (window-top self) line)) (set-screen-cursor-position (frame-screen frame) (+ (window-top self) line) (+ (window-left self) column)))) ;; +-----------------------------------------------------+ ;; |0,0 | |frame-width ;; | | | ;; | | | ;; | | | ;; | v | ;; | window-top | ;; | ---------------+---------------+ | ;; | | |0,0 | | | ;; | | | | | | ;; | | | |line | | ;; | | | | | | ;; | | | | | | ;; | v | | | | ;; | window-bottom | v | | ;; | ----------------+---------------+ | ;; | |window-left |window-width | ;; |---------------->|-------------->| | ;; | | ;; +-----------------------------------------------------+ ;; |frame-height | ;; Forward context methods: (defmethod context-buffer ((self window)) (and (window-context self) (context-buffer (window-context self)))) (defmethod context-point ((self window)) (and (window-context self) (context-point (window-context self)))) (defmethod context-mark ((self window)) (and (window-context self) (context-mark (window-context self)))) (defmethod (setf context-point) (value (self window)) (setf (context-point (window-context self)) value)) (defmethod (setf context-mark) (value (self window)) (setf (context-mark (window-context self)) value)) ;;;--------------------------------------------------------------------- ;;; Buffers & Markers ;;;--------------------------------------------------------------------- (defmethod initialize-instance :after ((self buffer) &key &allow-other-keys) (push self *buffer-list*) (setf (buffer-lines self) (dll)) (dll-insert (buffer-lines self) nil "") self) (defmethod print-object ((self buffer) stream) (print-unreadable-object (self stream :type t :identity t) (format stream ":name ~S" (buffer-name self))) stream) (defmethod initialize-instance :after ((self marker) &key &allow-other-keys) (buffer-add-marker (marker-buffer self) self)) (defmethod print-object ((self marker) stream) (print-unreadable-object (self stream :type t :identity t) (if (marker-valid-p self) (format stream ":buffer ~S :point ~A :gravity ~S" (buffer-name (marker-buffer self)) (marker-point self) (marker-gravity self)) (format stream ":valid-p nil"))) stream) (defmethod initialize-instance :after ((self context) &key &allow-other-keys) (setf (context-mark self) (or (context-mark self) (buffer-saved-mark (context-buffer self))) (context-point self) (or (context-point self) (buffer-saved-point (context-buffer self)) (make-instance 'marker :buffer (context-buffer self) :point 0 :gravity :end))) self) (defmethod context-save ((self context)) (setf (buffer-saved-mark (context-buffer self)) (context-mark self) (buffer-saved-point (context-buffer self)) (context-point self))) (defgeneric marker-delete (marker)) (defmethod marker-delete ((self marker)) (when (marker-valid-p self) (buffer-remove-marker (marker-buffer self) self)) (setf (marker-buffer self) nil) (values)) (defun current-buffer () "Return the current buffer as a Lisp object." (context-buffer *current-window*)) (defun buffer-line-count (buffer) (dll-length (buffer-lines buffer))) (defun buffer-or-error (buffer-or-name) (or (get-buffer buffer-or-name) (error "There is no buffer named ~S" buffer-or-name))) (defgeneric buffer-substring (buffer-designator start end)) (defgeneric buffer-contents (buffer)) (defgeneric buffer-delete-region (buffer-name start end)) (defmethod buffer-substring ((buffer-name string) start end) (buffer-substring (buffer-or-error buffer-name) start end)) (defmethod buffer-substring ((self buffer) start end) (in-order start end) (assert (<= start end)) (with-output-to-string (out) (multiple-value-bind (srow scolumn sline) (buffer-line-of-point self start) (declare (ignore srow)) (multiple-value-bind (erow ecolumn eline) (buffer-line-of-point self end) (declare (ignore erow)) (cond ((null sline)) ((eq sline eline) ;; one line: (format out "~A" (nsubseq (dll-node-item sline) scolumn ecolumn))) (t (when (plusp scolumn) ;; partial first line (format out "~A~%" (nsubseq (dll-node-item sline) scolumn)) (setf sline (dll-node-next sline))) (loop :until (eq sline eline) :do (format out "~A~%" (dll-node-item sline)) :do (setf sline (dll-node-next sline)) :finally (when eline (format out "~A~%" (nsubseq (dll-node-item eline) 0 ecolumn)))))))))) (defmethod buffer-contents (buffer) (buffer-substring buffer 0 (buffer-size buffer))) (defmethod buffer-delete-region ((buffer-name string) start end) (buffer-delete-region (buffer-or-error buffer-name) start end)) (defmethod buffer-delete-region ((self buffer) start end) (in-order start end) (assert (<= start end)) (when (< start end) (multiple-value-bind (srow scolumn sline) (buffer-line-of-point self start) (declare (ignore srow)) (multiple-value-bind (erow ecolumn eline) (buffer-line-of-point self end) (declare (ignore erow)) (if (eq sline eline) ;; one line: (setf (dll-node-item sline) (concatenate 'string (nsubseq (dll-node-item sline) 0 scolumn) (nsubseq (dll-node-item sline) ecolumn))) (progn (when (plusp scolumn) ;; partial first line (setf (dll-node-item sline) (nsubseq (dll-node-item sline) 0 scolumn)) (setf sline (dll-node-next sline))) (loop :until (eq sline eline) :do (let ((next (dll-node-next sline))) (dll-delete sline (buffer-lines self)) (setf sline next)) :finally (when sline (setf (dll-node-item sline) (nsubseq (dll-node-item sline) ecolumn)))))))) (setf (buffer-changed-p self) t) (buffer-move-markers-down self start (- end start)))) (defgeneric buffer-will-insert (buffer-designator) (:method ((buffer-name string)) (buffer-will-insert (buffer-or-error buffer-name))) (:method ((self buffer)) (when (buffer-read-only-p self) (error "Buffer is read-only: ~S" self)))) (defgeneric buffer-did-insert (buffer-designator) (:method ((buffer-name string)) (buffer-did-insert (buffer-or-error buffer-name))) (:method ((self buffer)) self)) (defgeneric buffer-insert (buffer-designator point text) (:method ((buffer-name string) point text) (buffer-insert (buffer-or-error buffer-name) point text)) (:method ((self buffer) (point marker) text) (buffer-insert self (marker-point point) text)) (:method ((self buffer) point text) (format *log* "buffer-insert buffer=~S point=~A text=~S~%" self point text) (when (plusp (length text)) (let ((lines (split-sequence #\newline text))) (format *log* "~{line: ~S~%~}" lines) (multiple-value-bind (row column current-line) (buffer-line-of-point self point) (declare (ignore row)) (cond ((null current-line) ; adding at the end of the buffer (loop :with new-node = (dll-last-node (buffer-lines self)) :for new-line :in lines :do (setf new-node (dll-insert (buffer-lines self) new-node new-line)))) ((null (cdr lines)) ; one line (let ((item (first lines))) (setf (dll-node-item current-line) (concatenate 'string (nsubseq (dll-node-item current-line) 0 column) item (nsubseq (dll-node-item current-line) column))))) (t ; at least two lines (loop :with before = (nsubseq (dll-node-item current-line) 0 column) :with after = (nsubseq (dll-node-item current-line) column) :with new-node = current-line :for new-lines :on (rest lines) :until (null (cdr new-lines)) :initially (setf (dll-node-item current-line) (concatenate 'string before (first lines))) (format *log* "inserting ~S~%" (first lines)) :do (setf new-node (dll-insert (buffer-lines self) new-node (car new-lines))) (format *log* "inserting ~S~%" (car new-lines)) :finally (format *log* "inserting ~S~%" after) (dll-insert (buffer-lines self) new-node after)))))) (setf (buffer-changed-p self) t) (buffer-move-markers-up self point (length text))) (clear-output *log*) (+ point (length text)))) (defgeneric buffer-point-of-line (buffer-designator line-number) (:method ((buffer-name string) line-number) (buffer-point-of-line (buffer-or-error buffer-name) line-number)) (:method ((self buffer) line-number) (loop :for line = (dll-first-node (buffer-lines self)) :then (dll-node-next line) :for point = 0 :then (+ point 1 (length (dll-node-item (dll-node-previous line)))) :repeat line-number :while (dll-node-next line) :finally (return point)))) (defgeneric buffer-line-of-point (buffer-designator point) (:documentation " RETURN: row; column; the line containing point, or NIL if point is at end of buffer on a new line. ") (:method ((buffer-name string) point) (buffer-line-of-point (buffer-or-error buffer-name) point)) (:method ((self buffer) point) (when (typep point 'marker) (setf point (marker-point point))) (loop :for line = (dll-first-node (buffer-lines self)) :then (dll-node-next line) :for bol = 0 :then eol :for eol = (if line (+ 1 (length (dll-node-item line))) 0) :then (if line (+ eol 1 (length (dll-node-item line))) eol) :for row :from 0 :while (and line (<= eol point)) :finally (return (values row (max 0 (- point bol)) line))))) (defgeneric buffer-size (buffer-designator) (:method ((buffer-name string)) (buffer-size (buffer-or-error buffer-name))) (:method ((self buffer)) (1- (loop :for line = (dll-first-node (buffer-lines self)) :then (dll-node-next line) :while line :sum (1+ (length (dll-node-item line))))))) (defgeneric buffer-add-marker (self marker)) (defgeneric buffer-remove-marker (self marker)) (defgeneric buffer-move-markers-up (self start offset)) (defgeneric buffer-move-markers-down (self start offset)) (defmethod buffer-add-marker ((self buffer) (marker marker)) (push marker (buffer-markers self)) (setf (marker-buffer marker) self) marker) (defmethod buffer-remove-marker ((self buffer) (marker marker)) (assert (eq self (marker-buffer marker))) (setf (buffer-markers self) (delete marker (buffer-markers self)) (marker-buffer marker) nil) self) (defmethod buffer-move-markers-up ((self buffer) start offset) (dolist (marker (buffer-markers self)) (format *log* "mup buffer=~S marker=~S start=~A offset=~A~%" self marker start offset) (format *log* "mup start=~A ~[<~;=~;~] point=~A ~%" start (cond ((< start (marker-point marker)) 0) ((= start (marker-point marker)) 1) (t 2)) (marker-point marker)) (clear-output *log*) (format *log* "mup new point = ~A ~%" (marker-point marker)) (when (or (< start (marker-point marker)) (and (= start (marker-point marker)) (eq :end (marker-gravity marker)))) (incf (marker-point marker) offset))) self) (defmethod buffer-move-markers-down ((self buffer) start offset) (let ((end (+ start offset))) (dolist (marker (buffer-markers self)) (cond ((<= end (marker-point marker)) (decf (marker-point marker) offset)) ((<= start (marker-point marker)) (setf (marker-point marker) start))))) self) (defun get-buffer (designator) (if (typep designator 'buffer) designator (find designator *buffer-list* :test (function string=) :key (function buffer-name)))) (defun get-buffer-create (designator) (or (get-buffer designator) (make-instance 'buffer :name designator))) (defun point () (marker-point (context-point *current-window*))) (defun mark () (and (context-mark *current-window*) (marker-point (context-mark *current-window*)))) (defun set-mark (point) (declare (interactive "d")) (if (context-mark *current-window*) (setf (marker-point (context-mark *current-window*)) point) (setf (context-mark *current-window*) (make-instance 'marker :buffer (current-buffer) :point point)))) (defun goto-char (target) (declare (interactive "n")) (assert (<= 0 target (buffer-size (context-buffer *current-window*)))) (setf (marker-point (context-point *current-window*)) target)) (defun point-min () 0) (defun point-max () (buffer-size (current-buffer))) (defun forward-char (&optional n) (declare (interactive "p")) (let* ((buffer (context-buffer *current-window*)) (size (buffer-size buffer))) (goto-char (if (<= (+ (point) n) size) (+ (point) n) size)))) (defun backward-char (&optional n) (declare (interactive "p")) (goto-char (if (minusp (- (point) n)) 0 (- (point) n)))) (defun beginning-of-line (&optional n) (declare (interactive "p")) (declare (ignore n)) ;; TODO: repeat (let ((buffer (context-buffer *current-window*))) (multiple-value-bind (row col line) (buffer-line-of-point buffer (context-point *current-window*)) (declare (ignore col line)) (goto-char (buffer-point-of-line buffer row))))) (defun end-of-line (&optional n) (declare (interactive "p")) (declare (ignore n)) ;; TODO: repeat (let ((buffer (context-buffer *current-window*))) (multiple-value-bind (row col line) (buffer-line-of-point buffer (context-point *current-window*)) (declare (ignore col)) (goto-char (if (or (null line) (null (dll-node-next line))) (buffer-size buffer) (+ (buffer-point-of-line buffer row) (length (dll-node-item line)))))))) (declaim (inline clip)) (defun clip (min value max) (cond ((< value min) min) ((< max value) max) (t value))) (defun increment-line (n successor-line) (let ((buffer (context-buffer *current-window*))) (multiple-value-bind (row col line) (buffer-line-of-point buffer (context-point *current-window*)) (let ((line (or line (dll-last-node (buffer-lines buffer))))) (goto-char (+ (buffer-point-of-line buffer (clip 0 (+ row n) (buffer-line-count buffer))) (loop :for next = (funcall successor-line line) :repeat n :while next :do (setf line next) :finally (return (min col (length (dll-node-item line))))))))))) (defun next-line (&optional (n 1)) (declare (interactive "p")) (increment-line n (function dll-node-next))) (defun previous-line (&optional (n 1)) (declare (interactive "p")) (increment-line (- n) (function dll-node-previous))) (defun erase-buffer () "Delete the entire contents of the current buffer. Any narrowing restriction in effect (see `narrow-to-region') is removed, so the buffer is truly empty after this." (declare (interactive)) (let* ((buffer (current-buffer)) (size (buffer-size buffer))) (setf (buffer-lines buffer) (dll)) (dll-insert (buffer-lines buffer) nil "") (buffer-move-markers-down buffer 0 size)) (dolist (marker (buffer-markers (current-buffer))) (assert (zerop (marker-point marker)))) (values)) (defun my-debug () (declare (interactive)) (dolist (window (apply (function append) (mapcar (function frame-window-list) *frame-list*))) (with-current-window window (erase-buffer) (insert "~S ~S" *current-window* (current-buffer))))) (defun message (ctrl-string &rest args) "Inserts a formated string in the *Messages* buffer, and displays it in the mini-window." (let ((text (apply (function format) nil ctrl-string args))) (with-buffer (get-buffer-create "*Messages*") (goto-char (point-max)) (insert "~A~%" text)) (with-current-window (frame-mini-window *current-frame*) (switch-to-buffer (frame-mini-buffer *current-frame*)) (erase-buffer) (insert "~A" text)) (when *log* (write-line text *log*)))) (defun backward-sexp (n) (declare (interactive "p")) (cond ((minusp n) (forward-sexp (- n))) ((plusp n) (let ((previous-text (buffer-substring (current-buffer) 0 (point)))) (if (plusp (length previous-text)) (with-input-from-string (src previous-text) (loop :for previous = nil :then current :for current = 0 :then (file-position src) :for sexp = (handler-case (read src nil src) (cl:error () src)) :until (eq sexp src) :finally (if previous (goto-char previous) (error "Cannot read previous S-expressions")))) (error "Beginning of buffer")))))) (defun forward-sexp (n) (declare (interactive "p")) (cond ((minusp n) (backward-sexp (- n))) ((plusp n) (goto-char (with-input-from-string (src (buffer-substring (current-buffer) (point) (buffer-size (current-buffer)))) (loop :for sexp = (read src nil src) :repeat n :until (eq sexp src) :finally (return (file-position src)))))))) (defun show-results (results insert-in-buffer-p) (if insert-in-buffer-p (insert "~%-->~{~S ~^;~% ~}" results) (message "~{~S~^ ;~}" results))) (defun eval-expression (expression &optional insert-results-p) (declare (interactive "xEval: ")) (show-results (multiple-value-list (eval expression)) insert-results-p)) (defun eval-last-sexp (result-in-buffer-p) (declare (interactive "P")) (let* ((end (point)) (start (prog1 (progn (backward-sexp 1) (point)) (goto-char end)))) (show-results (multiple-value-list (eval (read-from-string (buffer-substring (current-buffer) start end)))) result-in-buffer-p))) (defun execute-extended-command (command) (declare (interactive "CM-x ")) (insert "~S" command) (call-interactively command)) (defun buffer-for-file (path) " RETURN: The buffer associated with the file at PATH, or NIL if it doesn't exist. " (find-if (lambda (buffer) (and (buffer-file buffer) ;; we cannot use truename since that works only on existing files. (equalp path (file-pathname (buffer-file buffer))))) *buffer-list*)) (defun find-file (path) (declare (interactive "FFind file: ")) (let ((buffer (buffer-for-file path))) (if buffer (switch-to-buffer buffer) (let ((file (make-instance 'file :pathname path))) (switch-to-buffer (file-name file)) (setf (buffer-file (current-buffer)) file) (insert "~A" (file-contents file)) (goto-char 0))))) (defun save-buffer () (declare (interactive)) (let* ((buffer (current-buffer)) (file (buffer-file buffer))) (setf (file-contents file) (buffer-contents buffer)) (message "Wrote ~A" (file-pathname file)))) ;;;--------------------------------------------------------------------- ;;; Frames and Windows ;;;--------------------------------------------------------------------- (defvar *counter* 0) (defmethod initialize-instance :after ((self frame) &key &allow-other-keys) (setf ;; mini-buffer (frame-mini-buffer self) (get-buffer-create (format nil " *Minibuf~D*" (incf *counter*))) (frame-mini-window self) (make-instance 'window :name "mini" :frame self :context (make-instance 'context :buffer (frame-mini-buffer self)) :top (1- (frame-height self)) :height 1 :left 0 :width (frame-width self)) ;; prompt-buffer (frame-prompt-buffer self) (get-buffer-create (format nil " *Prompt~D*" *counter*)) (frame-prompt-window self) (make-instance 'window :name "prompt" :frame self :context (make-instance 'context :buffer (frame-prompt-buffer self)) :top (1- (frame-height self)) :height 1 :left 0 :width 0) ;; main window *current-window* (make-instance 'window-with-status-bar :name "main" :frame self :context (make-instance 'context :buffer (get-buffer-create "*scratch*")) :top 0 :height (1- (frame-height self)) :left 0 :width (frame-width self))) self) (defmethod print-object ((self frame) stream) (print-unreadable-object (self stream :type t :identity t) (format stream ":title ~S" (frame-title self))) stream) (defmethod initialize-instance :after ((self window) &key &allow-other-keys) (push self (frame-window-list (window-frame self))) self) (defmethod print-object ((self window) stream) (print-unreadable-object (self stream :type t :identity t) (when (window-context self) (format stream ":left ~D :bottom ~D :width ~D :height ~D :buffer ~S" (window-left self) (window-bottom self) (window-width self) (window-height self) (if (buffer-file (context-buffer self)) (file-name (buffer-file (context-buffer self))) (buffer-name (context-buffer self)))))) stream) (defparameter *mininum-minibuffer-width* 10 "BUG: Perhaps it should be relative to the screen width? Perhaps can't work with screen to narrow?") (defvar *recursive-edit* nil) (defun recursive-edit () (let ((*recursive-edit* t)) (catch 'abort-recursive-edit (return-from recursive-edit (catch 'end-recursive-edit (redisplay) (keyboard-loop)))) (throw 'keyboard-quit nil))) (defun read-char-exclusive (&key PROMPT INHERIT-INPUT-METHOD) (error "not implemented yet (~S ~S ~S)" 'read-char-exclusive PROMPT INHERIT-INPUT-METHOD)) (defun read-from-minibuffer (prompt &key initial-contents read keymap inherit-input-method history keep-all default-value) (declare (ignore default-value keep-all history inherit-input-method));TODO: handle them. (setf prompt (or prompt "")) (with-current-window (frame-mini-window *current-frame*) (let ((*keymap* (keymap-copy (or keymap *keymap*) :shallow t)) (done (lambda () (declare (interactive)) (throw 'end-recursive-edit nil))) (abort (lambda () (declare (interactive)) (throw 'abort-recursive-edit nil)))) (keymap-bind-key *keymap* #\return done) (keymap-bind-key *keymap* #\newline done) (keymap-bind-key *keymap* '(:control #\g) abort) (erase-buffer) (with-current-window (frame-prompt-window *current-frame*) (erase-buffer) (insert "~A" prompt)) (let ((mlen (- (frame-width *current-frame*) *mininum-minibuffer-width*)) (plen (length prompt))) (when (< mlen plen) (setf plen mlen)) (setf (window-left (frame-prompt-window *current-frame*)) 0 (window-width (frame-prompt-window *current-frame*)) plen (window-left *current-window*) plen (window-width *current-window*) (- (frame-width *current-frame*) plen))) (unwind-protect (progn (when initial-contents (insert "~A" initial-contents)) (recursive-edit) (if read (read-from-string (buffer-contents (current-buffer))) (buffer-contents (current-buffer)))) (setf (window-left (frame-prompt-window *current-frame*)) 0 (window-width (frame-prompt-window *current-frame*)) 0 (window-left *current-window*) 0 (window-width *current-window*) (frame-width *current-frame*)))))) (defun list-buffers (&optional file-only-p) (declare (interactive "P")) (declare (ignore file-only-p)) ;for now (switch-to-buffer "*Buffer List*") (erase-buffer) (insert "~20A ~8A ~18A ~A~%" "Buffer" "Size" "Mode" "File") (dolist (buffer *buffer-list*) (insert "~20A ~8D ~18A ~A~%" (buffer-name buffer) (buffer-line-count buffer) "Lisp" (if (buffer-file buffer) (file-pathname (buffer-file buffer)) "")))) (defun switch-to-buffer (buffer) "Select BUFFER in the current window. If BUFFER does not identify an existing buffer, then this command creates a buffer with that name." (declare (interactive "BSwitch to buffer: ")) (context-save (window-context *current-window*)) (setf (window-context *current-window*) (make-instance 'context :buffer (get-buffer-create buffer)))) (defun kill-buffer (&optional buffer) (declare (interactive "bKill buffer:")) ;; TODO: query buffer with current-buffer as default. (setf buffer (get-buffer (or buffer (current-buffer)))) (setf *buffer-list* (delete buffer *buffer-list*)) (when (eq buffer (current-buffer)) (switch-to-buffer (first *buffer-list*))) (dolist (frame *frame-list*) (dolist (window (frame-window-list frame)) (when (eq buffer (context-buffer window)) (let ((*current-window* window)) (switch-to-buffer (first *buffer-list*))))))) (defun insert (ctrl-string &rest args) (buffer-will-insert (current-buffer)) (buffer-insert (current-buffer) (context-point *current-window*) (apply (function format) nil ctrl-string args)) (buffer-did-insert (current-buffer))) ;; OLD: ;; +-----------------------------------------------------+ ;; |0,0 | |frame-width ;; | | | ;; | | | ;; | | | ;; | | | ;; | | window-height | ;; | | +---------------+ | ;; | | | ^ | | ;; | | | | | | ;; | | | |line | | ;; | | | | | | ;; | | | | | | ;; | v | | | | ;; | window-bottom |0,0 | |window-width | ;; | ----------------+---------------+ | ;; | |window-left | ;; |---------------->| | ;; | | ;; +-----------------------------------------------------+ ;; |frame-height | ;; NEW: ;;;--------------------------------------------------------------------- ;;; Display Engine ;;;--------------------------------------------------------------------- (defgeneric display-line (window line)) (defgeneric display (window)) (defmethod display-line ((self window) line) (format (screen-stream (frame-screen (window-frame self))) "~VA" (window-width self) (nsubseq line 0 (min (window-width self) (length line))))) (defmethod display ((self window)) (loop :with screen = (frame-screen (window-frame self)) :with width = (window-width self) :with buffer = (context-buffer (window-context self)) :for row :from (window-top-row self) :for line = (dll-node-nth (window-top-row self) (buffer-lines buffer)) :then (dll-node-next line) :repeat (print (min (window-visible-line-count self) (- (buffer-line-count buffer) (window-top-row self))) *log*) :do (window-move-cursor-to self :line row) :do (let ((line (dll-node-item line))) (screen-format screen "~VA" width (nsubseq line 0 (min width (length line)))) (clear-screen-to-eol screen)))) (defun scroll-up (&optional n) (declare (interactive "p")) (message "n=~S" n) (setf (window-top-row *current-window*) (min (mod (+ (window-top-row *current-window*) (etypecase n (null (window-height *current-window*)) (cons (first n)) (integer n))) (window-height *current-window*)) (dll-length (buffer-lines (context-buffer (window-context *current-window*))))))) (defun scroll-down (&optional n) (declare (interactive "P")) (scroll-up (etypecase n (null n) (cons (list (- (first n)))) (integer (- n))))) (defmethod display ((self window-with-status-bar)) ;; 1- display the status bar: (window-move-cursor-to self :line (window-bottom self)) (let ((screen (frame-screen (window-frame self)))) (unwind-protect (progn (screen-highlight-on screen) (window-move-cursor-to self :line (1- (window-height self))) (screen-format screen "~VA" (window-width self) (let* ((lines (dll-length (buffer-lines (current-buffer)))) (status (format nil "--:-- ~A ~D% L~D (~:(~{~A~^ ~}~))" (buffer-name (context-buffer self)) (truncate (/ (window-top-row *current-window*) (1+ lines)) 1/100) lines '(lisp)))) (subseq status 0 (min (window-width self) (length status)))))) (screen-highlight-off screen))) ;; 2- display the contents (call-next-method)) (defun redisplay () (declare (interactive)) ;; (dolist (frame *frame-list*) ;; (with-current-screen (frame-screen frame))) (unwind-protect (progn (format *log* "redisplay: clear-screen~%") (screen-cursor-off *current-screen*) (clear-screen *current-screen*) (dolist (window (frame-window-list *current-frame*)) (format *log* "redisplay: display window ~A~%" (window-name window)) (display window)) (multiple-value-bind (row column) (buffer-line-of-point (context-buffer *current-window*) (context-point *current-window*)) (format *log* "redisplay: move cursor to x:~A, y:~A~%" column (- row (window-top-row *current-window*))) (window-move-cursor-to *current-window* :line (- row (window-top-row *current-window*)) :column column))) ;; (finish-output (screen-stream *current-screen*)) (screen-cursor-on *current-screen*) (format *log* "redisplay: done~%") (finish-output *log*))) ;;;--------------------------------------------------------------------- ;;; Miscellaneous Commands ;;;--------------------------------------------------------------------- (defun not-implemented-yet () (declare (interactive)) (message "Not implemented yet.")) (defun test-command () (declare (interactive)) (insert "~%Test ~D~%" (incf *counter*))) ;;;--------------------------------------------------------------------- ;;; Editor ;;;--------------------------------------------------------------------- (defun editor-reset () (setf *current-screen* nil *buffer-list* '() *current-frame* nil *frame-list* '() *current-window* nil *counter* 0 *last-command-char* nil *keymap* (keymap-copy *default-keymap*)) (values)) (defun editor-initialize (screen) (multiple-value-bind (height width) (screen-size screen) (setf *current-frame* (make-instance 'frame :screen screen :width width :height height :title "editor") *frame-list* (list *current-frame*))) (insert *scratch-buffer-default-contents*) (redisplay)) (defun editor-terminate () (format t "~&Good bye!~%") (values)) (defun command-character (keyboard-event) (etypecase keyboard-event (character keyboard-event) (list (car (last keyboard-event))))) (defun yank (repeat-count) (declare (interactive "p")) (if (minusp repeat-count) (let ((start (point))) (yank (- repeat-count)) (goto-char start)) (loop :repeat repeat-count :do (insert "~A" *yank*)))) (defun kill-region (start end) (declare (interactive "r")) (setf *yank* (buffer-substring (current-buffer) start end)) (unless (buffer-read-only-p (current-buffer)) (buffer-delete-region (current-buffer) start end) (setf *this-command* 'kill-region))) (defun delete-char (&optional n) (declare (interactive "p")) (cond ((minusp n) (delete-backward-char (- n))) ((plusp n) (kill-region (point) (+ (point) n))))) (defun delete-backward-char (&optional n) (declare (interactive "p")) (cond ((minusp n) (delete-char (- n))) ((plusp n) (kill-region (point) (- (point) n))))) (defun kill-sexp (n) (declare (interactive "p")) (kill-region (point) (progn (forward-sexp n) (point)))) (defun kill-line (repeat-count) "Kill the rest of the current line; if no nonblanks there, kill thru newline. With prefix argument, kill that many lines from point. Negative arguments kill lines backward. With zero argument, kills the text before point on the current line. When calling from a program, nil means \"no arg\", a number counts as a prefix arg. To kill a whole line, when point is not at the beginning, type \ \\[beginning-of-line] \\[kill-line] \\[kill-line]. If `*kill-whole-line*' is non-nil, then this command kills the whole line including its terminating newline, when used at the beginning of a line with no argument. As a consequence, you can always kill a whole line by typing \\[beginning-of-line] \\[kill-line]. If you want to append the killed line to the last killed text, use \\[append-next-kill] before \\[kill-line]. If the buffer is read-only, Emacs will beep and refrain from deleting the line, but put the line in the kill ring anyway. This means that you can use this command to copy text from a read-only buffer. \(If the variable `kill-read-only-ok' is non-nil, then this won't even beep.)" (declare (interactive "*P")) (declare (ignorable repeat-count)) (kill-region (point) (progn (end-of-line) (1+ (point)))) #+ (or) (let ((start (point))) (if (zerop (length (string-trim #(#\space #\tab) (buffer-substring (current-buffer) start (progn (end-of-line) (point)))))) ;; TODO ))) (defun new-line (repeat-count) "Inserts a new line." (declare (interactive "p")) (insert "~V%" repeat-count)) (defun self-insert-command (repeat-count) "Inserts the last command character." (declare (interactive "p")) (loop :with datum = (command-character *last-command-char*) :repeat repeat-count :do (insert "~A" datum))) (defun digit-argument (prefix) "Part of the numeric argument for the next command. \\[universal-argument] following digits or minus sign ends the argument." (declare (interactive "P")) (let ((digit (digit-char-p (command-character *last-command-char*)))) (setf *prefix-arg* (cond ((integerp prefix) (+ (* prefix 10) (if (minusp prefix) (- digit) digit))) ((eql '- prefix)(if (zerop digit) '- (- digit))) (t digit)))) ;; (setq universal-argument-num-events (length (this-command-keys))) ;; (ensure-overriding-map-is-bound) ) (defun universal-argument () "Begin a numeric argument for the following command. Digits or minus sign following C-u make up the numeric argument. C-u following the digits or minus sign ends the argument. C-u without digits or minus sign provides 4 as argument. Repeating C-u without digits or minus sign multiplies the argument by 4 each time. For some commands, just C-u by itself serves as a flag which is different in effect from any particular numeric argument. These commands include C-@ and M-x start-kbd-macro." (declare (interactive)) (setf *prefix-arg* (list 4)) ;; (setq universal-argument-num-events (length (this-command-keys))) ;; (ensure-overriding-map-is-bound) ) (defun negative-argument (arg) "Begin a negative numeric argument for the next command. \\[universal-argument] following digits or minus sign ends the argument." (declare (interactive "P")) (setf *prefix-arg* (cond ((integerp arg) (- arg)) ((eq arg '-) nil) (t '-))) ;; (setq universal-argument-num-events (length (this-command-keys))) ;; (ensure-overriding-map-is-bound)) ) (defun editor-quit () "Quit the editor." (declare (interactive)) (throw 'editor-quit nil)) (defun keyboard-quit () "Reset the keyboard state" (declare (interactive)) (throw 'keyboard-quit nil)) (defun keyboard-modifiers (bits) (loop :for bit = 1 :then (* 2 bit) :for modifier :in '(:control :meta :super :hyper) :unless (zerop (logand bit bits)) :collect modifier)) (defvar *current-keymap* nil) (defvar *current-sequence* '()) (defun editor-reset-key () (setf *current-keymap* *keymap* *current-sequence* '())) (defun editor-process-key (key) (let ((binding (keymap-binding *current-keymap* key))) (push key *current-sequence*) (cond ((keymapp binding) (format *log* "editor-process-key -> keymap ~{~A ~}~%" (reverse *current-sequence*)) (setf *current-keymap* binding)) ((or (and (symbolp binding) (fboundp binding) (interactivep binding)) (and (functionp binding) (interactivep binding))) (format *log* "editor-process-key -> binding ~{~A ~} --> ~S~%" (reverse *current-sequence*) binding) (setf *last-command-char* (first *current-sequence*) *this-command* binding *current-prefix-arg* *prefix-arg* *prefix-arg* nil) (call-interactively binding) (setf *last-command* *this-command*) (editor-reset-key)) ((null binding) (beep)) (t (message "~{~A ~} is bound to a non-command: ~S~%" (reverse *current-sequence*) binding) (editor-reset-key))))) (defvar *handler-window-height* 10) (defvar *handler-window-current* 0) (defun handler-window-position () (multiple-value-bind (width height) (screen-size *current-screen*) (declare (ignore width)) (truncate (- height *handler-window-height*) 2))) (defun handler-window-current-position () (+ *handler-window-current* (handler-window-position))) (defun handler-window-initialize () (loop :for y = (handler-window-position) :repeat *handler-window-height* :do (set-screen-cursor-position *current-screen* y 0) (clear-screen-to-eol *current-screen*)) (setf *handler-window-current* 0)) (defun handler-window-writeln (format-control &rest arguments) (when (<= *handler-window-height* *handler-window-current*) (setf *handler-window-current* 0)) (set-screen-cursor-position *current-screen* (handler-window-current-position) 0) (ignore-errors (screen-write-string *current-screen* (apply (function format) nil format-control arguments))) (incf *handler-window-current*)) (defun beep ()) (defgeneric screen-read-line (screen)) (defmethod screen-read-line ((screen screen)) (restart-bind ((continue-reading (lambda () (throw 'continue-read (values))) :report-function (reportly "Continue reading line."))) (let ((line (make-array 80 :element-type 'character :adjustable t :fill-pointer 0)) (meta-seen-p nil)) (loop (catch 'continue-read (let ((chord (keyboard-chord-no-hang *current-screen*))) (when chord (let ((key (chord-character chord)) (modifiers (append (when meta-seen-p (setf meta-seen-p nil) '(:meta)) (symbolic-modifiers (chord-modifiers chord))))) (cond ((eql #\escape key) (setf meta-seen-p t)) (modifiers (beep)) ((eql #\rubout key) (when (plusp (fill-pointer line)) (decf (fill-pointer line)) (multiple-value-bind (column line) (screen-cursor-position *current-screen*) (set-screen-cursor-position *current-screen* (1- column) line) (screen-write-string *current-screen* " ")))) ((find key #(#\Newline #\Return #\Linefeed)) (return-from screen-read-line line)) (t (screen-write-string *current-screen* (string key)) (vector-push-extend key line))))))))))) (defvar *condition*) (defun handle-editor-error (condition) (let* ((restarts (compute-restarts condition)) (last-r (1- (length restarts)))) (flet ((print-restart-list () (setf last-r (loop :for r :in restarts :for i :from 0 :do (handler-window-writeln "~D: (~10A) ~A" i (restart-name r) r) :until (eq (restart-name r) 'abort) :finally (return i))))) (let ((restart (loop :for n = (progn (handler-window-initialize) (handler-window-writeln "~A" condition) (print-restart-list) (handler-window-writeln "Option: ") (prog1 (ignore-errors (read-from-string (screen-read-line *current-screen*))) (handler-window-writeln ""))) :until (and (typep n 'integer) (<= 0 n last-r)) :finally (return (nth n restarts))))) (handler-window-writeln "~S" (list 'restart '= (restart-name restart))) (handler-window-writeln "~S" (list '*debugger-hook* '= *debugger-hook*)) (let ((*condition* condition)) (handler-bind ((cl:error (function invoke-debugger))) (redisplay) (invoke-restart-interactively restart))))))) (defun reportly (string) (lambda (stream) (format stream "~A" string))) (defun keyboard-loop () (handler-bind ((cl:error (function handle-editor-error))) (restart-bind ((debug (lambda () (invoke-debugger *condition*)) :report-function (reportly "Invoke the debugger.")) (continue (lambda () (throw 'keyboard-quit (values))) :report-function (reportly "Continue editing.")) (abort (lambda () (throw 'editor-quit (values))) :report-function (reportly "Quit the editor."))) (catch 'editor-quit (loop (catch 'keyboard-quit (loop :with redisplayed = t :with meta-seen-p = nil :for chord = (keyboard-chord-no-hang *current-screen*) :initially (editor-reset-key) (redisplay) :do (if chord (let ((key (chord-character chord)) (modifiers (append (when meta-seen-p (setf meta-seen-p nil) '(:meta)) (symbolic-modifiers (chord-modifiers chord))))) (format *log* "chord = ~S meta-seen-p = ~S key = ~S modifiers = ~S~%" chord meta-seen-p key modifiers) (if (eql #\escape key) (setf meta-seen-p t) (progn (editor-process-key (if modifiers (append modifiers (list key)) key)) (setf redisplayed nil))) ;; (message "key=~S modifiers=~S" key modifiers) ) (unless redisplayed (redisplay) (setf redisplayed t)))))))))) #+mocl (defun shadow-synonym-stream (stream synonym) (declare (ignore synonym)) stream) #-mocl (defun shadow-synonym-stream (stream synonym) (if (and (typep stream 'synonym-stream) (eq synonym (synonym-stream-symbol stream))) (symbol-value synonym) stream)) (defun screen-editor (&key log (screen-class 'charms-screen)) (with-open-stream (*log* (typecase log ((member :xterm) (make-xterm-io-stream :geometry "100x24+0+0")) ((or string pathname) (open log :direction :output :if-exists :append :if-does-not-exist :create)) (file log) (otherwise (make-broadcast-stream)))) (let ((*error-output* *log*) (*trace-output* *log*) (screen (make-instance screen-class))) (screen-initialize-for-terminal screen (getenv "TERM")) (editor-reset) (with-screen screen (editor-initialize *current-screen*) (unwind-protect (keyboard-loop) (set-screen-cursor-position *current-screen* 0 (screen-size *current-screen*)) (clear-screen *current-screen*)) (editor-terminate))))) (defun editor () (screen-editor :log "/tmp/editor.log")) (defun ed (&rest args) (apply (function screen-editor) args)) #-mocl (defun reload () (in-package "CL-USER") (funcall (when (find-package "QL") (intern "QUICKLOAD" (find-package "QL")) (function identity)) :com.informatimago.editor) (in-package "EDITOR")) (in-package "COMMON-LISP-USER") #-mocl (progn (print '(COM.INFORMATIMAGO.EDITOR::reload)) (print '(COM.INFORMATIMAGO.EDITOR:screen-editor)) (print '(COM.INFORMATIMAGO.EDITOR:ed))) ;;;; THE END ;;;;
84,208
Common Lisp
.lisp
1,790
37.501117
212
0.55277
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
3bc57ab93522681f276aca977de75fcd055724fe527b858cc98d8fd5c1762a3b
4,816
[ -1 ]
4,817
package.lisp
informatimago_lisp/editor/package.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: package.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines the editor package. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-11 <PJB> Extracted from editor.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.EDITOR" (:use "COMMON-LISP" "SPLIT-SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DLL" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.LISP-SEXP.SOURCE-FORM" "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM") #+mocl (:shadowing-import-from "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING" "*TRACE-OUTPUT*" "ARRAY-DISPLACEMENT" "CHANGE-CLASS" "COMPILE" "COMPLEX" "ENSURE-DIRECTORIES-EXIST" "FILE-WRITE-DATE" "INVOKE-DEBUGGER" "*DEBUGGER-HOOK*" "LOAD" "LOGICAL-PATHNAME-TRANSLATIONS" "MACHINE-INSTANCE" "MACHINE-VERSION" "NSET-DIFFERENCE" "RENAME-FILE" "SUBSTITUTE-IF" "TRANSLATE-LOGICAL-PATHNAME") (:shadow "DEFUN" "LAMBDA" "ED" "ERROR") (:export "DEFUN" "LAMBDA" "ED") (:export "SCREEN-EDITOR" "EDITOR") (:documentation " An emacs-like editor written in Common Lisp. Copyright Pascal J. Bourguignon 2006 - 2015 AGPL3 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/>. ")) ;;;; THE END ;;;;
3,552
Common Lisp
.lisp
78
36.961538
83
0.577489
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
aa15a14f1effbc032d7a6195a83c7e493c7fc25b1f80337d86f2cdd4d41b87fd
4,817
[ -1 ]
4,818
charms-screen.lisp
informatimago_lisp/editor/charms-screen.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: charm-screen.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Implements a SCREEN using CL-CHARMS. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-11 <PJB> Extracted from editor.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.EDITOR") (defclass charms-screen (screen) () (:documentation "This SCREEN subclass uses cl-charms (ncurses).")) (defmethod screen-size ((screen charms-screen)) (multiple-value-bind (width height) (charms:window-dimensions charms:*standard-window*) (values height (1- width)))) (defmethod screen-cursor-position ((screen charms-screen)) (charms:cursor-position charms:*standard-window*)) (defmethod set-screen-cursor-position ((screen charms-screen) line column) (charms:move-cursor charms:*standard-window* column line)) (defmethod clear-screen-to-eot ((screen charms-screen)) (charms:clear-window-after-cursor charms:*standard-window*)) (defmethod clear-screen-to-eol ((screen charms-screen)) (charms:clear-line-after-cursor charms:*standard-window*)) (defmethod delete-screen-line ((screen charms-screen)) ;; (charms/ll:deleteln) ) (defmethod insert-screen-line ((screen charms-screen)) ;; (charms/ll:insertln) ) (defmethod screen-highlight-on ((screen charms-screen)) ) (defmethod screen-highlight-off ((screen charms-screen)) ) (defmethod screen-cursor-on ((screen charms-screen)) ) (defmethod screen-cursor-off ((screen charms-screen)) ) (defmethod screen-write-string ((screen charms-screen) string) (loop :for ch :across string :do (charms:write-char-at-cursor charms:*standard-window* ch)) ;; (charms:write-string-at-cursor charms:*standard-window* string) string) (defmethod screen-refresh ((screen charms-screen)) (charms:refresh-window charms:*standard-window*)) (defmethod keyboard-chord-no-hang ((screen charms-screen)) (let ((ch (charms:get-char charms:*standard-window* :ignore-error t))) (format *trace-output* "got char ~A~%" ch) (force-output *trace-output*) (when ch (if (find ch #(#\newline #\tab #\esc #\return #\rubout)) (make-instance 'chord :character ch :modifiers 0) (let* ((code (char-code ch)) (kode (mod code 128)) (controlp (< kode 32)) (metap (< 128 code))) (make-instance 'chord :character (code-char (+ kode (if controlp (if (< 0 kode 27) (load-time-value (char-code #\`)) (load-time-value (char-code #\@))) 0))) :modifiers (+ (if controlp (expt 2 +control+) 0) (if metap (expt 2 +meta+) 0)))))))) (defmethod call-with-screen ((screen charms-screen) thunk) (charms:with-curses () (charms:disable-echoing) (charms:enable-raw-input :interpret-control-characters nil) (charms:enable-non-blocking-mode charms:*standard-window*) (charms:enable-extra-keys charms:*standard-window*) ; keypad t (charms::check-status (charms/ll:meta (charms::window-pointer charms:*standard-window*) charms/ll:TRUE)) (funcall thunk screen))) ;; (defmethod call-with-current-screen ((screen charms-screen) thunk) ;; ) ;;;; THE END ;;;;
4,917
Common Lisp
.lisp
106
38.207547
108
0.585768
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ccbfb6d3b5e9c5fba9c2fbc75f5506bebd863cc911d18f447a3ae29a1f51e81c
4,818
[ -1 ]
4,819
xterm.lisp
informatimago_lisp/editor/xterm.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: xterm.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; XXX ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-03-16 <PJB> Added this header. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.EDITOR") (defvar *mktemp-program* "mktemp") (defvar *mkfifo-program* "mkfifo") (defvar *xterm-program* "/opt/X11/bin/xterm") (defun mktemp (pattern) (with-open-stream (input (process-output (run-program *mktemp-program* (list pattern) :output :stream))) (read-line input))) (defun make-xterm-io-stream (&key (display ":0.0") (geometry "80x24") (foreground "black") (background "white") (title "lisp") (font "fixed") (element-type 'character) (external-format :default)) (let ((pipe (mktemp "/tmp/xterm-io-XXXXXX"))) (ignore-errors (delete-file pipe)) (when (zerop (process-status (run-program *mkfifo-program* (list pipe) :wait t))) (run-program *xterm-program* (list "-geometry" geometry "-display" display "-fg" foreground "-bg" background "-title" title "-fn" font "-e" (let ((*print-circle* nil) (*print-escape* t)) (format nil "bash -c 'tty>>~A && cat ~:*~A'" pipe))) :wait nil) (let* ((tty-name (with-open-file (s pipe) (read-line s))) (xio (make-two-way-stream (open tty-name :direction :input :element-type element-type :external-format external-format #+clisp :buffered #+clisp nil) (open tty-name :direction :output :element-type element-type :external-format external-format :if-exists :append #+clisp :buffered #+clisp nil)))) ;; (system::terminal-raw (two-way-stream-input-stream xio) t t) (defmethod close :after ((x (eql xio)) &rest junk) (declare (ignore x junk)) (ignore-errors (with-open-file (s pipe :direction :output) (write-line "Bye." s) (finish-output s))) (delete-file pipe) (close (two-way-stream-input-stream xio)) (close (two-way-stream-output-stream xio)) (let () ;; ((clos::*warn-if-gf-already-called* nil)) (remove-method #'close (find-method #'close '(:after) `((eql ,xio)))))) xio)))) (cffi:defcfun "fdopen" :pointer (fd :int) (flag :string)) (cffi:defcfun "fclose" :int (file :pointer)) (defun make-xterm-io-filedes (&key (display ":0.0") (geometry "80x24") (foreground "black") (background "white") (title "lisp") (font "fixed")) #-ccl (error "Not implemented yet for ~S" (lisp-implementation-type)) (let ((pipe (mktemp "/tmp/xterm-io-XXXXXX"))) (ignore-errors (delete-file pipe)) (when (zerop (process-status (run-program *mkfifo-program* (list pipe) :wait t))) (run-program *xterm-program* (list "-geometry" geometry "-display" display "-fg" foreground "-bg" background "-title" title "-fn" font "-e" (let ((*print-circle* nil) (*print-escape* t)) (format nil "bash -c 'tty>>~A && cat ~:*~A'" pipe))) :wait nil) (let ((tty-name (with-open-file (s pipe) (read-line s)))) #+ccl (cffi:with-foreign-strings ((in "r") (out "a")) (values (fdopen (ccl::fd-open tty-name #$O_RDONLY) in) (fdopen (ccl::fd-open tty-name (logior #$O_WRONLY #$O_APPEND)) out))))))) (defclass xterm-screen (charms-screen) ((term :reader xterm-screen-term) (win :reader xterm-screen-win)) (:documentation #+french "Cette sous-classe de SCREEN utilise un xterm via un pty." #-(or french) "This SCREEN subclass uses an xterm thru a pty.")) (defmethod initialize-instance :after ((self xterm-screen) &key &allow-other-keys) (setf (slot-value self 'term) (multiple-value-bind (in out) (make-xterm-io-filedes) (cffi:with-foreign-string (term "xterm") (cl-charms/low-level:newterm term in out))))) (defmethod screen-size ((self xterm-screen)) (call-next-method)) (defmethod screen-cursor-position ((self xterm-screen)) (call-next-method)) (defmethod set-screen-cursor-position ((self xterm-screen) line column) (call-next-method)) (defmethod clear-screen-to-eot ((self xterm-screen)) (call-next-method)) (defmethod clear-screen-to-eol ((self xterm-screen)) (call-next-method)) (defmethod delete-screen-line ((self xterm-screen)) (call-next-method)) (defmethod insert-screen-line ((self xterm-screen)) (call-next-method)) (defmethod screen-highlight-on ((self xterm-screen)) (call-next-method)) (defmethod screen-highlight-off ((self xterm-screen)) (call-next-method)) (defmethod screen-cursor-on ((self xterm-screen)) (call-next-method)) (defmethod screen-cursor-off ((self xterm-screen)) (call-next-method)) (defmethod keyboard-chord-no-hang ((self xterm-screen)) (call-next-method)) (defmethod call-with-screen ((self xterm-screen) thunk) (unwind-protect (progn (cl-charms/low-level:set-term (xterm-screen-term self)) (setf (slot-value self 'win) (cl-charms:make-window 0 0 0 0)) (let ((charms:*standard-window* (xterm-screen-win self))) (charms:disable-echoing) (charms:enable-raw-input :interpret-control-characters nil) (charms:enable-non-blocking-mode charms:*standard-window*) (charms:enable-extra-keys charms:*standard-window*) ; keypad t (charms::check-status (charms/ll:meta (charms::window-pointer charms:*standard-window*) charms/ll:TRUE)) (funcall thunk self))) (charms::check-status (charms/ll:delwin (slot-value self 'win))) (setf (slot-value self 'win) nil) (charms:finalize))) #-(and) ( (defvar *x* (make-xterm-io-stream)) (defparameter *screen* ) (cl-charms/low-level:set-term *screen*) (defparameter *win* (cl-charms:make-window 0 0 0 0)) (let ((buffer (make-array 128 :element-type '(unsigned-byte 8)))) (values (read-sequence buffer (process-output *p*)) buffer)) (close (process-input *p*)) (close (process-output *p*)) (progn (defvar *in*) (defvar *out*) (multiple-value-setq (*in* *out*) (make-xterm-io-filedes)) (values *in* *out*)) (defparameter *screen* (multiple-value-bind (in out) (make-xterm-io-filedes) (cffi:with-foreign-string (term "xterm") (cl-charms/low-level:newterm term in out)))) (cl-charms/low-level:set-term *screen*) (defparameter *win* (cl-charms:make-window 0 0 0 0)) (make-xterm-io-filedes) )
8,905
Common Lisp
.lisp
177
38.80791
115
0.545423
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
64d7f3380c07830e0f1f74f23dd43042e8116fa5fdd2c48758197ea371979087
4,819
[ -1 ]
4,820
clisp.lisp
informatimago_lisp/editor/clisp.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: clisp.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; clisp specific functions. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-11 <PJB> Extracted from editor.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.EDITOR") (defun make-xterm-io-stream (&key display geometry) (let* ((pipe (with-open-stream (s (ext:make-pipe-input-stream "mktemp /tmp/clisp-x-io-XXXXXX")) (read-line s))) (title "CLISP I/O") ;; (clos::*warn-if-gf-already-called* nil) (font nil #+(or) "-*-console-medium-r-normal-*-16-*-*-*-*-*-*-*" #+(or)"-dec-terminal-bold-r-normal-*-14-*-*-*-*-*-dec-dectech")) ;; xterm creates a pty, forks, hooks the pty to stdin/stdout ;; and exec bash with the commands given in -e. ;; We write this pty path to our pipe, ;; and cat our pipe to wait for the end. ;; Meanwhile, we'll be reading and writing this pty. (ext:shell (format nil "rm -f ~S; mknod ~S p; xterm ~ ~:[~;~:*-geometry ~S~] ~:[~;~:*-display ~S~] ~ -fg green -bg black ~:[~;~:*-fn '~A'~] -n ~S -T ~S ~ -e 'tty >> ~S ; cat ~S' &" pipe pipe geometry display font title title pipe pipe)) (let* ((tty-name (with-open-file (s pipe) (read-line s))) (xio (make-two-way-stream (open tty-name :direction :input :buffered nil) (open tty-name :direction :output :buffered nil)))) (system::terminal-raw (two-way-stream-input-stream xio) t t) (defmethod close :after ((x (eql xio)) &rest junk) (declare (ignore x junk)) (ignore-errors (with-open-file (s pipe :direction :output) (write-line "Bye." s))) (delete-file pipe) (close (two-way-stream-input-stream xio)) (close (two-way-stream-output-stream xio)) (let () ;; ((clos::*warn-if-gf-already-called* nil)) (remove-method #'close (find-method #'close '(:after) `((eql ,xio)))))) xio))) (defun screen-editor (&key log) (cond ((string= "xterm" (getenv "TERM")) (setf custom:*terminal-encoding* (ext:make-encoding :charset charset:iso-8859-1 :line-terminator :unix))) ((string= "kterm" (getenv "TERM")) (setf custom:*terminal-encoding* (ext:make-encoding :charset charset:utf-8 :line-terminator :unix)))) (editor-reset) (let ((*log* (typecase log ((member :xterm) (make-xterm-io-stream :geometry "100x24+0+0")) ((or string pathname) (open log :direction :output :if-exists :append :if-does-not-exist :create)) (file log) (otherwise (make-broadcast-stream))))) (unwind-protect (with-open-screen (make-instance 'clisp-screen) (editor-initialize *current-screen*) (unwind-protect (keyboard-loop) (set-screen-cursor-position *current-screen* 0 (screen-size *current-screen*)) (clear-screen *current-screen*)) (editor-terminate)) (close *log*)))) (defun keyboard-test () (screen:with-window nil (screen:set-window-cursor-position screen:*window* 2 10) (format t "Hi") (EXT:WITH-KEYBOARD (LOOP :for ki = (READ-CHAR EXT:*KEYBOARD-INPUT*) :do (print ki) (print `((ext:char-key ki) ,(ext:char-key ki))) (print `((character ki) ,(and (not (ext:char-key ki)) (zerop (ext:char-bits ki)) (character ki)))) (print `((ext:char-font ki) ,(ext:char-font ki))) (print `((ext:char-bits ki) ,(ext:char-bits ki))) (dolist (modifier '(:control :meta :super :hyper)) (print `((ext:char-bit ki ,modifier) ,(ext:char-bit ki modifier)))) (finish-output) :until (EQL (and (not (ext:char-key ki)) (zerop (ext:char-bits ki)) (character ki)) #\q))))) (defun xexample (&key (display ":0.0")) (let* ((old-terminal-io *terminal-io*) (xterm-io (make-xterm-io-stream :display display :geometry "+0+0")) (*terminal-io* xterm-io) (*standard-output* (make-synonym-stream '*terminal-io*)) (*standard-input* (make-synonym-stream '*terminal-io*)) (*error-output* (make-synonym-stream '*terminal-io*)) (*query-io* (make-synonym-stream '*terminal-io*)) ;; (*debug-io* (make-synonym-stream '*terminal-io*)) ;; (*trace-output* (make-synonym-stream '*terminal-io*)) (old-term (getenv "TERM"))) (setf (getenv "TERM") "xterm") (unwind-protect (progn (format *query-io* "~&Hello!~%") (format *query-io* "~&X = ") (finish-output *query-io*) (let ((x (read *query-io*))) (format *query-io* "~&~S = ~A~%" '(- (* 2 x) 3) (- (* 2 x) 3))) (y-or-n-p "Happy?")) (setf *terminal-io* old-terminal-io) (close xterm-io) (setf (getenv "TERM") old-term)))) ;;;; THE END ;;;;
6,841
Common Lisp
.lisp
145
36.475862
85
0.515878
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
edc67e0007816b48a5d6fcd852e05ccadcec2e292cc2926e6b0daaea643900b6
4,820
[ -1 ]
4,821
language.lisp
informatimago_lisp/editor/language.lisp
;;; -- not used -- (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") ;; while debugging: #-(and) (when (find-package "COM.INFORMATIMAGO.EDITOR") (delete-package "COM.INFORMATIMAGO.EDITOR")) ;;;--------------------------------------------------------------------- ;;; ;;; We put on *FEATURES* a keyword representing the language to use for ;;; documentation strings: ;;; (defvar *languages* '((:DK . :DANSK) (:DE . :DEUTSCH) (:EN . :ENGLISH) (:ES . :ESPAÑOL) (:FR . :FRANÇAIS) (:NL . :NEDERLANDS) (:RU . :РУССКИЙ)) "Maps the language code (in keyword) as used in the LANG environment variable, to language names (as keyword).") ;; Remove the old languages, if any. (setf *features* (set-difference *features* (mapcar (function cdr) *languages*))) ;; Push the new language. By default we use :ENGLISH. (pushnew (progn ;; In clisp, we use the custom:*current-language* variable: #+clisp (intern (string custom:*current-language*) "KEYWORD") ;; Otherwise if we have ASDF, we try to get the environment variable LANG: #+(and (not clisp) asdf) (let* ((lang (getenv "LANG")) (entry (assoc lang *languages* :test (function string-equal)))) (if entry (cdr entry) :english)) ;; otherwise we use English: #-(or clisp asdf) :english) *features*) ;;; In any case, if we don't have the documentation in the selected ;;; language, we fall back to docstrings in English. ;;; ;;;---------------------------------------------------------------------
1,818
Common Lisp
.lisp
42
34.97619
85
0.539249
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
fb5fb7c3823623342aa84dfd7e41e2957f12a745a516f363549567d22d96c464
4,821
[ -1 ]
4,822
screen.lisp
informatimago_lisp/editor/screen.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: screen.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines the SCREEN interface. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-11 <PJB> Extracted from editor.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.EDITOR") ;;;--------------------------------------------------------------------- ;;; Screen interface ;;;--------------------------------------------------------------------- (defclass screen () ((stream :reader screen-stream)) (:documentation "This object represents the screen. There are subclasses specific to each available screen device. There are methods specialized on these subclasses to write on the screen.")) (defgeneric screen-open (screen)) (defgeneric screen-close (screen)) (defgeneric screen-initialize-for-terminal (screen terminal) (:method ((screen screen) terminal) terminal)) (defgeneric screen-size (screen)) (defgeneric screen-cursor-position (screen) (:documentation "Return the width and height of the screen.")) (defgeneric set-screen-cursor-position (screen line column)) (defgeneric clear-screen (screen) (:method ((screen screen)) (set-screen-cursor-position screen 0 0) (clear-screen-to-eot screen))) (defgeneric clear-screen-to-eot (screen)) (defgeneric clear-screen-to-eol (screen)) (defgeneric delete-screen-line (screen)) (defgeneric insert-screen-line (screen)) (defgeneric screen-highlight-on (screen)) (defgeneric screen-highlight-off (screen)) (defgeneric screen-cursor-on (screen) (:documentation "Show up the cursor.")) (defgeneric screen-cursor-off (screen) (:documentation "Hide the cursor.")) (defgeneric screen-write-string (screen string) (:documentation "Write the STRING on the SCREEN at the current cursor position.")) (defgeneric screen-format (screen format-control &rest arguments) (:documentation "Format and write on the Screen at the current cursor position.") (:method (screen format-control &rest arguments) (screen-write-string screen (apply (function format) nil format-control arguments)))) (defgeneric screen-refresh (screen)) (defgeneric chord-character (chord)) (defgeneric chord-modifiers (chord)) (defconstant +shift+ 0) (defconstant +control+ 1) (defconstant +meta+ 2) (defconstant +alt+ 3) (defconstant +super+ 4) (defconstant +hyper+ 5) (defconstant +command+ 6) (defgeneric chord-modifierp (chord modifier) (:method (chord (modifier integer)) (logbitp modifier (chord-modifiers chord))) (:method (chord (modifier symbol)) (chord-modifierp chord (ecase modifier (:shift +shift+) (:control +control+) (:meta +meta+) (:alt +alt+) (:super +super+) (:hyper +hyper+) (:command +command+))))) (defun symbolic-modifiers (modifiers) (loop :for bit = 1 :then (* 2 bit) :for modifier :in '(:shift :control :meta :alt :super :hyper :command) :unless (zerop (logand bit modifiers)) :collect modifier)) (defclass chord () ((character :initarg :character :reader chord-character) (modifiers :initarg :modifiers :reader chord-modifiers))) (defgeneric keyboard-chord-no-hang (screen) (:documentation "Returns the next keyboard chord, or NIL.")) (defvar *current-screen* nil "The current SCREEN instance. In this version, there's only one SCREEN instance, but a future version may be ''multitty'' (or ''multiframe'') like GNU emacs.") (defgeneric call-with-screen (screen body) (:documentation "Calls the BODY function with as argument, the SCREEN, while having activated this screen into the bidimentional mode. This methods sets up and terminates the global state of the screen system.")) (defmacro with-screen (SCREEN &body body) "Executes the BODY with *CURRENT-SCREEN* bound to SCREEN, while displaying this screen on the terminal. No other WITH-SCREEN may be called in the BODY. This macros is used for global setup and termination of the screen system." `(call-with-screen ,screen (lambda (*current-screen*) ,@body))) ;; (defgeneric call-with-current-screen (screen body) ;; (:documentation "Calls the BODY function with as argument, the SCREEN, ;; while having activated this screen into the bidimentional mode.")) ;; ;; (defmacro with-current-screen (SCREEN &body body) ;; "Executes the BODY with *CURRENT-SCREEN* bound to SCREEN, ;; while displaying this screen on the terminal. ;; The screen system must be currently activated with WITH-SCREEN. ;; This macro may be used to switch between alternate subscreens. ;; " ;; `(call-with-current-screen ,screen (lambda (*current-screen*) ,@body))) ;;;; THE END ;;;;
5,975
Common Lisp
.lisp
130
42.630769
89
0.66993
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cb93a74fef38d08dd94f4429e061ebdc7d17e173a458de33437ba73d87b4fd5a
4,822
[ -1 ]
4,823
macros.lisp
informatimago_lisp/editor/macros.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: macros.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines DEFUN and LAMBDA, to deal with interactive declarations. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-11 <PJB> Extracted from editor.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.EDITOR") ;;;--------------------------------------------------------------------- ;;; Commands: interactive functions ;;;--------------------------------------------------------------------- ;;; ;;; We want to define commands, with a special INTERACTIVE ;;; declaration. So we need to use our own DEFUN (and LAMBDA) macros. (declaim (declaration interactive)) (defvar *interactive-decls* (make-hash-table #+clisp :weak #+clisp :key) "A map of commands name or functions to INTERACTIVE declarations.") (defmacro defun (name arguments &body body) "Do additionnal book-keeping over CL:DEFUN, for INTERACTIVE commands." (let* ((decls (mapcan (function rest) (extract-declarations body))) (inter (find 'interactive decls :key (function first)))) (if inter `(progn (cl:defun ,name ,arguments ,@body) (setf (gethash ',name *interactive-decls*) ',inter (gethash (function ,name) *interactive-decls*) ',inter) ',name) `(progn (cl:defun ,name ,arguments ,@body) (remhash ',name *interactive-decls*) (remhash (function ,name) *interactive-decls*) ',name)))) (defmacro lambda (arguments &body body) "Do additionnal bookkeeping over CL:LAMBDA, for INTERACTIVE commands." (let* ((decls (mapcan (function rest) (extract-declarations body))) (inter (find 'interactive decls :key (function first)))) (if inter `(flet ((anonymous-function ,arguments ,@body)) (setf (gethash (function anonymous-function) *interactive-decls*) ',inter) (function anonymous-function)) `(cl:lambda ,arguments ,@body)))) (defun interactivep (fundesc) "Whether the function FUNCDESC is INTERACTIVE." (gethash fundesc *interactive-decls*)) (defun getenv (var) #+asdf3 (uiop:getenv var) #-asdf3 (asdf::getenv var)) (defun (setf getenv) (new-val var) #+asdf3 (setf (uiop:getenv var) new-val) #-asdf3 (setf (asdf::getenv var) new-val)) ;;;; THE END ;;;;
3,559
Common Lisp
.lisp
79
41.35443
85
0.605772
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e456c9de5f94ebf3cec3ec352127a874f2e7c410bdcdff45194f7509bd3702f5
4,823
[ -1 ]
4,824
clisp-screen.lisp
informatimago_lisp/editor/clisp-screen.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: clisp-screen.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Implements a SCREEN using clisp screen package. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-11 <PJB> Extracted from editor. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; 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/>. ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.EDITOR") (defclass clisp-screen (screen) ((stream :reader screen-stream :initform (screen:make-window))) (:documentation "This SCREEN subclass uses the CLISP SCREEN package.")) (defmethod screen-open ((screen clisp-screen)) (setf (screen-stream screen) (screen:make-window))) (defmethod screen-close ((screen clisp-screen)) (close (screen-stream screen))) (defmethod screen-initialize-for-terminal ((screen clisp-screen) terminal) (cond ((string= "xterm" terminal) (setf custom:*terminal-encoding* (ext:make-encoding :charset charset:iso-8859-1 :line-terminator :unix))) ((string= "kterm" terminal) (setf custom:*terminal-encoding* (ext:make-encoding :charset charset:utf-8 :line-terminator :unix))) (t (warn "Unexpected terminal ~S" terminal)))) (defmethod screen-size ((screen clisp-screen)) (screen:window-size (screen-stream screen))) (defmethod screen-cursor-position ((screen clisp-screen)) (screen:window-cursor-position (screen-stream screen))) (defmethod set-screen-cursor-position ((screen clisp-screen) line column) (screen:set-window-cursor-position (screen-stream screen) line column)) (defmethod clear-screen ((screen clisp-screen)) (screen:clear-window (screen-stream screen))) (defmethod clear-screen-to-eot ((screen clisp-screen)) (screen:clear-window-to-eot (screen-stream screen))) (defmethod clear-screen-to-eol ((screen clisp-screen)) (screen:clear-window-to-eol (screen-stream screen))) (defmethod delete-screen-line ((screen clisp-screen)) (screen:delete-window-line (screen-stream screen))) (defmethod insert-screen-line ((screen clisp-screen)) (screen:insert-window-line (screen-stream screen))) (defmethod screen-highlight-on ((screen clisp-screen)) (screen:highlight-on (screen-stream screen))) (defmethod screen-highlight-off ((screen clisp-screen)) (screen:highlight-off (screen-stream screen))) (defmethod screen-cursor-on ((screen clisp-screen)) (screen:window-cursor-on (screen-stream screen))) (defmethod screen-cursor-off ((screen clisp-screen)) (screen:window-cursor-off (screen-stream screen))) (defmethod screen-write-string ((screen clisp-screen) string) (write-string string (screen-stream screen)) (finish-output (screen-stream screen)) string) (defmethod screen-refresh ((screen clisp-screen)) screen) (defmethod keyboard-chord-no-hang ((screen clisp-screen)) (declare (ignorable screen)) (let ((ki (ext:with-keyboard (read-char-no-hang ext:*keyboard-input*)))) (when ki (make-instance 'chord :modifiers (loop :with bits = (ext:char-bits ki) :for (bit modifier) :in (load-time-value (list (list EXT:CHAR-CONTROL-BIT +control+) (list EXT:CHAR-META-BIT +meta+) (list EXT:CHAR-SUPER-BIT +super+) (list EXT:CHAR-HYPER-BIT +hyper+))) :when (logand bits bit) :sum (expt 2 modifier)) :character (let ((ch (or (ext:char-key ki) (character ki)))) (if (ext:char-bit ki :control) (char-downcase ch) ch)))))) (defmethod call-with-screen ((screen clisp-screen) thunk) (unwind-protect (screen:with-window (setf (screen-stream screen) screen:*window*) (funcall thunk screen)) (setf (screen-stream screen) nil))) ;; (defmethod call-with-current-screen ((screen clisp-screen) thunk) ;; (assert (and screen:*window* (eql screen:*window* (screen-stream screen)))) ;; (funcall thunk screen)) ;;;; THE END ;;;;
5,377
Common Lisp
.lisp
114
40.622807
83
0.628364
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9e751d804c3b68ccf39daa6de448bce04726a9fb0dbb6316893e1a7215f00d8e
4,824
[ -1 ]