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
5,126
set-test.lisp
informatimago_lisp/common-lisp/cesarum/set-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: set-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; The tests of set.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-08 <PJB> Extracted from set.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.COMMON-LISP.CESARUM.SET.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET") (:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET" "UNION" "INTERSECTION" "MERGE" "INCLUDE") (:export "TEST/ALL" "TEST/ALL/CLASS")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET.TEST") ;;;----------------------------------------------------------------------- ;;; TESTS ;;;----------------------------------------------------------------------- (defgeneric make-set (test-class elements)) (defmethod make-set ((test-class (eql 'list)) elements) (coerce elements 'list)) (defmethod make-set ((test-class (eql 'vector)) elements) (coerce elements 'vector)) (defmethod make-set (test-class elements) (assign (make-instance 'test-class) elements)) (defun test-sets (test-class) (list '() '(1) '(1 2 3) '#() '#(1) '#(1 2 3) (make-set test-class '()) (make-set test-class '(1)) (make-set test-class '(1 2 3)))) (define-test test/all/nil () (loop :for seq :in (test-sets 'list-set) :do (check eql (map-elements nil (function identity) seq) nil) (check set-equal (let ((result '())) (map-elements nil (lambda (element) (push element result)) seq) result) seq))) (define-test test/map-elements (test-class) (loop :for set :in (test-sets test-class) :do (loop :for class :in (list 'list 'vector test-class) :do (check set-equal (map-elements class (function identity) set) (ecase (cardinal set) (0 '()) (1 '(1)) (3 '(1 2 3))))))) (define-test test/copy (test-class) (loop :for (expected type original) :in (list (list nil 'nil '(1 2 3 4)) (list '(1 2 3 4) 'list '(1 2 3 4)) (list '(1 2 3 4) 'vector '(1 2 3 4)) (list '(1 2 3 4) test-class '(1 2 3 4))) :do (check set-equal (make-set type original) expected (type original)) (check set-equal (make-set 'list (make-set type original)) expected (type original)) (check set-equal (make-set 'vector (make-set type original)) expected (type original)))) (define-test test/is-subseq (test-class1 test-class2) (flet ((test-set1 (&rest elements) (make-set test-class1 elements)) (test-set2 (&rest elements) (make-set test-class2 elements))) (assert-true (is-subset (test-set1) (test-set2))) (assert-true (is-subset (test-set1 1) (test-set2 1))) (assert-true (is-subset (test-set1 1 2 3) (test-set2 1 2 3))) (assert-true (is-subset (test-set1 1 2 3 11 12 13) (test-set2 11 12 13 1 2 3))) (assert-true (is-subset (test-set1) (test-set2 1))) (assert-true (not (is-subset (test-set1 1) (test-set2)))) (assert-true (not (is-subset (test-set1 1) (test-set2 2)))) (assert-true (is-subset (test-set1 1 2 3) (test-set2 1 2 3 4))) (assert-true (not (is-subset (test-set1 1 2 3 4) (test-set2 1 2 3)))))) (define-test test/set-equal (test-class) (flet ((test-set (&rest elements) (make-set test-class elements))) (assert-true (set-equal (test-set) (test-set))) (assert-true (set-equal (test-set 1) (test-set 1))) (assert-true (set-equal (test-set 1 2 3) (test-set 1 2 3))) (assert-true (set-equal (test-set 1 2 3 11 12 13) (test-set 11 12 13 1 2 3))) (assert-true (not (set-equal (test-set) (test-set 1)))) (assert-true (not (set-equal (test-set 1) (test-set)))) (assert-true (not (set-equal (test-set 1) (test-set 2)))) (assert-true (not (set-equal (test-set 1 2 3) (test-set 1 2 3 4)))) (assert-true (not (set-equal (test-set 1 2 3 4) (test-set 1 2 3)))))) (define-test test/union (operator test-class) (flet ((test-set (&rest elements) (make-set test-class elements))) (check set-equal (funcall operator (test-set 1 2 3 7 8 10 11 12) (test-set 1 2 3 7 8 10 11 12)) (test-set 1 2 3 7 8 10 11 12)) (check set-equal (funcall operator (test-set) (test-set 1 2 3 7 8 10 11 12)) (test-set 1 2 3 7 8 10 11 12)) (check set-equal (funcall operator (test-set 1 2 3 7 8 10 11 12) (test-set)) (test-set 1 2 3 7 8 10 11 12)) (check set-equal (funcall operator (test-set 1 2 3 7 8 10 11 12) (test-set 0 4 5 6 9 10)) (test-set 0 1 2 3 4 5 6 7 8 9 10 11 12)) (check set-equal (funcall operator (test-set 10 11 12) (test-set 1 2 3 7 8)) (test-set 1 2 3 7 8 10 11 12)) (check set-equal (funcall operator (test-set 1 2 3 7 8) (test-set 10 11 12)) (test-set 1 2 3 7 8 10 11 12)) (check set-equal (funcall operator (test-set 1 2 3 5 6 7) (test-set 3 4 5 7 8 9 12 13)) (test-set 1 2 3 4 5 6 7 8 9 12 13)) (check set-equal (funcall operator (test-set 1 2 3 5 6 7 12 13) (test-set 3 4 5 7 8 9)) (test-set 1 2 3 4 5 6 7 8 9 12 13)) (check set-equal (funcall operator (test-set 1 2 3 11 12 13) (test-set 3 4 5 13 14 15)) (test-set 1 2 3 4 5 11 12 13 14 15)) (check set-equal (funcall operator (test-set 3 4 5 13 14 15) (test-set 1 2 3 11 12 13)) (test-set 1 2 3 4 5 11 12 13 14 15)))) (define-test test/intersection (operator test-class) (flet ((test-set (&rest elements) (make-set test-class elements))) (check set-equal (funcall operator (test-set 1 2 3 7 8 10 11 12) (test-set 1 2 3 7 8 10 11 12)) (test-set 1 2 3 7 8 10 11 12)) (check set-equal (funcall operator (test-set) (test-set 1 2 3 7 8 10 11 12)) (test-set)) (check set-equal (funcall operator (test-set 1 2 3 7 8 10 11 12) (test-set)) (test-set)) (check set-equal (funcall operator (test-set 1 2 3 7 8 10 11 12) (test-set 0 4 5 6 9 10)) (test-set 10)) (check set-equal (funcall operator (test-set 10 11 12) (test-set 1 2 3 7 8)) (test-set)) (check set-equal (funcall operator (test-set 1 2 3 7 8) (test-set 10 11 12)) (test-set)) (check set-equal (funcall operator (test-set 1 2 3 5 6 7) (test-set 3 4 5 7 8 9 12 13)) (test-set 3 5 7)) (check set-equal (funcall operator (test-set 1 2 3 5 6 7 12 13) (test-set 3 4 5 7 8 9)) (test-set 3 5 7)) (check set-equal (funcall operator (test-set 1 2 3 11 12 13) (test-set 3 4 5 13 14 15)) (test-set 3 13)) (check set-equal (funcall operator (test-set 3 4 5 13 14 15) (test-set 1 2 3 11 12 13)) (test-set 3 13)))) (define-test test/all/sequence (test-class) "All the tests working on LIST or VECTOR as sets." (test/is-subseq test-class test-class) (test/set-equal test-class) (test/copy test-class) (test/map-elements test-class)) (define-test test/all/class (test-class) "All the tests working on set classes." (test/all/sequence test-class) (test/is-subseq test-class 'list) (test/is-subseq test-class 'vector) (test/is-subseq 'list test-class) (test/is-subseq 'vector test-class) (test/union (function merge) test-class) (test/union (curry (function union) test-class) test-class) (test/union (curry (function union) 'vector) test-class) (test/intersection (function intersect) test-class) (test/intersection (curry (function intersection) test-class) test-class) (test/intersection (curry (function intersection) 'vector) test-class)) (define-test test/all () "All the set tests." (let ((*package* (find-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET"))) (test/all/nil) (test/all/sequence 'list) (test/all/sequence 'vector) (test/all/class 'list-set))) ;;;; THE END ;;;;
11,024
Common Lisp
.lisp
248
33.020161
92
0.508479
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
187b48b526abc9fe59aa38099b8a33ed480f0c6b62e90ac3e25b46eec78d9af3
5,126
[ -1 ]
5,127
set.lisp
informatimago_lisp/common-lisp/cesarum/set.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: set.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines an abstract SET class API. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-05-08 <PJB> Created. ;;;;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.COMMON-LISP.CESARUM.SET" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY") (:shadow "MERGE" "INTERSECTION" "UNION") (:export "CONTAINS" "CARDINAL" "EMPTYP" "MINIMUM" "MAXIMUM" "COLLECTING-RESULT" "MAKE-COLLECTOR" "MAP-ELEMENTS" "THEREIS" "THEREIS1" "ALWAYS" "SET-EQUAL" "IS-SUBSET" "IS-STRICT-SUBSET" "INTENSION" "COPY" "UNION" "INTERSECTION" "DIFFERENCE" "SYMETRIC-DIFFERENCE" "INCLUDE" "EXCLUDE" "ASSIGN-EMPTY" "ASSIGN-SINGLETON" "ASSIGN" "MERGE" "INTERSECT" "SUBTRACT") (:export "LIST-SET" "ELEMENTS") (:documentation " This package defines an abstract set class API. The minimum implementation should define methods for: INCLUDE, EXCLUDE, CONTAINS, CARDINAL, SELECT, MINIMUM, MAXIMUM, MAP-ELEMENTS and MAKE-COLLECTOR. But an efficient implementation will have to implement specializations for the other generic functions too. Methods of MAKE-COLLECTOR specify which RESULT-TYPE sets are available. Methods are defined for NIL, LIST and VECTOR, to make null collector (ignoring the collected elements), a list collector or a vector collector. License: AGPL3 Copyright Pascal J. Bourguignon 2013 - 2013 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.COMMON-LISP.CESARUM.SET") (defgeneric contains (set element) (:documentation " RETURN: Whether the SET contains the ELEMENT. ") (:method ((set sequence) element) (find element set))) (defgeneric cardinal (set) (:documentation " RETURN: The number of elements in the SET. NOTE: We only consider finite sets. ") (:method ((set sequence)) (length set))) (defgeneric emptyp (set) (:documentation " RETURN: (zerop (cardinal set)) NOTE: Implementations of EMPTYP may be more efficient than CARDINAL. ") (:method (set) (zerop (cardinal set))) (:method ((set null)) t) (:method ((set cons)) nil)) (defgeneric select (set) (:documentation " PRE: (not (emptyp SET)) RETURN: one element from the SET. ")) ;; When the elements are ordered: (defgeneric minimum (set) (:documentation " PRE: (not (emptyp SET)) RETURN: the smallest element of the SET. ")) (defgeneric maximum (set) (:documentation " PRE: (not (emptyp SET)) RETURN: the biggest element of the SET. ")) ;; result-type: ;; empty-result: --> set ;; include: set element -> set (defgeneric make-collector (result-type) (:documentation " RETURN: A collector for the RESULT-TYPE. A collector is a function that takes optionnaly two arguments, a set and an element. When called with no argument, it should return a fresh empty set object. When called with a set and an element argument, it should include the element into the set, and return the (possibly new) set. ") (:method ((result-type (eql 'nil))) (declare (ignore result-type)) (lambda (&optional set element) (declare (ignore set element)) (values))) (:method ((result-type (eql 'list))) (declare (ignorable result-type)) (lambda (&optional set (element nil add-element-p)) (if add-element-p (if (member element set) set (cons element set)) '()))) (:method ((result-type (eql 'vector))) (declare (ignorable result-type)) (lambda (&optional set (element nil add-element-p)) (if add-element-p (progn (unless (find element set) (vector-push-extend element set (length set))) set) (make-array 2 :adjustable t :fill-pointer 0))))) (defmacro collecting-result ((collect-operator-name result-type) &body body) " DO: Evaluate BODY in an environment where a function named by COLLECT-OPERATOR-NAME is defined to take one argument and to add it to a set of type RESULT-TYPE. RETURN: The collected set of elements. " (let ((collector (gensym)) (result (gensym))) `(let* ((,collector (make-collector ,result-type)) (,result (funcall ,collector))) (flet ((,collect-operator-name (element) (setf ,result (funcall ,collector ,result element)))) ,@body) ,result))) (defgeneric map-elements (result-type mapper set) (:documentation " DO: Calls MAPPER on each element of the SET in turn (no specified order), collecting the results in a set of type RESULT-TYPE. RESULT-TYPE: A symbol denoting a set class, or LIST or VECTOR. MAPPER: A function taking an element of SET as argument, and returning an element for the set of type RESULT-TYPE. SET: A set. RETURN: A set of type RESULT-TYPE containing the elements returned by MAPPER. ") (:method (result-type mapper (elements sequence)) (collecting-result (collect result-type) (map nil (lambda (element) (collect (funcall mapper element))) elements)))) (defgeneric thereis (predicate set) (:documentation " RETURN: Whether there is an element in the SET for which the PREDICATE is true. ") (:method (predicate set) (map-elements nil (lambda (element) (when (funcall predicate element) (return-from thereis t))) set) nil)) (defgeneric thereis1 (predicate set) (:documentation " RETURN: Whether there is exactly one element in the SET for which the PREDICATE is true. ") (:method (predicate set) (let ((seen-one nil)) (map-elements nil (lambda (element) (when (funcall predicate element) (if seen-one (return-from thereis1) (setf seen-one t)))) set) seen-one))) (defgeneric always (predicate set) (:documentation " RETURN: Whether the PREDICATE is true for all the elements of the SET. ") (:method (predicate set) (map-elements nil (lambda (element) (unless (funcall predicate element) (return-from always nil))) set) t)) (defgeneric set-equal (set1 set2) (:documentation " RETURN: Whether the two sets contains the same elements. ") (:method ((set1 list) (set2 list)) (and (subsetp set1 set2) (subsetp set2 set1))) (:method (set1 set2) (and (is-subset set1 set2) (is-subset set2 set1)))) (defgeneric is-subset (subset set) (:documentation " RETURN: Whether SUBSET is a subset of SET. ") (:method (subset set) (and (<= (cardinal subset) (cardinal set)) (always (curry (function contains) set) subset)))) (defgeneric is-strict-subset (subset set) (:documentation " RETURN: Whether SUBSET is a strict subset of SET. ") (:method (subset set) (and (< (cardinal subset) (cardinal set)) (always (curry (function contains) set) subset)))) (defgeneric intension (result-type predicate set) (:documentation " RETURN: A new set containing only the elements of SET that have PREDICATE true. ") (:method (result-type predicate set) (collecting-result (collect result-type) (map-elements nil (lambda (element) (when (funcall predicate element) (collect element))) set)))) (defgeneric copy (set &key &allow-other-keys) (:documentation " RETURN: A new set of same class as SET, containing the same elements as SET. ") (:method (set &key &allow-other-keys) (assign (make-instance (class-of set)) set))) (defgeneric union (result-type set1 set2) (:documentation " RETURN: A new set of type RESULT-TYPE containing the union of the two sets. ") (:method (result-type set1 set2) (collecting-result (collect result-type) (map-elements nil (function collect) set1) (map-elements nil (function collect) set2)))) (defgeneric intersection (result-type set1 set2) (:documentation " RETURN: A new set of type RESULT-TYPE containing the intersection of the two sets. ") (:method (result-type set1 set2) (let* ((smallest-is-1 (< (cardinal set1) (cardinal set2))) (smallest (if smallest-is-1 set1 set2)) (biggest (if smallest-is-1 set2 set1))) (intension result-type (curry (function contains) biggest) smallest)))) (defgeneric difference (result-type set1 set2) (:documentation " RETURN: A new set of type RESULT-TYPE containing the difference between set1 and set2. ") (:method (result-type set1 set2) (intension result-type (complement (curry (function contains) set2)) set1))) (defgeneric symetric-difference (result-type set1 set2) (:documentation " RETURN: A new set of type RESULT-TYPE containing the symetric difference between the two sets. ") (:method (result-type set1 set2) (union result-type (difference (class-of set1) set1 set2) (difference (class-of set2) set2 set1)))) ;;; Mutation (defgeneric include (destination-set element) (:documentation " POST: (contains DESTINATION-SET ELEMENT) RETURN: DESTINATION-SET ")) (defgeneric exclude (destination-set element) (:documentation " POST: (not (contains DESTINATION-SET ELEMENT)) RETURN: DESTINATION-SET ")) (defgeneric assign-empty (destination-set) (:documentation " POST: (emptyp DESTINATION-SET)) RETURN: DESTINATION-SET ") (:method (destination-set) (loop :until (emptyp destination-set) :do (exclude destination-set (select destination-set))) destination-set)) (defgeneric assign-singleton (destination-set element) (:documentation " POST: (and (= 1 (cardinal DESTINATION-SET)) (contains DESTINATION-SET ELEMENT)) RETURN: DESTINATION-SET ") (:method (destination-set element) (assign-empty destination-set) (include destination-set element) destination-set)) (defgeneric assign (destination-set source-set) (:documentation " POST: (and (set-equal DESTINATION-SET SOURCE-SET) (set-equal (old SOURCE-SET) SOURCE-SET)) RETURN: DESTINATION-SET ") (:method (destination-set source-set) (assign-empty destination-set) (map-elements nil (lambda (element) (include destination-set element)) source-set) destination-set)) (defgeneric merge (destination-set source-set) (:documentation " POST: (and (is-subset SOURCE-SET DESTINATION-SET) (set-equal (old SOURCE-SET) SOURCE-SET)) RETURN: DESTINATION-SET ") (:method (destination-set source-set) (map-elements nil (curry (function include) destination-set) source-set) destination-set)) (defgeneric intersect (destination-set source-set) (:documentation " POST: (and (set-equal DESTINATION-SET (intersection (old DESTINATION-SET) SOURCE-SET)) (set-equal (old SOURCE-SET) SOURCE-SET)) RETURN: DESTINATION-SET ") (:method (destination-set source-set) (map-elements nil (lambda (element) (unless (contains source-set element) (exclude destination-set element))) destination-set) destination-set)) (defgeneric subtract (destination-set source-set) (:documentation " POST: (and (set-equal DESTINATION-SET (difference (old DESTINATION-SET) SOURCE-SET)) (set-equal (old SOURCE-SET) SOURCE-SET)) RETURN: DESTINATION-SET ") (:method (destination-set source-set) (map-elements nil (curry (function exclude) destination-set) source-set) destination-set)) ;;; I/O ;; Note: different set could be serialized differently. (defgeneric read-set (set stream) (:documentation " DO: Accumulate in SET the elements read from the stream as a list. RETURN: SET. ") (:method (set stream) (assign-empty set) (when (peek-char (character "(") stream nil nil) (read-char stream) (do () ((char= (peek-char t stream nil (character ")")) (character ")"))) (include set (read stream)))) (read-char stream) set)) (defgeneric write-set (set stream) (:documentation " DO: Writes to the stream the elements in SET as a list of elements. RETURN: SET. ") (:method (set stream) (princ "(" stream) (let ((separator "")) (map-elements nil (lambda (element) (princ separator stream) (princ element stream) (setf separator " ")) set)) (princ ")" stream) set)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; LIST-SET CLASS ;;; ;;; A simple implementation to test the default methods. ;;; (defgeneric elements (set) (:documentation "The elements in the set.")) (defclass list-set () ((elements :initform '() :initarg :elements :reader elements))) (defmethod print-object ((set list-set) stream) (print-unreadable-object (set stream :type t :identity t) (prin1 (slot-value set 'elements) stream)) set) (defmethod include ((destination-set list-set) element) (pushnew element (slot-value destination-set 'elements)) destination-set) (defmethod exclude ((destination-set list-set) element) (setf (slot-value destination-set 'elements) (delete element (slot-value destination-set 'elements))) destination-set) (defmethod contains ((set list-set) element) (not (not (member element (slot-value set 'elements))))) (defmethod cardinal ((set list-set)) (length (slot-value set 'elements))) (defmethod select ((set list-set)) (if (slot-value set 'elements) (first (slot-value set 'elements)) (values))) (defmethod map-elements (result-type mapper (set list-set)) (collecting-result (collect result-type) (map nil (lambda (element) (collect (funcall mapper element))) (slot-value set 'elements)))) (defmethod make-collector ((result-type (eql 'list-set))) (declare (ignorable result-type)) (lambda (&optional set (element nil add-element-p)) (if add-element-p (progn (pushnew element (slot-value set 'elements)) set) (make-instance 'list-set)))) (defmethod minimum ((set list-set)) (when (every (function realp) (slot-value set 'elements)) (reduce (function min) (slot-value set 'elements)))) (defmethod maximum ((set list-set)) (when (every (function realp) (slot-value set 'elements)) (reduce (function max) (slot-value set 'elements)))) ;;;; THE END ;;;;
17,431
Common Lisp
.lisp
454
32.969163
104
0.634925
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
711b6072e8948b4167584ee886c981bc0e56f58f01d79684e626498656d70457
5,127
[ -1 ]
5,128
iso4217.lisp
informatimago_lisp/common-lisp/cesarum/iso4217.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: iso4217.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports functions and data to process ;;;; iso4217 currency codes. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-10-13 <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.COMMON-LISP.CESARUM.ISO4217" (:use "COMMON-LISP") (:export "GET-CURRENCIES" "FIND-CURRENCY" "CURRENCY-NAME" "CURRENCY-MINOR-UNIT" "CURRENCY-NUMERIC-CODE" "CURRENCY-ALPHABETIC-CODE" "CC-NOTE" "CC-CURRENCY" "CC-COUNTRY") (:documentation " This package exports functions and data to process iso4217 currency codes. License: AGPL3 Copyright Pascal J. Bourguignon 2004 - 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.COMMON-LISP.CESARUM.ISO4217") ;; http://www.unece.org/cefact/rec/cocucod.htm ;; http://www.xe.com/iso4217.htm ;; http://en.wikipedia.org/wiki/ISO_4217 (defparameter +country-currency-notes+ #("Notes" "Effective date is 7th October 2002. The conversion rate is 1AFN to 1000 AFA. The two codes will run concurent until 2nd January 2003." "CFA Franc BCEAO ; Responsible authority: Banque Centrale des États de l'Afrique de l'Ouest." "Customarily known as Bermuda Dollar." "Funds code." "CFA Franc BEAC ; Responsible authority; Banque des États de l'Afrique Centrale." "There is no current withdrawal date for TPE." "Effective on 1st January 2001. There is no current withdrawal date for SVC." "Currency name was effective 4th September 1985." "Effective on 1stJanuary 2004." "Will be suppressed on 1st January 2004." "Dinar is used in Serbia, Euro is used in Montenegro. Effective from February 2003." "The minor unit was changed from 0 to 2, for this edition, since the English Version of ISO 4217 had the wrong information.") "Notes for country-currency relations.") (defstruct (country-currency-row (:type list) (:conc-name cc-)) country currency note) (setf (documentation 'cc-country 'function) "The country of the currency." (documentation 'cc-currency 'function) "The currency." (documentation 'cc-note 'function) "A note.") (defparameter +country-currency+ '( ("AD" "EUR") ("AE" "AED") ("AF" "AFN" 1) ("AG" "XCD") ("AI" "XCD") ("AL" "ALL") ("AM" "AMD") ("AN" "ANG") ("AO" "AOA") ("AR" "ARS") ("AS" "USD") ("AT" "EUR") ("AU" "AUD") ("AW" "AWG") ("AZ" "AZM") ("BA" "BAM") ("BB" "BBD") ("BD" "BDT") ("BE" "EUR") ("BF" "XOF" 2) ("BG" "BGN") ("BH" "BHD") ("BI" "BIF") ("BJ" "XOF" 2) ("BM" "BMD" 3) ("BN" "BND") ("BO" "BOV" 4) ("BO" "BOB") ("BR" "BRL") ("BS" "BSD") ("BT" "BTN") ("BT" "INR") ("BV" "NOK") ("BW" "BWP") ("BY" "BYR") ("BZ" "BZD") ("CA" "CAD") ("CC" "AUD") ("CD" "CDF") ("CF" "XAF" 5) ("CG" "XAF" 5) ("CH" "CHF") ("CI" "XOF" 2) ("CK" "NZD") ("CL" "CLF" 4) ("CL" "CLP") ("CM" "XAF" 5) ("CN" "CNY") ("CO" "COU") ("CO" "COP") ("CR" "CRC") ("CS" "CSD" 11) ("CS" "EUR" 11) ("CU" "CUP") ("CV" "CVE") ("CX" "AUD") ("CY" "CYP") ("CZ" "CZK") ("DE" "EUR") ("DJ" "DJF") ("DK" "DKK") ("DM" "XCD") ("DO" "DOP") ("DZ" "DZD") ("EC" "USD") ("EE" "EEK") ("EG" "EGP") ("EH" "MAD") ("ER" "ERN") ("ES" "EUR") ("ET" "ETB") ("FI" "EUR") ("FJ" "FJD") ("FK" "FKP") ("FM" "USD") ("FO" "DKK") ("FR" "EUR") ("GA" "XAF" 5) ("GB" "GBP") ("GD" "XCD") ("GE" "GEL") ("GF" "EUR") ("GH" "GHC") ("GI" "GIP") ("GL" "DKK") ("GM" "GMD") ("GN" "GNF") ("GP" "EUR") ("GQ" "XAF" 5) ("GR" "EUR") ("GT" "GTQ") ("GU" "USD") ("GW" "XOF" 4) ("GW" "GWP") ("GY" "GYD") ("HK" "HKD") ("HM" "AUD") ("HN" "HNL") ("HR" "HRK") ("HT" "USD") ("HT" "HTG") ("HU" "HUF") ("ID" "IDR") ("IE" "EUR") ("IL" "ILS" 8) ("IN" "INR") ("IO" "USD") ("IQ" "IQD") ("IR" "IRR") ("IS" "ISK") ("IT" "EUR") ("JM" "JMD") ("JO" "JOD") ("JP" "JPY") ("KE" "KES") ("KG" "KGS") ("KH" "KHR") ("KI" "AUD") ("KM" "KMF") ("KN" "XCD") ("KP" "KPW") ("KR" "KRW") ("KW" "KWD") ("KY" "KYD") ("KZ" "KZT") ("LA" "LAK") ("LB" "LBP") ("LC" "XCD") ("LI" "CHF") ("LK" "LKR") ("LR" "LRD") ("LS" "LSL") ("LS" "ZAR") ("LT" "LTL") ("LU" "EUR") ("LV" "LVL") ("LY" "LYD") ("MA" "MAD") ("MC" "EUR") ("MD" "MDL") ("MG" "MGF") ("MG" "MGA" 9) ("MH" "USD") ("MK" "MKD") ("ML" "XOF" 2) ("MM" "MMK") ("MN" "MNT") ("MO" "MOP") ("MP" "USD") ("MQ" "EUR") ("MR" "MRO") ("MS" "XCD") ("MT" "MTL") ("MU" "MUR") ("MV" "MVR") ("MW" "MWK") ("MX" "MXV" 4) ("MX" "MXN") ("MY" "MYR") ("MZ" "MZM") ("NA" "NAD") ("NA" "ZAR") ("NC" "XPF") ("NE" "XOF" 2) ("NF" "AUD") ("NG" "NGN") ("NI" "NIO") ("NL" "EUR") ("NO" "NOK") ("NP" "NPR") ("NR" "AUD") ("NU" "NZD") ("NZ" "NZD") ("OM" "OMR") ("PA" "USD") ("PA" "PAB") ("PE" "PEN") ("PF" "XPF") ("PG" "PGK") ("PH" "PHP") ("PK" "PKR") ("PL" "PLN") ("PM" "EUR") ("PN" "NZD") ("PR" "USD") ("PT" "EUR") ("PW" "USD") ("PY" "PYG") ("QA" "QAR") ("RE" "EUR") ("RO" "ROL") ("RU" "RUB") ("RU" "RUR" 10) ("RW" "RWF") ("SA" "SAR") ("SB" "SBD") ("SC" "SCR") ("SD" "SDD") ("SE" "SEK") ("SG" "SGD") ("SH" "SHP") ("SI" "SIT") ("SJ" "NOK") ("SK" "SKK") ("SL" "SLL") ("SM" "EUR") ("SN" "XOF" 2) ("SO" "SOS") ("SR" "SRD" 9) ("ST" "STD") ("SV" "USD" 7) ("SV" "SVC" 7) ("SY" "SYP") ("SZ" "SZL") ("TC" "USD") ("TD" "XAF" 5) ("TF" "EUR") ("TG" "XOF" 2) ("TH" "THB") ("TJ" "TJS") ("TK" "NZD") ("TL" "USD") ("TM" "TMM") ("TN" "TND") ("TO" "TOP") ("TR" "TRL") ("TT" "TTD") ("TV" "AUD") ("TW" "TWD") ("TZ" "TZS") ("UA" "UAH") ("UG" "UGX" 12) ("UM" "USD") ("US" "USN" 4) ("US" "USS" 4) ("US" "USD") ("UY" "UYU") ("UZ" "UZS") ("VA" "EUR") ("VC" "XCD") ("VE" "VEB") ("VG" "USD") ("VI" "USD") ("VN" "VND") ("VU" "VUV") ("WF" "XPF") ("WS" "WST") ("YE" "YER") ("YT" "EUR") ("ZA" "ZAR") ("ZM" "ZMK") ("ZW" "ZWD") ) "Relation N-N between countries and currencies.") ;;+COUNTRY-CURRENCY+ (eval-when (:compile-toplevel :load-toplevel :execute) (defstruct (currency (:type list)) alphabetic-code numeric-code minor-unit name ) (setf (documentation 'currency-alphabetic-code 'function) "The alphabetic code (3 letters) of the currency." (documentation 'currency-numeric-code 'function) "The numeric code (between 0 and 999) of the currency." (documentation 'currency-minor-unit 'function) "The number of digits after the decimal point for amounts in the currency." (documentation 'currency-name 'function) "The name of the currency") (defparameter +currencies+ '( ("AED" 784 2 "UAE Dirham" ) ("AFN" 971 2 "Afghani" ) ("ALL" 8 2 "Lek" ) ("AMD" 51 2 "Armenian Dram" ) ("ANG" 532 2 "Netherlands Antillan Guilder" ) ("AOA" 973 2 "Kwanza" ) ("ARS" 32 2 "Argentine Peso" ) ("AUD" 36 2 "Australian Dollar" ) ("AWG" 533 2 "Aruban Guilder" ) ("AZM" 31 2 "Azerbaijanian Manat" ) ("BAM" 977 2 "Convertible Marks" ) ("BBD" 52 2 "Barbados Dollar" ) ("BDT" 50 2 "Taka" ) ("BGN" 975 2 "Bulgarian Lev" ) ("BHD" 48 3 "Bahraini Dinar" ) ("BIF" 108 0 "Burundi Franc" ) ("BMD" 60 2 "Bermudian Dollar" ) ("BND" 96 2 "Brunei Dollar" ) ("BOB" 68 2 "Boliviano" ) ("BOV" 984 2 "Mvdol" ) ("BRL" 986 2 "Brazilian Real" ) ("BSD" 44 2 "Bahamian Dollar" ) ("BTN" 64 2 "Ngultrum" ) ("BWP" 72 2 "Pula" ) ("BYR" 974 0 "Belarussian Ruble" ) ("BZD" 84 2 "Belize Dollar" ) ("CAD" 124 2 "Canadian Dollar" ) ("CDF" 976 2 "Franc Congolais" ) ("CHF" 756 2 "Swiss Franc" ) ("CLF" 990 0 "Unidades de fomento" ) ("CLP" 152 0 "Chilean Peso" ) ("CNY" 156 2 "Yuan Renminbi" ) ("COP" 170 2 "Colombian Peso" ) ("COU" 970 2 "Unidad de Valor Real" ) ("CRC" 188 2 "Costa Rican Colon" ) ("CSD" 891 2 "Serbian Dinar" ) ("CUP" 192 2 "Cuban Peso" ) ("CVE" 132 2 "Cape Verde Escudo" ) ("CYP" 196 2 "Cyprus Pound" ) ("CZK" 203 2 "Czech Koruna" ) ("DJF" 262 0 "Djibouti Franc" ) ("DKK" 208 2 "Danish Krone" ) ("DOP" 214 2 "Dominican Peso" ) ("DZD" 12 2 "Algerian Dinar" ) ("EEK" 233 2 "Kroon" ) ("EGP" 818 2 "Egyptian Pound" ) ("ERN" 232 2 "Nakfa" ) ("ETB" 230 2 "Ethiopian Birr" ) ("EUR" 978 2 "Euro" ) ("FJD" 242 2 "Fiji Dollar" ) ("FKP" 238 2 "Falkland Islands Pound" ) ("GBP" 826 2 "Pound Sterling" ) ("GEL" 981 2 "Lari" ) ("GHC" 288 2 "Cedi" ) ("GIP" 292 2 "Gibraltar Pound" ) ("GMD" 270 2 "Dalasi" ) ("GNF" 324 0 "Guinea Franc" ) ("GTQ" 320 2 "Quetzal" ) ("GWP" 624 2 "Guinea-Bissau Peso" ) ("GYD" 328 2 "Guyana Dollar" ) ("HKD" 344 2 "Hong Kong Dollar" ) ("HNL" 340 2 "Lempira" ) ("HRK" 191 2 "Croatian kuna" ) ("HTG" 332 2 "Gourde" ) ("HUF" 348 2 "Forint" ) ("IDR" 360 2 "Rupiah" ) ("ILS" 376 2 "New Israeli Sheqel" ) ("INR" 356 2 "Indian Rupee" ) ("IQD" 368 3 "Iraqi Dinar" ) ("IRR" 364 2 "Iranian Rial" ) ("ISK" 352 2 "Iceland Krona" ) ("JMD" 388 2 "Jamaican Dollar" ) ("JOD" 400 3 "Jordanian Dinar" ) ("JPY" 392 0 "Yen" ) ("KES" 404 2 "Kenyan Shilling" ) ("KGS" 417 2 "Som" ) ("KHR" 116 2 "Riel" ) ("KMF" 174 0 "Comoro Franc" ) ("KPW" 408 2 "North Korean Won" ) ("KRW" 410 0 "Won" ) ("KWD" 414 3 "Kuwaiti Dinar" ) ("KYD" 136 2 "Cayman Islands Dollar" ) ("KZT" 398 2 "Tenge" ) ("LAK" 418 2 "Kip" ) ("LBP" 422 2 "Lebanese Pound" ) ("LKR" 144 2 "Sri Lanka Rupee" ) ("LRD" 430 2 "Liberian Dollar" ) ("LSL" 426 2 "Loti" ) ("LTL" 440 2 "Lithuanian Litas" ) ("LVL" 428 2 "Latvian Lats" ) ("LYD" 434 3 "Lybian Dinar" ) ("MAD" 504 2 "Moroccan Dirham" ) ("MDL" 498 2 "Moldovan Leu" ) ("MGA" 969 0 "Ariary" ) ("MGF" 450 0 "Malagasy Franc" ) ("MKD" 807 2 "Denar" ) ("MMK" 104 2 "Kyat" ) ("MNT" 496 2 "Tugrik" ) ("MOP" 446 2 "Pataca" ) ("MRO" 478 2 "Ouguiya" ) ("MTL" 470 2 "Maltese Lira" ) ("MUR" 480 2 "Mauritius Rupee" ) ("MVR" 462 2 "Rufiyaa" ) ("MWK" 454 2 "Kwacha" ) ("MXN" 484 2 "Mexican Peso" ) ("MXV" 979 2 "Mexican Unidad de Inversion" ) ("MYR" 458 2 "Malaysian Ringgit" ) ("MZM" 508 2 "Metical" ) ("NAD" 516 2 "Namibia Dollar" ) ("NGN" 566 2 "Naira" ) ("NIO" 558 2 "Cordoba Oro" ) ("NOK" 578 2 "Norwegian Krone" ) ("NOK" 578 2 "Norvegian Krone" ) ("NPR" 524 2 "Nepalese Rupee" ) ("NZD" 554 2 "New Zealand Dollar" ) ("OMR" 512 3 "Rial Omani" ) ("PAB" 590 2 "Balboa" ) ("PEN" 604 2 "Nuevo Sol" ) ("PGK" 598 2 "Kina" ) ("PHP" 608 2 "Philippine Peso" ) ("PKR" 586 2 "Pakistan Rupee" ) ("PLN" 985 2 "Zloty" ) ("PYG" 600 0 "Guarani" ) ("QAR" 634 2 "Qatari Rial" ) ("ROL" 642 2 "Leu" ) ("RUB" 643 2 "Russian Ruble" ) ("RUR" 810 2 "Russian Ruble" ) ("RWF" 646 0 "Rwanda Franc" ) ("SAR" 682 2 "Saudi Riyal" ) ("SBD" 90 2 "Solomon Islands Dollar" ) ("SCR" 690 2 "Seychelles Rupee" ) ("SDD" 736 2 "Sudanese Dinar" ) ("SEK" 752 2 "Swedish Krona" ) ("SGD" 702 2 "Singapore Dollar" ) ("SHP" 654 2 "Saint Helena Pound" ) ("SIT" 705 2 "Tolar" ) ("SKK" 703 2 "Slovak Koruna" ) ("SLL" 694 2 "Leone" ) ("SOS" 706 2 "Somali Shilling" ) ("SRD" 968 2 "Suriname Dollar" ) ("STD" 678 2 "Dobra" ) ("SVC" 222 2 "El Salvador Colon" ) ("SYP" 760 2 "Syrian Pound" ) ("SZL" 748 2 "Lilangeni" ) ("THB" 764 2 "Baht" ) ("TJS" 972 2 "Somoni" ) ("TMM" 795 2 "Manat" ) ("TND" 788 3 "Tunisian Dinar" ) ("TOP" 776 2 "Pa'anga" ) ("TRL" 792 0 "Turkish Lira" ) ("TTD" 780 2 "Trinidad and Tobago Dollar" ) ("TWD" 901 2 "New Taiwan Dollar" ) ("TZS" 834 2 "Tanzanian Shilling" ) ("UAH" 980 2 "Hryvnia" ) ("UGX" 800 2 "Uganda Shilling" ) ("USD" 840 2 "US Dollar" ) ("USN" 997 2 "US Dollar (Next day)" ) ("USS" 998 2 "US Dollar (Same day)" ) ("UYU" 858 2 "Peso Uruguayo" ) ("UZS" 860 2 "Uzbekistan Sum" ) ("VEB" 862 2 "Bolivar" ) ("VND" 704 2 "Dong" ) ("VUV" 548 0 "Vatu" ) ("WST" 882 2 "Tala" ) ("XAF" 950 0 "CFA Franc BEAC" ) ("XCD" 951 2 "East Caribbean Dollar" ) ("XCD" 951 2 "East Carribean Dollar" ) ("XCD" 951 2 "East Carribbean Dollar" ) ("XOF" 952 0 "CFA Franc BCEAO" ) ("XPF" 953 0 "CFP Franc" ) ("YER" 886 2 "Yemeni Rial" ) ("ZAR" 710 2 "Rand" ) ("ZMK" 894 2 "Kwacha" ) ("ZWD" 716 2 "Zimbabwe Dollar" ) ) "Information about currencies.") (defparameter *currency-map* (make-hash-table :test (function eql)) "Maps codes to currencies.") (dolist (cur +currencies+) (setf (gethash (currency-alphabetic-code cur) *currency-map*) cur (gethash (with-standard-io-syntax (intern (currency-alphabetic-code cur) "KEYWORD")) *currency-map*) cur (gethash (currency-numeric-code cur) *currency-map*) cur (gethash cur *currency-map*) cur)) ) ;;eval-when (defun find-currency (designator) " DESIGNATOR: An integer between 0 and 999, or a string or a symbol, or a list whose first element is an integer between 0 and 999, or a string or a symbol, RETURN: A currency structure (list) if the designator matches one, or nil if none found. RAISE: An error when the type of DESIGNATOR is not as described above. " (or (gethash designator *currency-map*) (when (listp designator) (gethash (first designator) *currency-map*)) (progn (setf designator (if (listp designator) (first designator) designator)) (if (or (stringp designator) (symbolp designator)) (car (member-if (lambda (c) (or (string-equal designator (currency-alphabetic-code c)) (string-equal designator (currency-name c)))) +currencies+)) (error "Invalid currency designator: ~S" designator))))) ;;FIND-CURRENCY (defun get-currencies (&key only-existing order (language :en)) " ONLY-EXISTING: NOT IMPLEMENTED YET. Select only currencly in current use. LANGUAGE: NOT IMPLEMENTED YET. ORDER: :NAME or :ALPHABETIC-CODE or :NUMERIC-CODE. if not specified, no ordering is done. RETURN: A list of CURRENCY: (alphabetic-code numeric-code minor-unit name). " (declare (ignore only-existing language)) (let ((result (copy-seq +currencies+))) (when order (setq result (sort result (case order ((:name) (lambda (a b) (string-lessp (currency-name a) (currency-name b)))) ((:alphabetic-code) (lambda (a b) (string-lessp (currency-alphabetic-code a) (currency-alphabetic-code b)))) ((:numeric-code) (lambda (a b) (string-lessp (currency-numeric-code a) (currency-numeric-code b)))) (otherwise (error "Invalid order: ~S. Expected one of: ~ :NAME or :ALPHABETIC-CODE or :NUMERIC-CODE." order)))))) result)) ;;GET-CURRENCIES #|| //###################################################################### (defparameter +wikipedia-active+ '( ("AED" "United Arab Emirates Dirham") ("AFN" "Afghani") ("ALL" "Albanian Lek") ("AMD" "Armenian Dram") ("ANG" "Netherlands Antillian Guilder") ("AOA" "Angolan Kwanza") ("ARS" "Argentine Peso") ("AUD" "Australian Dollar") ("AWG" "Aruban Guilder") ("AZM" "Azerbaijani Manat") ("BAM" "Bosnia-Herzegovina Convertible Marks") ("BBD" "Barbados Dollar") ("BDT" "Bangladesh Taka") ("BGN" "Bulgarian Lev (since 1999-07-05)") ("BHD" "Bahraini Dinar") ("BIF" "Burundi Franc") ("BMD" "Bermuda Dollar") ("BND" "Brunei Dollar") ("BOB" "Bolivian Boliviano") ("BOV" "Bolivian Mvdol (Funds code)") ("BRL" "Brazilian Real") ("BSD" "Bahamian Dollar") ("BTN" "Bhutan Ngultrum") ("BWP" "Botswana Pula") ("BYR" "Belarussian Ruble") ("BZD" "Belize Dollar") ("CAD" "Canadian Dollar") ("CDF" "Franc Congolais") ("CHF" "Swiss franc") ("CLF" "Chilean Unidades de fomento (Funds code)") ("CLP" "Chilean Peso") ("CNY" "Yuan Renminbi") ("COP" "Colombian peso") ("COU" "Columbian unidad de valor real (added to the COP)") ("CRC" "Costa Rican Colón") ("CSD" "Serbian Dinar") ("CUP" "Cuban Peso") ("CVE" "Cape Verde Escudo") ("CYP" "Cyprus Pound") ("CZK" "Czech Koruna") ("DJF" "Djibouti Franc") ("DKK" "Danish Krone") ("DOP" "Dominican Peso") ("DZD" "Algerian Dinar") ("EEK" "Estonian Kroon") ("EGP" "Egyptian Pound") ("ERN" "Eritrea Nakfa") ("ETB" "Ethiopian Birr") ("EUR" "Euro") ("FJD" "Fiji Dollar") ("FKP" "Falkland Islands Pound") ("GBP" "Pound Sterling") ("GEL" "Georgian Lari") ("GHC" "Ghana Cedi") ("GIP" "Gibraltar Pound") ("GMD" "Gambian Dalasi") ("GNF" "Guinea Franc") ("GTQ" "Guatemalan Quetzal") ("GWP" "Guinea-Bissau Peso") ("GYD" "Guyana Dollar") ("HKD" "Hong Kong Dollar") ("HNL" "Honduran Lempira") ("HRK" "Croatian Kuna") ("HTG" "Haitian Gourde") ("HUF" "Hungarian Forint") ("IDR" "Indonesian Rupiah") ("ILS" "New Israeli Shekel") ("INR" "Indian Rupee") ("IQD" "Iraqi Dinar") ("IRR" "Iranian Rial") ("ISK" "Iceland Krona") ("JMD" "Jamaican Dollar") ("JOD" "Jordanian Dinar") ("JPY" "Japanese Yen") ("KES" "Kenyan Shilling") ("KGS" "Kyrgyzstan Som") ("KHR" "Cambodian Riel") ("KMF" "Comoro Franc") ("KPW" "North Korean Won") ("KRW" "South Korean Won") ("KWD" "Kuwaiti Dinar") ("KYD" "Cayman Islands Dollar") ("KZT" "Kazakhstan Tenge") ("LAK" "Lao Kip") ("LBP" "Lebanese Pound") ("LKR" "Sri Lanka Rupee") ("LRD" "Liberian Dollar") ("LSL" "Lesotho Loti") ("LTL" "Lithuanian Litus") ("LVL" "Latvian Lats") ("LYD" "Libyan Dinar") ("MAD" "Moroccan Dirham") ("MDL" "Moldovan Leu") ("MGA" "Malagasy ariary") ("MGF" "Malagasy Franc") ("MKD" "Macedonian(Former Yug. Rep.) Denar") ("MMK" "Myanmar Kyat") ("MNT" "Mongolian Tugrik") ("MOP" "Macau Pataca") ("MRO" "Mauritanian Ouguiya") ("MTL" "Maltese Lira") ("MUR" "Mauritius Rupee") ("MVR" "Maldives Rufiyaa") ("MWK" "Malawi Kwacha") ("MXN" "Mexican Peso") ("MXV" "Mexican Unidad de Inversion (UDI) (Funds code)") ("MYR" "Malaysian Ringgit") ("MZM" "Moazambique Metical") ("NAD" "Namibian Dollar") ("NGN" "Nigerian Naira") ("NIO" "Nicaraguan Córdoba Oro") ("NOK" "Norwegian Krone") ("NPR" "Nepalese Rupee") ("NZD" "New Zealand Dollar") ("OMR" "Omani Rial") ("PAB" "Panama Balboa") ("PEN" "Peruvian Nuevo Sol") ("PGK" "Papua New Guinea Kina") ("PHP" "Philippine peso") ("PKR" "Pakistani Rupee") ("PLN" "Polish Zloty") ("PYG" "Paraguay Guarani") ("QAR" "Qatari Rial") ("ROL" "Romanian Leu") ("RUB" "Russian Ruble") ("RWF" "Rwanda Franc") ("SAR" "Saudi Riya") ("SBD" "Solomon Islands Dollar") ("SCR" "Seychelles Rupee") ("SDD" "Sudanese Dinar") ("SEK" "Swedish Krona") ("SGD" "Singapore Dollar") ("SHP" "Saint Helena Pound") ("SIT" "Slovene Tolar") ("SKK" "Slovak Koruna") ("SLL" "Sierra Leonean Leone") ("SOS" "Somali Shilling") ("SRD" "Suriname dollar (since 2004-01-01)") ("STD" "So Tom and Principe Dobra") ("SVC" "El Salvador Colón") ("SYP" "Syrian Pound") ("SZL" "Swaziland Lilangeni") ("THB" "Thai Baht") ("TJS" "Tajikistani Somoni") ("TMM" "Turkmenistan Manat") ("TND" "Tunisian Dinar") ("TOP" "Tongan Pa'anga") ("TPE" "Timor Escudo") ("TRL" "Turkish Lira") ("TTD" "Trinidad and Tobago Dollar") ("TWD" "New Taiwan Dollar") ("TZS" "Tanzanian Shilling") ("UAH" "Ukrainian Hryvnia") ("UGX" "Uganda Shilling") ("USD" "United States Dollar") ("USN" "United States Dollar (Next day) (Funds code)") ("USS" "United States Dollar (Same day) (Funds code) (one source claims it is no longer used, but it is still on the ISO 4217-MA list)") ("UYU" "Peso Uruguayo") ("UZS" "Uzbekistan Sum") ("VEB" "Venezuelan Bolivar") ("VND" "Viet Nam Dong") ("VUV" "Vanuatu Vatu") ("WST" "Samoa Tala") ("XAF" "CFA Franc BEAC") ("XAG" "Silver Ounce") ("XAU" "Gold Ounce") ("XBA" "European Composite Unit (EURCO) (Bonds market unit)") ("XBB" "European Monetary Unit (E.M.U.-6) (Bonds market unit)") ("XBC" "European Unit of Account 9 (E.U.A.-9) (Bonds market unit)") ("XBD" "European Unit of Account 17 (E.U.A.-17) (Bonds market unit)") ("XCD" "East Caribbean Dollar") ("XDR" "Special Drawing Rights (IMF)") ("XFO" "Gold-Franc (Special settlement currency)") ("XFU" "UIC Franc (Special settlement currency)") ("XOF" "CFA Franc BCEAO") ("XPD" "Palladium Ounce") ("XPF" "CFP Franc") ("XPT" "Platinum Ounce") ("XTS" "Code reserved for testing purposes") ("XXX" "No currency") ("YER" "Yemeni Rial") ("ZAR" "South African Rand") ("ZMK" "Zambian Kwacha") ("ZWD" "Zimbabwe Dollar") )) ;;+wikipedia-active+ (defparameter +wikipedia-Obsolete+ '( ("ADP" "Andorran Peseta (Euro)") ("AFA" "Afghani (replaced by AFN)") ("AON" "Angolan New Kwanza (replaced by AOA)") ("AOR" "Angolan Kwanza Readjustado (replaced by AOA)") ("ATS" "Austrian Schilling (Euro)") ("BEC" "Belgian Franc (convertible)") ("BEF" "Belgian Franc (Euro)") ("BEL" "Belgian Franc (financial)") ("BGL" "Bulgarian Lev (before 1999-07-05)") ("CSK" "Czechoslovakia Koruna") ("DDM" "Mark der DDR (East Germany)") ("DEM" "Deutsche Mark (Euro)") ("ECS" "Ecuador Sucre (replaced by USD)") ("ECV" "Ecuador Unidad de Valor Constante (Funds code) (discontinued)") ("ESA" "Spanish Peseta (account A)") ("ESB" "Spanish Peseta (account B)") ("ESP" "Spanish Peseta (Euro)") ("FIM" "Finnish Markka (Euro)") ("FRF" "French Franc (Euro)") ("GRD" "Greek Drachma (Euro)") ("IEP" "Irish Pound (Euro)") ("ITL" "Italian Lira (Euro)") ("LUF" "Luxembourg Franc (Euro)") ("MXP" "Mexican Peso (replaced by MXN)") ("NLG" "Netherlands Guilder (Euro)") ("PLZ" "Polish Zloty (replaced by PLN)") ("PTE" "Portuguese Escudo (Euro)") ("RUR" "Russian Ruble (replaced by RUB)") ("SRG" "Suriname Guilder (replaced by SRD)") ("SUR" "Soviet Union Rouble") ("XEU" "European Currency Unit (replaced by EUR)") ("YUD" "New Yugoslavian Dinar (replaced by YUM)") ("YUM" "Yugoslavian Dinar (Serbian dinar - CSD)") ("ZAL" "South African financial rand (Funds code) (discontinued)") ("ZRN" "New Zaire (replaced by CDF)") ("ZRZ" "Zaire (replaced by ZRN, then by CDF)") )) ;;+wikipedia-Obsolete+ (defparameter +xe-countries+ '( ("AFA" "Afghanistan" "Afghanis") ("ALL" "Albania" "Leke") ("DZD" "Algeria" "Dinars") ("USD" "America (United States of America)" "Dollars") ("USD" "American Samoa" "United States Dollars") ("USD" "American Virgin Islands" "United States Dollars") ("EUR" "Andorra" "Euro") ("AOA" "Angola" "Kwanza") ("XCD" "Anguilla" "East Caribbean Dollars") ("XCD" "Antigua and Barbuda" "East Caribbean Dollars") ("ARS" "Argentina" "Pesos") ("AMD" "Armenia" "Drams") ("AWG" "Aruba" "Guilders") ("ANG" "Aruba" "Netherlands Antilles Guilders") ("AUD" "Australia" "Dollars") ("EUR" "Austria" "Euro") ("AZM" "Azerbaijan" "Manats") ("EUR" "Azores" "Euro") ("BSD" "Bahamas" "Dollars") ("BHD" "Bahrain" "Dinars") ("EUR" "Baleares (Balearic Islands)" "Euro") ("BDT" "Bangladesh" "Taka") ("BBD" "Barbados" "Dollars") ("XCD" "Barbuda and Antigua" "East Caribbean Dollars") ("BYR" "Belarus" "Rubles") ("EUR" "Belgium" "Euro") ("BZD" "Belize" "Dollars") ("XOF" "Benin" "Communauté Financière Africaine Francs(BCEAO)") ("BMD" "Bermuda" "Dollars") ("BTN" "Bhutan" "Ngultrum") ("INR" "Bhutan" "India Rupeess") ("BOB" "Bolivia" "Bolivianos") ("ANG" "Bonaire" "Netherlands Antilles Guilders") ("BAM" "Bosnia and Herzegovina" "Convertible Marka") ("BWP" "Botswana" "Pulas") ("NOK" "Bouvet Island" "Norway Kroner") ("BRL" "Brazil" "Real") ("GBP" "Britain (United Kingdom)" "Pounds") ("USD" "British Indian Ocean Territory" "United States Dollars") ("USD" "British Virgin Islands" "United States Dollars") ("BND" "Brunei Darussalam" "Dollars") ("BGN" "Bulgaria" "Leva") ("XOF" "Burkina Faso" "Communauté Financière Africaine Francs(BCEAO)") ("MMK" "Burma (Myanmar)" "Kyats") ("BIF" "Burundi" "Francs") ("XOF" "Côte D'Ivoire" "Communauté Financière Africaine Francs(BCEAO)") ("USD" "Caicos and Turks Islands" "United States Dollars") ("KHR" "Cambodia" "Riels") ("XAF" "Cameroon" "Communauté Financière Africaine Francs(BEAC)") ("CAD" "Canada" "Dollars") ("EUR" "Canary Islands" "Euro") ("CVE" "Cape Verde" "Escudos") ("KYD" "Cayman Islands" "Dollars") ("XAF" "Central African Republic" "Communauté Financière Africaine Francs(BEAC)") ("XAF" "Chad" "Communauté Financière Africaine Francs(BEAC)") ("CLP" "Chile" "Pesos") ("CNY" "China" "Yuan Renminbi") ("AUD" "Christmas Island" "Australia Dollars") ("AUD" "Cocos (Keeling) Islands" "Australia Dollars") ("COP" "Colombia" "Pesos") ("XAF" "Communauté Financière Africaine (CFA)" "Francs") ("KMF" "Comoros" "Francs") ("XPF" "Comptoirs Français du Pacifique (CFP)" "Francs") ("XAF" "Congo/Brazzaville" "Communauté Financière Africaine Francs(BEAC)") ("CDF" "Congo/Kinshasa" "Francs") ("NZD" "Cook Islands" "New Zealand Dollars") ("CRC" "Costa Rica" "Colones") ("HRK" "Croatia" "Kuna") ("CUP" "Cuba" "Pesos") ("ANG" "Curaço" "Netherlands Antilles Guilders") ("CYP" "Cyprus" "Pounds") ("CZK" "Czech Republic" "Koruny") ("DKK" "Denmark" "Kroner") ("DJF" "Djibouti" "Francs") ("XCD" "Dominica" "East Caribbean Dollars") ("DOP" "Dominican Republic" "Pesos") ("EUR" "Dutch (Netherlands)" "Euro") ("XCD" "East Caribbean" "Dollars") ("IDR" "East Timor" "Indonesia Rupiahs") ("USD" "Ecuador" "United States Dollars") ("EGP" "Egypt" "Pounds") ("EUR" "Eire (Ireland)" "Euro") ("SVC" "El Salvador" "Colones") ("GBP" "England (United Kingdom)" "Pounds") ("XAF" "Equatorial Guinea" "Communauté Financière Africaine Francs(BEAC)") ("ETB" "Eritrea" "Ethiopia Birr") ("ERN" "Eritrea" "Nakfa") ("EEK" "Estonia" "Krooni") ("ETB" "Ethiopia" "Birr") ("EUR" "Euro Member Countries" "Euro") ("FKP" "Falkland Islands (Malvinas)" "Pounds") ("DKK" "Faroe Islands" "Denmark Kroner") ("FJD" "Fiji" "Dollars") ("EUR" "Finland" "Euro") ("EUR" "France" "Euro") ("EUR" "French Guiana" "Euro") ("XPF" "French Pacific Islands (French Polynesia)" "Comptoirs Français du Pacifique Francs") ("XPF" "French Polynesia (French Pacific Islands)" "Comptoirs Français du Pacifique Francs") ("EUR" "French Southern Territories" "Euro") ("XPF" "Futuna and Wallis Islands" "Comptoirs Français du Pacifique Francs") ("XAF" "Gabon" "Communauté Financière Africaine Francs(BEAC)") ("GMD" "Gambia" "Dalasi") ("GEL" "Georgia" "Lari") ("EUR" "Germany" "Euro") ("GHC" "Ghana" "Cedis") ("GIP" "Gibraltar" "Pounds") ("XAU" "Gold" "Ounces") ("GBP" "Great Britain (United Kingdom)" "Pounds") ("EUR" "Greece" "Euro") ("DKK" "Greenland" "Denmark Kroner") ("XCD" "Grenada" "East Caribbean Dollars") ("XCD" "Grenadines (The) and Saint Vincent" "East Caribbean Dollars") ("EUR" "Guadeloupe" "Euro") ("USD" "Guam" "United States Dollars") ("GTQ" "Guatemala" "Quetzales") ("GGP" "Guernsey" "Pounds") ("GNF" "Guinea" "Francs") ("XOF" "Guinea-Bissau" "Communauté Financière Africaine Francs(BCEAO)") ("GYD" "Guyana" "Dollars") ("HTG" "Haiti" "Gourdes") ("USD" "Haiti" "United States Dollars") ("AUD" "Heard Island and McDonald Islands" "Australia Dollars") ("BAM" "Herzegovina and Bosnia" "Convertible Marka") ("EUR" "Holland (Netherlands)" "Euro") ("EUR Holy See" "(Vatican City)" "Euro") ("HNL" "Honduras" "Lempiras") ("HKD" "Hong Kong" "Dollars") ("HUF" "Hungary" "Forint") ("ISK" "Iceland" "Kronur") ("INR" "India" "Rupees") ("IDR" "Indonesia" "Rupiahs") ("XDR" "International Monetary Fund (IMF)" "Special Drawing Rights") ("IRR" "Iran" "Rials") ("IQD" "Iraq" "Dinars") ("EUR" "Ireland (Eire)" "Euro") ("IMP" "Isle of Man" "Pounds") ("ILS" "Israel" "New Shekels") ("EUR" "Italy" "Euro") ("JMD" "Jamaica" "Dollars") ("NOK" "Jan Mayen and Svalbard" "Norway Kroner") ("JPY" "Japan" "Yen") ("JEP" "Jersey" "Pounds") ("JOD" "Jordan" "Dinars") ("KZT" "Kazakstan" "Tenge") ("AUD" "Keeling (Cocos) Islands" "Australia Dollars") ("KES" "Kenya" "Shillings") ("AUD" "Kiribati" "Australia Dollars") ("KPW" "Korea (North)" "Won") ("KRW" "Korea (South)" "Won") ("KWD" "Kuwait" "Dinars") ("KGS" "Kyrgyzstan" "Soms") ("LAK" "Laos" "Kips") ("LVL" "Latvia" "Lati") ("LBP" "Lebanon" "Pounds") ("LSL" "Lesotho" "Maloti") ("ZAR" "Lesotho" "South Africa Rand") ("LRD" "Liberia" "Dollars") ("LYD" "Libya" "Dinars") ("CHF" "Liechtenstein" "Switzerland Francs") ("LTL" "Lithuania" "Litai") ("EUR" "Luxembourg" "Euro") ("MOP" "Macau" "Patacas") ("MKD" "Macedonia" "Denars") ("MGA" "Madagascar" "Ariary") ("EUR" "Madeira Islands" "Euro") ("MWK" "Malawi" "Kwachas") ("MYR" "Malaysia" "Ringgits") ("MVR" "Maldives (Maldive Islands)" "Rufiyaa") ("XOF" "Mali" "Communauté Financière Africaine Francs(BCEAO)") ("MTL" "Malta" "Liri") ("FKP" "Malvinas (Falkland Islands)" "Pounds") ("USD" "Mariana Islands (Northern)" "United States Dollars") ("USD" "Marshall Islands" "United States Dollars") ("EUR" "Martinique" "Euro") ("MRO" "Mauritania" "Ouguiyas") ("MUR" "Mauritius" "Rupees") ("EUR" "Mayotte" "Euro") ("AUD" "McDonald Islands and Heard Island" "Australia Dollars") ("MXN" "Mexico" "Pesos") ("USD" "Micronesia (Federated States of)" "United States Dollars") ("USD" "Midway Islands" "United States Dollars") ("EUR" "Miquelon and Saint Pierre" "Euro") ("MDL" "Moldova" "Lei") ("EUR" "Monaco" "Euro") ("MNT" "Mongolia" "Tugriks") ("EUR" "Montenegro" "Euro") ("XCD" "Montserrat" "East Caribbean Dollars") ("MAD" "Morocco" "Dirhams") ("MZM" "Mozambique" "Meticais") ("MMK" "Myanmar (Burma)" "Kyats") ("NAD" "Namibia" "Dollars") ("ZAR" "Namibia" "South Africa Rand") ("AUD" "Nauru" "Australia Dollars") ("NPR" "Nepal" "Rupees") ("ANG" "Netherlands Antilles" "Guilders") ("EUR" "Netherlands" "Euro") ("XCD" "Nevis and Saint Kitts" "East Caribbean Dollars") ("XPF" "New Caledonia" "Comptoirs Français du Pacifique Francs") ("NZD" "New Zealand" "Dollars") ("NIO" "Nicaragua" "Gold Cordobas") ("XOF" "Niger" "Communauté Financière Africaine Francs(BCEAO)") ("NGN" "Nigeria" "Nairas") ("NZD" "Niue" "New Zealand Dollars") ("AUD" "Norfolk Island" "Australia Dollars") ("USD" "Northern Mariana Islands" "United States Dollars") ("NOK" "Norway" "Kroner") ("OMR" "Oman" "Rials") ("PKR" "Pakistan" "Rupees") ("USD" "Palau" "United States Dollars") ("XPD" "Palladium" "Ounces") ("PAB" "Panama" "Balboa") ("USD" "Panama" "United States Dollars") ("PGK" "Papua New Guinea" "Kina") ("PYG" "Paraguay" "Guarani") ("PEN" "Peru" "Nuevos Soles") ("PHP" "Philippines" "Pesos") ("NZD" "Pitcairn Islands" "New Zealand Dollars") ("XPT" "Platinum" "Ounces") ("PLN" "Poland" "Zlotych") ("EUR" "Portugal" "Euro") ("STD" "Principe and São Tome" "Dobras") ("USD" "Puerto Rico" "United States Dollars") ("QAR" "Qatar" "Rials") ("EUR" "Réunion" "Euro") ("ROL" "Romania" "Lei") ("RUR" "Russia" "Rubles") ("RWF" "Rwanda" "Francs") ("STD" "São Tome and Principe" "Dobras") ("ANG" "Saba" "Netherlands Antilles Guilders") ("MAD" "Sahara (Western)" "Morocco Dirhams") ("XCD" "Saint Christopher" "East Caribbean Dollars") ("SHP" "Saint Helena" "Pounds") ("XCD" "Saint Kitts and Nevis" "East Caribbean Dollars") ("XCD" "Saint Lucia" "East Caribbean Dollars") ("EUR" "Saint Pierre and Miquelon" "Euro") ("XCD" "Saint Vincent and The Grenadines" "East Caribbean Dollars") ("EUR" "Saint-Martin" "Euro") ("USD" "Samoa (American)" "United States Dollars") ("WST" "Samoa" "Tala") ("EUR" "San Marino" "Euro") ("SAR" "Saudi Arabia" "Riyals") ("SPL" "Seborga" "Luigini") ("XOF" "Senegal" "Communauté Financière Africaine Francs(BCEAO)") ("CSD" "Serbia" "Dinars") ("SCR" "Seychelles" "Rupees") ("SLL" "Sierra Leone" "Leones") ("XAG" "Silver" "Ounces") ("SGD" "Singapore" "Dollars") ("ANG" "Sint Eustatius" "Netherlands Antilles Guilders") ("ANG" "Sint Maarten" "Netherlands Antilles Guilders") ("SKK" "Slovakia" "Koruny") ("SIT" "Slovenia" "Tolars") ("SBD" "Solomon Islands" "Dollars") ("SOS" "Somalia" "Shillings") ("ZAR" "South Africa" "Rand") ("GBP" "South Georgia" "United Kingdom Pounds") ("GBP" "South Sandwich Islands" "United Kingdom Pounds") ("EUR" "Spain" "Euro") ("XDR" NIL "Special Drawing Rights") ("LKR" "Sri Lanka" "Rupees") ("SDD" "Sudan" "Dinars") ("SRD" "Suriname" "Dollars") ("NOK" "Svalbard and Jan Mayen" "Norway Kroner") ("SZL" "Swaziland" "Emalangeni") ("SEK" "Sweden" "Kronor") ("CHF" "Switzerland" "Francs") ("SYP" "Syria" "Pounds") ("TWD" "Taiwan" "New Dollars") ("RUR" "Tajikistan" "Russia Rubles") ("TJS" "Tajikistan" "Somoni") ("TZS" "Tanzania" "Shillings") ("THB" "Thailand" "Baht") ("IDR" "Timor (East)" "Indonesia Rupiahs") ("TTD" "Tobago and Trinidad" "Dollars") ("XOF" "Togo" "Communauté Financière Africaine Francs(BCEAO)") ("NZD" "Tokelau" "New Zealand Dollars") ("TOP" "Tonga" "Pa'anga") ("TTD" "Trinidad and Tobago" "Dollars") ("TND" "Tunisia" "Dinars") ("TRL" "Turkey" "Liras") ("TMM" "Turkmenistan" "Manats") ("USD" "Turks and Caicos Islands" "United States Dollars") ("TVD" "Tuvalu" "Tuvalu Dollars") ("UGX" "Uganda" "Shillings") ("UAH" "Ukraine" "Hryvnia") ("AED" "United Arab Emirates" "Dirhams") ("GBP" "United Kingdom" "Pounds") ("USD" "United States Minor Outlying Islands" "United States Dollars") ("USD" "United States of America" "Dollars") ("UYU" "Uruguay" "Pesos") ("USD" "US Virgin Islands" "United States Dollars") ("UZS" "Uzbekistan" "Sums") ("VUV" "Vanuatu" "Vatu") ("EUR" "Vatican City (The Holy See)" "Euro") ("VEB" "Venezuela" "Bolivares") ("VND" "Viet Nam" "Dong") ("USD" "Virgin Islands (American)" "United States Dollars") ("USD" "Virgin Islands (British)" "United States Dollars") ("USD" "Wake Island" "United States Dollars") ("XPF" "Wallis and Futuna Islands" "Comptoirs Français du Pacifique Francs") ("WST" "West Samoa (Samoa)" "Tala") ("MAD" "Western Sahara" "Morocco Dirhams") ("WST" "Western Samoa (Samoa)" "Tala") ("YER" "Yemen" "Rials") ("ZMK" "Zambia" "Kwacha") ("ZWD" "Zimbabwe" "Zimbabwe Dollars") )) ;;+xe-countries+ (defparameter +xe-currencies+ '( ("AED" "United Arab Emirates" "Dirhams") ("AFA" "Afghanistan" "Afghanis") ("ALL" "Albania" "Leke") ("AMD" "Armenia" "Drams") ("ANG" "Netherlands Antilles" "Guilders") ("AOA" "Angola" "Kwanza") ("ARS" "Argentina" "Pesos") ("AUD" "Australia" "Dollars") ("AWG" "Aruba" "Guilders") ("AZM" "Azerbaijan" "Manats") ("BAM" "Bosnia and Herzegovina" "Convertible Marka") ("BBD" "Barbados" "Dollars") ("BDT" "Bangladesh" "Taka") ("BGN" "Bulgaria" "Leva") ("BHD" "Bahrain" "Dinars") ("BIF" "Burundi" "Francs") ("BMD" "Bermuda" "Dollars") ("BND" "Brunei Darussalam" "Dollars") ("BOB" "Bolivia" "Bolivianos") ("BRL" "Brazil" "Brazil Real") ("BSD" "Bahamas" "Dollars") ("BTN" "Bhutan" "Ngultrum") ("BWP" "Botswana" "Pulas") ("BYR" "Belarus" "Rubles") ("BZD" "Belize" "Dollars") ("CAD" "Canada" "Dollars") ("CDF" "Congo/Kinshasa" "Congolese Francs") ("CHF" "Switzerland" "Francs") ("CLP" "Chile" "Pesos") ("CNY" "China" "Yuan Renminbi") ("COP" "Colombia" "Pesos") ("CRC" "Costa Rica" "Colones") ("CSD" "Serbia" "Dinars") ("CUP" "Cuba" "Pesos") ("CVE" "Cape Verde" "Escudos") ("CYP" "Cyprus" "Pounds") ("CZK" "Czech Republic" "Koruny") ("DJF" "Djibouti" "Francs") ("DKK" "Denmark" "Kroner") ("DOP" "Dominican Republic" "Pesos") ("DZD" "Algeria" "Algeria Dinars") ("EEK" "Estonia" "Krooni") ("EGP" "Egypt" "Pounds") ("ERN" "Eritrea" "Nakfa") ("ETB" "Ethiopia" "Birr") ("EUR" "Euro Member Countries" "Euro") ("FJD" "Fiji" "Dollars") ("FKP" "Falkland Islands (Malvinas)" "Pounds") ("GBP" "United Kingdom" "Pounds") ("GEL" "Georgia" "Lari") ("GGP" "Guernsey" "Pounds") ("GHC" "Ghana" "Cedis") ("GIP" "Gibraltar" "Pounds") ("GMD" "Gambia" "Dalasi") ("GNF" "Guinea" "Francs") ("GTQ" "Guatemala" "Quetzales") ("GYD" "Guyana" "Dollars") ("HKD" "Hong Kong" "Dollars") ("HNL" "Honduras" "Lempiras") ("HRK" "Croatia" "Kuna") ("HTG" "Haiti" "Gourdes") ("HUF" "Hungary" "Forint") ("IDR" "Indonesia" "Rupiahs") ("ILS" "Israel" "New Shekels") ("IMP" "Isle of Man" "Pounds") ("INR" "India" "Rupees") ("IQD" "Iraq" "Dinars") ("IRR" "Iran" "Rials") ("ISK" "Iceland" "Kronur") ("JEP" "Jersey" "Pounds") ("JMD" "Jamaica" "Dollars") ("JOD" "Jordan" "Dinars") ("JPY" "Japan" "Yen") ("KES" "Kenya" "Shillings") ("KGS" "Kyrgyzstan" "Soms") ("KHR" "Cambodia" "Riels") ("KMF" "Comoros" "Francs") ("KPW" "Korea (North)" "Won") ("KRW" "Korea (South)" "Won") ("KWD" "Kuwait" "Dinars") ("KYD" "Cayman Islands" "Dollars") ("KZT" "Kazakstan" "Tenge") ("LAK" "Laos" "Kips") ("LBP" "Lebanon" "Pounds") ("LKR" "Sri Lanka" "Rupees") ("LRD" "Liberia" "Dollars") ("LSL" "Lesotho" "Maloti") ("LTL" "Lithuania" "Litai") ("LVL" "Latvia" "Lati") ("LYD" "Libya" "Dinars") ("MAD" "Morocco" "Dirhams") ("MDL" "Moldova" "Lei") ("MGA" "Madagascar" "Ariary") ("MKD" "Macedonia" "Denars") ("MMK" "Myanmar (Burma)" "Kyats") ("MNT" "Mongolia" "Tugriks") ("MOP" "Macau" "Patacas") ("MRO" "Mauritania" "Ouguiyas") ("MTL" "Malta" "Liri") ("MUR" "Mauritius" "Rupees") ("MVR" "Maldives (Maldive Islands)" "Rufiyaa") ("MWK" "Malawi" "Kwachas") ("MXN" "Mexico" "Pesos") ("MYR" "Malaysia" "Ringgits") ("MZM" "Mozambique" "Meticais") ("NAD" "Namibia" "Dollars") ("NGN" "Nigeria" "Nairas") ("NIO" "Nicaragua" "Gold Cordobas") ("NOK" "Norway" "Krone") ("NPR" "Nepal" "Nepal Rupees") ("NZD" "New Zealand" "Dollars") ("OMR" "Oman" "Rials") ("PAB" "Panama" "Balboa") ("PEN" "Peru" "Nuevos Soles") ("PGK" "Papua New Guinea" "Kina") ("PHP" "Philippines" "Pesos") ("PKR" "Pakistan" "Rupees") ("PLN" "Poland" "Zlotych") ("PYG" "Paraguay" "Guarani") ("QAR" "Qatar" "Rials") ("ROL" "Romania" "Lei") ("RUR" "Russia" "Rubles") ("RWF" "Rwanda" "Rwanda Francs") ("SAR" "Saudi Arabia" "Riyals") ("SBD" "Solomon Islands" "Dollars") ("SCR" "Seychelles" "Rupees") ("SDD" "Sudan" "Dinars") ("SEK" "Sweden" "Kronor") ("SGD" "Singapore" "Dollars") ("SHP" "Saint Helena" "Pounds") ("SIT" "Slovenia" "Tolars") ("SKK" "Slovakia" "Koruny") ("SLL" "Sierra Leone" "Leones") ("SOS" "Somalia" "Shillings") ("SPL" "Seborga" "Luigini") ("SRD" "Suriname" "Dollars") ("STD" "São Tome and Principe" "Dobras") ("SVC" "El Salvador" "Colones") ("SYP" "Syria" "Pounds") ("SZL" "Swaziland" "Emalangeni") ("THB" "Thailand" "Baht") ("TJS" "Tajikistan" "Somoni") ("TMM" "Turkmenistan" "Manats") ("TND" "Tunisia" "Dinars") ("TOP" "Tonga" "Pa'anga") ("TRL" "Turkey" "Liras") ("TTD" "Trinidad and Tobago" "Dollars") ("TVD" "Tuvalu" "Tuvalu Dollars") ("TWD" "Taiwan" "New Dollars") ("TZS" "Tanzania" "Shillings") ("UAH" "Ukraine" "Hryvnia") ("UGX" "Uganda" "Shillings") ("USD" "United States of America" "Dollars") ("UYU" "Uruguay" "Pesos") ("UZS" "Uzbekistan" "Sums") ("VEB" "Venezuela" "Bolivares") ("VND" "Viet Nam" "Dong") ("VUV" "Vanuatu" "Vatu") ("WST" "Samoa" "Tala") ("XAF" "Communauté Financière Africaine, BEAC" "Francs") ("XAG" "Silver" "Ounces") ("XAU" "Gold" "Ounces") ("XCD" "East Caribbean" "Dollars") ("XDR" "International Monetary Fund (IMF)" "Special Drawing Rights") ("XOF" "Communauté Financière Africaine, BCEAO" "Francs") ("XPD" "Palladium" "Ounces") ("XPF" "Comptoirs Français du Pacifique" "Francs") ("XPT" "Platinum" "Ounces") ("YER" "Yemen" "Rials") ("ZAR" "South Africa" "Rand") ("ZMK" "Zambia" "Kwacha") ("ZWD" "Zimbabwe" "Zimbabwe Dollars") )) ;;+xe-currencies+ (defun print-formated-data () (dolist (x '(+xe-countries+ +xe-currencies+ +wikipedia-active+ +wikipedia-Obsolete+)) (let ((maxes (make-array (list 20) :initial-element 0))) (dolist (y (eval x)) (do ((z y (cdr z)) (i 0 (1+ i))) ((null z)) (setf (aref maxes i) (max (aref maxes i) (length (if (typep (car z) 'sequence) (car z) (format nil "~A" (car z)))))))) (let* ((widths (map 'list (function identity) (subseq maxes 0 (1+ (position-if-not (function zerop) maxes :from-end t))))) (tot-width (apply (function +) widths))) ;; (format t "~&;; ~5D : ~{~4D ~}~%" tot-width widths) (unless (< tot-width 72) (let ((big-cnt 0) (big-wid 0) (sma-wid 0) (big-rat)) (dolist (w widths) (if (< 20 w) (incf big-wid (+ 3 w)) (incf sma-wid (+ 3 w)))) ;;(print (list :tot-width tot-width :sma-wid sma-wid :big-wid big-wid)) (setf big-rat (/ (- (+ (length widths) tot-width) sma-wid) (- 64 sma-wid))) (map-into widths (lambda (w) (if (< 20 w) (+ 2 (truncate w big-rat)) (+ 2 w))) widths))) ;;(format t "~&;; ~5D : ~{~4D ~}~%" (apply (function +) widths) widths) (format t "~%(defparameter ~A~%'(~%" x) (dolist (y (mapcar (lambda (y) y) (eval x))) (format t "(") (do ((y y (cdr y)) (w widths (cdr w))) ((null y) (format t ")~%")) (if (numberp (car y)) (format t "~VD " (car w) (car y)) (format t "~VS " (car w) (car y))))) (format t "))~2%"))))) ;;print-formated-data (DOLIST (CUR +COCUCOD+) (LET ((COU (CAR (MEMBER (SECOND CUR) +COUNTRIES+ :TEST (FUNCTION STRING-EQUAL) :KEY (FUNCTION FIRST))))) (IF (NOT COU) (FORMAT T "NOT FOUND: ~S~%" CUR) (IF (NOT (STRING-EQUAL (SECOND COU) (FIRST CUR))) (FORMAT T "COUNTRY NAME DOESN'T MATCH ~S ~% ~S~% ~S~%" (second cur) (first CUR) (second COU)))))) (progn (defparameter +country-currency+ '()) (defparameter +currencies+ '()) (dolist (cocu +cocucod+) (push (list (first cocu) (third cocu) (sixth cocu)) +country-currency+) (push (list (third cocu) (fourth cocu) (fifth cocu) (second cocu)) +currencies+)) (setf +country-currency+ (sort (delete-duplicates +country-currency+ :test (function equalp)) (function string<) :key (function first)) +currencies+ (sort (delete-duplicates +currencies+ :test (function equalp)) (function string<) :key (function first)))) ||# ;;;; iso4217.lisp -- -- ;;;;
55,960
Common Lisp
.lisp
1,375
34.591273
140
0.474214
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
407d533365f23ef587a8b0adb2dd1a988e9577f34463dd430572dd23b1452db8
5,128
[ -1 ]
5,129
list.lisp
informatimago_lisp/common-lisp/cesarum/list.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: list.lisp ;;;;LANGUAGE: common-lisp ;;;;SYSTEM: UNIX ;;;;USER-INTERFACE: UNIX ;;;;DESCRIPTION ;;;; This module exports some list utility functions. ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-19 <PJB> Removed dll from this package. cf. the dll package. ;;;; 2014-11-18 <PJB> Added map-cartesian-product. ;;;; 2012-03-14 <PJB> Added plist-keys. ;;;; 2012-02-19 <PJB> Moved HASHED-* functions that work on sequence to ;;;; COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SEQUENCE. ;;;; 2011-04-03 <PJB> Added LIST-LENGTHS. ;;;; 2008-06-24 <PJB> Added ENSURE-CIRCULAR, MAKE-CIRCULAR-LIST, CIRCULAR-LENGTH. ;;;; 2007-01-05 <PJB> Added REPLACE-TREE (should move to a new package later). ;;;; 2005-09-02 <PJB> Moved EQUIVALENCE-CLASSES in from ECMA048. ;;;; 2005-08-10 <PJB> Moved TRIM-LIST in from make-depends. ;;;; 2004-10-15 <PJB> Added IOTA. ;;;; 2004-08-24 <PJB> Added TRANSPOSE, HASHED-REMOVE-DUPLICATE. ;;;; 2003-06-10 <PJB> Added NSPLIT-LIST ;;;; 2002-12-03 <PJB> Common-Lisp'ized. ;;;; 2001-11-30 <PJB> Added list-remove-elements. ;;;; 199?-??-?? <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.COMMON-LISP.CESARUM.LIST" (:use "COMMON-LISP") (:export "APPENDF" "PREPENDF" "PREPEND" "PUSH*" "EQUIVALENCE-CLASSES" "SUBSETS" "COMBINE" "IOTA" "MAKE-LIST-OF-RANDOM-NUMBERS" "LIST-INSERT-SEPARATOR" "NSPLIT-LIST-ON-INDICATOR" "NSPLIT-LIST" "DEEPEST-REC" "DEEPEST" "DEPTH" "FLATTEN" "LIST-TRIM" "TRANSPOSE" "AGET" "MEMQ" "MAP-CARTESIAN-PRODUCT" "PLIST-KEYS" "PLIST-REMOVE" "PLIST-GET" "PLIST-PUT" "PLIST-CLEANUP" "HASHED-INTERSECTION" ;; "HASHED-REMOVE-DUPLICATES" moved to COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SEQUENCE "ENSURE-LIST" "PROPER-LIST-P" "LIST-LENGTHS" "LIST-ELEMENTS" "ENSURE-CIRCULAR" "MAKE-CIRCULAR-LIST" "CIRCULAR-LENGTH" "TREE-FIND" "TREE-DIFFERENCE" "REPLACE-TREE" "META-LIST" "MAPTREE") (:documentation " This package exports list processing functions. License: AGPL3 Copyright Pascal J. Bourguignon 2003 - 2014 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.COMMON-LISP.CESARUM.LIST") (defun prepend (tail &rest lists) (apply (function append) (append lists (list tail)))) (define-modify-macro prependf (&rest lists) prepend "Prepend the LISTS at the beginning of the PLACE.") (define-modify-macro appendf (&rest lists) append "Append the LISTS at the end of the PLACE.") (defmacro push* (&rest elements-and-place) `(prependf ,(car (last elements-and-place)) (list ,@(butlast elements-and-place)))) (assert (equal (let ((i -1) (v (vector nil))) (push* 5 6 7 8 (aref v (incf i))) (decf i) (push* 1 2 3 4 (aref v (incf i))) (aref v 0)) '(1 2 3 4 5 6 7 8))) (defun meta-list (list) " Returns a list whose CARs are the CONS cells of the LIST. LIST must be a proper list. " (loop :for meta :on list :collect meta)) (defun ensure-list (object) " RETURN: If OBJECT is a list then OBJECT, otherwise a fresh list containing OBJECT. " (if (listp object) object (list object))) (defun proper-list-p (object) " RETURN: whether OBJECT is a proper list NOTE: terminates with any kind of list, dotted, circular, etc. " (and (listp object) (loop :named proper :for current = object :then (cddr current) :for slow = (cons nil object) :then (cdr slow) :do (cond ((null current) (return-from proper t)) ((atom current) (return-from proper nil)) ((null (cdr current)) (return-from proper t)) ((atom (cdr current)) (return-from proper nil)) ((eq current slow) (return-from proper nil))))) #-(and) (labels ((proper (current slow) (cond ((null current) t) ((atom current) nil) ((null (cdr current)) t) ((atom (cdr current)) nil) ((eq current slow) nil) (t (proper (cddr current) (cdr slow)))))) (and (listp object) (proper object (cons nil object))))) (defun dotted-list-length (dotted-list) " DOTTED-LIST must be a dotted list or a proper list. RETURN: the number of cons cells in the list. " (loop :for length :from 0 :for current = dotted-list :then (cdr current) :until (atom current) :finally (return length))) (defun circular-list-lengths (circular-list) " CIRCULAR-LIST must be a circular list. RETURN: the length of the stem; the length of the circle. " (let ((cells (make-hash-table))) (loop :for index :from 0 :for cell = circular-list :then (cdr cell) :for previous = (gethash cell cells) :do (if previous (return-from circular-list-lengths (values previous (- index previous))) (setf (gethash cell cells) index))))) (defun list-lengths (list) " LIST is any kind of list: proper-list, circular-list or dotted-list. RETURN: for a proper list, the length of the list and 0; for a circular list, the length of the stem, and the length of the circle; for a dotted list, the number of cons cells, and nil; for an atom, 0, and nil. " (typecase list (cons (loop :named proper :for current = list :then (cddr current) :for slow = (cons nil list) :then (cdr slow) :do (cond ((null current) (return-from proper (values (list-length list) 0))) ((atom current) (return-from proper (values (dotted-list-length list) nil))) ((null (cdr current)) (return-from proper (values (list-length list) 0))) ((atom (cdr current)) (return-from proper (values (dotted-list-length list) nil))) ((eq current slow) (return-from proper (circular-list-lengths list)))))) (null (values 0 0)) (t (values 0 nil))) #-(and) (labels ((proper (current slow) ;; (print (list 'proper current slow)) (cond ((null current) (values (list-length list) 0)) ((atom current) (values (dotted-list-length list) nil)) ((null (cdr current)) (values (list-length list) 0)) ((atom (cdr current)) (values (dotted-list-length list) nil)) ((eq current slow) (circular-list-lengths list)) (t (proper (cddr current) (cdr slow)))))) (typecase list (cons (proper list (cons nil list))) (null (values 0 0)) (t (values 0 nil))))) (defun list-elements (clist) " CLIST is any kind of list: proper-list, circular-list or dotted-list. RETURN: for a proper list: a copy of clist, the length of the list and 0; for a circular list: a list of elements in the clist, the length of the stem, and the length of the circle; for a dotted list: a list of the elements in the clist, the number of cons cells, and nil; for an atom: a list of the atom, 0, and nil. " (cond ((null clist) ; a proper list (values '() 0 0)) ((atom clist) (values (list clist) 0 nil)) (t (loop :named scan :with cells = (make-hash-table) :with elements = '() :for index :from 0 :for cell = clist :then (cdr cell) :for previous = (gethash cell cells) :do (cond ((null cell) ; proper list (return-from scan (values (nreverse elements) index 0))) ((atom cell) ; dotted list (push cell elements) (return-from scan (values (nreverse elements) index nil))) (previous ; a circular list (return-from scan (values (nreverse elements) previous (- index previous)))) (t ; in the middle (setf (gethash cell cells) index) (push (car cell) elements))))))) (defun ensure-circular (list) " If list is not a circular list, then modify it to make it circular. RETURN: LIST " (if (proper-list-p list) (setf (cdr (last list)) list) list)) (defun make-circular-list (size &key initial-element) " RETURN: a new circular list of length SIZE. POST: (circular-length (make-circular-list size)) == (values size 0 size) " (let ((list (make-list size :initial-element initial-element))) (setf (cdr (last list)) list) list)) (defun circular-length (list) "LIST must be either a proper-list or a circular-list, not a dotted-list. RETURN: the total length ; the length of the stem ; the length of the circle. " (let ((indexes (make-hash-table))) (loop :for i :from 0 :for current :on list :do (let ((index (gethash current indexes))) (if index ;; found loop (return (values i index (- i index))) (setf (gethash current indexes) i))) :finally (return (values i i 0))))) (defun map-cartesian-product (fun &rest lists) " DO: Call FUN with as arguments the elements of the cartesian products of the lists in LISTS. RETURN: A list of all the results of FUN. EXAMPLE: (map-cartesian-product (function list) '(1 2 3) '(a b c) '(11 22)) --> ((1 a 11) (1 a 22) (1 b 11) (1 b 22) (1 c 11) (1 c 22) (2 a 11) (2 a 22) (2 b 11) (2 b 22) (2 c 11) (2 c 22) (3 a 11) (3 a 22) (3 b 11) (3 b 22) (3 c 11) (3 c 22)) " (unless (null lists) (if (null (cdr lists)) (mapcar fun (car lists)) (mapcan (lambda (element) (apply (function map-cartesian-product) (lambda (&rest args) (apply fun element args)) (cdr lists))) (car lists))))) (declaim (inline plist-put plist-get plist-remove memq)) (defun plist-keys (plist) "Returns a list of the properties in PLIST." (remove-duplicates (loop :for (key) :on plist :by (function cddr) :collect key))) (defun plist-cleanup (plist) "Returns a plist that has the same associations than PLIST, but with a single occurence of each key and the first value found. EXAMPLE: (plist-cleanup '(:a 1 :b 2 :a 11 :c 3)) --> (:b 2 :c 3 :a 1) " (loop :with h = (make-hash-table) :for (key value) :on plist :by (function cddr) :do (when (eq h (gethash key h h)) (setf (gethash key h) value)) :finally (let ((result '())) (maphash (lambda (key value) (push value result) (push key result)) h) (return result)))) (defun plist-put (plist prop value) " Change value in PLIST of PROP to VALUE. PLIST is a property list, which is a list of the form (PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VALUE is any object. If PROP is already a property on the list, its value is set to VALUE, otherwise the new PROP VALUE pair is added. The new plist is returned; use `(setq x (plist-put x prop val))' to be sure to use the new value. The PLIST is modified by side effects. " (setf (getf plist prop) value) plist) (defun plist-get (plist prop) " Extract a value from a property list. PLIST is a property list, which is a list of the form (PROP1 VALUE1 PROP2 VALUE2...). This function returns the value corresponding to the given PROP, or nil if PROP is not one of the properties on the list. " (getf plist prop)) (defun plist-remove (plist prop) " DO: (REMF PLIST PROP) RETURN: The modified PLIST. " (remf plist prop) plist) (defun memq (item list) " RETURN: (MEMBER ITEM LIST :TEST (FUNCTION EQ)) " (member item list :test (function eq))) (defun transpose (tree) " RETURN: A tree where all the CAR and CDR are exchanged. " (if (atom tree) tree (cons (transpose (cdr tree)) (transpose (car tree))))) (defun list-trim (bag list &key (test (function eql)) (key (function identity))) " RETURN: A sublist of LIST with the elements in the BAG removed from both ends. " (do ((list (reverse list) (cdr list))) ((or (null list) (not (member (car list) bag :test test :key key))) (do ((list (nreverse list) (cdr list))) ((or (null list) (not (member (car list) bag :test test :key key))) list))))) (defun list-trim-test () (every (lambda (x) (equalp '(d e f) x)) (list (list-trim '(a b c) '( a b c d e f a b c c c )) (list-trim '((a 1)(b 2)(c 3)) '( a b c d e f a b c c ) :key (function car)) (list-trim '(:a :b :c) '( a b c d e f a b c c ) :test (function string=)) (list-trim '(a b c) '( a b c d e f)) (list-trim '(a b c) '( d e f a b c c c ))))) (defun maptree (fun &rest trees) " DO: Calls FUN on each non-null atom of the TREES. PRE: The trees in TREES must be congruent, or else the result is pruned like the smallest tree. RETURN: A tree congruent to the TREES, each node being the result of FUN (it may be a subtree). " (cond ((null trees) nil) ((every (function null) trees) nil) ((every (function atom) trees) (apply fun trees)) ((every (function consp) trees) (cons (apply (function maptree) fun (mapcar (function car) trees)) (apply (function maptree) fun (mapcar (function cdr) trees)))) (t nil))) (defun flatten (tree) " RETURN: A list containing all the elements of the `tree'. " (loop :with result = nil :with stack = nil :while (or tree stack) :do (cond ((null tree) (setq tree (pop stack))) ((atom tree) (push tree result) (setq tree (pop stack))) ((listp (car tree)) (push (cdr tree) stack) (setq tree (car tree))) (t (push (car tree) result) (setq tree (cdr tree)))) :finally (return (nreverse result)))) (defun depth (tree) " RETURN: The depth of the tree. " (if (atom tree) 0 (1+ (apply (function max) 0 (do ((tree tree (cdr tree)) (results '())) ((atom tree) results) (if (listp (car tree)) (push (depth (car tree)) results))))))) (defun deepest-rec (tree) " RETURN: The deepest list in the tree. NOTE: Recursive algorithm. SEE-ALSO: deepest-iti " (let ((subtree (delete-if (function atom) tree))) (cond ((null subtree) tree) ((every (lambda (item) (every (function atom) item)) subtree) (car subtree)) (t (deepest-rec (apply 'concatenate 'list subtree)))))) (defun deepest (tree) " RETURN: The deepest list in the tree. NOTE: Iterative algorithm. SEE-ALSO: deepest-rec " (do* ((tree tree (apply 'concatenate 'list subtree)) (subtree (delete-if (function atom) tree) (delete-if (function atom) tree))) ((or (null subtree) (every (lambda (item) (every (function atom) item)) subtree)) (if (null subtree) tree (car subtree))))) (defun nsplit-list (list position &key (from-end nil)) " PRE: 0<=POSITION<=(LENGTH LIST) DO: SPLIT THE LIST IN TWO AT THE GIVEN POSITION. (NSPLIT-LIST (LIST 'A 'B 'C) 0) --> NIL ; (A B C) (NSPLIT-LIST (LIST 'A 'B 'C) 1) --> (A) ; (B C) (NSPLIT-LIST (LIST 'A 'B 'C) 2) --> (A B) ; (C) (NSPLIT-LIST (LIST 'A 'B 'C) 3) --> (A B C) ; NIL POSITION: POSITION OF THE SPLIT; WHEN FROM-START AND 0<=POSITION<=(LENGTH LIST), THAT'S THE LENGTH OF THE FIRST RESULT FROM-START: THE DEFAULT, SPLIT COUNTING FROM THE START. FROM-END: WHEN SET, COUNT FROM THE END OF THE LIST. (NSPLIT-LIST L P :FROM-END T) === (NSPLIT-LIST L (- (LENGTH L) P)) RETURN: THE FIRST PART ; THE LAST PART " (if from-end (nsplit-list list (- (length list) position)) (do* ((prev nil rest) (rest list (cdr rest))) ((or (null rest) (zerop position)) (progn (if prev (setf (cdr prev) nil) (setf list nil)) (values list rest))) (decf position)))) (defun nsplit-list-on-indicator (list indicator) " RETURN: a list of sublists of list (the conses from list are reused), the list is splited between items a and b for which (indicator a b). " (declare (type (function (t t) t) indicator)) (let* ((result nil) (sublist list) (current list) (next (cdr current))) (loop :while next :do (if (funcall indicator (car current) (car next)) (progn ;; split (setf (cdr current) nil) (push sublist result) (setq current next) (setq next (cdr current)) (setq sublist current)) (progn ;; keep (setq current next) (setq next (cdr current))))) (push sublist result) (nreverse result))) (defun list-insert-separator (list separator) " RETURN: A list composed of all the elements in `list' with `separator' in-between. EXAMPLE: (list-insert-separator '(a b (d e f) c) 'x) ==> (a x b x (d e f) x c) " (cond ((null list) '()) ((null (cdr list)) (list (car list))) (t (do ((result '()) (items list (cdr items))) ((endp items) (nreverse (cdr result))) (push (car items) result) (push separator result))))) (defun iota (count &optional (start 0) (step 1)) " RETURN: A list containing the elements (start start+step ... start+(count-1)*step) The start and step parameters default to 0 and 1, respectively. This procedure takes its name from the APL primitive. EXAMPLE: (iota 5) => (0 1 2 3 4) (iota 5 0 -0.1) => (0 -0.1 -0.2 -0.3 -0.4) " (loop :repeat count :for item = start :then (+ item step) :collect item)) (defun make-list-of-random-numbers (length &key (modulo most-positive-fixnum)) " RETURN: A list of length `length' filled with random numbers MODULO: The argument to RANDOM. " (loop while (< 0 length) collect (random modulo) into result do (setq length (1- length)) finally (return result))) (defun combine (&rest args) " RETURN: (elt args 0) x (elt args 1) x ... x (elt args (1- (length args))) = the set of tuples built taking one item in order from each list in args. EXAMPLE: (COMBINE '(WWW FTP) '(EXA) '(COM ORG))) --> ((WWW EXA COM) (WWW EXA ORG) (FTP EXA COM) (FTP EXA ORG)) " (cond ((null args) '(())) ;; Don't consider empty set for one of the arguments since the combination ;; should produce the empty set: ;; {} x {1,2} = {} ;; Instead, let it fall to the default case, considering it as the symbol NIL. ;; ((null (car args)) (apply (function combine) (cdr args))) ((consp (car args)) (mapcan (lambda (item) (apply (function combine) item (cdr args))) (car args))) (t (mapcan (lambda (rest) (list (cons (car args) rest))) (apply (function combine) (cdr args)))))) ;; Sets: (defun hashed-intersection (set1 set2) " AUTHORS: Paul F. Dietz <[email protected]> Thomas A. Russ <[email protected]> " (declare (optimize speed (safety 0) (debug 0)) (list set1 set2)) (let ((table (make-hash-table :size (length set2))) (result nil)) (dolist (e set2) (setf (gethash e table) t)) (dolist (e set1) (when (gethash e table) (push e result) (setf (gethash e table) nil))) result)) (defun subsets (set) " RETURN: The set of all subsets of the strict SET. " (loop :with card = (length set) :for indicator :from 0 :below (expt 2 card) :collect (loop :for index :from 0 :below card :for item :in set :nconc (if (logbitp index indicator) (list item) nil) :into result :finally (return result)) :into result :finally (return result))) (defun equivalence-classes (set &key (test (function eql)) (key (function identity))) " RETURN: The equivalence classes of SET, via KEY, modulo TEST. " (loop :with classes = '() :for item :in set :for item-key = (funcall key item) :for class = (car (member item-key classes :test test :key (function second))) :do (if class (push item (cddr class)) (push (list :class item-key item ) classes)) :finally (return (mapcar (function cddr) classes)))) ;; A-lists: (defun aget (place indicator &optional default) " RETURN: The value of the entry INDICATOR of the a-list PLACE, or DEFAULT. " (let ((a (assoc indicator place))) (if a (cdr a) default))) ;; (DEFSETF AGET (PLACE INDICATOR &OPTIONAL DEFAULT) (VALUE) ;; " ;; DO: Set or add a new entry INDICATOR in the a-list at PLACE. ;; " ;; (DECLARE (IGNORE DEFAULT)) ;; (ERROR "THIS DOES NOT WORK. DEALING WITH SETF EXPANSION IS NEEDED HERE!") ;; (LET ((ACS (GENSYM "AC"))) ;; `(LET* ((,ACS (ASSOC ,INDICATOR ,PLACE))) ;; (IF ,ACS ;; (SETF (CDR ,ACS) ,VALUE) ;; (SETF ,PLACE (ACONS ,INDICATOR ,VALUE ,PLACE))) ;; ,VALUE))) (define-setf-expander aget (place indicator &optional default &environment env) (multiple-value-bind (vars vals store-vars writer-form reader-form) (get-setf-expansion place env) (let* ((vindicator (gensym "INDICATOR")) (vvalue (gensym "VALUE")) (vstore (first store-vars)) (acs (gensym "PAIR"))) (values (list* vindicator vars) (list* indicator vals) (list vvalue) `(let* ((,acs (assoc ,vindicator ,reader-form))) (if ,acs (setf (cdr ,acs) ,vvalue) (let ((,vstore (acons ,vindicator ,vvalue ,reader-form))) ,writer-form)) ,vvalue) `(let ((,acs (assoc ,vindicator ,reader-form))) (if ,acs (cdr ,acs) ,default)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun tree-find (object tree &key (key (function identity)) (test (function eql))) " RETURN: The object in TREE that matches OBJECT (using the KEY and TEST functions. TREE: A sexp. " (if (atom tree) (if (funcall test object (funcall key tree)) tree nil) (or (tree-find object (car tree) :key key :test test) (tree-find object (cdr tree) :key key :test test)))) (defun tree-difference (a b &key (test (function eql))) " RETURN: A tree congruent to A and B where each node is = when the corresponding nodes are equal (as indicated by TEST), or (/= a-elem b-elem) otherwise. EXAMPLE: (tree-difference '((a b c) 1 (d e f)) '((a b c) (1) (d x f))) --> ((= = = . =) (/= 1 (1)) (= (/= e x) = . =) . =) " (cond ((funcall test a b) '=) ((or (atom a) (atom b)) `(/= ,a ,b)) (t (cons (tree-difference (car a) (car b) :test test) (tree-difference (cdr a) (cdr b) :test test))))) (defun tree-structure-and-leaf-difference (a b &key (test (function eql))) (cond ((and (null a) (null b)) '=) ((or (null a) (null b)) `(/= ,a ,b)) ((and (atom a) (atom b)) (if (funcall test a b) '= `(/= ,a ,b))) ((or (atom a) (atom b)) `(/= ,a ,b)) (t (cons (tree-structure-and-leaf-difference (car a) (car b) :test test) (tree-structure-and-leaf-difference (cdr a) (cdr b) :test test))))) (defun replace-tree (dst src) " DO: Copies the elements of the src tree into the dst tree. If dst is missing cons cells, structure sharing occurs. RETURN: dst " (cond ((atom dst) src) ((atom src) nil) (t (if (or (atom (car dst)) (atom (car src))) (setf (car dst) (car src)) (replace-tree (car dst) (car src))) (if (or (atom (cdr dst)) (atom (cdr src))) (setf (cdr dst) (cdr src)) (replace-tree (cdr dst) (cdr src))) dst))) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; Sets ;;; (DEFUN CONS-LESSP (A B) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (DO* ( (AP A (CDR AP)) ;;; (AI (CAR AP) (CAR AP)) ;;; (BP B (CDR BP)) ;;; (BI (CAR BP) (CAR BP)) ) ;;; ( (NOT (AND AI BI (EQ AI BI))) ;;; (ANY-LESSP AI BI) ) ;;; ) ;;; ) ;;cons-lessp ;;; (DEFUN FORMATED-LESSP (A B) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (STRING-LESSP (FORMAT NIL "~S" A) (FORMAT NIL "~S" B)) ;;; );;formated-lessp ;;; (DEFUN SYMBOL-LESSP (A B) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (STRING-LESSP (SYMBOL-NAME A) (SYMBOL-NAME B)) ;;; );;symbol-lessp ;;; (DEFUN VECTOR-LESSP (A B) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (IF (= (LENGTH A) (LENGTH B)) ;;; (LOOP FOR I FROM 0 BELOW (LENGTH A) ;;; FOR AI = (AREF A I) ;;; FOR BI = (AREF B I) ;;; WHILE (EQ AI BI) ;;; ;;do (show ai bi) ;;; ;;finally (show ai bi) (show (or bi (not ai))) ;;; FINALLY (RETURN (ANY-LESSP AI BI))) ;;; (< (LENGTH A) (LENGTH B))) ;;; );;vector-lessp ;;; (DEFUN ANY-LESSP (A B) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (IF (EQ (TYPE-OF A) (TYPE-OF B)) ;;; (FUNCALL ;;; (CDR (ASSOC ;;; (TYPE-OF A) ;;; '((BOOL-VECTOR . VECTOR-LESSP) ;;; (BUFFER . FORMATED-LESSP) ;;; (CHAR-TABLE . VECTOR-LESSP) ;;; (COMPILED-FUNCTION . VECTOR-LESSP) ;;; (CONS . CONS-LESSP) ;;; (FLOAT . <=) ;;; (FRAME . FORMATED-LESSP) ;;; (INTEGER . <=) ;;; (MARKER . <=) ;;; (OVERLAY . FORMATED-LESSP) ;;; (PROCESS . FORMATED-LESSP) ;;; (STRING . STRING-LESSP) ;;; (SUBR . FORMATED-LESSP) ;;; (SYMBOL . SYMBOL-LESSP) ;;; (VECTOR . VECTOR-LESSP) ;;; (WINDOW . FORMATED-LESSP) ;;; (WINDOW-CONFIGURATION . FORMATED-LESSP) ;;; ))) A B) ;;; (STRING-LESSP (SYMBOL-NAME (TYPE-OF A)) ;;; (SYMBOL-NAME (TYPE-OF B)))) ;;; );;any-lessp ;;; (DEFUN LIST-TO-SET-SORTED (LIST) ;;; " ;;; RETURN: A set, that is a list where duplicate elements from `list' are removed. ;;; NOTE: This implementation first sorts the list, so its complexity should be ;;; of the order of O(N*(1+log(N))) [N==(length list)] ;;; BUT, it's still slower than list-to-set ;;; " ;;; (IF (NULL LIST) ;;; NIL ;;; (LET* ((SORTED-LIST (SORT LIST 'ANY-LESSP)) ;;; (FIRST (CAR SORTED-LIST)) ;;; (REST (CDR SORTED-LIST)) ;;; (SET NIL)) ;;; (LOOP WHILE REST DO ;;; (IF (EQ FIRST (CAR REST)) ;;; (SETQ REST (CDR REST)) ;;; (PROGN ;;; (PUSH FIRST SET) ;;; (SETQ FIRST (CAR REST) ;;; REST (CDR REST))))) ;;; SET)));;list-to-set-sorted ;;; (loop for size = 10 then (* 10 size) ;;; for l1 = (make-list-of-random-numbers size) ;;; for l2 = (copy-seq l1) ;;; do ;;; (format t "~%-----------~%list-to-set (~s)~%-----------" size) ;;; (finish-output) ;;; (time (setf l1 (list-to-set l1))) ;;; (format t "~%-----------~%list-to-set-sorted (~s)~%-----------" size) ;;; (finish-output) ;;; (time (setf l2 (list-to-set l2)))) ;; (array->list array) --> (coerce array 'list) ;;;; THE END ;;;;
30,122
Common Lisp
.lisp
767
33.302477
117
0.566385
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c1a8fcadd1ac4269c8477353cfe8733c02ac5aa688c74fab87ca8656b358be78
5,129
[ -1 ]
5,130
constraints-test.lisp
informatimago_lisp/common-lisp/cesarum/constraints-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: constraints-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests constraints.lisp. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-28 <PJB> Extracted from constraints.lisp. ;;;;BUGS ;;;; ;;;; - test not implemented yet. ;;;; ;;;;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.COMMON-LISP.CESARUM.CONSTRAINTS" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CONSTRAINTS") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CONSTRAINTS") (defparameter *germany* (make-graph (mapcan (lambda (edge) (list edge (reverse edge))) '((frankfurt mannheim) (frankfurt wuerzburg) (frankfurt kassel) (stuttgart nuemberg) (mannheim karlsruhe) (wuerzburg erfurt) (wuerzburg nuemberg) (kassel muenchen) (karlsruhe augsburg) (augsburg muenchen) (nuemberg muenchen))))) (define-test test/all () ) ;;;; THE END ;;;;
2,422
Common Lisp
.lisp
60
34.7
83
0.573124
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8a117f788eca9cc5dec96fa64edbcd87451771227250c7208b704586f42860d8
5,130
[ -1 ]
5,131
array-test.lisp
informatimago_lisp/common-lisp/cesarum/array-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: array-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests for the array functions. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-07-27 <PJB> Created ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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.COMMON-LISP.CESARUM.ARRAY.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY.TEST") (define-test test/positions-of-subsequence () (assert-true (handler-case (positions-of-subsequence "" "abc hello abc world abc how do abc you do abc") (:no-error (&rest results) (declare (ignore results)) nil) (error (error) (declare (ignore error)) t))) (assert-true (equal (positions-of-subsequence "xyz" "abc hello abc world abc how do abc you do abc") '())) (assert-true (equal (positions-of-subsequence "abc" "abc") '((0 . 3)))) (assert-true (equal (positions-of-subsequence "abc" "abcabcabc") '((0 . 3) (3 . 6) (6 . 9)))) (assert-true (equal (positions-of-subsequence "aaa" "aaaaaaaaaa") '((0 . 3) (3 . 6) (6 . 9)))) (assert-true (equal (positions-of-subsequence "abc" "abc hello abc world abc how do abc you do abc") '((0 . 3) (10 . 13) (20 . 23) (31 . 34) (42 . 45)))) (assert-true (equal (positions-of-subsequence "xyz" "abc hello abc world abc how do abc you do abc" :from-end t) '())) (assert-true (equal (positions-of-subsequence "abc" "abc" :from-end t) '((0 . 3)))) (assert-true (equal (positions-of-subsequence "abc" "abcabcabc" :from-end t) '((0 . 3) (3 . 6) (6 . 9)))) (assert-true (equal (positions-of-subsequence "aaa" "aaaaaaaaaa" :from-end t) '((1 . 4) (4 . 7) (7 . 10)))) (assert-true (equal (positions-of-subsequence "abc" "abc hello abc world abc how do abc you do abc" :from-end t) '((0 . 3) (10 . 13) (20 . 23) (31 . 34) (42 . 45)))) (assert-true (equal (positions-of-subsequence #((1 ?) (2 ?) (3 ?)) #((1 a) (2 b) (3 c) (1 d) (2 e) (1 f) (2 g) (3 h) (2 i) (3 j)) :key (function car) :test (function =)) '((0 . 3) (5 . 8)))) (assert-true (equal (positions-of-subsequence #((1 ?) (2 ?) (3 ?)) #((1 a) (2 b) (3 c) (1 d) (2 e) (1 f) (2 g) (3 h) (2 i) (3 j)) :key (function car) :test (function /=)) '((1 . 4) (4 . 7))))) (define-test test/array-to-list () (assert-true (equal (array-to-lists #0A42) 42)) (assert-true (equal (array-to-lists #(1 2 3)) '(1 2 3))) (assert-true (equal (array-to-lists "abc") '(#\a #\b #\c))) (assert-true (equal (array-to-lists #1A(1 2 3)) '(1 2 3))) (assert-true (equal (array-to-lists #2A((1 2 3) (4 5 6) (7 8 9))) '((1 2 3) (4 5 6) (7 8 9)))) (assert-true (equal (array-to-lists #()) 'nil)) (assert-true (equal (array-to-lists #2A()) 'nil)) (assert-true (equal (array-to-lists #2A(())) '(nil))) (assert-true (equal (array-to-lists #2A((()))) '((nil)))) (assert-true (equal (array-to-lists #3A(((1 2 3) (4 5 6) (7 8 9)) ((a b c) (d e f) (g h i)))) '(((1 2 3) (4 5 6) (7 8 9)) ((a b c) (d e f) (g h i)))))) (define-test test/all () (test/positions-of-subsequence) (test/array-to-list)) ;;;; THE END ;;;;
6,079
Common Lisp
.lisp
123
33.634146
102
0.428379
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1adc6c803751375f2af61b2e4f044a8e771d981445f835fbae967ab94dba5839
5,131
[ -1 ]
5,132
file.lisp
informatimago_lisp/common-lisp/cesarum/file.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: file.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports some file utility functions. ;;;; ;;;; binary-file-contents, sexp-file-contents, text-file-contents, and ;;;; string-list-text-file-contents are accessors. ;;;; They can be used with setf to store data into the file. ;;;; (push 'hi (sexp-file-contents file :if-does-not-exist '())) ;;;; (incf (sexp-file-contents version-file :if-does-not-exist 0)) ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2021-05-12 <PJB> Corrected handling of :if-does-not-exist <value> for SETF functions. ;;;; 2018-08-18 <PJB> Added create-file. ;;;; 2014-10-22 <PJB> Factorized out file reader functions, handle if-does-not-exist non-nil values. ;;;; 2009-07-27 <PJB> Renamed TEXT-FILE-TO-STRING-LIST to STRING-LIST-TEXT-FILE-CONTENTS, ;;;; Added missing setf functions. ;;;; 2007-07-07 <PJB> Made use of new CONTENTS-FROM-STREAM function. ;;;; 2006-08-05 <PJB> Added SAFE-TEXT-FILE-TO-STRING-LIST. ;;;; 2005-03-17 <PJB> Added REMOVE-FIRST-LINES. ;;;; 2005-02-20 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2005 - 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.COMMON-LISP.CESARUM.FILE" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ASCII" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM") #+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") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM" "CONTENTS-FROM-STREAM" "STREAM-TO-STRING-LIST" "COPY-STREAM" "COPY-OVER") (:export "REMOVE-FIRST-LINES" "BINARY-FILE-CONTENTS" "SAFE-TEXT-FILE-TO-STRING-LIST" "STRING-LIST-TEXT-FILE-CONTENTS" "TEXT-FILE-CONTENTS" "SEXP-FILE-CONTENTS" "SEXP-LIST-FILE-CONTENTS" "CREATE-FILE" "COPY-FILE" "COPY-DIRECTORY") (:documentation " This package exports file utility functions. BINARY-FILE-CONTENTS, SEXP-FILE-CONTENTS, TEXT-FILE-CONTENTS, and STRING-LIST-TEXT-FILE-CONTENTS are accessors. They can be used with setf to store data into the file. Examples: (setf (sexp-file-contents list-file) (cons 'hi (sexp-file-contents file :if-does-not-exist '()))) (incf (sexp-file-contents version-file :if-does-not-exist 0)) See also: COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM License: AGPL3 Copyright Pascal J. Bourguignon 2005 - 2014 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.COMMON-LISP.CESARUM.FILE") (defun create-file (pathname &key (if-exists :error) (external-format :default) (element-type '(unsigned-byte 8))) (close (open pathname :direction :output :if-exists if-exists :if-does-not-exist :create :external-format external-format :element-type element-type))) (defun copy-file (src dst &key (if-exists :error) (external-format :default) (element-type '(unsigned-byte 8))) " DO: Copy the contents of the file at path SRC to the file at path DST. " (with-open-file (inp src :direction :input :if-does-not-exist :error :external-format external-format :element-type element-type) (with-open-file (out dst :direction :output :if-does-not-exist :create :if-exists if-exists :external-format external-format :element-type element-type) (copy-stream inp out)))) (defun copy-directory (src dst &key (recursively t) (verbose nil) (on-error :error) (if-exists :error) (external-format :default) (element-type '(unsigned-byte 8))) " DO: Copy files from the directory SRC to the directory DST, using the specified key parameters. RECURSIVELY: When NIL, only the files directly under SRC are copied. Otherwise, subdirectories and all their files are also copied. IF-ERROR: Can be :ERROR, then the error is signaled, :CONTINUE, then the error is ignored and copying continues, :ABORT, then the error is ignored, and copying is aborted. RETURN: list-of-destination-files-copied ; list-of-source-files-with-errors NOTE: Files are scanned with CL:DIRECTORY, so only those that are accessible from the CL implementation are copied. NOTE: Empty subdirectories are not copied. " (let* ((src (truename src)) (src-files (mapcar (lambda (path) (cons path (enough-namestring path src))) (remove-if (lambda (path) (not (or (pathname-name path) (pathname-type path)))) (remove-duplicates (append (directory (merge-pathnames (if recursively "**/*.*" "*.*") src)) (directory (merge-pathnames (if recursively "**/*" "*") src))) :test (function equalp))))) (copied-files '()) (error-files '())) (dolist (src-file src-files (values copied-files error-files)) (let ((dst-file (merge-pathnames (cdr src-file) dst))) (when verbose (format *trace-output* "~&;; ~S -> ~S~%" (car src-file) dst-file)) (ensure-directories-exist dst-file) (block :copy (handler-bind ((error (lambda (err) (push (cons (car src-file) err) error-files) (case on-error ((:error) nil) ((:continue) (when verbose (format *error-output* "~&ERROR: ~A~%" err)) (return-from :copy)) ((:abort) (when verbose (format *error-output* "~&ERROR: ~A~%" err)) (return-from copy-directory (values copied-files error-files))))))) (copy-file (car src-file) dst-file :if-exists if-exists :external-format external-format :element-type element-type) (push dst-file copied-files))))))) (defun call-with-input-file (path element-type if-does-not-exist external-format thunk) (let ((if-does-not-exist-action (if (member if-does-not-exist '(:error :create nil)) if-does-not-exist nil)) (if-does-not-exist-value (if (member if-does-not-exist '(:error :create nil)) nil if-does-not-exist))) (with-open-file (in path :direction :input :if-does-not-exist if-does-not-exist-action :element-type element-type :external-format external-format) (typecase in (null if-does-not-exist-value) (stream (funcall thunk in)))))) (defmacro with-input-file ((streamvar path element-type if-does-not-exist external-format) &body body) `(call-with-input-file ,path ,element-type ,if-does-not-exist ,external-format (lambda (,streamvar) ,@body))) (defun output-file-if-does-not-exist (if-does-not-exist) (case if-does-not-exist ((:error :create nil) if-does-not-exist) (otherwise :create))) (declaim (inline output-file-if-does-not-exist)) (defmacro with-io-syntax (&body body) ;; Leave the current package as-is. `(let (;; (*package* (load-time-value (or (find-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE.IO") ;; (make-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE.IO" ;; :use '())))) (*print-array* t) (*print-circle* t) ;* (*print-base* 10.) (*print-case* :upcase) (*print-escape* t) (*print-gensym* t) (*print-length* nil) (*print-level* nil) (*print-lines* nil) (*print-miser-width* nil) (*print-pretty* nil) (*print-radix* t) (*print-readably* t) (*print-right-margin* nil) (*read-base* 10.) (*read-default-float-format* 'double-float) ;* (*read-eval* nil) ;* (*read-suppress* nil)) ,@body)) (defun sexp-file-contents (path &key (if-does-not-exist :error) (external-format :default)) " IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value that is returned instead of the content of the file if it doesn't exist. RETURN: The first SEXP of the file at PATH, or the value of IF-DOES-NOT-EXIST when not :ERROR or :CREATE and the file doesn't exist. The second value is t, unless the file is empty. " (with-input-file (in path 'character if-does-not-exist external-format) (with-io-syntax (let ((contents (read in nil in))) (if (eq contents in) (values nil nil) (values contents t)))))) (defun (setf sexp-file-contents) (new-contents path &key (if-does-not-exist :create) (if-exists :supersede) (external-format :default)) " IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value, equivalent to :CREATE for setf. DO: Writes the NEW-CONTENTS SEXP readably into the file at PATH. By default, that file is created or superseded; this can be changed with the keyword IF-DOES-NOT-EXIST or IF-EXISTS. RETURN: The NEW-CONTENTS, or if-exists or if-does-not-exist in case of error. " (with-open-file (out path :direction :output :if-does-not-exist (output-file-if-does-not-exist if-does-not-exist) :if-exists if-exists :external-format external-format) (if (and (streamp out) (not (or (eq out if-exists) (eq out if-does-not-exist)))) (with-io-syntax (write new-contents :stream out)) out))) (defun sexp-list-file-contents (path &key (if-does-not-exist :error) (external-format :default)) " IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value that is returned instead of the content of the file if it doesn't exist. RETURN: All the SEXPs of the file at PATH gathered in a list, or the value of IF-DOES-NOT-EXIST when not :ERROR or :CREATE and the file doesn't exist. " (with-input-file (in path 'character if-does-not-exist external-format) (with-io-syntax (loop :for form = (read in nil in) :until (eq form in) :collect form)))) (defun (setf sexp-list-file-contents) (new-contents path &key (if-does-not-exist :create) (if-exists :supersede) (external-format :default)) " NEW-CONTENTS: A list of sexps. IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value, equivalent to :CREATE for setf. DO: Writes the NEW-CONTENTS SEXPs readably into the file at PATH. By default, that file is created or superseded; this can be changed with the keyword IF-DOES-NOT-EXIST or IF-EXISTS. RETURN: The NEW-CONTENTS, or if-exists or if-does-not-exist in case of error. " (with-open-file (out path :direction :output :if-does-not-exist if-does-not-exist :if-exists if-exists :external-format external-format) (if (and (streamp out) (not (or (eq out if-exists) (eq out if-does-not-exist)))) (with-io-syntax (loop :for form :in new-contents :do (write form :stream out :array t :base 10. :case :upcase :circle t :escape t :gensym t :length nil :level nil :lines nil :miser-width nil :pretty nil :radix t :readably t :right-margin nil) :do (terpri out))) out))) (defun string-list-text-file-contents (path &key (if-does-not-exist :error) (external-format :default)) " IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value that is returned instead of the content of the file if it doesn't exist. RETURN: The list of lines collected from the file, or the value of IF-DOES-NOT-EXIST when not :ERROR or :CREATE and the file doesn't exist. " (with-input-file (in path 'character if-does-not-exist external-format) (stream-to-string-list in))) (defun (setf string-list-text-file-contents) (new-contents path &key (if-does-not-exist :create) (if-exists :supersede) (external-format :default)) " DO: Store the NEW-CONTENTS, into the file at PATH, each string on a line. By default, that file is created or superseded; this can be changed with the keyword IF-DOES-NOT-EXIST or IF-EXISTS. NEW-CONTENT: A sequence of strings, none of them should contain #\newline, otherwise the mapping between strings and file lines won't be conserved. IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value, equivalent to :CREATE for setf. RETURN: The NEW-CONTENTS or if-exists or if-does-not-exist in case of error. " (with-open-file (out path :direction :output :if-does-not-exist (output-file-if-does-not-exist if-does-not-exist) :if-exists if-exists :external-format external-format) (if (and (streamp out) (not (or (eq out if-exists) (eq out if-does-not-exist)))) (progn (map nil (lambda (line) (write-line line out)) new-contents) new-contents) out))) (defun text-file-contents (path &key (if-does-not-exist :error) (external-format :default)) " IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value that is returned instead of the content of the file if it doesn't exist. RETURN: The contents of the file at PATH as a LIST of STRING lines, or the value of IF-DOES-NOT-EXIST when not :ERROR or :CREATE and the file doesn't exist. " (with-input-file (in path 'character if-does-not-exist external-format) (contents-from-stream in :min-size 16384))) (defun (setf text-file-contents) (new-contents path &key (if-does-not-exist :create) (if-exists :supersede) (external-format :default)) " RETURN: The NEW-CONTENTS, or if-exists or if-does-not-exist in case of error. IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value, equivalent to :CREATE for setf. DO: Store the NEW-CONTENTS into the file at PATH. By default, that file is created or superseded; this can be changed with the keyword IF-DOES-NOT-EXIST or IF-EXISTS. " (with-open-file (out path :direction :output :if-does-not-exist (output-file-if-does-not-exist if-does-not-exist) :if-exists if-exists :external-format external-format) (if (and (streamp out) (not (or (eq out if-exists) (eq out if-does-not-exist)))) (write-sequence new-contents out) out))) (defun binary-file-contents (path &key (if-does-not-exist :error) (element-type '(unsigned-byte 8)) (external-format :default)) " IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value that is returned instead of the content of the file if it doesn't exist. RETURN: The contents of the file at PATH as a VECTOR of (UNSIGNED-BYTE 8), or the value of IF-DOES-NOT-EXIST when not :ERROR or :CREATE and the file doesn't exist. " (with-input-file (in path element-type if-does-not-exist external-format) (contents-from-stream in :min-size 16384))) (defun (setf binary-file-contents) (new-contents path &key (if-does-not-exist :create) (if-exists :supersede) (element-type '(unsigned-byte 8)) (external-format :default)) " RETURN: The NEW-CONTENTS, or if-exists or if-does-not-exist in case of error. DO: Store the NEW-CONTENTS into the file at PATH. By default, that file is created or superseded; this can be changed with the keyword IF-DOES-NOT-EXIST or IF-EXISTS. NEW-CONTENT: A sequence of ELEMENT-TYPE. IF-DOES-NOT-EXIST: Can be :error, :create, nil, or another value, equivalent to :CREATE for setf. " (with-open-file (out path :direction :output :if-does-not-exist (output-file-if-does-not-exist if-does-not-exist) :if-exists if-exists :element-type element-type :external-format external-format) (if (and (streamp out) (not (or (eq out if-exists) (eq out if-does-not-exist)))) (write-sequence new-contents out) out))) (defun safe-text-file-to-string-list (path &key (if-does-not-exist :error)) " DO: - Read the file at PATH as a binary file, - Remove all null bytes (handle UTF-16, UCS-2, etc), - Split 'lines' on CR, CR+LF or LF, - Replace all bytes less than 32 or greater than 126 by #\?, - Convert the remaining bytes as ASCII codes into the CL standard set. RETURN: The contents of the file as a list of base-string lines. " (loop :with data = (delete 0 (binary-file-contents path :if-does-not-exist if-does-not-exist)) :with cursor = (make-array 1 :element-type '(unsigned-byte 8) :adjustable t :displaced-to data :displaced-index-offset 0) :for bol = 0 :then eol :for eol = (or (position-if (lambda (ch) (or (= 10 ch) (= 13 ch))) data :start bol) (length data)) :collect (map 'string (lambda (code) (if (<= sp code 126) (aref *ascii-characters* (- code sp)) #\?)) (adjust-array cursor (- eol bol) :displaced-to data :displaced-index-offset bol)) :do (cond ((<= (length data) eol)) ((and (= 13 (aref data eol)) (< (1+ eol) (length data)) (= 10 (aref data (1+ eol)))) (incf eol 2)) (t (incf eol))) :while (< eol (length data)))) (defun remove-first-lines (file-name line-count &key (element-type 'character)) " DO: Modifies the file at path FILE-NAME, removing the LINE-COUNT first lines. WARNING: There's no backup: if the COPY-OVER fails, the file will be left in an unspecified state. " (with-open-file (file file-name :direction :io :element-type element-type :if-exists :overwrite :if-does-not-exist :error) ;; skip over the LINE-COUNT first lines: (dotimes (i line-count) (unless(print (read-line file nil nil)) (error "Less than ~A lines in the file ~A." line-count file-name))) ;; copy over the rest of the file to the start: (copy-over file (file-position file) 0))) ;;;; THE END ;;;;
23,603
Common Lisp
.lisp
454
39.297357
128
0.551963
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
68365e6c405e1e67d2314043650fca7f9d0c3374420c4fd89d1a88fe0b61fda7
5,132
[ -1 ]
5,133
cache-test.lisp
informatimago_lisp/common-lisp/cesarum/cache-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: cache-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests cache.lisp. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-25 <PJB> Extracted from cache.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.COMMON-LISP.CESARUM.CACHE.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CACHE") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CACHE" "CACHE-MAP-ENTRIES") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CACHE.TEST") (defvar *test-counter* 0) (defvar *test-cache* nil) (defvar *test-cache-2* nil) (define-test test/cache (&key (verbose t)) (let ((*standard-output* (if verbose *standard-output* (make-broadcast-stream)))) (ignore-errors (map nil (function delete-file) (directory "/tmp/cache/**/*.*"))) (setf *test-counter* 0) (let ((delay 7)) (flet ((producer (key) (values (format nil "~(~A-~A~)" key (incf *test-counter* )) (+ delay (get-universal-time)))) (print-files () (dolist (file (sort (mapcar (function namestring) (directory "/tmp/cache/**/*.*")) (function string<))) (princ file) (terpri)))) (setf *test-cache* (make-cache #p"/tmp/cache/" (function producer) :value-file-type "SYM")) (assert-true (string= (cache-get *test-cache* :one) "one-1")) (assert-true (string= (cache-get *test-cache* :two) "two-2")) (assert-true (string= (cache-get *test-cache* :three) "three-3")) (assert-true (string= (cache-get *test-cache* :one) "one-1")) (assert-true (string= (cache-get *test-cache* :two) "two-2")) (assert-true (string= (cache-get *test-cache* :three) "three-3")) (setf *test-cache-2* (make-cache #p"/tmp/cache/" (function producer))) (assert-true (string= (cache-get *test-cache-2* :one) "one-1")) (assert-true (string= "SYM" (cache-value-file-type *test-cache-2*))) (format t "~2&filled:~%")(finish-output) (print-files) (cache-expire *test-cache* :one) (cache-expire *test-cache* :two :keep-file t) (format t "~2&expired :one and :two:~%")(finish-output) (print-files) (assert-true (string= (cache-get *test-cache* :one) "one-4")) (format t "~2&expirations~%~:{~15A in ~4D seconds~%~}" (cache-map-entries *test-cache* 'list (lambda (entry) (list (entry-key entry) (- (entry-expire-date entry) (get-universal-time)))))) (format t "~2&waiting ~D s expiration of :one and :three:~%" delay) (finish-output) (sleep (1+ delay)) (assert-true (string= (cache-get *test-cache* :one) "one-5")) (assert-true (string= (cache-get *test-cache* :three) "three-6")) (cache-expire-all *test-cache*) (format t "~2&expired all~%")(finish-output) (print-files) (assert-true (string= (cache-get *test-cache* :one) "one-7")) (assert-true (string= (cache-get *test-cache* :three) "three-8")) (assert-true (string= (cache-get *test-cache-2* :one) "one-7")) (assert-true (string= (cache-get *test-cache-2* :three) "three-8")) (cache-map-entries *test-cache* nil (function print)))))) #|| (define-message html-page-req (sender uri)) (define-message html-page-rep (sender page-ref)) (define-message html-tree-req (sender uri)) (define-message html-tree-rep (sender tree-ref)) (send (make-instance 'html-page-req :sender myself :uri uri)) (loop for mesg = (message-receive-sexp queue +cache-message-type+) (case (car mesg) ((:get-html-page) (let* ((sender (first mesg)) (uri (second mesg)) (page (get-resource-at-uri uri))) (if page ;; TODO: actually copy page to shared memory and send only a reference. (message-send-sexp queue sender (list :html-page uri page)) (progn ;; if the request is already in the queue, then forget it. ;; if it comes from somebody else, then keep it ;; keep the request in a queue: (save-request mesg) ;; only proceed if the uri is not in the request queue. (message-send-sexp queue *fetcher* (list :fetch-uri uri)))))) ((:get-html-tree) ;; about the same, but if the tree is not in the cache, check first for ;; the page and skip fetching: just request processing ) ((:fetched-resource) ))) ||# (define-test test/all () (test/cache :verbose nil)) ;;;; THE END ;;;;
6,244
Common Lisp
.lisp
130
39.623077
98
0.564384
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7da57d69c11c6dc4cd685bc29e588605bc8994539b95c7cb76ea0ac32ce5293a
5,133
[ -1 ]
5,134
circular.lisp
informatimago_lisp/common-lisp/cesarum/circular.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: circular.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Utility to deal with circular structures. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-04-14 <PJB> Created. ;;;;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.COMMON-LISP.CESARUM.CIRCULAR" (:use "COMMON-LISP") (:export "CIRCULAR-REFERENCE" "CIRCULAR-REGISTER" "WITH-CIRCULAR-REFERENCES" "*CIRCULAR-REFERENCES*")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CIRCULAR") (defvar *circular-references* nil) (defmacro with-circular-references ((&key (test ''eql)) &body body) `(let ((*circular-references* (cons (make-hash-table :test ,test) 0))) ,@body)) (defun circular-register (object) (let ((count (gethash object (car *circular-references*) 0))) (if count (= 1 (incf (gethash object (car *circular-references*) 0))) (progn (warn "BAD: re-registering ~S" object) nil)))) (defun circular-reference (object) (let ((index (gethash object (car *circular-references*)))) (typecase index (null nil) (integer (setf (gethash object (car *circular-references*)) (if (= 1 index) nil (cons (incf (cdr *circular-references*)) nil)))) (t index)))) ;;;; THE END ;;;;
2,576
Common Lisp
.lisp
65
35.707692
83
0.596169
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
461d3e0c87d11581c85ca728799c0e1262765f42cd8147b306ee9718bd447aab
5,134
[ -1 ]
5,135
date-test.lisp
informatimago_lisp/common-lisp/cesarum/date-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: date-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests date.lisp. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-25 <PJB> Extracted from date.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.COMMON-LISP.CESARUM.DATE.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DATE.UTILITY") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DATE.TEST") (define-test test/compare-lists-of-numbers () (dolist (test '((() () 0) ((1) () +1) (() (1) -1) ((1) (1) 0) ((2) (1) +1) ((1) (2) -1) ((1 1 1) (1 1 1) 0) ((1 1 1 1) (1 1 1) +1) ((1 1 1) (1 1 1 1) -1) ((2 1 1) (1 1 1) +1) ((2 1 1 1) (1 1 1) +1) ((2 1 1) (1 1 1 1) +1) ((0 1 1) (1 1 1) -1) ((0 1 1 1) (1 1 1) -1) ((0 1 1) (1 1 1 1) -1) ((1 2 1 1) (1 1 1) +1) ((1 2 1 1 1) (1 1 1) +1) ((1 2 1 1) (1 1 1 1) +1) ((1 0 1 1) (1 1 1) -1) ((1 0 1 1 1) (1 1 1) -1) ((1 0 1 1) (1 1 1 1) -1))) (assert-true (= (compare-lists-of-numbers (first test) (second test)) (third test))))) (define-test test/hms60 () #|| (loop :for secondes :from 0.0 :below 600.0 :by 13.1 :do (assert (= secondes (multiple-value-call (function hms60-to-secondes) (hms60-from-secondes secondes))) (secondes))) ||# (loop :for secondes :from 0 :below 4000 :do (assert-true (= secondes (multiple-value-call (function hms60-to-secondes) (hms60-from-secondes secondes))) (secondes)))) (define-test test/all () (test/compare-lists-of-numbers) (test/hms60)) ;;;; THE END ;;;;
3,322
Common Lisp
.lisp
84
32.392857
83
0.495356
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d570f9e48b62cd2dd5739c6b56125a1449d9b5ffd52ba8ee1a4f6726fcef5085
5,135
[ -1 ]
5,136
peek-stream-test.lisp
informatimago_lisp/common-lisp/cesarum/peek-stream-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: peek-stream-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests peek-stream.lisp. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-25 <PJB> Extracted from peek-stream.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.COMMON-LISP.CESARUM.PEEK-STREAM.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PEEK-STREAM") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PEEK-STREAM.TEST") (define-test test/peek-stream/get-future-char () (dotimes (n 10) (with-input-from-string (in "ComMon-Lisp") (let* ((ps (make-instance 'peek-stream :stream in)) (nc (loop :for ch = (get-future-char ps) :repeat n :collect ch :into result :finally (return result))) (gc (loop :for ch = (getchar ps) :repeat n :collect ch :into result :finally (return result)))) (assert-true (equal nc gc)))))) (define-test test/peek-stream/nextchar/1 () (with-input-from-string (in "ComMon-Lisp") (let ((ps (make-instance 'peek-stream :stream in)) c1 c2 c3) (setf c1 (getchar ps) c2 (getchar ps) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3) '(#\C #\o #\m))) (setf c1 (getchar ps) c2 (getchar ps) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3 (nextchar ps)) '(#\M #\o #\n #\-))) (ungetchar ps c3) (ungetchar ps c2) (ungetchar ps c1) (setf c1 (getchar ps) c2 (getchar ps) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3) '(#\M #\o #\n))) (setf c1 (getchar ps) c2 (getchar ps) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3) '(#\- #\L #\i)))))) (define-test test/peek-stream/nextchar/2 () (with-input-from-string (in "Common-Lisp") (let ((ps (make-instance 'peek-stream :stream in)) c1 c2 c3) (setf c1 (getchar ps) c2 (getchar ps) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3) '(#\C #\o #\m))) (setf c1 (getchar ps) c2 (getchar ps)) (assert-true (equal (list c1 c2 (nextchar ps)) '(#\m #\o #\n))) (setf c3 (getchar ps)) (assert-true (equal (list c3 (nextchar ps)) '(#\n #\-))) (ungetchar ps c3) (ungetchar ps c2) (ungetchar ps c1) (setf c1 (getchar ps) c2 (getchar ps) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3) '(#\m #\o #\n))) (setf c1 (getchar ps) c2 (getchar ps) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3) '(#\- #\L #\i)))))) (define-test test/peek-stream/nextchar/3 () (with-input-from-string (in " Common Lisp") (let ((ps (make-instance 'peek-stream :stream in)) c1 c2 c3) (setf c1 (getchar ps) c2 (getchar ps) c3 (nextchar ps)) (assert-true (equal (list c1 c2 c3) '(#\space #\space #\C))) (setf c1 (getchar ps) c2 (getchar ps) c3 (nextchar ps #\n)) (assert-true (equal (list c1 c2 c3) '(#\C #\o #\n))) (setf c1 (getchar ps) c2 (nextchar ps t) c3 (getchar ps)) (assert-true (equal (list c1 c2 c3) '(#\n #\L #\L)))))) (define-test test/all () (test/peek-stream/get-future-char) (test/peek-stream/nextchar/1) (test/peek-stream/nextchar/2) (test/peek-stream/nextchar/3)) ;;;; THE END ;;;;
4,808
Common Lisp
.lisp
107
37.962617
83
0.560341
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0cdf77c4224b8280f3086a0a20a3948519d1caaa0e11377ded620ef1f5db8196
5,136
[ -1 ]
5,137
activity-test.lisp
informatimago_lisp/common-lisp/cesarum/activity-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: activity-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test activity.lisp. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-03-01 <PJB> Extracted from activity.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.COMMON-LISP.CESARUM.ACTIVITY.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ACTIVITY") (:export "TEST/ALL" "INTERACTIVE-TEST")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ACTIVITY.TEST") (define-condition debugger-invocation (condition) ((format-control :accessor debugger-invocation-format-control :initarg :format-control :initform "Debugger invocation" :type string) (format-arguments :accessor debugger-invocation-format-arguments :initarg :format-arguments :initform '() :type list)) (:documentation "SBCL expects for INVOKE-DEBUGGER, objects of type CL:CONDITION, not mere 'condition' objects.") (:report (lambda (condition stream) (apply (function format) stream (debugger-invocation-format-control condition) (debugger-invocation-format-arguments condition))))) (defun cdebugger (&optional (reason "User request")) (restart-case (invoke-debugger (make-condition 'debugger-invocation :format-control "~A" :forma-arguments (list reason))) (continue () :report "Continue" (return-from cdebugger)))) (defmacro define-menu (name title &rest items) `(defun ,name () (loop (flet ((exit-menu-loop (&optional result) (return-from ,name result))) (block try-again (format *query-io* "~2%Menu ~A~2%" ,title) (format *query-io* "~:{ ~A) ~A~%~}" ',items) (format *query-io* "~%Your choice: ") (let ((choice (string-trim " " (read-line *query-io*)))) (format *query-io* "~%") (case (or (and (string= "" choice) (let ((item (find :default ',items :key (function fourth)))) (if item (first item) (progn (format *query-io* "~%Invalid choice~%") (return-from try-again))))) (aref choice 0)) ,@(mapcar (lambda (item) `((,(first item)) ,(third item))) items) (otherwise (format *query-io* "~%Invalid choice~%") )))))))) (define-menu act-created-menu "Activity Created" (#\g "Go on" (exit-menu-loop) :default) (#\d "Invoke the debugger" (block debugger (restart-case (invoke-debugger (make-condition 'debugger-invocation :format-control "User request")) (menu () :report "Back to the menu" (return-from debugger)) (goon () :report "Go on" (exit-menu-loop))))) (#\p "Print activities" (print-scheduler-activities *scheduler*))) (defun interactive-test (&key debug) (let ((start (get-universal-time))) (macrolet ((run (&body body) `(lambda () (formatalot "~12D :name ~30S :period ~3D~%" (- (get-universal-time) start) (activity-name (current-activity)) (activity-period (current-activity))) ,@body)) (mkact (&rest args) `(progn (when debug (formatalot "Before creating a new ") (print-scheduler-activities *scheduler*) (formatalot "Let's create the new activity.")) (prog1 (make-activity ,@args) (when debug (print-scheduler-activities *scheduler*) (act-created-menu)))))) (format t "~%") (mkact (run (return-from test)) :name "stopper" :start-in 60) (mkact (run ;; (cdebugger "Check increment period...") (incf (activity-period (current-activity)))) :name "period increasing from 0" :period 0) (mkact (let ((times 11)) (run (let ((act (current-activity))) (case (decf times) ((10) (setf (activity-period act) 30)) ((9) (setf (activity-period act) 2) (setf (activity-scheduled-time act) (+ (get-time act) 2))) ((0) (destroy-activity act)))))) :name "period 2 between 30 and 50" :period 30) (mkact (run) :name "period 10" :period 10) (mkact (run) :name "period 7" :period 7) (mkact (run) :name "period 5" :period 5) (mkact (run) :name "period 5'" :period 5) (let ((activity (mkact (run) :name "period 5\", to be destroyed in 15s" :period 5))) (mkact (run (if (activity-scheduler activity) (destroy-activity activity) (destroy-activity (current-activity)))) :name "Destroyer of [period 5\", to be destroyed in 15s]" :start-in 15))) (print-scheduler-activities *scheduler*) (activity-run) (values))) (define-test test/all () ) ;;;; THE END ;;;;
7,339
Common Lisp
.lisp
171
30.128655
84
0.493991
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
51da15464b9c65227f6ab2b00375fed1a5753fd18f30415689a88b2a5c1b0b5b
5,137
[ -1 ]
5,138
index-set.lisp
informatimago_lisp/common-lisp/cesarum/index-set.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: index-set.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Implements a set of indexes, represented as a list of ranges. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-05-08 <PJB> Created. ;;;;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.COMMON-LISP.CESARUM.INDEX-SET" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET") (:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET" "INCLUDE" "MERGE" "INTERSECTION" "UNION") (:export "CONTAINS" "CARDINAL" "EMPTYP" "MINIMUM" "MAXIMUM" "MAKE-COLLECTOR" "MAP-ELEMENTS" "THEREIS" "THEREIS1" "ALWAYS" "SET-EQUAL" "IS-SUBSET" "IS-STRICT-SUBSET" "INTENSION" "COPY" "UNION" "INTERSECTION" "DIFFERENCE" "SYMETRIC-DIFFERENCE" "INCLUDE" "EXCLUDE" "ASSIGN-EMPTY" "ASSIGN-SINGLETON" "ASSIGN" "MERGE" "INTERSECT" "SUBTRACT") (:export "INDEX-SET" "MAP-RANGES" "MAKE-RANGE" "COPY-RANGE" "EQUAL-RANGE" "RANGE" "RANGE-EMPTYP" "RANGE-COUNT" "RANGE-START" "RANGE-END" "RANGE-FIRST" "RANGE-LAST") (:documentation " This package implements sets of INTEGER as a sequence of ranges. License: AGPL3 Copyright Pascal J. Bourguignon 2013 - 2013 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.COMMON-LISP.CESARUM.INDEX-SET") ;;;===================================================================== ;;; RANGE CLASS (defclass range () ((start :initarg :start :initform 0 :type integer :writer (setf range-start) :documentation "First element in the range.") (end :initarg :end :initform 0 :type integer :writer (setf range-end) :documentation "First element beyond the range."))) (defmethod print-object ((range range) stream) (print-unreadable-object (range stream :type t) ;; (format stream "~{~S~^ ~}" (list :start (slot-value range 'start) ;; :end (slot-value range 'end))) (if (range-emptyp range) (princ "empty" stream) (format stream "~A-~A" (range-first range) (range-last range)))) range) (defun exactly-one (&rest parameters) (= 1 (count nil parameters :key (function not)))) (defun make-range (&key start end first last count) (assert (or (and (exactly-one start first) (exactly-one end last count)) (and (exactly-one start first count) (exactly-one end last)))) (make-instance 'range :start (cond (start start) (first first) (end (- end count)) (t (- last count -1))) :end (cond (end end) (last (1+ last)) (count (+ start count))))) (defgeneric range-emptyp (range) (:method ((range range)) (<= (slot-value range 'end) (slot-value range 'start)))) (defgeneric range-count (range) (:method ((range range)) (max 0 (- (range-end range) (range-start range))))) (defgeneric range-start (range) (:method ((range range)) (unless (range-emptyp range) (slot-value range 'start)))) (defgeneric range-end (range) (:method ((range range)) (unless (range-emptyp range) (slot-value range 'end)))) (defgeneric range-first (range) (:method ((range range)) (unless (range-emptyp range) (slot-value range 'start)))) (defgeneric range-last (range) (:method ((range range)) (unless (range-emptyp range) (1- (slot-value range 'end))))) (defgeneric copy-range (range) (:method ((range range)) (make-instance 'range :start (slot-value range 'start) :end (slot-value range 'end)))) (defgeneric equal-range (r1 r2) (:method ((r1 range) (r2 range)) (or (and (range-emptyp r1) (range-emptyp r2)) (and (= (range-start r1) (range-start r2)) (= (range-end r1) (range-end r2)))))) ;;;===================================================================== ;;; INDEX-SET CLASS (defclass index-set () ((ranges :initform #() :type vector :initarg ranges))) ;; Invariants: ;; no empty range ;; ∀i∈[0 .. (1- (length ranges))[, (< (range-end (aref ranges i)) (range-start (aref ranges (1+ i)))) (defmethod print-object ((set index-set) stream) (print-unreadable-object (set stream :identity t :type t) (format stream "~{~S~^ ~}" (coerce (slot-value set 'ranges) 'list))) set) (defun index-set (&rest elements) (assign (make-instance 'index-set) elements)) (defgeneric check-invariant (object)) (defmethod check-invariant ((set index-set)) (assert (slot-boundp set 'ranges)) (let ((ranges (slot-value set 'ranges))) (check-type ranges vector) (notany (function range-emptyp) ranges) (when (<= 2 (length ranges)) (assert (loop :for i :below (1- (length ranges)) :always (< (range-end (aref ranges i)) (range-start (aref ranges (1+ i))))))))) (defgeneric map-ranges (result-type mapper index-set) (:method (result-type mapper (set index-set)) (collecting-result (collect result-type) (loop :for range :across (slot-value set 'ranges) :do (collect (funcall mapper range)))))) (defmethod emptyp ((set index-set)) (vector-emptyp (slot-value set 'ranges))) (defmethod cardinal ((set index-set)) (reduce (function +) (slot-value set 'ranges) :key (function range-count))) (defmethod minimum ((set index-set)) (unless (emptyp set) (range-start (aref (slot-value set 'ranges) 0)))) (defmethod maximum ((set index-set)) (unless (emptyp set) (range-last (vector-last (slot-value set 'ranges))))) (defgeneric range-of-element (set element) (:method ((set index-set) element) (check-type element integer) (dichotomy-search (slot-value set 'ranges) element (lambda (element range) (cond ((< element (range-start range)) -1) ((< element (range-end range)) 0) (t +1)))))) (defmethod contains ((set index-set) element) (declare (ignore element)) nil) (defmethod contains ((set index-set) (element integer)) (values (range-of-element set element))) (defmethod make-collector ((result-type (eql 'index-set))) (declare (ignorable result-type)) (lambda (&optional set (element nil add-element-p)) (if add-element-p (include set element) (make-instance 'index-set)))) (defmethod map-elements (result-type mapper (set index-set)) (collecting-result (collect result-type) (loop :for range :across (slot-value set 'ranges) :do (loop :for element :from (range-start range) :below (range-end range) :do (collect (funcall mapper element)))))) (defmethod set-equal ((set1 index-set) (set2 index-set)) (and (= (length (slot-value set1 'ranges)) (length (slot-value set2 'ranges))) (loop :for r1 :across (slot-value set1 'ranges) :for r2 :across (slot-value set2 'ranges) :always (equal-range r1 r2)))) (defmethod is-subset ((set1 index-set) (set2 index-set)) (loop :for range :across (slot-value set1 'ranges) :always (multiple-value-bind (f1 i1) (range-of-element set2 (range-start range)) (multiple-value-bind (f2 i2) (range-of-element set2 (range-last range)) (and f1 f2 (= i1 i2)))))) (defmethod is-strict-subset ((set1 index-set) (set2 index-set)) (and (< (cardinal set1) (cardinal set2)) (is-subset set1 set2))) ;;----------------------------------------------------------------------- ;; Algorithms (defun complement-ranges (ranges start end) (assert (or (vector-emptyp ranges) (and (<= start (range-start (vector-first ranges))) (<= (range-end (vector-last ranges)) end)))) (cond ((vector-emptyp ranges) (vector (make-range :start start :end end))) (t (loop :with len = (length ranges) :with result = (make-array (1+ len) :fill-pointer 0 :adjustable t) :for r :across ranges :do (progn (unless (= start (range-start r)) (vector-push-extend (make-range :start start :end (range-start r)) result (length result))) (setf start (range-end r))) :finally (progn (unless (= start end) (vector-push-extend (make-range :start start :end end) result (length result))) (return result)))))) (defun merge-ranges (a b) (cond ((vector-emptyp b) a) ((vector-emptyp a) b) (t (loop :with lena = (length a) :with lenb = (length b) :with result = (make-array (+ lena lenb) :fill-pointer 0 :adjustable t) :with a-is-smallest = (< (range-start (aref a 0)) (range-start (aref b 0))) :with current = (copy-range (aref (if a-is-smallest a b) 0)) :with i = (if a-is-smallest 1 0) :with j = (if a-is-smallest 0 1) :do (progn (loop :with merge-a :while (or (setf merge-a (and (< i lena) (<= (range-start (aref a i)) (range-end current)))) (and (< j lenb) (<= (range-start (aref b j)) (range-end current)))) :do (if merge-a (progn (setf (range-end current) (range-end (aref a i))) (incf i)) (progn (setf (range-end current) (range-end (aref b j))) (incf j)))) (vector-push-extend current result (length result)) (if (and (< i lena) (< j lenb)) (if (< (range-start (aref a i)) (range-start (aref b j))) (progn (setf current (copy-range (aref a i))) (incf i)) (progn (setf current (copy-range (aref b j))) (incf j))) (progn (loop :while (< i lena) :do (progn (vector-push-extend (copy-range (aref a i)) result (length result)) (incf i))) (loop :while (< j lenb) :do (progn (vector-push-extend (copy-range (aref b j)) result (length result)) (incf j))) (return result)))))))) (defun intersect-ranges (a b) (cond ((vector-emptyp a) a) ((vector-emptyp b) b) (t (loop :with lena = (length a) :with lenb = (length b) :with result = (make-array 4 :fill-pointer 0 :adjustable t) :with i = 0 :with current-a = (aref a i) :with j = 0 :with current-b = (aref b j) :do (progn (loop :while (and (< i lena) (<= (range-end current-a) (range-start current-b))) :do (progn (incf i) (setf current-a (when (< i lena) (aref a i))))) (unless current-a (return result)) (loop :while (and (< j lenb) (<= (range-end current-b) (range-start current-a))) :do (progn (incf j) (setf current-b (when (< j lenb) (aref b j))))) (unless current-b (return result)) (unless (or (<= (range-end current-a) (range-start current-b)) (<= (range-end current-b) (range-start current-a))) (vector-push-extend (make-range :start (max (range-start current-a) (range-start current-b)) :end (min (range-end current-a) (range-end current-b))) result (length result)) (cond ((= (range-end current-a) (range-end current-b)) (incf i) (if (< i lena) (setf current-a (aref a i)) (return result)) (incf j) (if (< j lenb) (setf current-b (aref b j)) (return result))) ((< (range-end current-a) (range-end current-b)) (incf i) (if (< i lena) (setf current-a (aref a i)) (return result))) (t (incf j) (if (< j lenb) (setf current-b (aref b j)) (return result)))))))))) (defun difference-ranges (r1 r2) (if (or (vector-emptyp r1) (vector-emptyp r2)) r1 (let* ((start (min (range-start r1) (range-start r2))) (end (max (range-end r1) (range-end r2)))) (intersect-ranges r1 (complement-ranges r2 start end))))) (defun symetric-difference-ranges (r1 r2) (cond ((vector-emptyp r1) r2) ((vector-emptyp r2) r1) (t (let* ((start (min (range-start r1) (range-start r2))) (end (max (range-end r1) (range-end r2)))) (intersect-ranges (merge-ranges r1 r2) (complement-ranges (intersect-ranges r1 r2) start end)))))) (defun collect-ranges (result-type ranges) (collecting-result (collect result-type) (loop :for range :across ranges :do (loop :for element :from (range-start range) :below (range-end range) :do (collect element))))) (defun equal-ranges (a b) (and (vectorp a) (vectorp b) (= (length a) (length b)) (every (function equal-range) a b))) ;;---------------------------------------------------------------------- ;; Functional (defmethod union ((result-type (eql 'index-set)) (set1 index-set) (set2 index-set)) (make-instance 'index-set 'ranges (merge-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) (defmethod union (result-type (set1 index-set) (set2 index-set)) (collect-ranges result-type (merge-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) (defmethod intersection ((result-type (eql 'index-set)) (set1 index-set) (set2 index-set)) (make-instance 'index-set 'ranges (intersect-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) (defmethod intersection (result-type (set1 index-set) (set2 index-set)) (collect-ranges result-type (intersect-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) (defmethod difference ((result-type (eql 'index-set)) (set1 index-set) (set2 index-set)) (make-instance 'index-set 'ranges (difference-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) (defmethod difference (result-type (set1 index-set) (set2 index-set)) (collect-ranges result-type (difference-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) (defmethod symetric-difference ((result-type (eql 'index-set)) (set1 index-set) set2) (make-instance 'index-set 'ranges (symetric-difference-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) (defmethod symetric-difference (result-type (set1 index-set) set2) (collect-ranges result-type (symetric-difference-ranges (slot-value set1 'ranges) (slot-value set2 'ranges)))) ;;---------------------------------------------------------------------- ;; Mutation (defmethod include ((destination-set index-set) (range range)) (unless (range-emptyp range) (merge destination-set (make-instance 'index-set 'ranges (vector range)))) destination-set) (defmethod include ((destination-set index-set) (element integer)) (multiple-value-bind (found index order) (range-of-element destination-set element) (unless found (let ((ranges (slot-value destination-set 'ranges))) (flet ((check-fusion (index) (when (= (range-end (aref ranges index)) (range-start (aref ranges (1+ index)))) (setf (range-end (aref ranges index)) (range-end (aref ranges (1+ index))) (slot-value destination-set 'ranges) (replace-subseq '() ranges index (1+ index)))))) (cond ((vector-emptyp ranges) (setf (slot-value destination-set 'ranges) (vector (make-range :start element :count 1)))) ((minusp order) (if (= (1+ element) (range-start (vector-first ranges))) (decf (range-start (vector-first ranges))) (setf (slot-value destination-set 'ranges) (replace-subseq (list (make-range :start element :count 1)) ranges 0 0)))) ((< (1+ (maximum destination-set)) element) (setf (slot-value destination-set 'ranges) (replace-subseq (list (make-range :start element :count 1)) ranges (length ranges) (length ranges)))) ((< (maximum destination-set) element) (incf (range-end (vector-last ranges)))) ((= (1+ element) (range-start (aref ranges (1+ index)))) (decf (range-start (aref ranges (1+ index)))) (check-fusion index)) ((= (range-end (aref ranges index)) element) (incf (range-end (aref ranges index))) (check-fusion index)) (t (setf (slot-value destination-set 'ranges) (replace-subseq (list (make-range :start element :count 1)) ranges index index)))))))) destination-set) (defmethod exclude ((destination-set index-set) (range range)) (unless (range-emptyp range) (subtract destination-set (make-instance 'index-set 'ranges (vector range)))) destination-set) (defmethod exclude ((destination-set index-set) (element integer)) (multiple-value-bind (found index) (range-of-element destination-set element) (when found (let ((ranges (slot-value destination-set 'ranges))) (flet ((check-empty (index) (when (range-emptyp (aref ranges index)) (setf (slot-value destination-set 'ranges) (replace-subseq '() ranges index (1+ index)))))) (cond ((= element (range-start (aref ranges index))) (incf (range-start (aref ranges index))) (check-empty index)) ((= (range-last (aref ranges index)) element) (decf (range-end (aref ranges index))) (check-empty index)) (t (let ((new-range (make-range :start (1+ element) :end (range-end (aref ranges index))))) (setf (range-end (aref ranges index)) element (slot-value destination-set 'ranges) (replace-subseq (list new-range) ranges (1+ index) (1+ index)))))))))) destination-set) (defmethod assign-empty ((destination-set index-set)) (setf (slot-value destination-set 'ranges) #()) destination-set) (defmethod assign-singleton ((destination-set index-set) element) (setf (slot-value destination-set 'ranges) (vector (make-range :start element :count 1))) destination-set) (defmethod assign ((destination-set index-set) (source-set index-set)) (setf (slot-value destination-set 'ranges) (map 'vector (function copy-range) (slot-value source-set 'ranges))) destination-set) (defmethod merge ((destination-set index-set) (source-set index-set)) (let ((merged-ranges (merge-ranges (slot-value destination-set 'ranges) (slot-value source-set 'ranges)))) (setf (slot-value destination-set 'ranges) (if (eq merged-ranges (slot-value source-set 'ranges)) (map-into (make-array (length merged-ranges) :fill-pointer (length merged-ranges) :adjustable t) (function copy-range) merged-ranges) merged-ranges))) destination-set) (defmethod intersect ((destination-set index-set) (source-set index-set)) (let ((intersected-ranges (intersect-ranges (slot-value destination-set 'ranges) (slot-value source-set 'ranges)))) (setf (slot-value destination-set 'ranges) (if (eq intersected-ranges (slot-value source-set 'ranges)) (map-into (make-array (length intersected-ranges) :fill-pointer (length intersected-ranges) :adjustable t) (function copy-range) intersected-ranges) intersected-ranges))) destination-set) (defmethod subtract ((destination-set index-set) (source-set index-set)) (setf (slot-value destination-set 'ranges) (difference-ranges (slot-value destination-set 'ranges) (slot-value source-set 'ranges))) destination-set) ;; (index-set '(1 2 3 4)) ;; (map-elements 'list 'identity (index-set '(1 2 3 4))) ;; (map-elements 'vector 'identity (index-set '(1 2 3 4))) ;; (map-elements 'vector 'identity (index-set '(1 2 3 4))) ;;;; THE END ;;;;
23,903
Common Lisp
.lisp
499
38.004008
118
0.558736
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
81e2c8482c7d0eef187a8841e885b5e604f0d64eee22b92a48a0802b89f29a6c
5,138
[ -1 ]
5,139
iso639a.lisp
informatimago_lisp/common-lisp/cesarum/iso639a.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: iso639a.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports functions and data to process ;;;; iso639a language codes. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2003-09-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.COMMON-LISP.CESARUM.ISO639A" (:use "COMMON-LISP") (:export "GET-LANGUAGES") (:documentation " This package exports functions and data to process iso639a language codes. License: AGPL3 Copyright Pascal J. Bourguignon 2003 - 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.COMMON-LISP.CESARUM.ISO639A") ;; http://www.loc.gov/standards/iso639-2/langcodes.html (defvar +languages+ '( ( aymara ay amerindian ) ( guarani gn amerindian ) ( quechua qu amerindian ) ( bhutani dz asian ) ( burmese my asian ) ( cambodian km asian ) ( chinese zh asian ) ( japanese ja asian ) ( korean ko asian ) ( laothian lo asian ) ( thai th asian ) ( tibetan bo asian ) ( vietnamese vi asian ) ( latvian lv baltic ) ( lithuanian lt baltic ) ( basque eu basque ) ( breton br celtic ) ( irish ga celtic ) ( scots-gaelic gd celtic ) ( welsh cy celtic ) ( kannada kn dravidian ) ( malayalam ml dravidian ) ( tamil ta dravidian ) ( telugu te dravidian ) ( greenlandic kl eskimo ) ( inupiak ik eskimo ) ( estonian et finno-ugric ) ( finnish fi finno-ugric ) ( hungarian hu finno-ugric ) ( afrikaans af germanic ) ( danish da germanic ) ( dutch nl germanic ) ( english en germanic ) ( faroese fo germanic ) ( frisian fy germanic ) ( german de germanic ) ( icelandic is germanic ) ( norwegian no germanic ) ( swedish sv germanic ) ( yiddish yi germanic ) ( afan om hamitic ) ( afar aa hamitic ) ( somali so hamitic ) ( abkhazian ab ibero-caucasian ) ( georgian ka ibero-caucasian ) ( assamese as indian ) ( bengali bn indian ) ( bihari bh indian ) ( gujarati gu indian ) ( hindi hi indian ) ( kashmiri ks indian ) ( marathi mr indian ) ( nepali ne indian ) ( oriya or indian ) ( punjabi pa indian ) ( sanskrit sa indian ) ( sindhi sd indian ) ( singhalese si indian ) ( urdu ur indian ) ( albanian sq indo-european/other) ( armenian hy indo-european/other) ( esperanto eo international ) ( interlingua ia international ) ( interlingue ie international ) ( volapuk vo international ) ( kurdish ku iranian ) ( pashto ps iranian ) ( persian fa iranian ) ( tajik tg iranian ) ( greek el latin/greek ) ( latin la latin/greek ) ( hausa ha negro-african ) ( kinyarwanda rw negro-african ) ( kurundi rn negro-african ) ( lingala ln negro-african ) ( sangho sg negro-african ) ( sesotho st negro-african ) ( setswana tn negro-african ) ( shona sn negro-african ) ( siswati ss negro-african ) ( swahili sw negro-african ) ( tsonga ts negro-african ) ( twi tw negro-african ) ( wolof wo negro-african ) ( xhosa xh negro-african ) ( yoruba yo negro-african ) ( zulu zu negro-african ) ( fiji fj oceanic/indonesian ) ( indonesian id oceanic/indonesian ) ( javanese jv oceanic/indonesian ) ( malagasy mg oceanic/indonesian ) ( malay ms oceanic/indonesian ) ( maori mi oceanic/indonesian ) ( samoan sm oceanic/indonesian ) ( sundanese su oceanic/indonesian ) ( tagalog tl oceanic/indonesian ) ( tonga to oceanic/indonesian ) ( catalan ca romance ) ( corsican co romance ) ( french fr romance ) ( galician gl romance ) ( italian it romance ) ( moldavian mo romance ) ( occitan oc romance ) ( portuguese pt romance ) ( rhaeto-romance rm romance ) ( romanian ro romance ) ( spanish es romance ) ( amharic am semitic ) ( arabic ar semitic ) ( hebrew he semitic ) ( maltese mt semitic ) ( tigrinya ti semitic ) ( bulgarian bg slavic ) ( byelorussian be slavic ) ( croatian hr slavic ) ( czech cs slavic ) ( macedonian mk slavic ) ( polish pl slavic ) ( russian ru slavic ) ( serbian sr slavic ) ( serbo-croatian sh slavic ) ( slovak sk slavic ) ( slovenian sl slavic ) ( ukrainian uk slavic ) ( azerbaijani az turkic/altaic ) ( bashkir ba turkic/altaic ) ( kazakh kk turkic/altaic ) ( kirghiz ky turkic/altaic ) ( tatar tt turkic/altaic ) ( turkish tr turkic/altaic ) ( turkmen tk turkic/altaic ) ( uzbek uz turkic/altaic ) ( bislama bi miscellaneous ) ( mongolian mn miscellaneous ) ( nauru na miscellaneous ) ) "A list of language records: ( name code family )." ) ;;+LANGUAGES+ (defun get-field (record order-code) (case order-code (:name (first record)) (:code (second record)) (:family (third record)) (otherwise ""))) (defun split-groups (list cut-indicator) " RETURN: A list of sublists of LIST, split where the CUT-INDICATOR function indicated. LIST: A list. CUT-INDICATOR: A function of two successive elements of the list, indicating whether the list must be split between the two elements. " (do* ((groups '()) (group '()) (list list (cdr list)) (current (car list) (car list)) (next (cadr list) (cadr list))) ((null list) (progn (when group (push (nreverse group) groups)) (nreverse groups))) (push current group) (if next (when (funcall cut-indicator current next) (push (nreverse group) groups) (setq group nil))))) (defun make-compare (order) (lambda (r1 r2) (do ((order-list order (cdr order-list)) (cmp 0)) ((or (/= 0 cmp) (null order-list)) (<= cmp 0)) (let ((f1 (get-field r1 (car order-list))) (f2 (get-field r2 (car order-list)))) (setq cmp (cond ((string< f1 f2) -1) ((string> f1 f2) 1) (t 0))))))) (defun get-languages (&key (group-per-family nil) (order nil)) " RETURN: If group-per-family is true, then a list of ( family (name code)* ) else a list of ( name code family ). In both cases, the list(s) of languages are ordered as indicated by the order list, which may contain any combination of: :NAME :CODE :FAMILY. " (when group-per-family (setq order (cons :family (remove :family order)))) (let ((languages (sort (copy-seq +languages+) (make-compare order)))) (if group-per-family (mapcar (lambda (group) (cons (third (car group)) (mapcar (lambda (item) (list (first item) (second item))) group))) (split-groups languages (lambda (curr next) (string/= (third curr) (third next))))) languages))) (defun ncapitalize (tree) " DO: Replace in place in TREE all occurence of a string or a symbol of length>2 by a string-capitalize'd copy. " (do ((items tree (cdr items))) ((null items) tree) (setf (car items) (cond ((listp (car items)) (ncapitalize (car items))) ((< 2 (length (string (car items)))) (string-capitalize (car items))) (t (string (car items))))))) ;;;; THE END ;;;;
11,158
Common Lisp
.lisp
274
35.470803
83
0.520077
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6bd7e2cef94fcaae8f02fd3181ba39a51f52d811ff07c8870d29fa94fbf91817
5,139
[ -1 ]
5,140
histogram.lisp
informatimago_lisp/common-lisp/cesarum/histogram.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: histogram.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; XXX ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-11-11 <PJB> Created ;;;;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.COMMON-LISP.CESARUM.HISTOGRAM" (:use "COMMON-LISP") (:export "HISTOGRAM" "HISTOGRAM-BINS-AND-LABELS" "MAKE-HISTOGRAM" "HISTOGRAM-BINS" "HISTOGRAM-SIZE" "HISTOGRAM-COUNT" "HISTOGRAM-MIN-VALUE" "HISTOGRAM-MAX-VALUE" "HISTOGRAM-ENTER" "HISTOGRAM-COMPUTE-BIN") (:documentation " This package provides functions to deal with histograms. License: AGPL3 Copyright Pascal J. Bourguignon 2013 - 2013 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.COMMON-LISP.CESARUM.HISTOGRAM") (defstruct (histogram (:constructor %make-histogram)) bins bin-size bin-count min-value max-value) (defun make-histogram (bin-count min-value max-value) " +-------+-------+-------+ | | | | count=3 +-------+-------+-------+ | | min max " (check-type bin-count (integer 1)) (check-type min-value real) (check-type max-value real) (assert (< min-value max-value)) (%make-histogram :bins (make-array (+ 2 bin-count) :element-type 'unsigned-byte :initial-element 0) :bin-size (/ (- max-value min-value) bin-count) :bin-count bin-count :min-value min-value :max-value max-value)) (defun histogram-bin-labels (histogram) (let* ((bins (histogram-bins histogram)) (labels (make-array (length bins)))) (setf (aref labels 0) (format nil "x<~A" (histogram-min-value histogram)) (aref labels (1- (length bins))) (format nil "~A<=x" (histogram-max-value histogram))) (loop :with size = (histogram-bin-size histogram) :for i :from 1 :to (histogram-bin-count histogram) :for left := (histogram-min-value histogram) :then right :for right = (+ left size) :do (setf (aref labels i) (format nil "~A<=x<~A" left right))) labels)) (defun histogram-compute-bin (histogram value) (cond ((< value (histogram-min-value histogram)) 0) ((<= (histogram-max-value histogram) value) (1- (length (histogram-bins histogram)))) (t (1+ (truncate (- value (histogram-min-value histogram)) (histogram-bin-size histogram)))))) (defun histogram-enter (histogram value) (check-type value real) (incf (aref (histogram-bins histogram) (histogram-compute-bin histogram value)))) (defun histogram (data bin-count &key (key (function identity)) min-value max-value) " If MIN-VALUE or MAX-VALUE is not given, then they're computed from the data. RETURN: An histogram of BIN-COUNT bins, built from the DATA, mapped by KEY. " (check-type data sequence) (assert (or (and (listp data) (cdr data)) (and (vectorp data) (plusp (length data))))) (let* ((data-min-value (or min-value (funcall key (elt data 0)))) (data-max-value (or max-value (funcall key (elt data 0)))) (data (map 'vector (if min-value (if max-value key (lambda (element) (let ((value (funcall key element))) (setf data-max-value (max data-max-value value)) value))) (if max-value (lambda (element) (let ((value (funcall key element))) (setf data-min-value (min data-min-value value)) value)) (lambda (element) (let ((value (funcall key element))) (setf data-min-value (min data-min-value value)) (setf data-max-value (max data-max-value value)) value)))) data)) (histogram (make-histogram bin-count data-min-value data-max-value))) (loop :for value :across data :do (histogram-enter histogram value)) histogram)) (defun histogram-bins-and-labels (data bin-count &key (key (function identity)) min-value max-value) (let ((histogram (histogram data bin-count :key key :min-value min-value :max-value max-value))) (map 'vector 'cons (histogram-bins histogram) (histogram-bin-labels histogram)))) ;; (histogram-bins-and-labels (com.informatimago.common-lisp.cesarum.list:iota 100) 7 :min-value 0 :max-value 7 ;; :key (lambda (x) (mod x 7))) ;; ;; #((0 . "x<0") (15 . "0<=x<1") (15 . "1<=x<2") (14 . "2<=x<3") (14 . "3<=x<4") (14 . "4<=x<5") (14 . "5<=x<6") (14 . "6<=x<7") (0 . "7<=x")) ;;;; THE END ;;;;
6,748
Common Lisp
.lisp
154
36.974026
142
0.591165
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5c2d8f7440292df9d0af895418ea63c584998afb197c9f972e821de55e0fa1f0
5,140
[ -1 ]
5,141
priority-queue-test.lisp
informatimago_lisp/common-lisp/cesarum/priority-queue-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: priority-queue-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests priority-queue.lisp. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-25 <PJB> Extracted from priority-queue.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.COMMON-LISP.CESARUM.PRIORITY-QUEUE.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PRIORITY-QUEUE")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PRIORITY-QUEUE.TEST") (define-test test/pq () (let ((p (make-pq))) (pq-insert p 4) (pq-insert p 8) (pq-insert p 2) (pq-remove p 4) (pq-insert p 16) (assert-true (= 2 (pq-first p))) (pq-insert p 1) (pq-insert p 5) (assert-true (= 1 (pq-first p))) (assert-true (= 1 (pq-pop p))) (assert-true (= 2 (pq-first p))) (assert-true (equal (pq-elements p) '(2 5 8 16)))) (let ((p (make-pq :lessp (function >) :key (function length))) (bye "Bye!")) (pq-insert p bye) (pq-insert p "Au revoir") (pq-insert p "Ah") (pq-remove p bye) (let ((long "Comment ça va?")) (pq-insert p long) (assert-true (eql long (pq-first p))) (let ((long "Moi ça va, et toi comment ça va?")) (pq-insert p long) (let ((long "Viens chez moi j'habite chez une copine.")) (pq-insert p long) (assert-true (eql long (pq-first p))) (assert-true (eql long (pq-pop p)))) (assert-true (eql long (pq-first p))))) (assert-true (equal '("Moi ça va, et toi comment ça va?" "Comment ça va?" "Au revoir" "Ah") (pq-elements p))))) (define-test test/all () (test/pq)) ;;;; THE END ;;;;
2,965
Common Lisp
.lisp
75
35.706667
95
0.588889
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2ac73fc2502554590226b6ec5b936292024cc1470cc05f6b7f9d7692f0ee3a04
5,141
[ -1 ]
5,142
table-file-test.lisp
informatimago_lisp/common-lisp/file/table-file/table-file-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: table-file-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tests the table-file file access method. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-10-16 <PJB> Extracted from table-file.lisp ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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.COMMON-LISP.FILE.TABLE-FILE") (defun test/table-file () (let ((path "/tmp/test-txt.table") (path2 "/tmp/test-bin.table") (rows 7) (cols 5) (rsize 64)) (create-table-file path rows cols rsize) (let ((table (open-table-file path :direction :io)) (record (make-array rsize :element-type 'octet))) (loop :for i :from 1 :below rows :do (loop :for j :from 1 :below cols :for value := (* i j) :do (replace record (map 'vector (function char-code) (format nil "~D~%" value))) (setf (table-file-ref table i j) record))) (close-table-file table)) (let ((table (open-table-file path :direction :io)) (record (make-array rsize :element-type 'octet))) (loop :for i :from 1 :below rows :do (replace record (map 'vector (function char-code) (format nil "~D~%" i))) (setf (table-file-ref table i 0) record)) (loop :for j :from 1 :below cols :do (replace record (map 'vector (function char-code) (format nil "~D~%" j))) (setf (table-file-ref table 0 j) record)) (loop :for i :from 1 :below rows :do (loop :for j :from 1 :below cols :for value := (* i j) :do (assert (eql value (read-from-string (map 'string (function code-char) (table-file-ref table i j record))))))) (close-table-file table)) (flet ((dump-table (path deserializer) (let* ((table (open-table-file path :direction :input :deserializer deserializer)) (record (make-array (table-file-record-size table) :element-type 'octet))) (loop :for i :from 1 :below (table-file-rows table) :do (loop :for j :from 1 :below (table-file-cols table) :do (format t "~4D " (table-file-ref table i j record))) (terpri)) (close-table-file table)))) (format t "~%Stored as text:~%") (dump-table path (lambda (record) (read-from-string (map 'string (function code-char) record)))) (let ((rsize 4)) (flet ((serializer (integer) (loop :with record := (make-array rsize :element-type 'octet) :for i :below (length record) :do (setf (aref record i) (ldb (byte 8 (* 8 i)) integer)) :finally (return record))) (deserializer (record) (loop :with integer := 0 :for i :below (length record) :do (setf integer (dpb (aref record i) (byte 8 (* 8 i)) integer)) :finally (return integer)))) (create-table-file path2 rows cols rsize) (let ((table (open-table-file path2 :direction :io :serializer (function serializer) :deserializer (function deserializer))) (record (make-array rsize :element-type 'octet))) (loop :for i :from 1 :below rows :do (setf (table-file-ref table i 0) i)) (loop :for j :from 1 :below cols :do (setf (table-file-ref table 0 j) j)) (loop :for i :from 1 :below rows :do (loop :for j :from 1 :below cols :do (setf (table-file-ref table i j record) (* i j)))) (loop :for i :from 1 :below rows :do (loop :for j :from 1 :below cols :do (assert (= (table-file-ref table i j record) (* i j))))) (close-table-file table) (format t "~%Stored as binary:~%") (dump-table path2 (function deserializer)))))))) #| cl-user> (test/table-file) Stored as text: 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 5 10 15 20 6 12 18 24 Stored as binary: 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 5 10 15 20 6 12 18 24 t cl-user> |# (defun test/all () (test/table-file) :success) ;;;; THE END ;;;;
5,848
Common Lisp
.lisp
130
34.384615
103
0.506573
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ce49de9595d536fc8c7e6a682a02170b3f4062f119c307c6993039ab2c27d1c6
5,142
[ -1 ]
5,143
com.informatimago.common-lisp.file.table-file.test.asd
informatimago_lisp/common-lisp/file/table-file/com.informatimago.common-lisp.file.table-file.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.file.table-file.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.file.table-file.test system. ;;;; Tests the com.informatimago.common-lisp.file.table-file system. ;;;; ;;;;USAGE: ;;;; ;;;;AUTHORS: ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-10-16 <PJB> Created. ;;;;BUGS: ;;;; ;;;;LEGAL: ;;;; ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.file.table-file.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.file.table-file system." :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.0.0" :properties ((#:author-email . "[email protected]") (#:date . "Autumn 2018") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.file.table-file.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.common-lisp.file.table-file") :components ((:file "table-file-test" :depends-on ())) #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) (dolist (p '("COM.INFORMATIMAGO.COMMON-LISP.FILE.TABLE-FILE")) (let ((*package* (find-package p))) (uiop:symbol-call p "TEST/ALL"))))) ;;;; THE END ;;;;
3,044
Common Lisp
.lisp
66
40.181818
95
0.567731
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2090e36395b6982f62a6aebbc71625b51c674849b573d2d20f18b690231ede14
5,143
[ -1 ]
5,144
com.informatimago.common-lisp.file.table-file.asd
informatimago_lisp/common-lisp/file/table-file/com.informatimago.common-lisp.file.table-file.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.file.table-file.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.file.table-file library. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-10-16 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.file.table-file" ;; system attributes: :description "Fixed Size Record, indexed by row and column, binary file access method." :long-description " This package implements a binary file access method, with fixed-size records, indexed by row and column. The record size, and the numbers of rows and columns are fixed and determined at file creation time. " :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.0.0" :properties ((#:author-email . "[email protected]") (#:date . "Autumn 2018") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.file.table-file/") ((#: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 ((:file "table-file" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.file.table-file.test")))) ;;;; THE END ;;;;
2,777
Common Lisp
.lisp
59
44.050847
119
0.608471
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f475b59294ef4513a46b7cc76ddc879c993c954975a9723d5b6884fd3d474232
5,144
[ -1 ]
5,145
table-file.lisp
informatimago_lisp/common-lisp/file/table-file/table-file.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: table-file.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package implements a binary file access method, ;;;; with fixed-size records, indexed by row and column. ;;;; The record size, and the numbers of rows and columns are fixed ;;;; and determined at file creation time. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-10-15 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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/>. ;;;;************************************************************************** (defpackage "COM.INFORMATIMAGO.COMMON-LISP.FILE.TABLE-FILE" (:use "COMMON-LISP") (:export "CREATE-TABLE-FILE" "OPEN-TABLE-FILE" "TABLE-FILE-REF" "CLOSE-TABLE-FILE" "TABLE-FILE" "TABLE-FILE-P" "TABLE-FILE-VERSION" "TABLE-FILE-ROWS" "TABLE-FILE-COLS" "TABLE-FILE-RECORD-SIZE")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.FILE.TABLE-FILE") (define-condition table-file-error (stream-error) ((table-file :initarg :table-file :reader table-file-error-table-file) (format-string :initarg :format-string :reader table-file-error-format-string) (format-arguments :initarg :format-arguments :reader table-file-error-format-arguments) (stream-error :initarg :stream-error :reader table-file-error-stream-error))) (define-condition table-file-header-too-big-error (table-file-error) ()) (deftype octet () '(unsigned-byte 8)) (defconstant +header-size+ 1024) (defconstant +filler+ (char-code #\newline) "Default byte to fill buffers with.") (defun write-header (file rows cols record-size) (let* ((header (make-array +header-size+ :element-type 'octet :initial-element +filler+)) (data (map 'vector 'char-code (with-output-to-string (out) (prin1 (list :file :table :version 1 :rows rows :cols cols :record-size record-size) out) (terpri out))))) (when (< (length header) (length data)) (error 'table-file-header-too-big-error :table-file file :format-string "Data header for the ~S at pathname ~S is too big (more than ~D bytes)." :format-arguments 'table-file (pathname file) +header-size+)) (replace header data) (file-position file 0) (write-sequence header file))) (defun create-table-file (pathname rows cols record-size) (with-open-file (file pathname :element-type 'octet :direction :io :if-does-not-exist :create :if-exists :supersede) (write-header file rows cols record-size) (let ((row (make-array (* cols record-size) :element-type 'octet :initial-element +filler+))) (file-position file +header-size+) (loop :repeat rows :do (write-sequence row file))))) (defstruct table-file stream version rows cols record-size serializer deserializer) (defun read-header (stream) (file-position stream 0) (let ((header (make-array +header-size+ :element-type 'octet))) (read-sequence header stream) (let ((header (read-from-string (map 'string (function code-char) header)))) (destructuring-bind (&key file version rows cols record-size) header (assert (and (eql file :table) (eql version 1) (typep rows '(integer 1)) (typep cols '(integer 1)) (typep record-size '(integer 1))) () "Bad header ~S for file ~S" header (pathname stream)) (make-table-file :stream stream :version version :rows rows :cols cols :record-size record-size))))) (defun open-table-file (pathname &key (direction :input) serializer deserializer) (assert (member direction '(:input :io))) (let* ((stream (open pathname :direction direction :if-does-not-exist :error :if-exists :append ; with :io :element-type 'octet)) (file (read-header stream))) (setf (table-file-serializer file) serializer (table-file-deserializer file) deserializer) file)) (defun check-arguments (file row col record) (assert (< -1 row (table-file-rows file)) (row) "row ~A out of bounds 0 .. ~A" row (1- (table-file-rows file))) (assert (< -1 col (table-file-cols file)) (col) "col ~A out of bounds 0 .. ~A" col (1- (table-file-cols file))) (when record (assert (and (typep record 'vector) (subtypep 'octet (array-element-type record)) (<= (table-file-record-size file) (array-dimension record 0))) (record) "Improper record type ~S for the ~S at pathname ~S" (type-of record) 'table-file (pathname (table-file-stream file))))) (defun table-file-ref (file row col &optional record) (check-arguments file row col record) (let ((pos (+ +header-size+ (* (table-file-record-size file) (+ col (* row (table-file-cols file)))))) (record (or record (make-array (table-file-record-size file) :element-type 'octet))) (stream (table-file-stream file))) (file-position stream pos) (read-sequence record stream) (if (table-file-deserializer file) (funcall (table-file-deserializer file) record) record))) (defun (setf table-file-ref) (new-value file row col &optional record) (check-arguments file row col record) (let ((pos (+ +header-size+ (* (table-file-record-size file) (+ col (* row (table-file-cols file)))))) (record (or record (make-array (table-file-record-size file) :element-type 'octet :initial-element +filler+))) (stream (table-file-stream file))) (replace record (if (table-file-serializer file) (funcall (table-file-serializer file) new-value) new-value)) (file-position stream pos) (write-sequence record stream) new-value)) (defun close-table-file (file) (close (table-file-stream file)))
7,718
Common Lisp
.lisp
170
35.470588
100
0.56699
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7aa11054e12e6bcd0a3d05cd911bf471fcd9772264dee6819fa59ce33c0a7e14
5,145
[ -1 ]
5,146
regexp-posix-test.lisp
informatimago_lisp/common-lisp/regexp/regexp-posix-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: regexp-posix-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test regexp-posix.lisp. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-25 <PJB> Extracted from regexp-posix.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.COMMON-LISP.REGEXP.REGEXP-POSIX.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP-POSIX") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP-POSIX" "RANGE-SET-UNION" "RANGE") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP-POSIX.TEST") (define-test test/range-set-union () (map nil (lambda (test) (let ((u (range-set-union (first test) (second test))) (v (range-set-union (second test) (first test)))) (if (and (equal u v) (equal u (third test))) (progress-success) (progress-failure-message '(and (equal u v) (equal u (third test))) "ERROR:~%a= ~S~%b= ~S~%e= ~S~%u= ~S~%v= ~S~2%" (first test) (second test) (third test) u v)))) '( ((1 (nil)) (3 (nil)) (1 3 (nil))) ((1 (nil)) (2 (nil)) ((1 . 2) (nil))) (((1 . 3) (nil)) ((5 . 7) (nil)) ((1 . 3) (5 . 7) (nil))) (((1 . 3) (nil)) ((4 . 6) (nil)) ((1 . 6) (nil))) (((1 . 4) (nil)) ((4 . 6) (nil)) ((1 . 6) (nil))) (((1 . 4) (nil)) ((3 . 6) (nil)) ((1 . 6) (nil))) (((1 . 4) (nil)) ((1 . 6) (nil)) ((1 . 6) (nil))) (((1 . 4) (nil)) ((0 . 6) (nil)) ((0 . 6) (nil))) (((1 . 3) (5 . 7) (9 . 11) (nil)) ((3 . 5) (7 . 9) (11 . 13) (nil)) ((1 . 13) (nil))) (((1 . 3) (5 . 7) (9 . 11) (nil)) (4 8 12 (nil)) ((1 . 12) (nil))) (((2 . 6) (10 . 14) (18 . 22) (nil)) (0 8 16 34 (nil)) (0 (2 . 6) 8 (10 . 14) 16 (18 . 22) 34 (nil)))))) (define-test test/all () (test/range-set-union)) ;;;; THE END ;;;;
3,364
Common Lisp
.lisp
90
31.755556
83
0.500459
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d526381ba35a2337f78af11488b840dc66302a1649a8b80d99216919acf073ce
5,146
[ -1 ]
5,147
com.informatimago.common-lisp.regexp.test.asd
informatimago_lisp/common-lisp/regexp/com.informatimago.common-lisp.regexp.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.regexp.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.regexp.test system. ;;;; Tests the com.informatimago.common-lisp.regexp 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.regexp.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.regexp 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.common-lisp.regexp.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.common-lisp.regexp") :components ((:file "regexp-posix-test" :depends-on nil)) #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) (let ((*package* (find-package "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP-POSIX.TEST"))) (uiop:symbol-call "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP-POSIX.TEST" "TEST/ALL")))) ;;;; THE END ;;;;
3,054
Common Lisp
.lisp
66
39.984848
118
0.566309
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
16394297609d1fdefe72c02e295624339b802275520371a85e5372645e14c423
5,147
[ -1 ]
5,148
com.informatimago.common-lisp.regexp.asd
informatimago_lisp/common-lisp/regexp/com.informatimago.common-lisp.regexp.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.regexp.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.regexp 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.regexp" ;; system attributes: :description "Informatimago Common Lisp Regular Expressions" :long-description "INCOMPLETE. Do not use yet." :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.6.0" :properties ((#:author-email . "[email protected]") (#:date . "Autumn 2015") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.regexp/") ((#: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.common-lisp.picture" "cl-ppcre") :components ((:file "regexp-emacs" :depends-on ()) (:file "regexp-posix" :depends-on ()) (:file "regexp" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.regexp.test")))) ;;;; THE END ;;;;
2,789
Common Lisp
.lisp
58
44.017241
110
0.580432
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9dc718faf1a0bdc452680780e9c03a4e01a3df57dc05450c671ed292f4f9810c
5,148
[ -1 ]
5,149
regexp-posix.lisp
informatimago_lisp/common-lisp/regexp/regexp-posix.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: regexp-posix.lisp ;;;;LANGUAGE: common-lisp ;;;;SYSTEM: UNIX ;;;;USER-INTERFACE: UNIX ;;;;NOWEB: t ;;;;DESCRIPTION ;;;; ;;;; See defpackage documentation string. ;;;; ;;;;USAGE ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-01-02 <PJB> Implemented POSIX regexp parser. ;;;; 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.COMMON-LISP.REGEXP.REGEXP-POSIX" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY") (:export ;; CLISP REGEXP API: "REGEXP-MATCH" "REGEXP-QUOTE" "MATCH-STRING" "MATCH-END" "MATCH-START" "MATCH" ;; POSIX API: "REGEXEC" "REGCOMP" "RM-EO" "RM-SO" "REGMATCH-T" "RE-NSUB" "REGEX-T" "REGOFF-T" "SIZE-T") (:documentation " NOT COMPLETE YET. This package implement POSIX Regular Expressions in Common-Lisp. This is interesting because it's available on any Common-Lisp platform while external C regexp libraries or internals are available or not, and not always implement these same syntax or semantic. Posix Regexp implemented in Common-Lisp. See specifications at: http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap09.html This is a strict implementation that will work both in clisp (Common-Lisp) and emacs (with cl and pjb-cl Common-Lisp extensions). This implementation is entirely in lisp, contrarily to what regexp packages are available under clisp or emacs. Thus it has the advantage of portability and availability (you don't have to compile or link a lisp system written in some barbarous language, and you get the same regexp features in all programs including this module). License: AGPL3 Copyright Pascal J. Bourguignon 2002 - 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/> ")) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP-POSIX.KEYWORD" (:nicknames "RK") (:use) (:export "COLLATING-SYMBOL" "EQUIVALENCE-CLASS" "CHARACTER-CLASS" "RANGE" "ANY" "L-ANCHOR" "R-ANCHOR" "MATCHING" "NON-MATCHING" "BACKREF" "SUBEXP" "SEQUENCE" "REPEAT" "REPEAT-SHY" "INFINITY" "ALTERNATIVE" "B-ANCHOR" "E-ANCHOR" "ITEM" "SET-SEQUENCE") (:documentation " This package gathers and exports regexp keywords. ALTERNATIVE ANY BACKREF B-ANCHOR CHARACTER-CLASS COLLATING-SYMBOL E-ANCHOR EQUIVALENCE-CLASS INFINITY ITEM L-ANCHOR MATCHING NON-MATCHING R-ANCHOR RANGE REPEAT REPEAT-SHY SEQUENCE SET-SEQUENCE SUBEXP License: AGPL3 Copyright Pascal J. Bourguignon 2002 - 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.COMMON-LISP.REGEXP.REGEXP-POSIX") #|| regexp --> (or character rk:any rk:l-anchor rk:r-anchor (rk:matching mexpr...) (rk:non-matching mexpr...) (rk:backref integer) (rk:subexp regex) (rk:sequence regex...) (rk:repeat integer (or integer rk:infinity) bexp) (rk:alternative regex...)) (rk:collating-symbol coll-elem) (rk:equivalence-class coll-elem) (rk:character-class class-name) (rk:range start end) ||# (defun lessp (a b) (if (or (eq a 'rk:infinity) (eq b 'rk:infinity)) nil (< a b))) ;;LESSP (defmacro if^2 (c1 c2 tt tf ft ff) `(if ,c1 (if ,c2 ,tt ,tf) (if ,c2 ,ft ,ff))) ;; (if^2 cond1 cond2 ;; (t t) (t f) ;; (f t) (f f)) (defmacro top (stack) `(car ,stack)) (defmacro invariant (condition &body body) `(progn (assert ,condition) (prog1 (progn ,@body) (assert ,condition)))) (defun pjb-re-split-string (string &optional separators) " DOES: Splits STRING into substrings where there are matches for SEPARATORS. RETURNS: A list of substrings. separators: A regexp matching the sub-string separators. Defaults to \"[ \f\t\n\r\v]+\". NOTE: Current implementation only accepts as separators a literal string containing only one character. " (let ((sep (aref separators 0)) (chunks '()) (position 0) (nextpos 0) (strlen (length string)) ) (loop while (< position strlen) do (loop while (and (< nextpos strlen) (char/= sep (aref string nextpos))) do (setq nextpos (1+ nextpos))) (push (subseq string position nextpos) chunks) (setq position (1+ nextpos)) (setq nextpos position)) (nreverse chunks))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; String Scanner ;; -------------- ;; (defstruct sc (string "" :type string) (position 0 :type integer) (bracket-position 0 :type integer) (expression-start () :type list)) (defun sc-length (sc) (length (sc-string sc))) (defun sc-eos (sc) (>= (sc-position sc) (sc-length sc))) (defun sc-curr-char (sc) " RETURN: The current character, or nil if EOS. " (if (sc-eos sc) nil (char (sc-string sc) (sc-position sc)))) (defun sc-next-char (sc) " RETURN: The next character, or nil if EOS. " (if (< (1+ (sc-position sc)) (sc-length sc)) (char (sc-string sc) (1+ (sc-position sc))) nil)) (defun sc-after-next-char (sc) " RETURN: The after next character, or nil if EOS. " (if (< (+ 2 (sc-position sc)) (sc-length sc)) (char (sc-string sc) (+ 2 (sc-position sc))) nil)) (defun sc-advance (sc &optional (increment 1)) " PRE: (= p (sc-position sc)) POST: (= (min (sc-length sc) (+ p increment)) (sc-position sc)) RETURN: The character at position p+increment or nil if EOS. " (setf (sc-position sc) (min (sc-length sc) (+ (sc-position sc) increment))) (sc-curr-char sc)) (defun sc-looking-at (sc substring) " " (string= (sc-string sc) substring :start1 (sc-position sc) :end1 (min (sc-length sc) (+ (sc-position sc) (length substring))))) (defun sc-scan-to (sc substring) " RETURN: the substring of (sc-string sc) starting from current position to the position just before the first occurence of the substring found from this position. PRE: (= p (sc-position sc)) POST: (and (<= p (sc-position sc)) (or (and (< (sc-position sc) (length (sc-string sc))) (string= substring (substring (sc-string sc) p (sc-position sc)))) (= (sc-position sc) (length (sc-string sc)))) (forall i between p and (1- (sc-position sc)) (string/= substring (substring (sc-string sc) i (+ i (length substring)))))) " (let* ((start (sc-position sc)) (end (search substring (sc-string sc) :start2 start))) (if end (progn (setf (sc-position sc) end) (subseq (sc-string sc) start end)) nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Regular Expression Parsing Utilities ;; ------------------------------------ (defun length>1 (list) (cdr list)) (defun errorp (expr) (and (consp expr) (eq :error (car expr)))) (define-condition parsing-error (error) ((arguments :initarg :arguments :accessor parsing-error-arguments))) (defun err (&rest args) ;; (error 'parsing-error :arguments (copy-list args)) (cons :error (copy-list args))) (defun re-integer (sc) " DO: Parses an integer. RETURN: The integer, or NIL. " (do ((start (sc-position sc))) ((or (sc-eos sc) (not (digit-char-p (sc-curr-char sc) 10))) (if (< start (sc-position sc)) (parse-integer (sc-string sc) :start start :end (sc-position sc) :radix 10 :junk-allowed nil) nil)) (sc-advance sc))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Parsing: Bracket Expression ;; --------------------------- (defun be-collating-symbol (sc) " DO: Parses a collating-symbol. RETURN: (rk:collating-symbol coll-elem) or (:error message) or nil if not looking at '[='. NOTE: collating_symbol : Open_dot COLL_ELEM_SINGLE Dot_close | Open_dot COLL_ELEM_MULTI Dot_close | Open_dot META_CHAR Dot_close ; COLL_ELEM_SINGLE and META_CHAR form a partition of all characters. " (if (sc-looking-at sc "[.") (progn (sc-advance sc 2) (let ((collating-symbol (sc-scan-to sc ".]"))) (if collating-symbol (progn (sc-advance sc 2) (list 'rk:collating-symbol collating-symbol)) (err "Missing a closing '.]' after '[.'.")))) nil)) ;;BE-COLLATING-SYMBOL (defun be-equivalence-class (sc) " DO: Parses an equivalence class. RETURN: (rk:equivalence-class coll-elem) or (:error message) or nil if not looking at '[='. NOTE: equivalence_class : Open_equal COLL_ELEM_SINGLE Equal_close | Open_equal COLL_ELEM_MULTI Equal_close ; META_CHAR One of the characters: ^ When found first in a bracket expression - When found anywhere but first (after an initial '^' , if any) or last in a bracket expression, or as the ending range point in a range expression ] When found anywhere but first (after an initial '^' , if any) in a bracket expression Inside an equivalence-class: ^ is not first in a bracket expression ==> ^ is not meta-char ] is not first in a bracket expression ==> ] is meta-char - isn't first, shouldn't be last, isn't ending a range ==> - is meta-char " (if (sc-looking-at sc "[=") (progn (sc-advance sc 2) (if (or (sc-looking-at sc "-") (sc-looking-at sc "]")) (err (format nil "Invalid meta-char ~S in equivalence class." (sc-curr-char sc))) (let ((equivalence-class (sc-scan-to sc "=]"))) (if equivalence-class (progn (sc-advance sc 2) (list 'rk:equivalence-class equivalence-class)) (err "Missing a closing '=]' after '[='."))))) nil)) ;;BE-EQUIVALENCE-CLASS (defun be-character-class (sc) " DO: Parses a character class RETURN: (rk:character-class class-name) or (:error message) or nil if not looking at '[:'. NOTES: character_class : Open_colon class_name Colon_close ; " (if (sc-looking-at sc "[:") (progn (sc-advance sc 2) (let ((class-name (sc-scan-to sc ":]"))) (if class-name (progn (sc-advance sc 2) (list 'rk:character-class class-name)) (err "Missing a closing ':]' after '[:'.")))) nil)) ;;BE-CHARACTER-CLASS (defun be-end-range (sc) " DO: Parses an end-range. RETURN: character or (rk:collating-symbol coll-elem) NOTES: end_range : COLL_ELEM_SINGLE | collating_symbol ; COLL_ELEM_SINGLE Any single-character collating element, unless it is a META_CHAR. META_CHAR One of the characters: ^ When found first in a bracket expression - When found anywhere but first (after an initial '^' , if any) or last in a bracket expression, or as the ending range point in a range expression ] When found anywhere but first (after an initial '^' , if any) in a bracket expression " (let ((coll-sym (be-collating-symbol sc))) (cond (coll-sym coll-sym) ((sc-eos sc) nil) ((and (= (sc-position sc) (sc-bracket-position sc)) (sc-looking-at sc "-")) (prog1 (sc-curr-char sc) (sc-advance sc))) ((sc-looking-at sc "-]") (prog1 (sc-curr-char sc) (sc-advance sc))) ((sc-looking-at sc "-") nil) ((sc-looking-at sc "]") nil) (t (prog1 (sc-curr-char sc) (sc-advance sc)))))) (defun be-start-range (sc) " DO: Parses a start-range. RETURN: character or (rk:collating-symbol coll-elem) or nil if not looking at a start-range. NOTES: start_range : end_range '-' ; " (let ((start (sc-position sc)) (result (be-end-range sc))) (cond ((null result) (setf (sc-position sc) start) nil) ((errorp result) result) ((sc-looking-at sc "-") (sc-advance sc) result) (t (setf (sc-position sc) start) nil)))) (defun be-range-expression (sc) " DO: Parses a range-expression. RETURN: (rk:range start end) or nil of not looking at a range-expression. NOTES: range_expression : start_range end_range | start_range '-' ; " (let ((start (sc-position sc)) (range-start (be-start-range sc))) (cond ((null range-start) nil) ((errorp range-start) range-start) ((sc-looking-at sc "-") (list 'rk:range range-start (character "-"))) (t (let ((range-end (be-end-range sc))) (cond ((null range-end) (setf (sc-position sc) start) nil) ((errorp range-end) range-end) ;; error or not error? (t (list 'rk:range range-start range-end)))))))) (defun be-single-expression (sc) " DO: Parses a single-expression. RETURN: (or (rk:equivalence-class ec) (rk:character-class cc) (rk:collating-symbol cs) character nil) NOTES: single_expression : end_range | character_class | equivalence_class ; " (let ((start (sc-position sc)) (se (be-character-class sc)) (errpos nil) (err nil)) (cond ((null se) (setf se (be-equivalence-class sc))) ((errorp se) (setf errpos (or errpos (sc-position sc)) (sc-position sc) start err (or err se) se (be-equivalence-class sc))) (t (return-from be-single-expression se))) (cond ((null se) (setf se (be-end-range sc))) ((errorp se) (setf errpos (or errpos (sc-position sc)) (sc-position sc) start err (or err se) se (be-end-range sc))) (t (return-from be-single-expression se))) (cond ((null se) nil) ((errorp se) (setf errpos (or errpos (sc-position sc)) err (or err se) (sc-position sc) errpos) err) (t se)))) (defun be-expression-term (sc) " DO: RETURN: (or (rk:equivalence-class ec) (rk:character-class cc) (rk:collating-symbol cs) character (rk:range start end) nil) NOTES: expression_term : single_expression | range_expression ; " (let ((start (sc-position sc)) (et (be-range-expression sc)) (errpos nil) (err nil)) (cond ((null et) (setf et (be-single-expression sc))) ((errorp et) (setf errpos (or errpos (sc-position sc)) (sc-position sc) start err (or err et) et (be-single-expression sc))) (t (return-from be-expression-term et))) (cond ((null et) nil) ((errorp et) (setf errpos (or errpos (sc-position sc)) err (or err et) (sc-position sc) errpos) err) (t et)))) (defun be-follow-list (sc) " DO: RETURN: (:follow-list expression...) or (:error message) or nil follow_list : expression_term | follow_list expression_term ; " (do ((expression-term (be-expression-term sc) (be-expression-term sc)) (follow-list nil)) ((or (null expression-term) (errorp expression-term)) (if (errorp expression-term) expression-term ;; (:error ...) (and follow-list (cons :follow-list (nreverse follow-list))))) (push expression-term follow-list))) (defun be-bracket-list (sc) " DO: Parses a bracket-list. RETURN: (:follow-list expression...) or nil. NOTES: bracket_list : follow_list | follow_list '-' ; " (let ((follow-list (be-follow-list sc))) (cond ((null follow-list) nil) ((errorp follow-list) follow-list) (t (or (and (sc-looking-at sc "-") (prog1 (nconc follow-list (list (sc-curr-char sc))) (sc-advance sc))) follow-list))))) (defun be-bracket-expression (sc) " DO: Parses a bracket-expression. RETURN: (rk:matching expression...) or (rk:non-matching expression...) or (:error message) or nil. NOTES: bracket_expression : '[' matching_list ']' | '[' nonmatching_list ']' ; matching_list : bracket_list ; nonmatching_list : '^' bracket_list ; " (let ((start (sc-position sc)) be) (cond ((sc-looking-at sc "[^") (sc-advance sc 2) (setf be 'rk:non-matching)) ((sc-looking-at sc "[") (sc-advance sc) (setf be 'rk:matching)) (t (return-from be-bracket-expression nil))) (setf (sc-bracket-position sc) (sc-position sc)) (let ((matching-list (be-bracket-list sc))) (cond ((null matching-list) (setf (sc-position sc) start) nil) ((errorp matching-list) matching-list) ((sc-looking-at sc "]") (sc-advance sc) (cons be (cdr matching-list))) (t (err "Missing ']' in bracket expression.")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Basic Regular Expression ;; ------------------------ (defun bre-dupl-symbol (sc) " DO: Parse RETURN: (rk:repeat min max) with min,max in (or rk:infinity (integer 0)) or (:error message) or nil if not looking at a re-dupl-symbol. NOTES: RE_dupl_symbol : '*' | Back_open_brace DUP_COUNT Back_close_brace | Back_open_brace DUP_COUNT ',' Back_close_brace | Back_open_brace DUP_COUNT ',' DUP_COUNT Back_close_brace ; " (cond ((sc-looking-at sc "*") (sc-advance sc) (list 'rk:repeat 0 'rk:infinity)) ((sc-looking-at sc "{") (sc-advance sc) (let ((min (re-integer sc))) (cond ((null min) (err "Missing duplication count after '{'.")) ((sc-looking-at sc "}") (sc-advance sc) (list 'rk:repeat min min)) ((sc-looking-at sc ",") (sc-advance sc) (if (sc-looking-at sc "}") (progn (sc-advance sc) (list 'rk:repeat min 'rk:infinity)) (let ((max (re-integer sc))) (cond ((null max) (err (format nil "Invalid ~S character in {...}." (sc-curr-char sc)))) ((sc-looking-at sc "}") (sc-advance sc) (list 'rk:repeat min max)) ((sc-eos sc) (err "Missing '}'.")) (t (err (format nil "Invalid ~S character in {...}." (sc-curr-char sc)))))))) ((sc-eos sc) (err "Missing '}'.")) (t (err (format nil "Invalid ~S character in {...}." (sc-curr-char sc))))) )) (t nil))) (defun bre-one-char-or-coll-elem (sc) " DO: Parses s single character or a coll-elem regexp. RETURN: (or (rk:matching ...) (rk:non-matching ...) rk:any character) NOTES: one_char_or_coll_elem_RE : ORD_CHAR | QUOTED_CHAR | '.' | bracket_expression ; QUOTED_CHAR  \^ \. \* \[ \$ \\ ORD_CHAR any but SPEC_CHAR SPEC_CHAR For basic regular expressions, one of the following special characters: . Anywhere outside bracket expressions \ Anywhere outside bracket expressions [ Anywhere outside bracket expressions ^ When used as an anchor (see BRE Expression Anchoring ) or when first in a bracket expression $ When used as an anchor * Anywhere except first in an entire RE, anywhere in a bracket expression, directly following '\(' , directly following an anchoring '^'. ==> ORD_CHAR excludes . \ [ and * but when first of the expression. " (cond ((sc-eos sc) nil) ;; quoted-char: ((and (char= (character "\\") (sc-curr-char sc)) (position (sc-next-char sc) "^.*[$\\")) (sc-advance sc) (prog1 (sc-curr-char sc) (sc-advance sc))) ;; dot: ((sc-looking-at sc ".") (sc-advance sc) 'rk:any) ;; bracket expression: ((sc-looking-at sc "[") (be-bracket-expression sc)) ;; [ is not an ord-char anyway. ;; not looking at one-char-or-coll-elem-re: ((or (sc-looking-at sc "\\") (sc-looking-at sc "[") (and (sc-expression-start sc) (sc-looking-at sc "*")) (and (= (1+ (sc-position sc)) (sc-length sc)) (sc-looking-at sc "$"))) nil) ;; spec-char ((and (sc-expression-start sc) (or (sc-looking-at sc "^") (sc-looking-at sc "$"))) (err (format nil "Invalid ~S character inside '\\(' and '\\)'." (sc-curr-char sc)))) (t (prog1 (sc-curr-char sc) (sc-advance sc))))) (defun bre-nondupl-re (sc) " nondupl_RE : one_char_or_coll_elem_RE | Back_open_paren RE_expression Back_close_paren | BACKREF ; " (cond ((sc-looking-at sc "\\(") (sc-advance sc 2) (push (sc-position sc) (sc-expression-start sc)) (let ((expression (prog1 (bre-expression sc) (pop (sc-expression-start sc))))) (cond ((null expression) (err "Missing a regular expression after '\\('.")) ((errorp expression) expression) ((sc-looking-at sc "\\)") (sc-advance sc 2) (list 'rk:subexp expression)) (t (err "Missing '\\)'."))))) ((and (sc-looking-at sc "\\") (digit-char-p (sc-next-char sc) 10)) (sc-advance sc 2) (list 'rk:backref (parse-integer (sc-string sc) :start (1- (sc-position sc)) :end (sc-position sc)))) (t (bre-one-char-or-coll-elem sc)))) (defun bre-simple-re (sc) " simple_RE : nondupl_RE | nondupl_RE RE_dupl_symbol ; " (let ((expression (bre-nondupl-re sc))) (cond ((null expression) nil) ((errorp expression) expression) (t (let ((dupl (bre-dupl-symbol sc))) (cond ((null dupl) expression) ((errorp dupl) dupl) (t (nconc dupl (list expression))))))))) (defun bre-expression (sc) " RE_expression : simple_RE | RE_expression simple_RE ; " (do ((simple-re (bre-simple-re sc) (bre-simple-re sc)) (expression-list nil)) ((or (null simple-re) (errorp simple-re)) (cond ((errorp simple-re) simple-re) ;; (:error ...) ((length>1 expression-list) (cons 'rk:sequence (nreverse expression-list))) (t (car expression-list)))) (push simple-re expression-list))) (defun bre-basic-reg-exp (sc) " basic_reg_exp : RE_expression | L_ANCHOR | R_ANCHOR | L_ANCHOR R_ANCHOR | L_ANCHOR RE_expression | RE_expression R_ANCHOR | L_ANCHOR RE_expression R_ANCHOR ; " (let ((sequence (list)) (re-expression)) (when (sc-looking-at sc "^") (setf sequence (list 'rk:l-anchor)) (sc-advance sc)) (setf re-expression (bre-expression sc)) (cond ((null re-expression)) ((errorp re-expression) (return-from bre-basic-reg-exp re-expression)) (t (setf sequence (append sequence (if (and (listp re-expression) (eq 'rk:sequence (car re-expression))) (cdr re-expression) (list re-expression)))))) (when (sc-looking-at sc "$") (setq sequence (nconc sequence (list 'rk:r-anchor))) (sc-advance sc)) (if (length>1 sequence) (cons 'rk:sequence sequence) (car sequence)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Extended Regular Expression ;; --------------------------- (defun ere-dupl-symbol (sc) " DO: Parse RETURN: (rk:repeat min max) with min,max in (or rk:infinity (integer 0)) or (:error message) or nil if not looking at a re-dupl-symbol. NOTES: ERE_dupl_symbol : '*' | '+' | '?' | '{' DUP_COUNT '}' | '{' DUP_COUNT ',' '}' | '{' DUP_COUNT ',' DUP_COUNT '}' ; " (cond ((sc-looking-at sc "*") (sc-advance sc) (list 'rk:repeat 0 'rk:infinity)) ((sc-looking-at sc "+") (sc-advance sc) (list 'rk:repeat 1 'rk:infinity)) ((sc-looking-at sc "?") (sc-advance sc) (list 'rk:repeat 0 1)) ((sc-looking-at sc "{") (sc-advance sc) (let ((min (re-integer sc))) (cond ((null min) (err "Missing duplication count after '{'.")) ((sc-looking-at sc "}") (sc-advance sc) (list 'rk:repeat min min)) ((sc-looking-at sc ",") (sc-advance sc) (if (sc-looking-at sc "}") (progn (sc-advance sc) (list 'rk:repeat min 'rk:infinity)) (let ((max (re-integer sc))) (cond ((null max) (err (format nil "Invalid ~S character in {...}." (sc-curr-char sc)))) ((sc-looking-at sc "}") (sc-advance sc) (list 'rk:repeat min max)) ((sc-eos sc) (err "Missing '}'.")) (t (err (format nil "Invalid ~S character in {...}." (sc-curr-char sc)))))))) ((sc-eos sc) (err "Missing '}'.")) (t (err (format nil "Invalid ~S character in {...}." (sc-curr-char sc))))) )) (t nil))) (defun ere-one-char-or-coll-elem (sc) " DO: Parses s single character or a coll-elem regexp. RETURN: (or (rk:matching ...) (rk:non-matching ...) rk:any character) NOTES: one_char_or_coll_elem_ERE : ORD_CHAR | QUOTED_CHAR | '.' | bracket_expression ; QUOTED_CHAR  \^ \. \[ \$ \( \) \| \* \+ \? \{ \\ ORD_CHAR any but SPEC_CHAR SPEC_CHAR For basic regular expressions, one of the following special characters: . Anywhere outside bracket expressions \ Anywhere outside bracket expressions [ Anywhere outside bracket expressions ^ When used as an anchor (see BRE Expression Anchoring ) or when first in a bracket expression $ When used as an anchor * Anywhere except first in an entire RE, anywhere in a bracket expression, directly following '\(' , directly following an anchoring '^'. ^ . [ $ ( ) | * + ? { \ ==> ORD_CHAR excludes . \ [ and * but when first of the expression. " (cond ((sc-eos sc) nil) ;; quoted-char: ((and (char= (character "\\") (sc-curr-char sc)) (position (sc-next-char sc) "^.[$()|*+?{\\")) (sc-advance sc) (prog1 (sc-curr-char sc) (sc-advance sc))) ;; dot: ((sc-looking-at sc ".") (sc-advance sc) 'rk:any) ;; bracket expression: ((sc-looking-at sc "[") (be-bracket-expression sc)) ;; [ is not an ord-char anyway. ;; spec-char: ((position (sc-curr-char sc) "^.[$()|*+?{\\") nil) ;;spec-char (t (prog1 (sc-curr-char sc) (sc-advance sc))))) (defun ere-expression (sc) " ERE_expression : one_char_or_coll_elem_ERE | '^' | '$' | '(' extended_reg_exp ')' | ERE_expression ERE_dupl_symbol ; " (let ((expression (cond ((and (null (sc-expression-start sc)) (sc-looking-at sc "^")) (sc-advance sc) 'rk:l-anchor) ((and (null (sc-expression-start sc)) (sc-looking-at sc "$")) (sc-advance sc) 'rk:r-anchor) ((sc-looking-at sc "(") (sc-advance sc) (push (sc-position sc) (sc-expression-start sc)) (let ((ere (prog1 (ere-extended-reg-exp sc) (pop (sc-expression-start sc))))) (cond ((null ere) (err (format nil "Expected a regular expression after ~ '(', not ~S." (sc-curr-char sc)))) ((errorp ere) ere) ((sc-looking-at sc ")") (sc-advance sc) (list 'rk:subexp ere)) (t (err "Missing ')' after '('."))))) (t (ere-one-char-or-coll-elem sc))))) (cond ((null expression) nil) ((errorp expression) expression) (t (let ((dupl (ere-dupl-symbol sc))) (cond ((null dupl) expression) ((errorp dupl) dupl) (t (nconc dupl (list expression))))))))) (defun ere-branch (sc) " ERE_branch : ERE_expression | ERE_branch ERE_expression ; " (do ((expression (ere-expression sc) (ere-expression sc)) (expression-list nil)) ((or (null expression) (errorp expression)) (cond ((errorp expression) expression) ;; (:error ...) ((length>1 expression-list) (cons 'rk:sequence (nreverse expression-list))) (t (car expression-list)))) (push expression expression-list))) (defun ere-extended-reg-exp (sc) " extended_reg_exp : ERE_branch | extended_reg_exp '|' ERE_branch ; " (do ((branch (ere-branch sc) (if (sc-looking-at sc "|") (let ((start (sc-position sc)) (branch (progn (sc-advance sc) (ere-branch sc)))) (if (null branch) (progn (setf (sc-position sc) start) nil) branch)))) (branch-list nil)) ((or (null branch) (errorp branch)) (cond ((errorp branch) branch) ;; (:error ...) ((length>1 branch-list) (cons 'rk:alternative (nreverse branch-list))) (t (car branch-list)))) (push branch branch-list))) (defun parse-basic-re (restring) (let* ((sc (make-sc :string restring)) (re (bre-basic-reg-exp sc))) (cond ((errorp re) (err restring (sc-position sc) (second re))) ((sc-eos sc) re) (t (err restring (sc-position sc) "Junk after basic regular expression."))))) (defun parse-extended-re (restring) (let* ((sc (make-sc :string restring)) (re (ere-extended-reg-exp sc))) (cond ((errorp re) (err restring (sc-position sc) (second re))) ((sc-eos sc) re) (t (err restring (sc-position sc) "Junk after extended regular expression."))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BRACKET EXPRESSIONS ;; ------------------- ;; ;; Bracket expressions can be implemented with a list of ranges and ;; elements, or with a bitset. Since some char-code-limit may be huge ;; (21 bits for Unicode UCS4, or even more for other codes), we don't ;; want to allocate bit sets so big (128 KB or more). ;; ;; On the other hand, most bracket expresions will come from user input ;; (regular expressions), and will be less than 80 bytes of source. So ;; it seems that a nice limit for the bitset size would be about 80 byte ;; worth. Hence the maximum bit set size used here: 1024. ;; ;; ;; In Common-Lisp, string< definition is directly based on char<. ;; (char< a b) is defined as (< (char-code a) (char-code b)). There is no ;; provision for collating symbols, or equivalence classes, nor for ;; locales. (We should implement them, and add locale based comparisons). ;; There is however, support for character classes in the form of predicates. ;; ;; collating symbols: ;; [.ch.] [.ll.] ;; ;; equivalence classes: ;; [=é=] == [=e=] ;; ;; character classes: ;; [:alnum:] [:cntrl:] [:lower:] [:space:] ;; [:alpha:] [:digit:] [:print:] [:upper:] ;; [:blank:] [:graph:] [:punct:] [:xdigit:] ;; ;; ;; [:alnum:] (alphanumericp ch) ;; [:alpha:] (alpha-char-p ch) ;; [:blank:] (or (char= #\SPACE ch) (char= #\TAB ch)) ;; [:cntrl:] (not (graphic-char-p ch)) ;; [:digit:] (digit-char-p ch 10) ;; [:graph:] (and (graphic-char-p ch) (not (char= (character " ") ch))) ;; [:lower:] (lower-case-p ch) ;; [:print:] (graphic-char-p ch) ;; [:punct:] (and (graphic-char-p ch) (not (alphanumericp ch))) ;; [:space:] <space> <form-feed> <newline> <carriage-return> <tab> <vertical-tab> ;; [:upper:] (upper-case-p ch) ;; [:xdigit:] (digit-char-p ch 16) ;; ;; ;; upper or lower ==> alpha ;; alpha ==> not ( cntrl or digit or punct or space ) ;; alnum <=> ( alpha or digit ) ;; space <== blank or <space> or <form-feed> or <newline> or <carriage-return> or <tab> or <vertical-tab> ;; space ==> not ( upper or lower or alpha or digit or graph or xdigit ) ;; cntrl ==> not ( alpha or print ) ;; cntrl ==> not ( upper or lower or alpha or digit or graph or xdigit or punct or print ) ;; punct ==> not ( <space> or alpha or digit or cntrl ) ;; punct ==> not ( <space> or alpha or digit or cntrl or upper or lower or xdigit) ;; graph <== upper or lower or alpha or digit or xdigit or punct ;; graph ==> not cntrl ;; print <=> graph or <space> ;; print <== upper or lower or alpha or digit or xdigit or punct or graph or <space> ;; print ==> not cntrl ;; xdigit <=> or( 0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f ) ;; blank <== <space> or <tab> (defparameter *character-classes* ;; POSIX ==> ASCII. (list (list "alnum" (function alphanumericp)) (list "alpha" (function alpha-char-p)) (list "blank" (lambda (ch) (or (char= (code-char 32) ch) (char= (code-char 9) ch)))) (list "cntrl" (complement (function graphic-char-p))) (list "digit" (lambda (ch) (digit-char-p ch 10))) (list "graph" (lambda (ch) (and (graphic-char-p ch) (not (char= (code-char 32) ch))))) (list "lower" (function lower-case-p)) (list "print" (function graphic-char-p)) (list "punct" (lambda (ch) (and (graphic-char-p ch) (not (alphanumericp ch))))) (list "space" (lambda (ch) (member (char-code ch) '(32 9 10 11 12 13)))) (list "upper" (function upper-case-p)) (list "xdigit" (lambda (ch) (digit-char-p ch 16))))) ;;*CHARACTER-CLASSES* ;; 0 NUL 1 SOH 2 STX 3 ETX 4 EOT 5 ENQ 6 ACK 7 BEL ;; 8 BS 9 HT 10 LF 11 VT 12 FF 13 CR 14 SO 15 SI ;; 16 DLE 17 DC1 18 DC2 19 DC3 20 DC4 21 NAK 22 SYN 23 ETB ;; 24 CAN 25 EM 26 SUB 27 ESC 28 FS 29 GS 30 RS 31 US ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; charset ;; ------- (defclass charset () () (:documentation "An abstract class for a character set. This class defines the interface to whatever charset implementation.")) (defun make-charset () " RETURN: An instance of a subclass of charset, selected according to the value of char-code-limit. " (make-instance (if (<= char-code-limit 1024) 'charset-bitmap 'charset-range))) (defgeneric add-char (charset character)) (defgeneric add-range (charset char-min char-max)) (defgeneric add-class (charset char-class-name)) (defgeneric inverse (charset)) (defgeneric contains-char-p (charset character)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; charset-bitmap ;; -------------- (defclass charset-bitmap (charset) ((bits :accessor bits :type (array bit (*)))) (:documentation "A character set representation based on bit array. This is representation may be used when char-code-limit is 'small'.")) ;; NOTE: Micro-optimization: ;; (aref (bits self) ch) == 0 <=> ch is present ;; (aref (bits self) ch) == 1 <=> ch is absent ;; This allow us to skip a not in contains-char-p... (defmethod initialize-instance ((self charset-bitmap) &rest args) (declare (ignore args)) (setf (bits self) (make-array (list char-code-limit) :element-type 'bit :initial-element 1)) self) ;;INITIALIZE-INSTANCE (defmethod add-char ((self charset-bitmap) (ch character)) (setf (aref (bits self) (char-code ch)) 0)) (defmethod add-range ((self charset-bitmap) (min character) (max character)) (do ((bits (bits self)) (limit (char-code max)) (ch (char-code min) (1+ ch)) ) ((>= ch limit)) (setf (aref bits ch) 0))) (defmethod add-class ((self charset-bitmap) (char-class-name string)) (let ((ccf (second (assoc char-class-name *character-classes* :test (function string=))))) (unless ccf (error "Invalid character class ~S." char-class-name)) (do ((bits (bits self)) (ch 0 (1+ ch))) ((>= ch char-code-limit)) (when (funcall ccf ch) (setf (aref bits ch) 0))))) (defmethod inverse ((self charset-bitmap)) " DO: complements the set. " (do ((bits (bits self)) (ch 0 (1+ ch))) ((>= ch char-code-limit)) (setf (aref bits ch) (1- (aref bits ch))))) (defmethod contains-char-p ((self charset-bitmap) (ch character)) (zerop (aref (bits self) (char-code ch)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; charset-range ;; ------------- ;; ranges ;; ------ ;; ;; A range = an integer n for [n,n] or a cons (min . max) for [min,max]. (defstruct (range (:constructor make-range (%min %max))) %min %max) ;; (DEFMACRO MAKE-RANGE (MIN MAX) `(CONS ,MIN ,MAX)) ;; (DEFMACRO RANGE-MIN (RANGE) `(IF (INTEGERP ,RANGE) ,RANGE (CAR ,RANGE))) ;; (DEFMACRO RANGE-MAX (RANGE) `(IF (INTEGERP ,RANGE) ,RANGE (CDR ,RANGE))) (defgeneric range-min (range) (:method ((range range)) (range-%min range)) (:method ((range cons)) (car range)) (:method ((range number)) range)) (defgeneric range-max (range) (:method ((range range)) (range-%max range)) (:method ((range cons)) (cdr range)) (:method ((range number)) range)) (defgeneric (setf range-min) (new-value range) (:method (new-value (range range)) (setf (range-%min range) new-value)) (:method (new-value (range cons)) (setf (car range) new-value))) (defgeneric (setf range-max) (new-value range) (:method (new-value (range range)) (setf (range-%max range) new-value)) (:method (new-value (range cons)) (setf (car range) new-value))) (defun range-after-last (range) (1+ (if (numberp range) range (range-max range)))) (defun range-contains-p (range n) (if (integerp range) (= range n) (<= (range-min range) n (range-max range)))) ;; range sets ;; ---------- ;; ;; A range set is an ordered set of disjoint ranges terminated with (nil) ;; Moreover, the distance between two ranges must be >=2. ;; ;; '( (1 . 3) 5 (7 . 13) (32 . 44) (nil) ) ;; 01234 56 7-14 15-45 46- (defun make-range-set (&optional (range-list nil)) (append range-list '((nil)))) (defun range-set-guard-p (rs) (equal '(nil) (car rs))) (defun range-set-seek (rs n) " RETURN: The last cons whose cdr+1 is >= n. " (do ((rs rs (cdr rs))) ((or (range-set-guard-p rs) (<= n (range-after-last (car rs)))) rs))) (defun range-set-add-number (rs n) (if (range-set-guard-p rs) ;; empty range set (progn (push n rs) rs) (let ((prev (range-set-seek rs n))) (cond ((< (1+ n) (range-min (car prev))) ;; new singleton (if (eq prev rs) (setf rs (push n prev)) (push n prev))) ((= (1+ n) (range-min (car prev))) ;; extend lower (setf (range-min (car prev)) n)) ((= (1- n) (range-max (car prev))) ;; extend upper (setf (range-max (car prev)) n)) ;; otherwise (range-contains-p (car prev) n) ;; inside ) rs))) ;;RANGE-SET-ADD-NUMBER (defun range-set-copy (rs &optional (copy nil)) (cond ((null rs) (error "Not guarded range set encountered.")) ((range-set-guard-p rs) (push (car rs) copy) (nreverse copy)) ((integerp (car rs)) (range-set-copy (cdr rs) (cons (car rs) copy))) (t (range-set-copy (cdr rs) (cons (cons (range-min (car rs)) (range-max (car rs))) copy))))) (defun range-set-union (rsa rsb &optional (min nil) (max nil) (union nil)) (cond ((null rsa) (error "Not guarded range set encountered.")) ((null rsb) (error "Not guarded range set encountered.")) ((and (range-set-guard-p rsa) (range-set-guard-p rsb)) ;; union = (min . max) U union (when max (push (if (= min max) min (cons min max)) union)) (nconc (nreverse union) (make-range-set)) ) ((or (range-set-guard-p rsa) (range-set-guard-p rsb)) ;; union = (min . max) U union U (rsa or rsb) (when (range-set-guard-p rsa) (psetf rsa rsb rsb rsa)) ;; union = (min . max) U union U rsa (if max (if (<= (+ 2 max) (range-min (car rsa))) (range-set-union rsa rsb nil nil (push (if (= min max) min (cons min max)) union)) (range-set-union (cdr rsa) rsb min (max max (range-max (car rsa))) union)) ;; union = union U rsa (nconc (nreverse union) (range-set-copy rsa)))) (max (assert (and (not (range-set-guard-p rsa)) (not (range-set-guard-p rsb)))) (cond ((and (<= (+ 2 max) (range-min (car rsa))) (<= (+ 2 max) (range-min (car rsb)))) (range-set-union rsa rsb nil nil (push (if (= min max) min (cons min max)) union))) ((> (+ 2 max) (range-min (car rsa))) (range-set-union (cdr rsa) rsb min (max max (range-max (car rsa))) union)) ((> (+ 2 max) (range-min (car rsb))) (range-set-union rsa (cdr rsb) min (max max (range-max (car rsb))) union)) )) (t ;; initial (let ((min (min (range-min (car rsa)) (range-min (car rsb))))) (range-set-union rsa rsb min min union))))) (defun range-set-contains-p (rs n) (let ((prev (range-set-seek rs n))) (and prev (not (range-set-guard-p prev)) (range-contains-p (car prev) n)))) (defun make-range-set-vector (rs) (make-array (list (1- (length rs))) :initial-contents (butlast rs))) ;; (setq v (make-array '(11) :initial-contents (mapcar (lambda (x) (* 3 x)) '( 1 2 3 4 5 6 7 8 9 10 11 )))) ;; (mapcar (lambda (k) (multiple-value-list (dichotomy-search v k (lambda (a b) (cond ((< a b) -1) ((> a b) 1) (t 0)))))) '(0 1 2 3 4 5 6 7 8 9 30 31 32 33 34 35 )) ;; charset-range ;; ------------- (defclass charset-range (charset) ( (range-set :accessor range-set :type list :initform (make-range-set)) (range-vector :accessor range-vector :type (or null vector) :initform nil) (char-classes :accessor char-classes :type list :initform '()) (complemented :accessor complemented :type boolean :initform nil) ) (:documentation "A character set representation based on binary trees of ranges and additional list of character classes. This is representation may be used when char-code-limit is 'big'.")) (defun rccompare (range cc) (cond ((< cc (range-min range)) -1) ((> cc (range-max range)) +1) (t 0))) (defmethod add-char ((self charset-range) (ch character)) (setf (range-vector self) nil) (range-set-add-number (range-set self) (char-code ch))) (defmethod add-range ((self charset-range) (min character) (max character)) (setf (range-vector self) nil) (setf (range-set self) (range-set-union (range-set self) (make-range-set (list (make-range (char-code min) (char-code max))))))) (defmethod add-class ((self charset-range) (char-class-name string)) (let ((ccf (second (assoc char-class-name *character-classes* :test (function string=))))) (unless ccf (error "Invalid character class ~S." char-class-name)) (pushnew ccf (char-classes self)))) (defmethod inverse ((self charset-range)) " DO: complements the set. " (setf (complemented self) (not (complemented self)))) (defmethod contains-char-p ((self charset-range) (ch character)) (let ((code (char-code ch)) (result nil)) (when (null (range-vector self)) (setf (range-vector self) (make-range-vector (range-set self)))) (multiple-value-bind (found index order) (dichotomy-search (range-vector self) code (function rccompare)) (declare (ignore order)) (setf result (and found (range-contains-p (aref (range-vector self) index) code)))) (unless result (setf result (some (lambda (classf) (funcall classf code)) (char-classes self)))) (if (complemented self) (not result) result))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Matching regular expression ;; --------------------------- (defun lighten (obj) (cond ((symbolp obj) (symbol-name obj)) ((consp obj) (cons (lighten (car obj)) (lighten (cdr obj)))) (t obj))) ;;LIGHTEN (defstruct (rnode (:print-function print-rnode)) "A rnode represent a compiled regexp node" ;; code: (matchf nil) (token nil) (children nil :type (or null (array #+lispworks t #-lispworks rnode (*))))) ;; (equiv (null children) (not (< 0 (length children))))) (defun print-rnode (node stream level) (declare (ignore level)) (format stream "<~A~{ ~S~}>" (lighten (rnode-token node)) (map 'list (function identity) (rnode-children node)))) (defmacro with-rnode (node &body body) `(with-slots ((matchf matchf) (token token) (children children)) ,node ,@body)) (defmacro rnode-match (node state env) (if (symbolp node) `(funcall (rnode-matchf ,node) ,node ,state ,env) `(let ((node ,node)) (funcall (rnode-matchf node) node ,state ,env)))) (defun rnode-walk (node fun) (funcall fun node) (map nil (lambda (node) (rnode-walk node fun)) (rnode-children node))) (defstruct (rstate (:print-function (lambda (state stream level) (declare (ignore level)) (format stream "<rstate :try ~S :start ~S :end ~S>" (rstate-try state) (rstate-start state) (rstate-end state))))) "State data used when matching a rnode." (try nil) (start 0 :type (or null (integer 0))) (end 0 :type (or null (integer 0)))) ;;RSTATE (defmacro with-rstate (state &body body) `(with-slots ((start start) (end end) (try try)) ,state ,@body)) (defun rstate-retry (state position) (with-rstate state (setf start position end nil try nil))) (defmacro try-once (&body body) `(if try nil (progn (setf try t) ,@body))) (defmacro try (&rest clauses) " SYNTAX: (try (initially [sexp|(immediately-then)]...) (then sexp...)) " (let ((initial nil) (then nil)) (do ((clauses clauses (cdr clauses))) ((null clauses)) (cond ((string-equal (caar clauses) :initially) (if initial (error "Can't have two (initially ...) in try.") (setf initial (cdar clauses)))) ((string-equal (caar clauses) :then) (if then (error "Can't have two (then ...) in try.") (setf then (cdar clauses)))) (t (error "Invalid clause (~S) in try." (caar clauses))))) (if initial (if then ;; both initial and then: (with-gensyms (label-try label-then) `(block ,label-try (tagbody (unless try (macrolet ((immediately-then () `(go ,',label-then))) (setf try t) (return-from ,label-try (progn ,@initial)))) ,label-then (return-from ,label-try (progn ,@then))))) ;; initial alone: `(unless try ,@initial)) (if then ;; then alone: `(when try ,@then) ;; nothing (values))))) (defstruct renv "An renv gather the environment (variables) used to run a compiled regexp matched, ie. rnode." (equalf (function equal)) ;; use equalp for case insensitive. ;; equalf must take two sequence arguments ;; and accept :start1 :end1 :start2 :end2 keys. (newlinepf (lambda (ch) (eql #\NEWLINE ch))) (sequence "" :type vector) ;; renv-set-sequence sets length and position too. (length 0 :type (integer 0)) (position 0 :type (integer 0)) (subexps nil :type (or null (vector cons *))) (regexp nil :type (or null rnode)) ;; renv-set-regexp sets subexps too. (bol t :type boolean) (eol t :type boolean) (newline t :type boolean)) (defmacro with-renv (env &body body) `(with-slots ((equalf equalf ) (newlinepf newlinepf) (sequence sequence ) (length length ) (position position ) (subexps subexps ) (regexp regexp ) (bol bol ) (eol eol ) (newline newline )) ,env ,@body)) (defun subexp-filled-p (subexp) subexp) (defmacro subexp-clear (subexp) `(pop ,subexp)) (defmacro subexp-set (subexp start end) `(push (cons ,start ,end) ,subexp)) (defmacro subexp-start (subexp) `(car (top ,subexp))) (defmacro subexp-end (subexp) `(cdr (top ,subexp))) (defun renv-set-sequence (env new-seq) (with-renv env (setf sequence (cond ((vectorp new-seq) new-seq) ((listp new-seq) (make-array (list (length new-seq)) :initial-contents new-seq)) (t (error "Can match only vectors and lists."))) length (length sequence) position 0))) (defun renv-set-regexp (env regexp) (let ((cregexp (if (rnode-p regexp) regexp (compile-regexp regexp))) (subexp-num 0)) (rnode-walk cregexp (lambda (node) (with-rnode node (when (and (consp token) (eq 'rk:subexp (car token))) (setf (cdr token) subexp-num) (incf subexp-num))))) (with-renv env (setf regexp cregexp subexps (make-array (list subexp-num))) (dotimes (i subexp-num) (setf (aref subexps i) nil))))) ;;(dolist (s '(collating-symbol equivalence-class character-class range any l-anchor r-anchor matching non-matching backref subexp sequence repeat infinity alternative b-anchor e-anchor item set-sequence)) (insert (format "(defun rmatch-%s (node env)\n)\n\n\n" s))) (defmacro with-rens (env node state &body body) `(with-renv ,env (with-rnode ,node (with-rstate ,state ,@body)))) (defun rmatch-b-anchor (node state env) " Beginning of string anchor. " (declare (ignorable node)) (with-rens env node state (try-once (when (zerop position) (setf end position) t)))) (defun rmatch-e-anchor (node state env) " End of string anchor. " (declare (ignorable node)) (with-rens env node state (try-once (when (= length position) (setf end position) t)))) (defun rmatch-l-anchor (node state env) " Beginning of line anchor. " (declare (ignorable node)) (with-rens env node state (try-once (if (or (and bol (= 0 position)) (and newline (< 1 position) (funcall newlinepf (aref sequence (1- position))))) (progn (setf end position) t) nil)))) (defun rmatch-r-anchor (node state env) " End of line anchor. " (declare (ignorable node)) (with-rens env node state (try-once (if (or (and eol (= length position)) (and newline (< (1+ position) (length sequence)) (funcall newlinepf (aref sequence (1+ position))))) (progn (setf end position) t) nil)))) (defun rmatch-any (node state env) (declare (ignorable node)) (with-rens env node state (try-once (if (or (<= length position) (and newline ;; don't match newline (funcall newlinepf (aref sequence position)))) nil (progn (incf position) (setf end position) t))))) (defun rmatch-item (node state env) (declare (ignorable node)) (with-rens env node state (try-once (if (and (< position length) (funcall equalf token (aref sequence position))) (progn (incf position) (setf end position) t) nil)))) (defun rmatch-sequence (node state env) (with-rens env node state (if children (invariant (or (null try) (and (integerp try) (or (= 0 try) (= try (1- (length children)))))) (let (p n) ;; try = ( n state[n-1] state[n-1] ... state[0] ) ;; n is the number of children matched in sequence so far. ;; follows the states of the n children in reverse order (stack). ;; We exit with either 0 or (1- (length children)). ;; ;; The 'position' pointer advances and tracks back, walking the ;; tree of matching child position until we find one (or more, ;; in following tries) matching sequence. (try (initially (setf n 0) (push (make-rstate :start position) try)) (then (setf n (pop try)))) (setf p (rnode-match (aref children n) (top try) env)) (while (or (and p (< (1+ n) (length children))) (and (not p) (<= 0 (1- n)))) (if p (progn (incf n) (push (make-rstate :start position) try)) (progn ;; backtrack (decf n) (pop try) (setf position (rstate-start (top try))))) (setf p (rnode-match (aref children n) (top try) env))) (push n try) (setf end position) p)) (try-once ;; no child -- empty sequence -- match once. (setf end position) t)))) ;; shy ;; ;; / ;; 0 ;; 1 ;; 2 ;; 00 ;; 01 ;; 02 ;; 10 ;; 11 ;; 12 ;; 20 ;; 21 ;; 22 ;; 000 ;; 001 ;; 002 ;; 010 ;; 011 ;; 012 ;; 200 ;; 201 ;; 202 ;; 210 ;; 211 ;; 212 ;; 220 ;; 221 ;; 222 (defun rmatch-repeat-shy (node state env) " DO: match min to max repeatition, smallest first. " (with-rens env node state (if (and children (lessp 0 (cdr token))) (let ((min (car token)) (max (cdr token)) (child (aref children 0)) p n) (if (lessp max min) nil ;; never match. ;; try = ( n state[n-1] state[n-1] ... state[0] ) ;; n is the number of children matched in sequence so far. ;; follows the states of the n children in reverse order (stack). ;; ;; The 'position' pointer advances and tracks back, walking the ;; tree of matching child position until we find one (or more, ;; in following tries) matching sequence. (tagbody :init (try (initially (setf try nil n 0 p position) (if (< n min) (go :fill) (go :match))) (then (when (eq :failed try) (return-from rmatch-repeat-shy nil)) (setf n (pop try)) (if (= 0 n) (go :add) (go :increment)))) :fill (progn (push (make-rstate :start p) try) (incf n) (setf p (rnode-match child (top try) env)) (cond ((not p) (go :remove-1)) ((< n min) (go :fill)) (t (go :match)))) ;; n=min :add (progn (push (make-rstate :start p) try) (incf n) (setf p (rnode-match child (top try) env)) (if p (go :match) (go :remove-1))) :remove-1 (progn (pop try) (decf n) (cond ((<= min n) (go :match)) ((= 0 n) (go :fail)) (t (go :increment)))) :increment (progn (setf p (rnode-match child (top try) env)) (cond ((not p) (go :remove-1)) ((< n min) (go :fill)) ((lessp n max) (go :add)) (t (go :match)))) :match (progn (setf end position) (push n try) (return-from rmatch-repeat-shy p)) :fail (progn (setf try :failed) (return-from rmatch-repeat-shy nil)) ))) (try-once ;; max=0 or no child -- empty sequence -- match once. (setf end position) t)))) ;; "(a.{0,4}){1,}" ;; "axxxayyyazzzbzattttbaaabaa" ;; --------====- shy-1 ;; --------------=====- shy-2 ;; ----------------------=- shy-3 ;; "(a.*)*b" ;; "axxxayyyazzzbzattttbaaabaa" ;; =======================- greedy-1 ;; ===================- greedy-2 ;; ============- greedy-3 ;; greedy: ;; {} is greedy! ;; ;; 00x ;; 010x ;; 0110 ;; 0111 ;; 1000 ;; 101x ;; 11x ;; 1000 ;; 1001 ;; ... ;; 1110 ;; 1111 ;; 111 ;; 11 ;; 1 ;; / (defun rmatch-repeat-greedy (node state env) " DO: match min to max repeatition, greatest first. " (with-rens env node state (if (and children (lessp 0 (cdr token))) (let ((min (car token)) (max (cdr token)) (child (aref children 0)) p n) (if (lessp max min) nil ;; never match. ;; try = ( n state[n-1] state[n-1] ... state[0] ) ;; n is the number of children matched in sequence so far. ;; follows the states of the n children in reverse order (stack). ;; ;; The 'position' pointer advances and tracks back, walking the ;; tree of matching child position until we find one (or more, ;; in following tries) matching sequence. (tagbody :init (try (initially (setf try nil n 0 p position) (go :fill)) (then (when (eq :failed try) (return-from rmatch-repeat-greedy nil)) (setf n (pop try)) (go :increment))) :fill (progn (assert (lessp n max)) (push (make-rstate :start p) try) (incf n) (setf p (rnode-match child (top try) env)) (cond ((not p) (go :remove-1)) ((lessp n max) (go :fill)) (t (go :match)))) ;; n=max :remove-1 (progn (pop try) (decf n) (cond ((<= min n) (go :match)) ((= 0 n) (go :fail)) (t (go :increment)))) :increment (progn (setf p (rnode-match child (top try) env)) (cond ((not p) (go :remove-1)) ((lessp n max) (go :fill)) (t (go :match)))) :match (progn (setf end position) (push n try) (return-from rmatch-repeat-greedy p)) :fail (progn (setf try :failed) (return-from rmatch-repeat-greedy nil)) ))) (try-once ;; max=0 or no child -- empty sequence -- match once. (setf end position) t)))) (defun rmatch-alternative (node state env) (with-rens env node state (if children (progn (try ;; try = (index of alternative tried. (initially (setf try (cons 0 (make-rstate :start position))))) (loop (let ((child (aref children (car try)))) (if (rnode-match child (cdr try) env) (progn (setf end position) (return-from rmatch-alternative t)) (progn (incf (car try)) (if (< (car try) (length children)) (rstate-retry (cdr try) (rstate-start (cdr try))) (return-from rmatch-alternative nil))))))) (try-once ;; no child -- empty alternative -- match once. (setf end position) t)))) (defun rmatch-subexp (node state env) (with-rens env node state ;; token = (cons 'rk:subexp subexp-index) ;; one child (if children (let ((index (cdr token)) (child (aref children 0))) (try (initially (setf try (make-rstate :start position))) (then (when (eq :failed try) (return-from rmatch-subexp nil)))) (let ((p (rnode-match child try env))) (if p (progn (setf end position) (subexp-set (aref subexps index) start end)) (progn (setf try :failed) (subexp-clear (aref subexps index)))) p)) (let ((index (cdr token))) (try ;; no child : match once (initially (subexp-set (aref subexps index) position position) t) (then (subexp-clear (aref subexps index)) nil)))))) (defun rmatch-backref (node state env) (with-rens env node state (try-once (let ((index token)) (if (and (numberp index) (<= 0 index) (< index (length subexps)) (subexp-filled-p (aref subexps index))) (let* ((match (aref subexps index)) (e (+ position (- (subexp-end match) (subexp-start match))))) (if (and (<= e length) (funcall equalf sequence sequence :start1 (subexp-start match) :end1 (subexp-end match) :start2 position :end2 e)) (progn (setf end e) t) nil)) (error "Invalid back reference (\\~S)." index)))))) (defun rmatch-matching (node state env) (with-rens env node state (try-once (if (and (< position length) (contains-char-p token (aref sequence position))) (progn (incf position) (setf end position) t) nil)))) (defun rmatch-non-matching (node state env) (with-rens env node state (try-once (if (or (<= length position) (and newline ;; don't match newline (funcall newlinepf (aref sequence position))) (contains-char-p token (aref sequence position))) nil (progn (incf position) (setf end position) t))))) (defparameter *match-function-alist* `( (rk:b-anchor . ,(function rmatch-b-anchor)) (rk:e-anchor . ,(function rmatch-e-anchor)) (rk:l-anchor . ,(function rmatch-l-anchor)) (rk:r-anchor . ,(function rmatch-r-anchor)) (rk:any . ,(function rmatch-any)) (rk:item . ,(function rmatch-item)) (rk:sequence . ,(function rmatch-sequence)) (rk:repeat . ,(function rmatch-repeat-greedy)) (rk:repeat-shy . ,(function rmatch-repeat-shy)) (rk:alternative . ,(function rmatch-alternative)) (rk:subexp . ,(function rmatch-subexp)) (rk:backref . ,(function rmatch-backref)) ;; --- (rk:matching . ,(function rmatch-matching)) (rk:non-matching . ,(function rmatch-non-matching)))) ;; (rk:collating-symbol . ,(function rmatch-collating-symbol)) ;; (rk:equivalence-class . ,(function rmatch-equivalence-class)) ;; (rk:character-class . ,(function rmatch-character-class)) ;; (rk:range . ,(function rmatch-range)))) (defun find-match-function (node) (let ((ass (assoc node *match-function-alist*))) (if ass (cdr ass) (cdr (assoc 'rk:item *match-function-alist*))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; mexpr --> (or ;; character ;; (rk:collating-symbol string/collating-element) ;; (rk:equivalence-class string/equivalence-class) ;; (rk:character-class string/class-name) ;; (rk:range (or coll-elem-single collating-symbol)/start ;; (or coll-elem-single collating-symbol)/end)) (defun compile-bracket-expression (regexp) " RETURN: The charset described by the regex, either a rk:matching or a rk:non-matching. The charset is not complemented for rk:non-matching, this should be done by match function. regexp --> (or (rk:matching mexpr...) (rk:non-matching mexpr...) mexpr --> (or character (rk:collating-symbol string/collating-element) (rk:equivalence-class string/equivalence-class) (rk:character-class string/class-name) (rk:range (or coll-elem-single collating-symbol)/start (or coll-elem-single collating-symbol)/end)) NOTE: We don't compile bracket expressions for other atoms than characters! " (let ((charset (make-charset))) (do ((items (cdr regexp) (cdr items))) ((null items) charset) (cond ((characterp (car items)) (add-char charset (car items))) ((atom (car items)) (error "Invalid atom in bracket expression ~S." (car items))) ((eq (caar items) 'rk:collating-symbol) (error "Collating symbols are not implemented yet.")) ((eq (caar items) 'rk:equivalence-class) (error "Equivalence classes are not implemented yet.")) ((eq (caar items) 'rk:character-class) (add-class charset (second (car items)))) ((eq (caar items) 'rk:range) (let ((min (second (car items))) (max (third (car items))) ) (when (or (listp min) (listp max)) (error "Collating symbols are not implemented yet.")) (add-range charset min max))) (t (error "Unexpected item in bracket expression ~S." (car items))))))) (defun compile-regexp (regexp) " RETURN: A rnode representing the compiled regexp. regexp --> (or character rk:any rk:l-anchor rk:r-anchor (rk:matching mexpr...) (rk:non-matching mexpr...) (rk:backref integer) (rk:subexp regex) (rk:sequence regex...) (rk:repeat integer (or integer rk:infinity) bexp) (rk:alternative regex...)) " (macrolet ((mnode (mfkey token &optional (children nil)) `(make-rnode :matchf (find-match-function ,mfkey) :token ,token :children (when ,children (make-array (list (length ,children)) :initial-contents (mapcar (function compile-regexp) ,children)))))) (if (listp regexp) (case (car regexp) ((rk:backref) (mnode (first regexp) (second regexp))) ((rk:subexp) (mnode (car regexp) (cons (car regexp) 0) (cdr regexp))) ((rk:repeat rk:repeat-shy) (when (< 1 (length (cdddr regexp))) (error "Found a ~A with more than one child." (car regexp))) (mnode (first regexp) (cons (second regexp) (third regexp)) (cdddr regexp))) ((rk:matching rk:non-matching) (mnode (first regexp) (compile-bracket-expression regexp))) (otherwise (mnode (car regexp) (car regexp) (cdr regexp)))) (mnode regexp regexp)))) (defun count-subexp (regexp) " RETURN: The number of subexp found in regexp " (let ((count 0)) (labels ((walk (regexp) (when (listp regexp) (case (car regexp) ((rk:sequence rk:alternative) (map nil (function walk) (cdr regexp))) ((rk:repeat rk:repeat-shy) (map nil (function walk) (cdddr regexp))) ((rk:subexp) (incf count) (map nil (function walk) (cdr regexp))))) )) (walk regexp)) count)) (defstruct match "This structure stores a (start,end) couple specifying the range matched by a group (or the whole regexp)." (start nil :type (or null integer)) (end nil :type (or null integer))) (defun match-string (string match) "Extracts the substring of STRING corresponding to a given pair of start and end indices. The result is shared with STRING. If you want a freshly consed string, use copy-string or (coerce (match-string ...) 'simple-string)." (subseq string (match-start match) (match-end match))) (defun regexp-quote (string) (declare (ignore string)) (error "Not Implemented Yet: REGEXP-QUOTE~%" )) (defun make-range-vector (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun pjb-re-parse-whole-regexp (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun pjb-re-decorate-tree (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun pjb-re-collect-groups (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun pjb-re-init (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun pjb-re-match (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun pjb-re-slot-begin (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun pjb-re-slot-end (&rest arguments) (declare (ignore arguments)) (error "NOT IMPLEMENTED YET")) (defun match (regexp string &optional start end) "Common-Lisp: This function returns as first value a match structure containing the indices of the start and end of the first match for the regular expression REGEXP in STRING, or nil if there is no match. If START is non-nil, the search starts at that index in STRING. If END is non-nil, only (subseq STRING START END) is considered. The next values are match structures for every '\(...\)' construct in REGEXP, in the order that the open parentheses appear in REGEXP. start: the first character of STRING to be considered (defaults to 0) end: the after last character of STRING to be considered (defaults to (length string)). RETURN: index of start of first match for REGEXP in STRING, nor nil. " (unless start (setq start 0)) (unless end (setq end (length string))) (when (< end start) (setq end start)) ;; TODO: What to do when start or end are out of bounds ? (let* ((syn-tree (pjb-re-parse-whole-regexp (make-sc :string (concatenate 'string "\\`.*?\\(" regexp "\\).*?\\'")))) (dec-tree (pjb-re-decorate-tree syn-tree string)) (groups (pjb-re-collect-groups dec-tree)) ) (pjb-re-init dec-tree start) (pjb-re-match dec-tree) ;; there's nowhere to backtrack at the top level... (values-list (mapcar (lambda (g) (let ((s (pjb-re-slot-begin g)) (e (pjb-re-slot-end g)) ) (if (and s e) (make-match :start s :end e) (make-match :start nil :end nil)))) groups)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; POSIX API ;;; --------- (deftype size-t () "Used for sizes of objects." '(integer 0 *)) (deftype regoff-t () "The type regoff_t shall be defined as a signed integer type that can hold the largest value that can be stored in either a type off_t or type ssize_t. " 'integer) ;;REGOFF-T (defstruct (regex-t (:conc-name "RE-")) " NSUB: Number of parenthesized subexpressions. " (nsub 0 :type size-t) ;; the rest is private! (env nil :type (or null renv)) (extended nil :type boolean) (ignore-case nil :type boolean) (nosub nil :type boolean) (newline nil :type boolean)) (defstruct (regmatch-t (:conc-name "RM-")) " SO: Byte offset from start of string to start of substring. EO: Byte offset from start of string of the first character after the end of substring. " (so -1 :type regoff-t) (eo -1 :type regoff-t)) ;; int regcomp(regex_t *restrict preg,const char *restrict pattern, ;; int cflags); ;; --> regcomp ;;size_t regerror(int errcode, const regex_t *restrict preg, ;; char *restrict errbuf, size_t errbuf_size); ;; not implemented (we use lisp conditions) ;;int regexec(const regex_t *restrict preg, const char *restrict string, ;; size_t nmatch, regmatch_t pmatch[restrict], int eflags); ;; --> regexec ;;void regfree(regex_t *preg); ;; not implemented (we use lisp garbage collector) (defun regcomp (pattern &key (extended nil) (ignore-case nil) (nosub nil) (newline nil)) " RETURN: A regex-t representing the compiled regular expression PATTERN. RAISE: An ERROR condition, in case of syntax error. " (let ((regexp (if extended (parse-extended-re pattern) (parse-basic-re pattern)))) (if (errorp regexp) (error "~D:~A" (third regexp) (fourth regexp)) (let ((env (make-renv :equalf (if ignore-case (function equalp) (function equal)) :newline newline))) (renv-set-regexp env `(rk:sequence rk:b-anchor (rk:repeat-shy 0 rk:infinity rk:any) (rk:subexp ,regexp) (rk:repeat-shy 0 rk:infinity rk:any) rk:e-anchor)) (make-regex-t :nsub (count-subexp regexp) :env env :extended extended :ignore-case ignore-case :nosub nosub :newline newline))))) (defun regexec (regex string &key (nmatch nil) (bol t) (eol t)) " RETURN: match ; (or (not match) (null nmatch) (zerop nmatch) (re-nosub regex)) ==> nil (eq t nmatch) ==> A vector of regmatch-t with (1+ (re-nsub regex)) items (numberp nmatch) ==> A vector of regmatch-t with nmatch items. WARNING: Entry #0 of the result vector is always the start and end of the whole expression. To get the start and end of the last subexpression you need to pass :nmatch (1+ (re-nsub regex)) [or T]. " (when (or (null nmatch) (re-nosub regex) (and (numberp nmatch) (zerop nmatch))) (setf nmatch nil)) (with-slots ((env env)) regex (setf (renv-bol env) bol (renv-eol env) eol) (renv-set-sequence env string) (if (rnode-match (renv-regexp env) (make-rstate) env) (values t ;; matches (if (null nmatch) nil (let* ((size (if (numberp nmatch) nmatch ;;(min nmatch(length(renv-subexps env))) (length (renv-subexps env)))) (result (make-array (list size) :element-type 'regmatch-t :initial-element (make-regmatch-t)))) (dotimes (i size) (setf (aref result i) (if (< i (length (renv-subexps env))) (let ((se (aref (renv-subexps env) i))) (if (subexp-filled-p se) (make-regmatch-t :so (subexp-start se) :eo (subexp-end se)) (make-regmatch-t))) (make-regmatch-t)))) result))) (values nil ;; does not match nil)))) ;;;; THE END ;;;;
84,105
Common Lisp
.lisp
2,058
31.059767
265
0.522788
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f9f54f2ab40944cd4b84439f64dcc6908b94765e78a2feba2574fe0b7bda0432
5,149
[ -1 ]
5,150
regexp-emacs.lisp
informatimago_lisp/common-lisp/regexp/regexp-emacs.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: regexp-emacs.lisp ;;;;LANGUAGE: common-lisp ;;;;SYSTEM: UNIX ;;;;USER-INTERFACE: UNIX ;;;;NOWEB: t ;;;;DESCRIPTION ;;;; ;;;;USAGE ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 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.COMMON-LISP.REGEXP.REGEXP-EMACS" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.PICTURE.TREE-TO-ASCII") (:export "REGEXP-MATCH" "REGEXP-QUOTE" "MATCH-STRING" "MATCH-END" "MATCH-START" "MATCH") (:documentation " NOT COMPLETE YET. This package implement REGEXP in COMMON-LISP, which is interesting because then it's available on any COMMON-LISP platform whether the external C regexp library is available or not, and moreover, it's the same (that is, it's compatible) on all COMMON-LIST platforms. Posix Regexp implemented in Common-Lisp. See specifications at: http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap09.html This is a strict implementation that will work both in clisp (Common-Lisp) and emacs (with cl and pjb-cl Common-Lisp extensions). This implementation is entirely in lisp, contrarily to what regexp packages are available under clisp or emacs. Thus it as the advantage of portability and availability (you don't have to compile or link a lisp system written in some barbarous language, and you get the same regexp features in all programs including this module). License: AGPL3 Copyright Pascal J. Bourguignon 2002 - 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.COMMON-LISP.REGEXP.REGEXP-EMACS") ;;; (DEFUN EMACS-STRING-MATCH (REGEXP STRING &OPTIONAL START) ;;; " ;;; DO: Plain emacs string-match ;;; just returning same result as match. ;;; " ;;; (LET* ((START (STRING-MATCH REGEXP STRING START)) ;;; (MD (MATCH-DATA T)) ;;; (COUNT (1+ (LOOP FOR START = 0 THEN (+ 2 MATCH) ;;; FOR MATCH = (STRING-MATCH "\\\\(" REGEXP START) ;;; WHILE MATCH ;;; SUM 1 INTO COUNT ;;; FINALLY (RETURN COUNT)))) ) ;;; (VALUES-LIST ;;; (LOOP FOR I FROM 0 BELOW COUNT ;;; FOR DATA = MD THEN (CDDR DATA) ;;; FOR S = (CAR DATA) ;;; FOR E = (CADR DATA) ;;; COLLECT (IF (AND S E) ;;; (MAKE-MATCH :START S :END E) ;;; (MAKE-MATCH :START NIL :END NIL)) ;;; INTO VALUES ;;; FINALLY (RETURN VALUES))) ;;; )) ;;emacs-string-match (defun pjb-re-split-string (string &optional separators) " DO: Splits STRING into substrings where there are matches for SEPARATORS. RETURNS: A list of substrings. separators: A regexp matching the sub-string separators. Defaults to \"[ \f\t\n\r\v]+\". NOTE: Current implementation only accepts as separators a literal string containing only one character. " (let ((sep (aref separators 0)) (chunks '()) (position 0) (nextpos 0) (strlen (length string))) (loop :while (< position strlen) :do (loop :while (and (< nextpos strlen) (char/= sep (aref string nextpos))) :do (setq nextpos (1+ nextpos))) (push (subseq string position nextpos) chunks) (setq position (1+ nextpos)) (setq nextpos position)) (nreverse chunks))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; regexp module ;; ------------- ;; string scanner: ;; (defun make-sc (string) (let ((sc (make-array '(3)))) (setf (aref sc 0) string) (setf (aref sc 1) 0) (setf (aref sc 2) (length string)) sc)) (defun sc-string (sc) " RETURN: The string being scanned. " (aref sc 0)) (defun sc-position (sc) " RETURN: The current position. " (aref sc 1)) (defun sc-curr-char (sc) " RETURN: The current character, or nil if EOS. " (if (< (aref sc 1) (aref sc 2)) (char (aref sc 0) (aref sc 1)) nil)) (defun sc-next-char (sc) " RETURN: The next character, or nil if EOS. " (if (< (1+ (aref sc 1)) (aref sc 2)) (char (aref sc 0) (1+ (aref sc 1))) nil)) (defun sc-advance (sc) " PRE: (= p (sc-position sc)) POST: (= (1+ p) (sc-position sc)) RETURN: The character at position 1+p. " (if (< (aref sc 1) (aref sc 2)) (setf (aref sc 1) (1+ (aref sc 1)))) (sc-curr-char sc)) (defun sc-scan-to-char (sc char) " RETURN: the substring of (sc-string sc) starting from current position to the position just before the first character equal to `char' found from this position. PRE: (= p (sc-position sc)) POST: (and (<= p (sc-position sc)) (or (and (< (sc-position sc) (length (sc-string sc))) (char= char (sc-curr-char sc))) (= (sc-position sc) (length (sc-string sc)))) (forall i between p and (1- (sc-position sc)) (char/= char (char (sc-string sc) i)))) " (let ((s (aref sc 0)) (p (aref sc 1)) (l (aref sc 2))) (loop :while (and (< p l) (char/= char (char s p))) :do (setq p (1+ p))) (prog1 (subseq s (aref sc 1) p) (setf (aref sc 1) p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; parsing regular expression strings ;; ---------------------------------- ;; This produces a syntactical tree. ;; (defun pjb-re-parse-simple (sc) " DO: Parses a regexp simple. RETURN: A parse tree. simple ::= '\\(' regexp '\\)' . (:group regexp) simple ::= '\\(?:' regexp '\\)' . (:shy-group regexp) simple ::= '\\0' |'\\1' |'\\2' |'\\3' | '\\4' |'\\5' |'\\6' |'\\7' |'\\8' | '\\9' . (:reference number) simple ::= regular-character . regular-character simple ::= '.' | '\\w' | '\\W' | '\\sC' | '\\SC' | '\\cC' | '\\CC' . :any-character :any-word-character :any-not-word-character (:any-syntax-class class) (:any-not-syntax-class class) (:any-category category) (:any-not-category category) simple ::= '\\=' | '\\b' | '\\B' | '\\<' | '\\>' . :empty-at-point NEVER MATCH IN STRING! :empty-at-limit-of-word :empty-not-at-limit-of-word :empty-at-beginning-of-word :empty-at-end-of-word simple ::= '^' | '\\`' . :empty-at-beginning-of-line :empty-at-beginning-of-string simple ::= '$' | '\\'' . :empty-at-end-of-line :empty-at-end-of-string simple ::= '\\$' | '\\^' | '\\.' | '\\*' | '\\+' | '\\?' | '\\[' | '\\]' | '\\\\' . regular-character simple ::= '[' '^' character-set ']' . (:inverse-char-set char-or-char-interval ) simple ::= '[' character-set ']' . (:char-set char-or-char-interval ) " (let ((tree nil) curr-char token) (setq curr-char (sc-curr-char sc)) (cond ((null curr-char) (setq tree '(:error "EOS"))) ((setq token (cdr (assoc curr-char (list (cons (character '\.) :any-character) (cons (character '\^) :empty-at-beginning-of-line) (cons (character '\$) :empty-at-end-of-line) ) :test (function eq)))) (sc-advance sc) (setq tree token)) ((eq (character '\[) curr-char) ;; simple ::= '[' '^' character-set ']' . ;; (:inverse-char-set char-or-char-interval ) ;; simple ::= '[' character-set ']' . ;; (:char-set char-or-char-interval ) ;; ;; charset ::= '[:alnum:]' | '[:cntrl:]' | '[:lower:]' | '[:space:]' ;; | '[:alpha:]' | '[:digit:]' | '[:print:]' | '[:upper:]' ;; | '[:blank:]' | '[:graph:]' | '[:punct:]' | '[:xdigit:]' . ;; ;; charset ::= '[' ['^'] [']'|'-'] ;; [ any-but-dorb ;; | any-but-dorb '-' any-but-dorb [ '-' ] ]* [ '-' ] ']' . ;; ;; any-but-dorb ::= <any character but dash or right bracket> . ;; ;; [x-]] could be: { x to ] } ;; but that's: { x , - } ] ;; ;; So, after the optional initial ']', we can search for the next ']' ;; and parse then. A missing closing ']' is an error. (error "[charset] Not implemented yet.") ;;; (let ((set nil) ;;; (min nil) ;;; max) ;;; (setq curr-char (sc-advance sc)) ;;; (if (char= (character '\^) curr-char) ;;; (progn ;;; (setq token :inverse-char-set) ;;; (setq curr-char (sc-advance sc))) ;;; (setq token :char-set )) ;;; (if (char= (character '\]) curr-char) ;;; (progn ;;; (sc-advance sc) ;;; (setq charsetstr (concatenate 'string ;;; "]" (sc-scan-to-char sc (character '\])))) ;;; ) ;;; (setq charsetstr (sc-scan-to-char sc (character '\])))) ;;; (string-match "[[:digit:][:punct:]]" "ABC123abc") ;;; (setq charsetstr (sc-scan-to-char sc (character '\])) ;;; (loop while (char/= curr-char (character '\])) ;;; do ;;; (if (char= (character '\-) curr-char) ;;; (if min ;;; (progn ;;; (setq curr-char (sc-advance sc)) ;;; (if (char/= curr-char (character '\])) ;;; (progn ;;; (push min set) ;;; (push (character '\-) set)) ;;; (push (cons min curr-char) set)) ;;; (setq min nil)) ;;; (push (character '\-) set)) ;;; (setq min curr-char) ;;; )))) ) ((eq (character '\\) curr-char) (unless (or (eq (sc-next-char sc) (character '\|)) (eq (sc-next-char sc) (character ")"))) (sc-advance sc) (setq curr-char (sc-curr-char sc)) (if (setq token (cdr (assoc curr-char (list (cons (character '\w) :any-word-character) (cons (character '\W) :any-not-word-character) (cons (character '\=) :empty-at-point) (cons (character '\b) :empty-at-limit-of-word) (cons (character '\B) :empty-not-at-limit-of-word) (cons (character '\<) :empty-at-beginning-of-word) (cons (character '\>) :empty-at-end-of-word) (cons (character '\`) :empty-at-beginning-of-string) (cons (character '\') :empty-at-end-of-string) (cons (character '\$) (character '\$)) (cons (character '\^) (character '\^)) (cons (character '\.) (character '\.)) (cons (character '\*) (character '\*)) (cons (character '\+) (character '\+)) (cons (character '\?) (character '\?)) (cons (character '\[) (character '\[)) (cons (character '\]) (character '\])) (cons (character '\\) (character '\\)) (cons (character '\0) '(:reference 0)) (cons (character '\1) '(:reference 1)) (cons (character '\2) '(:reference 2)) (cons (character '\3) '(:reference 3)) (cons (character '\4) '(:reference 4)) (cons (character '\5) '(:reference 5)) (cons (character '\6) '(:reference 6)) (cons (character '\7) '(:reference 7)) (cons (character '\8) '(:reference 8)) (cons (character '\9) '(:reference 9)) ) :test (function eq)))) (progn (setq tree token) (sc-advance sc)) (cond ((eq (character "(") curr-char) ;; simple ::= '\(' regexp '\)' . (:group regexp) ;; simple ::= '\(?:' regexp '\)' . (:shy-group regexp) (sc-advance sc) (if (and (eq (character '\?) (sc-curr-char sc)) (eq (character '\:) (sc-next-char sc))) (progn (sc-advance sc) (sc-advance sc) (setq token :shy-group) ) (setq token :group)) (setq tree (list token (pjb-re-parse-regexp sc))) (if (and (eq (character '\\) (sc-curr-char sc)) (eq (character ")") (sc-next-char sc))) (progn (sc-advance sc) (sc-advance sc)) (setq tree (list :error (format nil "Invalid character at ~D '~A~A' expected '\\)'." (sc-position sc) (sc-curr-char sc) (if (sc-next-char sc) (sc-next-char sc) "")) tree))) ) ((setq token (cdr (assoc curr-char (list (cons (character '\s) :any-syntax-class) (cons (character '\S) :any-not-syntax-class) (cons (character '\c) :any-category) (cons (character '\C) :any-not-category)) :test (function eq)))) (sc-advance sc) (setq curr-char (sc-curr-char sc)) (if curr-char (progn (setq tree (list token curr-char)) (sc-advance sc)) (setq tree '(:error "EOS")))) ((eq (character '\|) (sc-next-char sc)) ))))) (t (setq tree curr-char) (sc-advance sc))) tree)) (defun pjb-re-parse-element (sc) " DO: Parses a regexp element. RETURNS: A parse tree. element ::= simple . simple element ::= simple '*' . (:zero-or-more simple) element ::= simple '+' . (:one-or-more simple) element ::= simple '?' . (:optional simple) element ::= simple '*?' . (:non-greedy-zero-or-more simple) element ::= simple '+?' . (:non-greedy-one-or-more simple) element ::= simple '??' . (:non-greedy-optional simple) element ::= simple '\{' number '\}' . (:repeat-exact simple number) element ::= simple '\{' number ',' [ number ] '\}' . (:repeat-between simple number [number]) " (let (tree simple curr-char) (setq simple (pjb-re-parse-simple sc)) (setq curr-char (sc-curr-char sc)) (cond ((null curr-char) (setq tree simple)) ((eq (character '\?) curr-char) (sc-advance sc) (if (eq (character '\?) (sc-curr-char sc)) (progn (sc-advance sc) (setq tree (list :non-greedy-optional simple))) (setq tree (list :optional simple)))) ((eq (character '\*) curr-char) (sc-advance sc) (if (eq (character '\?) (sc-curr-char sc)) (progn (sc-advance sc) (setq tree (list :non-greedy-zero-or-more simple))) (setq tree (list :zero-or-more simple)))) ((eq (character '\+) curr-char) (sc-advance sc) (if (eq (character '\?) (sc-curr-char sc)) (progn (sc-advance sc) (setq tree (list :non-greedy-one-or-more simple))) (setq tree (list :one-or-more simple)))) ((and (eq (character '\\) curr-char) (eq (character '\{) (sc-next-char sc))) (sc-advance sc) (sc-advance sc) (setq tree '(:error "\{...\} not implemented yet."))) (t (setq tree simple))) tree)) (defun pjb-re-collapse-strings (tree) " RETURNS: A new list where all sequences of characters are collapsed into strings. Signle characters are not collapsed. NOTE: Does not works recursively because recursive sequences are built bottom-up. " (loop :with result = nil :with string = nil :for item :in tree :do (if (characterp item) (push item string) (progn (when string (if (= 1 (length string)) (push (car string) result) (push (implode-string (nreverse string)) result)) (setq string nil)) (push item result))) :finally (when string (if (= 1 (length string)) (push (car string) result) (push (implode-string (nreverse string)) result)) (setq string nil)) (return (nreverse result)))) (defun pjb-re-parse-sequence (sc) " DO: Parses a regexp sequence. RETURNS: A parse tree. sequence ::= element sequence . (:sequence element element ...) sequence ::= element . element sequence ::= . nil " (let ((tree nil)) (loop :while (and (sc-curr-char sc) (not (and (eq (character '\\) (sc-curr-char sc)) (or (eq (sc-next-char sc) (character '\|)) (eq (sc-next-char sc) (character ")") ))))) :do (push (pjb-re-parse-element sc) tree)) (cons :sequence (pjb-re-collapse-strings (nreverse tree))) ;;; (if (<= (length tree) 1) ;;; (car tree) ;;; (progn ;;; (setq tree (pjb-re-collapse-strings (nreverse tree))) ;;; (if (<= (length tree) 1) ;;; (car tree) ;;; tree))) )) (defun pjb-re-parse-regexp (sc) " DO: Parses a regexp. RETURNS: A parse tree. NOTE: The result may contain the symbol :error followed by a string. regexp ::= sequence '\|' regexp . (:alternative sequence sequence...) regexp ::= sequence . sequence " (let (tree) (setq tree (list (pjb-re-parse-sequence sc))) (loop :while (and (eq (character '\\) (sc-curr-char sc)) (eq (character '\|) (sc-next-char sc))) :do (sc-advance sc) (sc-advance sc) (push (pjb-re-parse-sequence sc) tree)) (if (= 1 (length tree)) (car tree) (cons :alternative (nreverse tree))))) (defun pjb-re-parse-whole-regexp (sc) (let ((tree (pjb-re-parse-regexp sc)) (curr-char (sc-curr-char sc))) (if curr-char (setq tree (list :error (format nil "Syntax error at ~D (~A ~A)." (sc-position sc) curr-char (if (sc-next-char sc) (sc-next-char sc) "")) tree))) tree)) ;; $^.*+?[]\ ;; regexp ::= sequence '\|' regexp . (:alternative sequence sequence...) ;; regexp ::= sequence . sequence ;; sequence ::= element sequence . (:sequence element element ...) ;; sequence ::= element . element ;; sequence ::= . nil ;; An element can be a string, corresponding to ;; a concatenated sequence of regular-character. ;; element ::= simple . simple ;; element ::= simple '*' . (:zero-or-more simple) ;; element ::= simple '+' . (:one-or-more simple) ;; element ::= simple '?' . (:optional simple) ;; element ::= simple '*?' . (:non-greedy-zero-or-more simple) ;; element ::= simple '+?' . (:non-greedy-one-or-more simple) ;; element ::= simple '??' . (:non-greedy-optional simple) ;; element ::= simple '\{' number '\}' . ;; (:repeat-exact simple number) ;; element ::= simple '\{' number ',' [ number ] '\}' . ;; (:repeat-between simple number [number]) ;; simple ::= '\(' regexp '\)' . (:group regexp) ;; simple ::= '\(?:' regexp '\)' . (:shy-group regexp) ;; simple ::= '\0' |'\1' |'\2' |'\3' |'\4' |'\5' |'\6' |'\7' |'\8' | '\9' . ;; (:reference number) ;; simple ::= regular-character . regular-character ;; simple ::= '.' | '\w' | '\W' | '\sC' | '\SC' | '\cC' | '\CC' . ;; :any-character ;; :any-word-character ;; :any-not-word-character ;; (:any-syntax-class class) ;; (:any-not-syntax-class class) ;; (:any-category category) ;; (:any-not-category category) ;; simple ::= '\=' | '\b' | '\B' | '\<' | '\>' . ;; :empty-at-point # NEVER MATCH IN STRING! ;; :empty-at-limit-of-word ;; :empty-not-at-limit-of-word ;; :empty-at-beginning-of-word ;; :empty-at-end-of-word ;; simple ::= '^' | '\`' . ;; :empty-at-beginning-of-line ;; :empty-at-beginning-of-string ;; simple ::= '$' | '\'' . ;; :empty-at-end-of-line ;; :empty-at-end-of-string ;; simple ::= '\$' | '\^' | '\.' | '\*' | '\+' | '\?' | '\[' | '\]' | '\\' . ;; regular-character ;; simple ::= '[' '^' character-set ']' . ;; (:inverse-char-set char-or-char-interval ) ;; simple ::= '[' character-set ']' . ;; (:char-set char-or-char-interval ) ;; char-or-char-interval is a sequence of regular-character ;; or (cons min-char max-char). ;; character-set ::= initial-c-set rest-c-set . ;; initial-c-set ::= ']' | '-' . ;; initial-c-set ::= . ;; rest-c-set ::= . ;; rest-c-set ::= c-set-char rest-c-set . ;; rest-c-set ::= c-set-char '-' c-set-char rest-c-set . ;; rest-c-set ::= c-set-char '-' c-set-char '-' rest-c-set . ;; c-set-char ::= any-but-right-bracket-or-dash . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; matching a regexp tree to a string ;; ---------------------------------- ;; (defvar pjb-re-new-line (code-char 10) "A new-line.") (defmacro pjb-re-slot-node (obj) `(aref ,obj 0)) (defmacro pjb-re-slot-match (obj) `(aref ,obj 1)) (defmacro pjb-re-slot-string (obj) `(aref ,obj 2)) (defmacro pjb-re-slot-begin (obj) `(aref ,obj 3)) (defmacro pjb-re-slot-end (obj) `(aref ,obj 4)) (defmacro pjb-re-slot-try (obj) `(aref ,obj 5)) (defmacro pjb-re-slot-private (obj) `(aref ,obj 6)) (defmacro pjb-re-slot-children (obj) `(aref ,obj 7)) ;;; (DEFMACRO PJB-RE-SLOT-BEGIN-SET (OBJ VALUE) `(SETF (AREF ,OBJ 3) ,VALUE)) ;;; (DEFMACRO PJB-RE-SLOT-END-SET (OBJ VALUE) `(SETF (AREF ,OBJ 4) ,VALUE)) ;;; (DEFMACRO PJB-RE-SLOT-TRY-SET (OBJ VALUE) `(SETF (AREF ,OBJ 5) ,VALUE)) ;;; (DEFMACRO PJB-RE-SLOT-PRIVATE-SET (OBJ VALUE) `(SETF (AREF ,OBJ 6) ,VALUE)) ;;; (DEFSETF PJB-RE-SLOT-BEGIN PJB-RE-SLOT-BEGIN-SET) ;;; (DEFSETF PJB-RE-SLOT-END PJB-RE-SLOT-END-SET) ;;; (DEFSETF PJB-RE-SLOT-TRY PJB-RE-SLOT-TRY-SET) ;;; (DEFSETF PJB-RE-SLOT-PRIVATE PJB-RE-SLOT-PRIVATE-SET) (declaim (type (function (array) (function (array) t)) pjb-re-slot-match)) (defmacro pjb-re-init (node position) `(let ((node ,node) (position ,position)) (setf (pjb-re-slot-begin node) position) (setf (pjb-re-slot-try node) nil) (setf (pjb-re-slot-end node) nil) (values))) (defmacro pjb-re-match (node) `(let ((node ,node)) (funcall (pjb-re-slot-match node) node))) (defun pjb-re-character-match (node) "Matches a character. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) ) (if (pjb-re-slot-try node) ;; already tested. no more match: nil ;; first test, let's see: (progn (setf (pjb-re-slot-try node) t) (if (char= (pjb-re-slot-node node) (char (pjb-re-slot-string node) p)) (progn (setq p (1+ p)) (setf (pjb-re-slot-end node) p) p) nil))))) (defun pjb-re-string-match (node) "Matches a string. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) ) (if (pjb-re-slot-try node) ;; already tested. no more match: nil ;; first test, let's see: (let* ((m (pjb-re-slot-node node)) (len (length m)) (e (+ p len)) (s (pjb-re-slot-string node)) ) (setf (pjb-re-slot-try node) t) (unless (and (< e (length s)) (string= m s :start2 p :end2 e)) (setq e nil)) (setf (pjb-re-slot-end node) e) e)))) (defun pjb-re-null-match (node) "Matches a null. RETURNS: nil when no match, or the next unmatched position when there's a match. " (if (pjb-re-slot-try node) ;; already tested. no more match: nil ;; first test, let's see: (progn (setf (pjb-re-slot-try node) t) t ;; yes! we match. ))) (defun pjb-re-alternative-match (node) "Matches a alternative. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) (found nil) ) (when (null n) (setq n 0)) (loop :while (and (< n (length children)) (not found)) :do (pjb-re-init (aref children n) p) (setq found (pjb-re-match (aref children n))) :finally (setf (pjb-re-slot-end node) found) (setf (pjb-re-slot-try node) (1+ n)) :finally (return found)))) (defun pjb-re-any-category-match (node) "Matches a any-category. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-any-character-match (node) "Matches a any-character. That is, anything but a NEW-LINE! RETURNS: nil when no match, or the next unmatched position when there's a match. A period ( '.' ), when used outside a bracket expression, is a BRE that shall match any character in the supported character set except NUL. " (let ((p (pjb-re-slot-begin node)) ) (if (pjb-re-slot-try node) ;; already tested. no more match: nil (progn ;; first test, let's see: (setf (pjb-re-slot-try node) t) (if (< p (length (pjb-re-slot-string node))) (progn (setq p (1+ p)) (setf (pjb-re-slot-end node) p)) (setf (pjb-re-slot-end node) nil)))))) (defun pjb-re-any-not-category-match (node) "Matches a any-not-category. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-any-not-syntax-class-match (node) "Matches a any-not-syntax-class. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-any-not-word-character-match (node) "Matches a any-not-word-character. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-any-syntax-class-match (node) "Matches a any-syntax-class. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-any-word-character-match (node) "Matches a any-word-character. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-char-set-match (node) "Matches a char-set. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-empty-at-beginning-of-line-match (node) "Matches a empty-at-beginning-of-line. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-empty-at-beginning-of-string-match (node) "Matches a empty-at-beginning-of-string. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) ) (if (pjb-re-slot-try node) ;; already tested. no more match: nil ;; first test, let's see: (progn (setf (pjb-re-slot-try node) t) (if (= 0 p) ;; TODO use a :start / :end for the string! (progn (setf (pjb-re-slot-end node) p) p) nil))))) (defun pjb-re-empty-at-beginning-of-word-match (node) "Matches a empty-at-beginning-of-word. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-empty-at-end-of-line-match (node) "Matches a empty-at-end-of-line. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-empty-at-end-of-string-match (node) "Matches a empty-at-end-of-string. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) ) (if (pjb-re-slot-try node) ;; already tested. no more match: nil ;; first test, let's see: (progn (setf (pjb-re-slot-try node) t) (if (= (length (pjb-re-slot-string node)) p) ;; TODO use a :start / :end for the string! (progn (setf (pjb-re-slot-end node) p) p) nil))))) (defun pjb-re-empty-at-end-of-word-match (node) "Matches a empty-at-end-of-word. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-empty-at-limit-of-word-match (node) "Matches a empty-at-limit-of-word. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-empty-at-point-match (node) "Matches a empty-at-point. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-empty-not-at-limit-of-word-match (node) "Matches a empty-not-at-limit-of-word. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-error-match (node) "Matches a error. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-group-match (node) "Matches a group. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (child (aref (pjb-re-slot-children node) 0)) ) (if (pjb-re-slot-try node) ;; already tested. no more match: nil ;; first test, let's see: (progn (setf (pjb-re-slot-try node) t) (pjb-re-init child p) (setq p (pjb-re-match child)) (when p (setf (pjb-re-slot-end node) p)) p)))) (defun pjb-re-inverse-char-set-match (node) "Matches a inverse-char-set. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-non-greedy-one-or-more-match (node) "Matches a non-greedy-one-or-more. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((n (pjb-re-slot-try node)) (p (pjb-re-slot-begin node)) (child (aref (pjb-re-slot-children node) 0)) ) (cond ((null n) ;; first time (pjb-re-init child p) (setq p (pjb-re-match child)) (setf (pjb-re-slot-end node) p) (setf (pjb-re-slot-try node) (if p :more :over)) p) ((eq :more n) (setq p (pjb-re-slot-end node)) (pjb-re-init child p) (setq p (pjb-re-match child)) (setf (pjb-re-slot-end node) p) (setf (pjb-re-slot-try node) (if p :more :over)) p) (t nil)))) (defun pjb-re-non-greedy-optional-match (node) "Matches a non-greedy-optional. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (child (aref (pjb-re-slot-children node) 0)) ) (cond ((null n) ;; first time, let's be non greedy: match nothing. (setf (pjb-re-slot-end node) p) (setf (pjb-re-slot-try node) :second) ) ((eq n :second) ;; second time, we expect the child. (pjb-re-init child p) (setq p (pjb-re-match child)) (setf (pjb-re-slot-end node) p) (setf (pjb-re-slot-try node) :last) ) (t ;; too late we don't match anything. (setq p nil) (setf (pjb-re-slot-end node) p) )) p)) (defun pjb-re-non-greedy-zero-or-more-match (node) "Matches a non-greedy-zero-or-more. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((n (pjb-re-slot-try node)) (s (pjb-re-slot-string node)) (child (aref (pjb-re-slot-children node) 0)) ) (cond ((null n) ;; case zero (setq n (pjb-re-slot-begin node)) (setf (pjb-re-slot-end node) n) (setf (pjb-re-slot-try node) n) ) ((eq t n) ;; no more match ) ((= n (length s)) ;; match end of string with any number, but no more. (setf (pjb-re-slot-end node) n) (setf (pjb-re-slot-try node) t)) (t (pjb-re-init child n) (setq n (pjb-re-match child)) (if n (progn (setf (pjb-re-slot-end node) n) (setf (pjb-re-slot-try node) n)) (progn (setf (pjb-re-slot-end node) nil) (setf (pjb-re-slot-try node) t))))) n)) (defun pjb-re-optional-match (node) "Matches a optional. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (child (aref (pjb-re-slot-children node) 0)) ) (cond ((null n) ;; first time, we expect the child. (pjb-re-init child p) (setq p (pjb-re-match child)) (setf (pjb-re-slot-end node) p) (setf (pjb-re-slot-try node) :second) ) ((eq n :second) ;; second time, let's be non greedy: match nothing. (setf (pjb-re-slot-end node) p) (setf (pjb-re-slot-try node) :last) ) (t ;; too late we don't match anything. (setq p nil) (setf (pjb-re-slot-end node) p) )) p)) (defun pjb-re-one-or-more-match (node) "Matches a one-or-more. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-reference-match (node) "Matches a reference. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-repeat-between-match (node) "Matches a repeat-between. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-repeat-exact-match (node) "Matches a repeat-exact. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-sequence-match (node) "Matches a sequence. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (when children (unless n (setq n 0) (pjb-re-init (aref children n) p)) (setq p (pjb-re-match (aref children n))) (loop :while (or (and p (< (1+ n) (length children))) (and (not p) (<= 0 (1- n)))) :do (if p (progn (setq n (1+ n)) (pjb-re-init (aref children n) p)) (setq n (1- n))) (setq p (pjb-re-match (aref children n)))) ;; p ==> (= (1+ n) (length children)) ==> 0 <= n < (length children) ;; (not p) ==> (= -1 (1- n)) ==> n=0 ==> 0 <= n < (length children) (setf (pjb-re-slot-try node) n) (setf (pjb-re-slot-end node) p)) p)) (defun pjb-re-shy-group-match (node) "Matches a shy-group. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((p (pjb-re-slot-begin node)) (n (pjb-re-slot-try node)) (children (pjb-re-slot-children node)) ) (declare (ignore p n children)) (error "Not Implemented Yet: ~S~%" (pjb-re-slot-node node)))) (defun pjb-re-zero-or-more-match (node) "Matches a zero-or-more. RETURNS: nil when no match, or the next unmatched position when there's a match. " (let ((n (pjb-re-slot-try node)) (s (pjb-re-slot-string node)) (p (pjb-re-slot-begin node)) (child (aref (pjb-re-slot-children node) 0)) ) ;; Note: we should try to save all the previous matches (from zero to n) ;; to backtrack faster, but we would need to save possibly a lot ;; of recursive state for all the child subtree... (cond ((null n) ;; first time: match all we can. (setq n (loop :with p = (pjb-re-slot-begin node) :for n = 0 :then (1+ n) :while (and p (< p (length s))) :do (pjb-re-init child p) (setq p (pjb-re-match child)) :finally (return n))) ;; oops we did one too many. ;; let's redo it till the limit (setf (pjb-re-slot-try node) n) (pjb-re-zero-or-more-match node)) ((< n 0) ;; we tried everything. (setf (pjb-re-slot-end node) nil)) (t ;; match n-1 times. (loop :for i :from 1 :below n :do (pjb-re-init child p) (setq p (pjb-re-match child))) (setf (pjb-re-slot-end node) p) (setf (pjb-re-slot-try node) (1- n)) p)))) (defun pjb-re-make-pjb-re-symbol (key ext) " RETURN: A symbol corresponding to one of the pjb-re-*-{init,match} functions defined here. ext: A string, either \"init\" or \"match\". key: A keyword, one of those used in the regexp syntactic trees. NOTE: emacs Common-Lisp ---------------------- ------------ ------------ (symbol-name 'key) ''key'' ''KEY'' (symbol-name :key) '':key'' ''KEY'' (eq 'key 'KEY) nil T URL: <http://www.informatimago.com/local/lisp/HyperSpec/Body/02_cd.htm> <http://www.informatimago.com/local/lisp/HyperSpec/Body/f_intern.htm#intern> " (if (string= "emacs" (lisp-implementation-type)) (intern (string-downcase (format nil "pjb-re-~s-~s" (subseq (symbol-name key) 1) ext))) (intern (string-upcase (format nil "pjb-re-~a-~a" (symbol-name key) ext)) (find-package "PJB-REGEXP")))) (defun pjb-re-decorate-tree (tree string) " RETURN: A decorated tree that can be used for the matching the string. " (tree-decorate tree (lambda (node children) (let ((obj (make-array '(9))) key) (cond ((null node) (setq key :null)) ((characterp node) (setq key :character)) ((stringp node) (setq key :string)) ((listp node) (setq key :list)) ((member node '( :alternative :any-category :any-character :any-not-category :any-not-syntax-class :any-not-word-character :any-syntax-class :any-word-character :char-set :empty-at-beginning-of-line :empty-at-beginning-of-string :empty-at-beginning-of-word :empty-at-end-of-line :empty-at-end-of-string :empty-at-end-of-word :empty-at-limit-of-word :empty-at-point :empty-not-at-limit-of-word :error :group :inverse-char-set :non-greedy-one-or-more :non-greedy-optional :non-greedy-zero-or-more :optional :one-or-more :reference :repeat-between :repeat-exact :sequence :shy-group :zero-or-more) :test (function eq)) (setq key node)) (t (error "INTERNAL: Unexpected node in match tree: ~S !" node))) (setf (aref obj 0) node) (setf (aref obj 1) (pjb-re-make-pjb-re-symbol key "match")) (setf (aref obj 2) string) (setf (aref obj 3) 0) ;; beg (start) (setf (aref obj 4) 0) ;; end (setf (aref obj 5) nil) ;; try (setf (aref obj 6) nil) ;; private (setf (aref obj 7) (when children (make-array (list (length children)) :initial-contents children))) obj)))) (defun pjb-re-collect-groups (dec-tree &optional groups) (let ((make-groups-flag (not groups))) (unless groups (setq groups (cons :groups nil))) (if (eq :group (pjb-re-slot-node dec-tree)) (push dec-tree (cdr groups))) (loop :with children = (pjb-re-slot-children dec-tree) :for i :from 0 :below (length children) :for child = (aref children i) :do (pjb-re-collect-groups child groups)) (if make-groups-flag (nreverse (cdr groups)) nil))) (defstruct match "This structure stores a (start,end) couple specifying the range matched by a group (or the whole regexp)." (start nil :type (or null integer)) (end nil :type (or null integer))) (defun match-string (string match) "Extracts the substring of STRING corresponding to a given pair of start and end indices. The result is shared with STRING. If you want a freshly consed string, use copy-string or (coerce (match-string ...) 'simple-string)." (subseq string (match-start match) (match-end match))) (defun regexp-quote (string) (declare (ignore string)) (error "Not Implemented Yet: REGEXP-QUOTE~%" )) (defun match (regexp string &optional start end) "Common-Lisp: This function returns as first value a match structure containing the indices of the start and end of the first match for the regular expression REGEXP in STRING, or nil if there is no match. If START is non-nil, the search starts at that index in STRING. If END is non-nil, only (subseq STRING START END) is considered. The next values are match structures for every '\(...\)' construct in REGEXP, in the order that the open parentheses appear in REGEXP. start: the first character of STRING to be considered (defaults to 0) end: the after last character of STRING to be considered (defaults to (length string)). RETURN: index of start of first match for REGEXP in STRING, nor nil. " (unless start (setq start 0)) (unless end (setq end (length string))) (when (< end start) (setq end start)) ;; TODO: What to do when start or end are out of bounds ? (let* ((syn-tree (pjb-re-parse-whole-regexp (make-sc (concatenate 'string "\\`.*?\\(" regexp "\\).*?\\'")))) (dec-tree (pjb-re-decorate-tree syn-tree string)) (groups (pjb-re-collect-groups dec-tree)) ) (pjb-re-init dec-tree start) (pjb-re-match dec-tree) ;; there's nowhere to backtrack at the top level... (values-list (mapcar (lambda (g) (let ((s (pjb-re-slot-begin g)) (e (pjb-re-slot-end g)) ) (if (and s e) (make-match :start s :end e) (make-match :start nil :end nil)))) groups)))) ;;;; THE END ;;;;
52,760
Common Lisp
.lisp
1,243
34.21078
99
0.51848
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
94bd2d8cbe188068784ba50737a19690ae9c213837e1ccf1ffe353d804339dd2
5,150
[ -1 ]
5,151
rfc2822.lisp
informatimago_lisp/common-lisp/rfc2822/rfc2822.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: rfc2822.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; See defpackage documentation string. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-09-01 <PJB> Made use of ecma048/iso6429. ;;;; 2004-08-17 <PJB> Created (fetched basic functions from antispam.lisp). ;;;;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 "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ECMA048")) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.RFC2822.RFC2822" (:use "COMMON-LISP") (:export "REMOVE-COMMENTS" "REMOVE-SPACES" "UNQUOTE") (:documentation "RFC0822/RFC2822 support funtions. RFC0822/RFC2822 support funtions. RFC822 STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES RFC2822 Internet Message Format RFC822 in fixnum words: In transmission, message lines are separated by CRLF. Header lines are separated from body lines by an empty line (CRLFCRLF). Header lines may be cut by replacing any space or tab by CRLF, (space or tab). Field name consists of any ASCII printable character but space and colon, followed by a colon. Field body begins immediately after the colon. (Customary space included). NOTE: rfc2822 forbid spaces between field name and colon, but it IS possible in rfc822 to insert spaces here. (For example, see Annex A of RFC822). License: AGPL3 Copyright Pascal J. Bourguignon 2004 - 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.COMMON-LISP.RFC2822.RFC2822") (defparameter +space+ (character " ") "An ASCII SPACE character.") (defparameter +tab+ (code-char #+mocl 9 #-mocl com.informatimago.common-lisp.cesarum.ecma048:ht) "An ASCII TABULATION character.") (defparameter +cr+ (code-char #+mocl 13 #-mocl com.informatimago.common-lisp.cesarum.ecma048:cr) "An ASCII CARRIAGE-RETURN.") (defparameter +lf+ (code-char #+mocl 10 #-mocl com.informatimago.common-lisp.cesarum.ecma048:lf) "An ASCII LINE-FEED.") (defun unquote (value) " RETURN: A string where the quotes and escapes are moved. NOTE: It is assumed that the value contains only one string, or none. EXAMPLE: (unquote \"A string \\\\\" with \\\\\" a quoted word.\") --> \"A string \\\" with \\\" a quoted word.\" " (macrolet ((when-char (ch) (if (stringp ch) `(char= (character ,ch) (aref value i)) `(char= ,ch (aref value i)))) (copy () `(progn (setf (aref temp j) (aref value i)) (incf i) (incf j))) (skip () `(incf i))) (do ((temp (make-string (length value))) (i 0) (j 0) (state '(:out))) ;; :QUOTE :COMMENT ((<= (length value) i) (subseq temp 0 j)) (case (car state) ((:out) (cond ((when-char "\\") (skip) (copy)) ((when-char "\"") (skip) (push :quote state)) (t (copy)))) ((:quote) (cond ((when-char "\\") (skip) (copy)) ((when-char "\"") (skip) (pop state)) (t (copy)))) )))) (defun remove-spaces (value) " RETURN: A string with unquoted spaces and tabulations removed. " (macrolet ((when-char (ch) (if (stringp ch) `(char= (character ,ch) (aref value i)) `(char= ,ch (aref value i)))) (copy () `(progn (setf (aref temp j) (aref value i)) (incf i) (incf j))) (skip () `(incf i))) (do ((temp (make-string (length value))) (i 0) (j 0) (state '(:out))) ;; :QUOTE :COMMENT ((<= (length value) i) (subseq temp 0 j)) (case (car state) ((:out) (cond ((when-char "\\") (copy) (copy)) ((when-char "\"") (copy) (push :quote state)) ((or (when-char " ") (when-char +tab+)) (skip)) (t (copy)))) ((:quote) (cond ((when-char "\\") (copy) (copy)) ((when-char "\"") (copy) (pop state)) (t (copy)))) )))) (defun remove-comments (value) " RETURN: A string with the RFC822 comments removed. " ;;; comment = "(" *(ctext / quoted-pair / comment) ")" ;;; ctext = <any CHAR excluding "(", ; => may be folded ;;; ")", "\" & CR, & including ;;; linear-white-space> ;;; quoted-pair = "\" CHAR ; may quote any char ;;; linear-white-space = 1*([CRLF] LWSP-char) ; semantics = SPACE ;;; ; CRLF => folding ;;; CHAR = <any ASCII character> ; ( 0-177, 0.-127.) ;;; ;;; qtext = <any CHAR excepting <">, ; => may be folded ;;; "\" & CR, and including ;;; linear-white-space> ;;; quoted-string = <"> *(qtext/quoted-pair) <">; Regular qtext or ;;; ; quoted chars. (macrolet ((when-char (ch) (if (stringp ch) `(char= (character ,ch) (aref value i)) `(char= ,ch (aref value i)))) (copy () `(progn (setf (aref temp j) (aref value i)) (incf i) (incf j))) (skip () `(incf i))) (do ((temp (make-string (length value))) (i 0) (j 0) (state '(:out))) ;; :QUOTE :COMMENT ((<= (length value) i) (subseq temp 0 j)) (case (car state) ((:out) (cond ((when-char "\\") (copy) (copy)) ((when-char "\"") (copy) (push :quote state)) ((when-char "(") (skip) (push :comment state)) (t (copy)))) ((:quote) (cond ((when-char "\\") (copy) (copy)) ((when-char "\"") (copy) (pop state)) (t (copy)))) ((:comment) (cond ((when-char "\\") (skip) (skip)) ((when-char "(") (skip) (push :comment state)) ((when-char ")") (skip) (pop state)) (t (skip)))))))) ;;;; THE END ;;;;
8,492
Common Lisp
.lisp
181
40.403315
134
0.52239
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1ca840ede77e0d4ff7be24c3200a84b0857810775c8f06afcc6d01327e124a2e
5,151
[ -1 ]
5,152
com.informatimago.common-lisp.rfc2822.asd
informatimago_lisp/common-lisp/rfc2822/com.informatimago.common-lisp.rfc2822.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.rfc2822.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.rfc2822 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.rfc2822" :description "Informatimago Common Lisp RFC0822/RFC2822 Utilities" :long-description " A few RFC0822/RFC2822 utility fucntions. " :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 . "Autumn 2010") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.rfc2822/") ((#: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 "rfc2822" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.rfc2822.test")))) ;;;; THE END ;;;;
2,578
Common Lisp
.lisp
55
43.727273
111
0.597062
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4d084ab7394b0a48e3f8714b487e61b8db09c26cf200628423aaf7aadf765333
5,152
[ -1 ]
5,153
com.informatimago.common-lisp.rfc2822.test.asd
informatimago_lisp/common-lisp/rfc2822/com.informatimago.common-lisp.rfc2822.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.rfc2822.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.rfc2822.test system. ;;;; Tests the com.informatimago.common-lisp.rfc2822 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.rfc2822.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.rfc2822 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.common-lisp.rfc2822.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.common-lisp.rfc2822") :components () #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) ;; (let ((*package* (find-package "TESTED-PACKAGE"))) ;; (uiop:symbol-call "TESTED-PACKAGE" ;; "TEST/ALL")) )) ;;;; THE END ;;;;
2,976
Common Lisp
.lisp
67
38.238806
87
0.550052
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
81475f928555eec5b86d7cc6abffe3e45cdf4998c504f78eddc2fda47e63e455
5,153
[ -1 ]
5,154
com.informatimago.common-lisp.html-base.test.asd
informatimago_lisp/common-lisp/html-base/com.informatimago.common-lisp.html-base.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.html-base.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.html-base.test system. ;;;; Tests the com.informatimago.common-lisp.html-base 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.html-base.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.html-base 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.common-lisp.html-base.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.html-base" "com.informatimago.common-lisp.cesarum") :components () #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) ;; (let ((*package* (find-package "TESTED-PACKAGE"))) ;; (uiop:symbol-call "TESTED-PACKAGE" ;; "TEST/ALL")) )) ;;;; THE END ;;;;
2,990
Common Lisp
.lisp
67
38.447761
89
0.549812
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
772bcfb65c5cd6bc9650399c51a68559b4c693d84acbbe7dae6089056f5d0448
5,154
[ -1 ]
5,155
com.informatimago.common-lisp.html-base.asd
informatimago_lisp/common-lisp/html-base/com.informatimago.common-lisp.html-base.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.html-base.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.html-base 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.html-base" ;; system attributes: :description "Informatimago Common Lisp HTML 4.01 standard and entities" :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 . "Autumn 2010") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.html-base/") ((#: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.common-lisp.lisp-sexp") :components ((:file "html-entities" :depends-on ()) ;; The html401.lisp file is designed to be loaded in various packages ;; where different definitions of the DEFELEMENT and DEFATTRIBUTE macros ;; will process it. ;; (:file "html401" :depends-on ()) (:file "ml-sexp" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.html-base.test")))) ;;;; THE END ;;;;
2,929
Common Lisp
.lisp
59
45.152542
113
0.587866
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d594b9fe26291920ccd46fe2e6f14c928e62e4bd021fbff3d43843f7457e38dc
5,155
[ -1 ]
5,156
ml-sexp.lisp
informatimago_lisp/common-lisp/html-base/ml-sexp.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: ml-sexp.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports a functional abstraction ;;;; to manage a sexp representing a structured document (XML, HTML, SGML). ;;;; It is basically a DOM working on sexp of a specific form. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-10-22 <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.COMMON-LISP.HTML-BASE.ML-SEXP" (:use "COMMON-LISP") (:export "MAKE-ELEMENT" "ELEMENT-TAG" "ELEMENT-ATTRIBUTES" "ELEMENT-CHILDREN" "ELEMENT-TAG-EQUAL-P" "ATTRIBUTE-NAMED" "VALUE-OF-ATTRIBUTE-NAMED" "MAKE-ATTRIBUTE" "ATTRIBUTE-NAME" "ATTRIBUTE-VALUE" "ATTRIBUTE-NAME-EQUAL-P" "ELEMENT-CHILD" "STRING-SINGLE-CHILD-P" "CHILD-TAGGED" "CHILD-VALUED" "CHILD-TAGGED-AND-VALUED" "CHILDREN-TAGGED" "CHILDREN-VALUED" "CHILDREN-TAGGED-AND-VALUED" "GRANDCHILD-TAGGED" "GRANDCHILD-VALUED" "GRANDCHILD-TAGGED-AND-VALUED" "GRANDCHILDREN-TAGGED" "GRANDCHILDREN-VALUED" "GRANDCHILDREN-TAGGED-AND-VALUED" "ELEMENT-AT-PATH" "VALUE-TO-BOOLEAN") (:documentation " This package exports a functional abstraction to manage a sexp representing a structured document (XML, HTML, SGML). It is basically a DOM working on sexp of a specific form. AGPL3 Copyright Pascal J. Bourguignon 2015 - 2015 ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.HTML-BASE.ML-SEXP") #| Principles: A SGML element is represented by a single list containing: - the tag - a list of attributes - the contents of the elements, as the rest of the element list. The tag is represented as a string designator. It can be a keyword, symbol or string (or possibly a character, but it would be unexpected). Symbols whose letters are all uppercase are considered case insensitive: when generating the default case for the DTD is used (lowercase for XML, uppercase for HTML). Mixed case symbols or strings are case sensitive: the case is transmitted as is. When xml name spaces are used, the tag can be qualified by the namespace, by including it in the designated string: :: <ns:tag /> is represented as: :: ("ns:tag" ()) or by: :: (:ns\:tag ()) Note: we may also accept a xmls sexp such as: :: ((tag . "ns") ()) to represent the tag in this namespace, but notice that xmls doesn't handle properly qualified attribute names, the namespace is lost for attributes. This xmls representation is discouraged. In addition to normal elements, there are sgml directives (eg. ``<!DOCTYPE>``) and xml declarations (eg. ``<?xml>``). (:?|xml| (:version "1.0" :encoding "utf-8")) (:!doctype :|html| :PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd") (:!-- " comment ") :: <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- comment --> <tag attribute="value" att2="val2"><content1 /><content2 /></tag> :: (:tag (:attribute "value" :att2 "val2") (:content1 ()) (:content2 ())) |# (defgeneric element-name (element) (:method ((element t)) nil)) (defgeneric element-attributes (element) (:method ((element t)) nil)) (defgeneric element-children (element) (:method ((element t)) nil)) (defgeneric attribute-name (attribute) (:method ((attribute t)) nil)) (defgeneric attribute-value (attribute) (:method ((attribute t)) nil)) (defun make-element (tag attributes children) (list* tag attributes children)) (defmethod element-name ((entity cons)) (car entity)) (defmethod element-attributes ((entity cons)) (cadr entity)) (defmethod element-children ((entity cons)) (cddr entity)) (defun make-attribute (name value) (list name value)) (defmethod attribute-name ((attribute cons)) (first attribute)) (defmethod attribute-value ((attribute cons)) (second attribute)) ;;; xmls entity name may go in namespaces in which case they're lists: (name namespace). (defgeneric element-tag (element) (:method ((element t)) "") (:method ((element cons)) (let ((tag (element-name element))) (if (listp tag) (first tag) tag)))) (defgeneric element-tag-equal-p (a b) (:method ((a string) (b string)) (string-equal a b)) (:method ((a string) (b symbol)) (string-equal a b)) (:method ((a symbol) (b string)) (string-equal a b)) (:method ((a symbol) (b symbol)) (string-equal a b)) (:method ((a cons) (b cons)) (element-tag-equal-p (element-tag a) (element-tag b))) (:method ((a cons) (b string)) (element-tag-equal-p (element-tag a) b)) (:method ((a cons) (b symbol)) (element-tag-equal-p (element-tag a) b)) (:method ((a string) (b cons)) (element-tag-equal-p a (element-tag b))) (:method ((a symbol) (b cons)) (element-tag-equal-p a (element-tag b)))) (defgeneric attribute-name-equal-p (a b) (:method ((a string) (b string)) (string-equal a b)) (:method ((a string) (b symbol)) (string-equal a b)) (:method ((a symbol) (b string)) (string-equal a b)) (:method ((a symbol) (b symbol)) (string-equal a b)) (:method ((a cons) (b cons)) (attribute-name-equal-p (attribute-name a) (attribute-name b))) (:method ((a cons) (b string)) (attribute-name-equal-p (attribute-name a) b)) (:method ((a cons) (b symbol)) (attribute-name-equal-p (attribute-name a) b)) (:method ((a string) (b cons)) (attribute-name-equal-p a (attribute-name b))) (:method ((a symbol) (b cons)) (attribute-name-equal-p a (attribute-name b)))) (defgeneric attribute-named (element attribute)) (defgeneric value-of-attribute-named (element attribute)) (defgeneric element-child (element)) (defgeneric string-single-child-p (element)) (defgeneric child-tagged (element tag)) (defgeneric children-tagged (element tag)) (defgeneric grandchildren-tagged (element tag)) (defgeneric grandchild-tagged (element tag) (:method (element tag) (first (grandchildren-tagged element tag)))) (defgeneric child-valued (element attribute value)) (defgeneric children-valued (element attribute value)) (defgeneric grandchildren-valued (element attribute value)) (defgeneric grandchild-valued (element attribute value) (:method (element attribute value) (first (grandchildren-valued element attribute value)))) (defgeneric child-tagged-and-valued (element tag attribute value)) (defgeneric children-tagged-and-valued (element tag attribute value)) (defgeneric grandchildren-tagged-and-valued (element tag attribute value)) (defgeneric grandchild-tagged-and-valued (element tag attribute value) (:method (element tag attribute value) (first (grandchildren-tagged-and-valued element tag attribute value)))) (defgeneric element-at-path (element tag-path)) (defmethod attribute-named (element attribute-name) (loop :for (k v) :on (element-attributes element) :by (function cddr) :until (attribute-name-equal-p attribute-name k) :finally (return (list k v)))) (defmethod value-of-attribute-named (element attribute-name) (attribute-value (attribute-named element attribute-name))) (defmethod element-child (element) (first (element-children element))) (defmethod string-single-child-p (element) (and (= 1 (length (element-children element))) (stringp (element-child element)))) (defmethod child-tagged (element tag) (find tag (element-children element) :test (function element-tag-equal-p) :key (function element-tag))) (defmethod children-tagged (element tag) (remove tag (element-children element) :test-not (function element-tag-equal-p) :key (function element-tag))) (defmethod grandchildren-tagged (element tag) (append (children-tagged element tag) (mapcan (lambda (child) (grandchildren-tagged child tag)) (element-children element)))) (defmethod child-valued (element attribute value) (find-if (lambda (child) (string-equal value (value-of-attribute-named child attribute))) (element-children element))) (defmethod children-valued (element attribute value) (remove-if-not (lambda (child) (string-equal value (value-of-attribute-named child attribute))) (element-children element))) (defmethod grandchildren-valued (element attribute value) (append (children-valued element attribute value) (mapcan (lambda (child) (grandchildren-valued child attribute value)) (element-children element)))) (defmethod child-tagged-and-valued (element tag attribute value) (find-if (lambda (child) (and (consp child) (element-tag-equal-p (element-tag child) tag) (string-equal (value-of-attribute-named child attribute) value))) (element-children element))) (defmethod children-tagged-and-valued (element tag attribute value) (remove-if-not (lambda (child) (and (consp child) (element-tag-equal-p (element-tag child) tag) (string-equal (value-of-attribute-named child attribute) value))) (element-children element))) (defmethod grandchildren-tagged-and-valued (element tag attribute value) (append (children-tagged-and-valued element tag attribute value) (mapcan (lambda (child) (grandchildren-tagged-and-valued child tag attribute value)) (element-children element)))) (defmethod element-at-path (element tag-path) (if (null tag-path) element (element-at-path (child-tagged element (first tag-path)) (rest tag-path)))) (defun value-to-boolean (value) (string-equal "true" value)) ;;;; THE END ;;;;
10,995
Common Lisp
.lisp
228
44.315789
126
0.685581
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9cd98534ecf7c8d5b850d0382a2acffd21f18fad8d5631a82913432892a1bf06
5,156
[ -1 ]
5,157
html401.lisp
informatimago_lisp/common-lisp/html-base/html401.lisp
;;;; -*- coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: html401.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; HTML 4.01 DTD ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2003-11-12 <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/> ;;;;*************************************************************************** ;; ;; (defelement name options [documentation-string]) ;; options: ([:start-optional] [:end-forbidden] [:empty] [:deprecated] ;; [:loose-dtd] [:frameset-dtd]) ;; (defelement a () "anchor") (defelement abbr () "abbreviated form (e.g., WWW, HTTP, etc.)") (defelement acronym ()) (defelement address () "information on author") (defelement applet (:deprecated :loose-dtd) "Java applet") (defelement area (:end-forbidden :empty) "client-side image map area") (defelement b () "bold text style") (defelement base (:end-forbidden :empty) "document base URI") (defelement basefont (:end-forbidden :empty :deprecated :loose-dtd) "base font size") (defelement bdo () "I18N BiDi over-ride") (defelement big () "large text style") (defelement blockquote () "long quotation") (defelement body (:start-optional :end-optional) "document body") (defelement br (:end-forbidden :empty) "forced line break") (defelement button () "push button") (defelement caption () "table caption") (defelement center (:deprecated :loose-dtd) "shorthand for DIV align=center") (defelement cite () "citation") (defelement code () "computer code fragment") (defelement col (:end-forbidden :empty) "table column") (defelement colgroup (:end-optional) "table column group") (defelement dd (:end-optional) "defelementinition description") (defelement del () "deleted text") (defelement dfn () "instance defelementinition") (defelement dir (:deprecated :loose-dtd) "directory list") (defelement div () "generic language/style container") (defelement dl () "defelementinition list") (defelement dt (:end-optional) "defelementinition term") (defelement em () "emphasis") (defelement fieldset () "form control group") (defelement font (:deprecated :loose-dtd) "local change to font") (defelement form () "interactive form") (defelement frame (:end-forbidden :empty :frameset-dtd) "subwindow") (defelement frameset (:frameset-dtd) "window subdivision") (defelement h1 () "Heading") (defelement h2 () "Heading") (defelement h3 () "Heading") (defelement h4 () "Heading") (defelement h5 () "Heading") (defelement h6 () "Heading") (defelement head (:start-optional :end-optional) "document head") (defelement hr (:end-forbidden :empty) "horizontal rule") (defelement html (:start-optional :end-optional) "document root element") (defelement i () "italic text style") (defelement iframe (:loose-dtd) "inline subwindow") (defelement img (:end-forbidden :empty) "embedded image") (defelement input (:end-forbidden :empty) "form control") (defelement ins () "inserted text") (defelement isindex (:end-forbidden :empty :deprecated :loose-dtd) "single line prompt") (defelement kbd () "text to be entered by the user") (defelement label () "form field label text") (defelement legend () "fieldset legend") (defelement li (:end-optional) "list item") (defelement link (:end-forbidden :empty) "a media-independent link") (defelement map () "client-side image map") (defelement menu (:deprecated :loose-dtd) "menu list") (defelement meta (:end-forbidden :empty) "generic metainformation") (defelement noframes (:frameset-dtd) "alternate content container for non frame-based rendering") (defelement noscript () "alternate content container for non script-based rendering") (defelement object () "generic embedded object") (defelement ol () "ordered list") (defelement optgroup () "option group") (defelement option (:end-optional) "selectable choice") (defelement p (:end-optional) "paragraph") (defelement param (:end-forbidden :empty) "named property value") (defelement pre () "preformatted text") (defelement q () "short inline quotation") (defelement s (:deprecated :loose-dtd) "strike-through text style") (defelement samp () "sample program output, scripts, etc.") (defelement script () "script statements") (defelement select () "option selector") (defelement small () "small text style") (defelement span () "generic language/style container") (defelement strike (:deprecated :loose-dtd) "strike-through text") (defelement strong () "strong emphasis") (defelement style () "style info") (defelement sub () "subscript") (defelement sup () "superscript") (defelement table ()) (defelement tbody (:start-optional :end-optional) "table body") (defelement td (:end-optional) "table data cell") (defelement textarea () "multi-line text field") (defelement tfoot (:end-optional) "table footer") (defelement th (:end-optional) "table header cell") (defelement thead (:end-optional) "table header") (defelement title () "document title") (defelement tr (:end-optional) "table row") (defelement tt () "teletype or monospaced text style") (defelement u (:deprecated :loose-dtd) "underlined text style") (defelement ul () "unordered list") (defelement var () "instance of a variable or program argument") (defattribute abbr (td th) (%text) :implied () "abbreviation for header cell") (defattribute accept-charset (form) (%charsets) :implied () "list of supported charsets") (defattribute accept (form input) (%contenttypes) :implied () "list of MIME types for file upload") (defattribute accesskey (a area button input label legend textarea) (%character) :implied () "accessibility key character") (defattribute action (form) (%uri) :required () "server-side form handler") ;; ;; (DEFATTRIBUTE ATTR-NAME ELEMENTS TYPE DEFAULT OPTIONS DOCUMENTATION) ;; (defattribute align (caption) (%calign) :implied (:deprecated :loose-dtd) "relative to table") (defattribute align (applet iframe img input object) (%ialign) :implied (:deprecated :loose-dtd) "vertical or horizontal alignment") (defattribute align (legend) (%lalign) :implied (:deprecated :loose-dtd) "relative to fieldset") (defattribute align (table) (%talign) :implied (:deprecated :loose-dtd) "table position relative to window") (defattribute align (hr) (or "LEFT" "CENTER" "RIGHT") :implied (:deprecated :loose-dtd) "") (defattribute align (div h1 h2 h3 h4 h5 h6 p) (or "LEFT" "CENTER" "RIGHT" "JUSTIFY") :implied (:deprecated :loose-dtd) "align, text alignment") (defattribute align (col colgroup tbody td tfoot th thead tr) (or "LEFT" "CENTER" "RIGHT" "JUSTIFY" "CHAR") :implied () "") (defattribute alink (body) (%color) :implied (:deprecated :loose-dtd) "color of selected links") (defattribute alt (applet) (%text) :implied (:deprecated :loose-dtd) "short description") (defattribute alt (area img) (%text) :required () "short description") (defattribute alt (input) (cdata) :implied () "short description") (defattribute archive (applet) (cdata) :implied (:deprecated :loose-dtd) "comma-separated archive list") (defattribute archive (object) (cdata) :implied () "space-separated list of URIs") (defattribute axis (td th) (cdata) :implied () "comma-separated list of related headers") (defattribute background (body) (%uri) :implied (:deprecated :loose-dtd) "texture tile for document background") (defattribute bgcolor (table) (%color) :implied (:deprecated :loose-dtd) "background color for cells") (defattribute bgcolor (tr) (%color) :implied (:deprecated :loose-dtd) "background color for row") (defattribute bgcolor (td th) (%color) :implied (:deprecated :loose-dtd) "cell background color") (defattribute bgcolor (body) (%color) :implied (:deprecated :loose-dtd) "document background color") (defattribute border (table) (%pixels) :implied () "controls frame width around table") (defattribute border (img object) (%pixels) :implied (:deprecated :loose-dtd) "link border width") (defattribute cellpadding (table) (%length) :implied () "spacing within cells") (defattribute cellspacing (table) (%length) :implied () "spacing between cells") (defattribute char (col colgroup tbody td tfoot th thead tr) (%character) :implied () "alignment char, e.g. char=':'") (defattribute charoff (col colgroup tbody td tfoot th thead tr) (%length) :implied () "offset for alignment char") (defattribute charset (a link script) (%charset) :implied () "char encoding of linked resource") (defattribute checked (input) (checked) :implied () "for radio buttons and check boxes") (defattribute cite (blockquote q) (%uri) :implied () "URI for source document or msg") (defattribute cite (del ins) (%uri) :implied () "info on reason for change") (defattribute class (:all-elements-but base basefont head html meta param script style title) (cdata) :implied () "space-separated list of classes") (defattribute classid (object) (%uri) :implied () "identifies an implementation") (defattribute clear (br) (or "LEFT" "ALL" "RIGHT" "NONE") "NONE" (:deprecated :loose-dtd) "control of text flow") (defattribute code (applet) (cdata) :implied (:deprecated :loose-dtd) "applet class file") (defattribute codebase (object) (%uri) :implied () "base URI for classid, data, archive") (defattribute codebase (applet) (%uri) :implied (:deprecated :loose-dtd) "optional base URI for applet") (defattribute codetype (object) (%contenttype) :implied () "content type for code") (defattribute color (basefont font) (%color) :implied (:deprecated :loose-dtd) "text color") (defattribute cols (frameset) (%multilengths) :implied (:frameset-dtd) "list of lengths, default: 100% (1 col)") (defattribute cols (textarea) (number) :required () "") (defattribute colspan (td th) (number) "1" () "number of cols spanned by cell") (defattribute compact (dir dl menu ol ul) (compact) :implied (:deprecated :loose-dtd) "reduced interitem spacing") (defattribute content (meta) (cdata) :required () "associated information") (defattribute coords (area) (%coords) :implied () "comma-separated list of lengths") (defattribute coords (a) (%coords) :implied () "for use with client-side image maps") (defattribute data (object) (%uri) :implied () "reference to object's data") (defattribute datetime (del ins) (%datetime) :implied () "date and time of change") (defattribute declare (object) (declare) :implied () "declare but don't instantiate flag") (defattribute defer (script) (defer) :implied () "UA may defer execution of script") (defattribute dir (:all-elements-but applet base basefont bdo br frame frameset iframe param script) (or "LTR" "RTL") :implied () "direction for weak/neutral text") (defattribute dir (bdo) (or "LTR" "RTL") :required () "directionality") (defattribute disabled (button input optgroup option select textarea) (disabled) :implied () "unavailable in this context") (defattribute enctype (form) (%contenttype) "application/x-www-form-urlencoded" () "") (defattribute face (basefont font) (cdata) :implied (:deprecated :loose-dtd) "comma-separated list of font names") (defattribute for (label) (idref) :implied () "matches field ID value") (defattribute frame (table) (%tframe) :implied () "which parts of frame to render") (defattribute frameborder (frame iframe) (or "1" "0") "1" :frameset-dtd "request frame borders?") (defattribute headers (td th) (idrefs) :implied () "list of id's for header cells") (defattribute height (iframe) (%length) :implied (:loose-dtd) "frame height") (defattribute height (td th) (%length) :implied (:deprecated :loose-dtd) "height for cell") (defattribute height (img object) (%length) :implied () "override height") (defattribute height (applet) (%length) :required (:deprecated :loose-dtd) "initial height") (defattribute href (a area link) (%uri) :implied () "URI for linked resource") (defattribute href (base) (%uri) :implied () "URI that acts as base URI") (defattribute hreflang (a link) (%languagecode) :implied () "language code") (defattribute hspace (applet img object) (%pixels) :implied (:deprecated :loose-dtd) "horizontal gutter") (defattribute http-equiv (meta) (name) :implied () "HTTP response header name") (defattribute id (:all-elements-but base head html meta script style title) (id) :implied () "document-wide unique id") (defattribute ismap (img input) (ismap) :implied () "use server-side image map") (defattribute label (option) (%text) :implied () "for use in hierarchical menus") (defattribute label (optgroup) (%text) :required () "for use in hierarchical menus") (defattribute lang (:all-elements-but applet base basefont br frame frameset iframe param script) (%languagecode) :implied () "language code") (defattribute language (script) (cdata) :implied (:deprecated :loose-dtd) "predefined script language name") (defattribute link (body) (%color) :implied (:deprecated :loose-dtd) "color of links") (defattribute longdesc (img) (%uri) :implied () "link to long description (complements alt)") (defattribute longdesc (frame iframe) (%uri) :implied (:frameset-dtd) "link to long description (complements title)") (defattribute marginheight (frame iframe) (%pixels) :implied (:frameset-dtd) "margin height in pixels") (defattribute marginwidth (frame iframe) (%pixels) :implied (:frameset-dtd) "margin widths in pixels") (defattribute maxlength (input) (number) :implied () "max chars for text fields") (defattribute media (style) (%mediadesc) :implied () "designed for use with these media") (defattribute media (link) (%mediadesc) :implied () "for rendering on these media") (defattribute method (form) (or "GET" "POST") "GET" () "HTTP method used to submit the form") (defattribute multiple (select) (multiple) :implied () "default is single selection") (defattribute name (button textarea) (cdata) :implied () "") (defattribute name (applet) (cdata) :implied (:deprecated :loose-dtd) "allows applets to find each other") (defattribute name (select) (cdata) :implied () "field name") (defattribute name (form) (cdata) :implied () "name of form for scripting") (defattribute name (frame iframe) (cdata) :implied (:frameset-dtd) "name of frame for targetting") (defattribute name (img) (cdata) :implied () "name of image for scripting") (defattribute name (a) (cdata) :implied () "named link end") (defattribute name (input object) (cdata) :implied () "submit as part of form") (defattribute name (map) (cdata) :required () "for reference by usemap") (defattribute name (param) (cdata) :required () "property name") (defattribute name (meta) (name) :implied () "metainformation name") (defattribute nohref (area) (nohref) :implied () "this region has no action") (defattribute noresize (frame) (noresize) :implied (:frameset-dtd) "allow users to resize frames?") (defattribute noshade (hr) (noshade) :implied (:deprecated :loose-dtd) "") (defattribute nowrap (td th) (nowrap) :implied (:deprecated :loose-dtd) "suppress word wrap") (defattribute object (applet) (cdata) :implied (:deprecated :loose-dtd) "serialized applet file") (defattribute onblur (a area button input label select textarea) (%script) :implied () "the element lost the focus") (defattribute onchange (input select textarea) (%script) :implied () "the element value was changed") (defattribute onclick (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a pointer button was clicked") (defattribute ondblclick (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a pointer button was double clicked") (defattribute onfocus (a area button input label select textarea) (%script) :implied () "the element got the focus") (defattribute onkeydown (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a key was pressed down") (defattribute onkeypress (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a key was pressed and released") (defattribute onkeyup (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a key was released") (defattribute onload (frameset) (%script) :implied (:frameset-dtd) "all the frames have been loaded") (defattribute onload (body) (%script) :implied () "the document has been loaded") (defattribute onmousedown (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a pointer button was pressed down") (defattribute onmousemove (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a pointer was moved within") (defattribute onmouseout (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a pointer was moved away") (defattribute onmouseover (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a pointer was moved onto") (defattribute onmouseup (:all-elements-but applet base basefont bdo br font frame frameset head html iframe isindex meta param script style title) (%script) :implied () "a pointer button was released") (defattribute onreset (form) (%script) :implied () "the form was reset") (defattribute onselect (input textarea) (%script) :implied () "some text was selected") (defattribute onsubmit (form) (%script) :implied () "the form was submitted") (defattribute onunload (frameset) (%script) :implied (:frameset-dtd) "all the frames have been removed") (defattribute onunload (body) (%script) :implied () "the document has been removed") (defattribute profile (head) (%uri) :implied () "named dictionary of meta info") (defattribute prompt (isindex) (%text) :implied (:deprecated :loose-dtd) "prompt message") (defattribute readonly (textarea) (readonly) :implied () "") (defattribute readonly (input) (readonly) :implied () "for text and passwd") (defattribute rel (a link) (%linktypes) :implied () "forward link types") (defattribute rev (a link) (%linktypes) :implied () "reverse link types") (defattribute rows (frameset) (%multilengths) :implied (:frameset-dtd) "list of lengths, default: 100% (1 row)") (defattribute rows (textarea) (number) :required () "") (defattribute rowspan (td th) (number) "1" () "number of rows spanned by cell") (defattribute rules (table) (%trules) :implied () "rulings between rows and cols") (defattribute scheme (meta) (cdata) :implied () "select form of content") (defattribute scope (td th) (%scope) :implied () "scope covered by header cells") (defattribute scrolling (frame iframe) (or "YES" "NO" "AUTO") "AUTO" (:frameset-dtd) "scrollbar or none") (defattribute selected (option) (selected) :implied () "") (defattribute shape (area) (%shape) "rect" () "controls interpretation of coords") (defattribute shape (a) (%shape) "RECT" () "for use with client-side image maps") (defattribute size (hr) (%pixels) :implied (:deprecated :loose-dtd) "") (defattribute size (font) (cdata) :implied (:deprecated :loose-dtd) "[+ -]nn e.g. size=\"+1\", size=\"4\"") (defattribute size (input) (cdata) :implied () "specific to each type of field") (defattribute size (basefont) (cdata) :required (:deprecated :loose-dtd) "base font size for FONT elements") (defattribute size (select) (number) :implied () "rows visible") (defattribute span (col) (number) "1" () "COL attributes affect N columns") (defattribute span (colgroup) (number) "1" () "default number of columns in group") (defattribute src (script) (%uri) :implied () "URI for an external script") (defattribute src (input) (%uri) :implied () "for fields with images") (defattribute src (frame iframe) (%uri) :implied (:frameset-dtd) "source of frame content") (defattribute src (img) (%uri) :required () "URI of image to embed") (defattribute standby (object) (%text) :implied () "message to show while loading") (defattribute start (ol) (number) :implied (:deprecated :loose-dtd) "starting sequence number") (defattribute style (:all-elements-but base basefont head html meta param script style title) (%stylesheet) :implied () "associated style info") (defattribute summary (table) (%text) :implied () "purpose/structure for speech output") (defattribute tabindex (a area button input object select textarea) (number) :implied () "position in tabbing order") (defattribute target (a area base form link) (%frametarget) :implied (:loose-dtd) "render in this frame") (defattribute text (body) (%color) :implied (:deprecated :loose-dtd) "document text color") (defattribute title (:all-elements-but base basefont head html meta param script title) (%text) :implied () "advisory title") (defattribute type (a link) (%contenttype) :implied () "advisory content type") (defattribute type (object) (%contenttype) :implied () "content type for data") (defattribute type (param) (%contenttype) :implied () "content type for value when valuetype=ref") (defattribute type (script) (%contenttype) :required () "content type of script language") (defattribute type (style) (%contenttype) :required () "content type of style language") (defattribute type (input) (%inputtype) "TEXT" () "what kind of widget is needed") (defattribute type (li) (%listyle) :implied (:deprecated :loose-dtd) "list item style") (defattribute type (ol) (%olstyle) :implied (:deprecated :loose-dtd) "numbering style") (defattribute type (ul) (%ulstyle) :implied (:deprecated :loose-dtd) "bullet style") (defattribute type (button) (or "BUTTON" "SUBMIT" "RESET") "SUBMIT" () "for use as form button") (defattribute usemap (img input object) (%uri) :implied () "use client-side image map") (defattribute valign (col colgroup tbody td tfoot th thead tr) (or "TOP" "MIDDLE" "BOTTOM" "BASELINE") :implied () "vertical alignment in cells") (defattribute value (input) (cdata) :implied () "Specify for radio buttons and checkboxes") (defattribute value (option) (cdata) :implied () "defaults to element content") (defattribute value (param) (cdata) :implied () "property value") (defattribute value (button) (cdata) :implied () "sent to server when submitted") (defattribute value (li) (number) :implied (:deprecated :loose-dtd) "reset sequence number") (defattribute valuetype (param) (or "DATA" "REF" "OBJECT") "DATA" () "How to interpret value") (defattribute version (html) (cdata) :%html.version (:deprecated :loose-dtd) "Constant") (defattribute vlink (body) (%color) :implied (:deprecated :loose-dtd) "color of visited links") (defattribute vspace (applet img object) (%pixels) :implied (:deprecated :loose-dtd) "vertical gutter") (defattribute width (hr) (%length) :implied (:deprecated :loose-dtd) "") (defattribute width (iframe) (%length) :implied (:loose-dtd) "frame width") (defattribute width (img object) (%length) :implied () "override width") (defattribute width (table) (%length) :implied () "table width") (defattribute width (td th) (%length) :implied (:deprecated :loose-dtd) "width for cell") (defattribute width (applet) (%length) :required (:deprecated :loose-dtd) "initial width") (defattribute width (col) (%multilength) :implied () "column width specification") (defattribute width (colgroup) (%multilength) :implied () "default width for enclosed COLs") (defattribute width (pre) (number) :implied (:deprecated :loose-dtd) "") ;;;; THE END ;;;;
27,521
Common Lisp
.lisp
896
28.212054
124
0.665733
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b99e57a5f2d9f9c218619ae8aae02fd508187f6c974de81c755b2765ef761e0d
5,157
[ -1 ]
5,158
html-entities.lisp
informatimago_lisp/common-lisp/html-base/html-entities.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: html-entities.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ISO 8879:1986 SGML entities (HTML 3.2). ;;;; (Related to, but distinct from: ISO 8859-1). ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-10-22 <PJB> Added &quot; and &apo; Added *PRE* for MELT-ENTITIES. ;;;; 2010-10-16 <PJB> Renamed HTML-ENTITIES. ;;;; Added handling of numerical &#...; and &#x...; entities. ;;;; 2003-11-14 <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.COMMON-LISP.HTML-GENERATOR.HTML-ENTITIES" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING") (:export "yuml" "thorn" "yacute" "uuml" "ucirc" "uacute" "ugrave" "oslash" "divide" "ouml" "otilde" "ocirc" "oacute" "ograve" "ntilde" "eth" "iuml" "icirc" "iacute" "igrave" "euml" "ecirc" "eacute" "egrave" "ccedil" "aelig" "aring" "auml" "atilde" "acirc" "aacute" "agrave" "szlig" "THORN" "Yacute" "Uuml" "Ucirc" "Uacute" "Ugrave" "Oslash" "times" "Ouml" "Otilde" "Ocirc" "Oacute" "Ograve" "Ntilde" "ETH" "Iuml" "Icirc" "Iacute" "Igrave" "Euml" "Ecirc" "Eacute" "Egrave" "Ccedil" "AElig" "Aring" "Auml" "Atilde" "Acirc" "Aacute" "Agrave" "iquest" "frac34" "frac12" "frac14" "raquo" "ordm" "sup1" "cedil" "middot" "para" "micro" "acute" "sup3" "sup2" "plusmn" "deg" "macr" "reg" "shy" "not" "laquo" "ordf" "copy" "uml" "sect" "brvbar" "yen" "curren" "pound" "cent" "iexcl" "nbsp" "lt" "gt" "amp" "quot" "apo" "MELT-ENTITIES" "*PRE*") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY" "DISPLACED-VECTOR") (:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "STRING-REPLACE") (:documentation " ISO 8879:1986 SGML entities (HTML 3.2). (Related to, but distinct from: ISO 8859-1). License: AGPL3 Copyright Pascal J. Bourguignon 2003 - 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.COMMON-LISP.HTML-GENERATOR.HTML-ENTITIES") (defparameter *entities* (make-hash-table :test (function equal)) "Maps entity names (case sensitive strings) to a string containing their corresponding characters.") (defvar *pre* nil "When true, MELT-ENTITIES will keep spaces and newlines.") (defun melt-entities (text) " RETURN: A string with any HTML ISO-Latin-1 entity occurence replaced by the corresponding character. BUG: We don't manage the encodings, assuming CODE-CHAR gives ISO-Latin-1. " (with-output-to-string (*standard-output*) (loop :with state = :normal :with buffer = (make-array 8 :element-type 'character :adjustable t :fill-pointer 0) :for ch :across text ;; :do (print (list state ch)) :do (ecase state ((:normal) (case ch ((#\&) (setf state :ampersand)) ((#\newline #\space) (if *pre* (princ ch) (princ " ")) (setf state :space)) (otherwise (princ ch)))) ((:space) (case ch ((#\newline #\space) (when *pre* (princ ch))) ((#\&) (setf state :ampersand)) (otherwise (princ ch) (setf state :normal)))) ((:ampersand) (case ch ((#\#) (setf state :numeric-ampersand)) (otherwise (setf (fill-pointer buffer) 0) (vector-push-extend ch buffer) (setf state :named-entity)))) ((:numeric-ampersand) (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf (fill-pointer buffer) 0) (vector-push-extend ch buffer) (setf state :decimal-entity)) ((#\x #\X) (setf (fill-pointer buffer) 0) (vector-push-extend ch buffer) (setf state :hexadecimal-entity)) (otherwise ;; broken (format t "&#~C" ch) (setf state :normal)))) ((:named-entity) (case ch ((#\; #\space) ; space is for buggy entities... (let ((ch (gethash buffer *entities*))) (if ch (princ ch) (format t "&~A;" buffer))) (setf state :normal)) (otherwise (vector-push-extend ch buffer)))) ((:decimal-entity) (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (vector-push-extend ch buffer)) ((#\; #\space) ; space is for buggy entities... (let ((ch (ignore-errors (code-char (parse-integer buffer))))) (if ch (princ ch) (format t "&~A;" buffer))) (setf state :normal)) (otherwise ;; broken (format t "&#~A~C" buffer ch) (setf state :normal)))) ((:hexadecimal-entity) (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f #\A #\B #\C #\D #\E #\F) (vector-push-extend ch buffer)) ((#\; #\space) ; space is for buggy entities... (let ((ch (ignore-errors (code-char (parse-integer buffer :radix 16.))))) (if ch (princ ch) (format t "&x~A;" buffer))) (setf state :normal)) (otherwise ;; broken (format t "&#x~A~C" buffer ch) (setf state :normal))))) :finally (case state ((:normal :space)) (otherwise (princ buffer)))))) (defmacro defentity (name code &optional documentation) `(progn (setf (gethash (string ',name) *entities*) (code-char ,code)) (defconstant ,name (code-char ,code) ,documentation))) ;; Not strictly ISO-8879, but it's convenient here... (defentity |amp| 38 "ampersand") (defentity |gt| 62 "greater than") (defentity |lt| 60 "less than") (defentity |quot| 34 "double quote") (defentity |apo| 39 "quote") ;; The meat: (defentity |nbsp| 160 "no-break space") (defentity |iexcl| 161 "inverted exclamation mark") (defentity |cent| 162 "cent sign") (defentity |pound| 163 "pound sterling sign") (defentity |curren| 164 "general currency sign") (defentity |yen| 165 "yen sign") (defentity |brvbar| 166 "broken (vertical) bar") (defentity |sect| 167 "section sign") (defentity |uml| 168 "umlaut (dieresis)") (defentity |copy| 169 "copyright sign") (defentity |ordf| 170 "ordinal indicator, feminine") (defentity |laquo| 171 "angle quotation mark, left") (defentity |not| 172 "not sign") (defentity |shy| 173 "soft hyphen") (defentity |reg| 174 "registered sign") (defentity |macr| 175 "macron") (defentity |deg| 176 "degree sign") (defentity |plusmn| 177 "plus-or-minus sign") (defentity |sup2| 178 "superscript two") (defentity |sup3| 179 "superscript three") (defentity |acute| 180 "acute accent") (defentity |micro| 181 "micro sign") (defentity |para| 182 "pilcrow (paragraph sign)") (defentity |middot| 183 "middle dot") (defentity |cedil| 184 "cedilla") (defentity |sup1| 185 "superscript one") (defentity |ordm| 186 "ordinal indicator, masculine") (defentity |raquo| 187 "angle quotation mark, right") (defentity |frac14| 188 "fraction one-quarter") (defentity |frac12| 189 "fraction one-half") (defentity |frac34| 190 "fraction three-quarters") (defentity |iquest| 191 "inverted question mark") (defentity |Agrave| 192 "capital A, grave accent") (defentity |Aacute| 193 "capital A, acute accent") (defentity |Acirc| 194 "capital A, circumflex accent") (defentity |Atilde| 195 "capital A, tilde") (defentity |Auml| 196 "capital A, dieresis or umlaut mark") (defentity |Aring| 197 "capital A, ring") (defentity |AElig| 198 "capital AE diphthong (ligature)") (defentity |Ccedil| 199 "capital C, cedilla") (defentity |Egrave| 200 "capital E, grave accent") (defentity |Eacute| 201 "capital E, acute accent") (defentity |Ecirc| 202 "capital E, circumflex accent") (defentity |Euml| 203 "capital E, dieresis or umlaut mark") (defentity |Igrave| 204 "capital I, grave accent") (defentity |Iacute| 205 "capital I, acute accent") (defentity |Icirc| 206 "capital I, circumflex accent") (defentity |Iuml| 207 "capital I, dieresis or umlaut mark") (defentity |ETH| 208 "capital Eth, Icelandic") (defentity |Ntilde| 209 "capital N, tilde") (defentity |Ograve| 210 "capital O, grave accent") (defentity |Oacute| 211 "capital O, acute accent") (defentity |Ocirc| 212 "capital O, circumflex accent") (defentity |Otilde| 213 "capital O, tilde") (defentity |Ouml| 214 "capital O, dieresis or umlaut mark") (defentity |times| 215 "multiply sign") (defentity |Oslash| 216 "capital O, slash") (defentity |Ugrave| 217 "capital U, grave accent") (defentity |Uacute| 218 "capital U, acute accent") (defentity |Ucirc| 219 "capital U, circumflex accent") (defentity |Uuml| 220 "capital U, dieresis or umlaut mark") (defentity |Yacute| 221 "capital Y, acute accent") (defentity |THORN| 222 "capital THORN, Icelandic") (defentity |szlig| 223 "small sharp s, German (sz ligature)") (defentity |agrave| 224 "small a, grave accent") (defentity |aacute| 225 "small a, acute accent") (defentity |acirc| 226 "small a, circumflex accent") (defentity |atilde| 227 "small a, tilde") (defentity |auml| 228 "small a, dieresis or umlaut mark") (defentity |aring| 229 "small a, ring") (defentity |aelig| 230 "small ae diphthong (ligature)") (defentity |ccedil| 231 "small c, cedilla") (defentity |egrave| 232 "small e, grave accent") (defentity |eacute| 233 "small e, acute accent") (defentity |ecirc| 234 "small e, circumflex accent") (defentity |euml| 235 "small e, dieresis or umlaut mark") (defentity |igrave| 236 "small i, grave accent") (defentity |iacute| 237 "small i, acute accent") (defentity |icirc| 238 "small i, circumflex accent") (defentity |iuml| 239 "small i, dieresis or umlaut mark") (defentity |eth| 240 "small eth, Icelandic") (defentity |ntilde| 241 "small n, tilde") (defentity |ograve| 242 "small o, grave accent") (defentity |oacute| 243 "small o, acute accent") (defentity |ocirc| 244 "small o, circumflex accent") (defentity |otilde| 245 "small o, tilde") (defentity |ouml| 246 "small o, dieresis or umlaut mark") (defentity |divide| 247 "divide sign") (defentity |oslash| 248 "small o, slash") (defentity |ugrave| 249 "small u, grave accent") (defentity |uacute| 250 "small u, acute accent") (defentity |ucirc| 251 "small u, circumflex accent") (defentity |uuml| 252 "small u, dieresis or umlaut mark") (defentity |yacute| 253 "small y, acute accent") (defentity |thorn| 254 "small thorn, Icelandic") (defentity |yuml| 255 "small y, dieresis or umlaut mark") ;;;; THE END ;;;;
14,002
Common Lisp
.lisp
292
40.123288
90
0.565989
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2bc725924cafc4a6a4f83124346582f1c1340001fb785b7adbf878241320d906
5,158
[ -1 ]
5,159
group.lisp
informatimago_lisp/common-lisp/unix/group.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: group.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports a function to read unix group files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-19 <PJB> Renamed ENTRY -> GROUP. ;;;; 2004-08-09 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 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.COMMON-LISP.UNIX.GROUP" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM") (:export "GROUP" "GROUP-NAME" "GROUP-GID" "GROUP-PASSWD" "GROUP-USERS" "READ-GROUP") (:export "MAKE-GROUP") (:documentation " This package exports a function to read unix group files. License: AGPL3 Copyright Pascal J. Bourguignon 2004 - 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.COMMON-LISP.UNIX.GROUP") ;; group_name:passwd:GID:user_list (defstruct group "A unix /etc/group group." (name "" :type string) (passwd "" :type string) (gid 0 :type integer) (users () :type list)) ;;of string: the user names (setf (documentation 'group-name 'function) "The name of the group." (documentation 'group-passwd 'function) "The password of the group." (documentation 'group-gid 'function) "The group ID." (documentation 'group-users 'function) "The list of user logins (strings).") (defun parse-group (line) (let ((fields (split-escaped-string line "\\" ":"))) (if (= (length fields) 4) (let ((gid (parse-integer (third fields) :junk-allowed nil)) (users (split-escaped-string (fourth fields) "\\" ","))) (make-group :name (first fields) :passwd (second fields) :gid gid :users users)) (warn "Invalid group line ~S~%" line)))) (defun read-group (&optional (group-file-path "/etc/group")) " DO: Read the group file. GROUP-FILE-PATH: The pathname to the group file; default: \"/etc/group\" RETURN: A list of group GROUP structures. " (delete nil (mapcar (function parse-group) (with-open-file (in group-file-path :direction :input :if-does-not-exist :error) (stream-to-string-list in))))) ;;;; THE END ;;;
4,235
Common Lisp
.lisp
100
37.33
83
0.620355
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
56a4127a630403c426d8c7d5a2ee419c70e8a883747014b87f527651e934a10c
5,159
[ -1 ]
5,160
com.informatimago.common-lisp.unix.test.asd
informatimago_lisp/common-lisp/unix/com.informatimago.common-lisp.unix.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.unix.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.unix.test system. ;;;; Tests the com.informatimago.common-lisp.unix 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.unix.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.unix 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.common-lisp.unix.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.common-lisp.unix") :components () #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) ;; (let ((*package* (find-package "TESTED-PACKAGE"))) ;; (uiop:symbol-call "TESTED-PACKAGE" ;; "TEST/ALL")) )) ;;;; THE END ;;;;
2,955
Common Lisp
.lisp
67
37.925373
84
0.546778
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4daa0f69c6e938219939f1d222446000ffde0a94f7b8c7438a92ae24a9f3e07e
5,160
[ -1 ]
5,161
passwd.lisp
informatimago_lisp/common-lisp/unix/passwd.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: passwd.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports a function to read unix passwd files. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-19 <PJB> Renamed ENTRY -> USER. ;;;; 2004-03-31 <PJB> Created ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2004 - 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.COMMON-LISP.UNIX.PASSWD" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM") (:export "USER-SHELL" "USER-HOME" "USER-GECOS" "USER-GID" "USER-UID" "USER-PASSWD" "USER-LOGIN" "USER" "READ-PASSWD") (:export "MAKE-USER") (:documentation " This package exports a function to read unix passwd files. License: AGPL3 Copyright Pascal J. Bourguignon 2004 - 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.COMMON-LISP.UNIX.PASSWD") ;; pwent ::= login ':' passwd ':' uid ':' gid ':' gecos ':' home ':' shell (defstruct user "A unix /etc/passwd USER." (login "" :type string) (passwd "" :type string) (uid 0 :type integer) (gid 0 :type integer) (gecos () :type list) (home "" :type string) (shell "" :type string)) (setf (documentation 'user-login 'function) "The login of the user (string)." (documentation 'user-passwd 'function) "The password of the user (string)." (documentation 'user-uid 'function) "The user ID (integer)." (documentation 'user-gid 'function) "The user Group ID (integer)." (documentation 'user-gecos 'function) "The user GECOS field (a list of strings)." (documentation 'user-home 'function) "The user home directory (string)." (documentation 'user-shell 'function) "The user shell (string).") (defun parse-passwd (line) (let ((fields (split-escaped-string line "\\" ":"))) (if (= (length fields) 7) (let ((uid (parse-integer (third fields) :junk-allowed nil)) (gid (parse-integer (fourth fields) :junk-allowed nil)) (gecos (split-escaped-string (fifth fields) "\\" ","))) (make-user :login (first fields) :passwd (second fields) :uid uid :gid gid :gecos gecos :home (sixth fields) :shell (seventh fields))) (warn "Invalid passwd line ~S~%" line)))) (defun read-passwd (&optional (passwd-file-path "/etc/passwd")) " DO: Read a passwd file. PASSWD-FILE-PATH: The pathname of the passwd file. Default: \"/etc/passwd\". RETURN: A list of passwd USER structures. " (delete nil (mapcar (function parse-passwd) (with-open-file (in passwd-file-path :direction :input :if-does-not-exist :error) (stream-to-string-list in))))) ;;;; THE END ;;;;
4,834
Common Lisp
.lisp
113
37.141593
83
0.610461
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2e8764b78886d8214048c6527357c0a9b28de32522a126999749ab4dadaf3a97
5,161
[ -1 ]
5,162
com.informatimago.common-lisp.unix.asd
informatimago_lisp/common-lisp/unix/com.informatimago.common-lisp.unix.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.unix.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.unix library. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-03-13 <PJB> Added "option". ;;;; 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.unix" ;; system attributes: :description "Informatimago Common Lisp Unix Utilities" :long-description "Access to a few unix administrative files (passwd, group, etc)." :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.5.0" :properties ((#:author-email . "[email protected]") (#:date . "Winter 2012") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.unix/") ((#: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 "aliases" :depends-on ()) (:file "group" :depends-on ()) (:file "passwd" :depends-on ()) (:file "option" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.unix.test")))) ;;;; THE END ;;;;
2,780
Common Lisp
.lisp
58
44.12069
108
0.583824
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cfb283a2e56088144b03978097d1546dea7ed28a20ad36004e5fd238498c45a7
5,162
[ -1 ]
5,163
aliases.lisp
informatimago_lisp/common-lisp/unix/aliases.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: aliases.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2007-01-14 <PJB> Added alias db functions. ;;;; 2005-09-01 <PJB> Made use of iso6429. ;;;; 2005-05-19 <PJB> Corrected handling of :include: in parse-address ;;;; adding a follow set attribute. ;;;; 2003-10-22 <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))) (in-package "COMMON-LISP-USER") (declaim (declaration also-use-packages)) (declaim (also-use-packages "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ECMA048")) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.UNIX.ALIASES" (: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.STREAM") (:export "READ-DOT-FORWARD" "READ-ALIASES") (:documentation " This package exports a function to read sendmail aliases files. License: AGPL3 Copyright Pascal J. Bourguignon 2003 - 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.COMMON-LISP.UNIX.ALIASES") ;; (setf db (load-aliases [file])) ;; (save-aliases db [file]) ;; (db-records db) --> list-of-records ;; ;; (make-alias name address-list) --> record ;; (make-comment text) --> record ;; (find-record-if db predicate) --> record ;; (alias-record db name) --> record ;; (comment-record-containing db substring) --> record ;; (insert-record db record [:before record] [:after record]) ;; (delete-record db record) ;; ;; (list-all-aliases db) --> (\"name1\" \"name2\" ...) ;; (alias-addresses db name) --> list ;; (setf (alias-addresses db name) list) ;; (insert-alias db name type value [:before record] [:after record]) ;; (delete-alias db name) (defvar +ht+ #+mocl (code-char 9) #-mocl (or (ignore-errors (read-from-string "#\\TAB")) (code-char com.informatimago.common-lisp.cesarum.ecma048:ht))) ;; How can we define a HT character portably? ;; Even (code-char 9) may not work... ;; If the TAB code doesn't exist on the host, ;; the input files wouldn't contain any, and we shouldn't evey try to test it. (defvar +sphtcrlf+ (format nil " ~C~C~C" (code-char #+mocl 9 #-mocl com.informatimago.common-lisp.cesarum.ecma048:ht) (code-char #+mocl 13 #-mocl com.informatimago.common-lisp.cesarum.ecma048:cr) (code-char #+mocl 10 #-mocl com.informatimago.common-lisp.cesarum.ecma048:lf)) "A string containing space, tabulation, carriage return and line feed.") (defvar +spht+ (format nil " ~C" (code-char #+mocl 9 #-mocl com.informatimago.common-lisp.cesarum.ecma048:ht)) "A string containing space and tabulation.") (defvar +crlf+ (format nil "~C~C" (code-char #+mocl 13 #-mocl com.informatimago.common-lisp.cesarum.ecma048:cr) (code-char #+mocl 10 #-mocl com.informatimago.common-lisp.cesarum.ecma048:lf)) "A string containing a carriage return and a line feed.") (defvar +cr+ (format nil "~C" (code-char #+mocl 13 #-mocl com.informatimago.common-lisp.cesarum.ecma048:cr)) "A string containing a carriage return.") ;; alias ::= address ':' address-list . ;; address ::= '"' {not-double-quote} '"' | { letter-or-digit-or-underline } . ;; address-list ::= address ',' address-list | address . ;; ;; address ( :address address ) ;; \address ( :quote address ) ;; /file/name ( :file /file/name ) ;; |command ( :command command ) ;; :include:/file/name ( :include /file/name ) (defun parse-token (line pos token) (and (<= (+ pos (length token)) (length line)) (string= line token :start1 pos :end1 (+ pos (length token))))) (defun skip-spaces (line pos) (while (parse-token line pos " ") (incf pos)) pos) (defun parse-address (line pos follow) " start ::= address | file | command | include . address ::= rfc822-address . file ::= '/' path . command ::= '|' command . include ::= ':include:' '/' path. " (setq pos (skip-spaces line pos)) (cond ((<= (length line) pos) (error "Expected an address, got end of line.")) ((char= (character "\"") (char line pos)) (read-from-string line nil nil :start pos)) (t (do ((i pos (1+ i))) ((or (<= (length line) i) (position (char line i) follow)) (values (subseq line pos i) i)))))) (defun parse-address-list (line pos) (multiple-value-bind (address npos) (parse-address line pos ", #") (let ((address-list (list address))) (setq pos (skip-spaces line npos)) (loop :while (< pos (length line)) :do (multiple-value-bind (address npos) (parse-address line (+ (if (parse-token line pos ",") 1 0) pos) ", #") (push address address-list) (setq pos (skip-spaces line npos)))) (values (nreverse address-list) pos)))) ;; address-list ::= address | address-list [ ',' ] address . ;; address ::= '"' ( but-quote-or-antislash | '\' anychar ) * '"' ;; | but-quote-space-or-comma . (defun parse-eoln (line pos) (setq pos (skip-spaces line pos)) (<= (length line) pos)) (defun encapsulate (addr) (cond ((char= (char addr 0) (character "\\")) (cons :quote (string-downcase (subseq addr 1)))) ((char= (char addr 0) (character "|")) (cons :command (subseq addr 1))) ((char= (char addr 0) (character "/")) (cons :file addr)) ((prefixp ":include:" addr) (cons :include (subseq addr 9))) (t (cons :address (string-downcase addr))))) (defun parse-dot-forward-alias (line) (multiple-value-bind (address-list pos) (parse-address-list line 0) ;; TODO: Check that we reach EOLN!!! (parse-eoln line pos) (mapcar (function encapsulate) address-list))) (defun parse-alias (line) (if (or (zerop (length line)) (char= #\# (aref line 0))) ;; A comment (list :comment line) ;; An alias (multiple-value-bind (address pos) (parse-address line 0 ": #") (setq pos (skip-spaces line pos)) (if (parse-token line pos ":") (multiple-value-bind (address-list pos) (parse-address-list line (1+ pos)) ;; TODO: Check that we reach EOLN!!! (parse-eoln line pos) (cons (string-downcase address) (mapcar (function encapsulate) address-list))) (error "Expected a ':'."))))) (defun join-continuation-lines (lines) (nreverse (cdr (let ((tag (gensym))) (reduce (lambda (&optional a b) (let (joined line) (if (and (listp a) (eq tag (car a))) (setq joined a line b) (setq joined b line a)) (if (and (and (plusp (length line)) (char= (character " ") (char line 0))) (first (cdr joined))) ;; continuation-line (setf (first (cdr joined)) (concatenate 'string (first (cdr joined)) line)) (setf (cdr joined) (cons line (cdr joined)))) joined)) lines :initial-value (cons tag nil)))))) (defun remove-comments (lines) (mapcan (lambda (line) (setq line (string-right-trim " " line)) (when (and (< 0 (length line)) (char/= (character "#") (char line 0))) (list line))) lines)) (defun clean-lines (lines) " DO: Clean CR/LF stuff and replace tabulations by spaces. " (mapcan (lambda (in-line) (mapcar (lambda (line) (substitute (character " ") (code-char 9) line)) ;; This SPLIT-STRING returns NIL for an empty string. (split-string (string-trim +crlf+ in-line) +crlf+))) lines)) (defun read-aliases (&optional (alias-file-path "/etc/aliases")) " RETURN: A list of ( alias address...). alias is a downcased string containing the alias name. address is a cons: ( :address . address ) ;; address (downcased) ( :quote . address ) ;; \address (downcased) ( :file . /file/name ) ;; /file/name ( :command . command ) ;; |command ( :include . /file/name ) ;; :include:/file/name " (mapcar (function parse-alias) (join-continuation-lines (remove-comments (clean-lines (with-open-file (in alias-file-path :direction :input :if-does-not-exist :error) (stream-to-string-list in))))))) (defun read-dot-forward (forward-file-path) " RETURN: A list of ( address...). address is a cons: ( :address . address ) ;; address (downcased) ( :quote . address ) ;; \address (downcased) ( :file . /file/name ) ;; /file/name ( :command . command ) ;; |command ( :include . /file/name ) ;; :include:/file/name " (mapcar (function parse-dot-forward-alias) (join-continuation-lines (remove-comments (clean-lines (with-open-file (in forward-file-path :direction :input :if-does-not-exist nil) (when in (stream-to-string-list in)))))))) (defparameter *normal-characters* ".-/0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz|") (defun normal-character-p (ch) (position ch *normal-characters*)) (defun normal-string-p (string) (every (function normal-character-p) string)) (defun quote-string (string) (with-output-to-string (out) (princ #\" out) (loop :for ch :across string :do (when (or (char= #\\ ch) (char= #\" ch)) (princ #\\ out)) :do (princ ch out)) (princ #\" out))) (defun normal-or-quote-string (string) (if (normal-string-p string) string (quote-string string))) (defun make-comment (text) (list :comment text)) (defun commentp (object) (and (listp object) (eq :comment (first object)))) (defun comment-text (comment) (second comment)) (defparameter *address-types* '(:address :quote :file :command :include)) (defun make-address (type value) (assert (and (member type *address-types*) (stringp value))) (cons type value)) (defun addressp (object) (and (consp object) (member (car object) *address-types*) (stringp (cdr object)))) (defun address-type (address) (car address)) (defun address-value (address) (cdr address)) (defun address-string (address) (let ((value (address-value address))) (case (address-type address) ((:address :file) (normal-or-quote-string value)) ((:quote) (if (normal-string-p value) (format nil "\\~A" value) (format nil "\"\\~A" (subseq (quote-string value) 1)))) ((:command) (normal-or-quote-string (format nil "|~A" value))) ((:include) (if (normal-string-p value) (format nil ":include:~A" value) (normal-or-quote-string (format nil ":include:~A" value))))))) (defun make-alias (name addresses) (assert (and (stringp name) (every (function addressp) addresses))) (cons name addresses)) (defun aliasp (object) (and (listp object) (stringp (first object)) (listp (rest object)) (every (function addressp) (rest object)))) (defun alias-name (alias) (first alias)) (defun alias-addresses (alias) (rest alias)) (defun (setf alias-addresses) (addresses alias) (setf (rest alias) addresses)) (defstruct db path records) (defun clean-db-lines (lines) (loop :for current :on lines :do (setf (car current) (substitute #\space #\tab (car current)))) lines) (defun load-aliases (&optional (alias-file-path "/etc/aliases") &key (external-format :default)) (make-db :path alias-file-path :records (mapcar (function parse-alias) (join-continuation-lines (clean-db-lines (with-open-file (in alias-file-path :direction :input :if-does-not-exist :error :external-format external-format) (stream-to-string-list in))))))) (defparameter *max-column* 78) (defun save-aliases (db &key (stream *standard-output* streamp) (file-path (db-path db) file-path-p) (if-exists :error) (if-does-not-exist :create) (external-format :default)) (flet ((write-aliases (out) (dolist (record (db-records db)) (if (commentp record) (format out "~A~%" (comment-text record)) (let ((name (normal-or-quote-string (alias-name record))) (column 0)) (format out "~A: " name) (incf column (+ (length name) 2)) (let* ((address (first (alias-addresses record))) (item (address-string address))) (if (< (+ column (length item)) *max-column*) (progn (format out "~A" item) (incf column (length item))) (progn (format out "~% ~A" item) (setf column (+ 4 (length item)))))) (dolist (address (rest (alias-addresses record))) (let ((item (address-string address))) (if (< (+ column 2 (length item)) *max-column*) (progn (format out ", ~A" item) (incf column (+ 2 (length item)))) (progn (format out "~% ~A" item) (setf column (+ 4 (length item))))))) (format out "~%")))))) (when (and streamp file-path-p) (error ":stream and :file-path are mutually exclusive.")) (if file-path-p (with-open-file (out file-path :direction :output :if-exists if-exists :if-does-not-exist if-does-not-exist :external-format external-format) (write-aliases out)) (write-aliases stream))) (values)) (defun find-record-if (db predicate) (find-if predicate (db-records db))) (defun alias-record (db name) (find-record-if db (lambda (record) (and (aliasp record) (string-equal (alias-name record) name))))) (defun comment-record-containing (db substring) (find-record-if db (lambda (record) (and (commentp record) (search substring (comment-text record) :test (function char=)))))) (defun list-all-aliases (db) (mapcan (lambda (record) (when (aliasp record) (list (alias-name record)))) (db-records db))) (defun insert-record (db record &key (before nil beforep) (after :all afterp)) (when (and beforep afterp) (error "Cannot insert both :BEFORE and :AFTER at the same time.")) (flet ((insert (where which) (loop :for current :on (db-records db) :until (or (null (cdr current)) (eq (funcall where current) which)) :finally (push record (cdr current))))) (if beforep (if (or (eq :all before) (eq (first (db-records db)) before)) (push record (db-records db)) (insert (function cadr) before)) (if (eq :all after) (push record (cdr (last (db-records db)))) (insert (function car) after)))) (values)) (defun delete-record (db record) (setf (db-records db) (delete record (db-records db))) (values)) (defun remove-user (db name) (let ((removed-records '())) (dolist (record (db-records db)) (when (aliasp record) (setf (alias-addresses record) (delete-if (lambda (address) (and (eq :address (address-type address)) (string-equal (address-value address) name))) (alias-addresses record))) (when (null (alias-addresses record)) (push record removed-records)))) (when removed-records (setf (db-records db) (delete-if (lambda (record) (member record removed-records)) (db-records db)))) (loop :for record :in (db-records db) :if (and (aliasp record) (equal name (alias-name record))) :collect record :into deleted :else :collect record :into kept :finally (setf (db-records db) kept removed-records (nconc deleted removed-records))) removed-records)) (defun records-between-tags (db begin end) (loop :for record :in (cdr (member-if (lambda (record) (and (commentp record) (search begin (comment-text record) :test (function char=)))) (db-records db))) :while (and record (not (and (commentp record) (search end (comment-text record) :test (function char=))))) :collect record)) (defmacro with-alias-file ((varname pathname &key (external-format :default)) &body body) `(let ((,varname (load-aliases ,pathname :external-format ,external-format))) (prog1 (progn ,@body) (save-aliases db :file-path ,pathname :external-format ,external-format :if-exists :supersede)))) ;;; (ext:shell "diff -twb afaa.alias afaa-new.alias") ;;; postalias -f -q file2 hash:test.alias ;;;; THE END ;;;;
20,205
Common Lisp
.lisp
459
34.830065
98
0.567221
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8c14debb1a82a3e5f9d1fe42c1a477372c8ec78a9f437020b44fac6bfadb1875
5,163
[ -1 ]
5,164
option.lisp
informatimago_lisp/common-lisp/unix/option.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: option.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; See defpackage documentation string. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-01-29 <PJB> Replaced wrap-option-function by generate-wrap-option-function ;;;; to avoid calling COMPILE at compilation time, since abcl seems ;;;; to be not liking it. ;;;; 2012-03-10 <PJB> Extracted from ~/bin/script.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.COMMON-LISP.UNIX.OPTION" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SYMBOL") (:export "PNAME" "*PROGRAM-NAME*" "*DEBUG-OPTIONS*" "REDIRECTING-STDOUT-TO-STDERR" "DEFINE-OPTION" "CALL-OPTION-FUNCTION" "*DOCUMENTATION-TEXT*" "*BASH-COMPLETION-HOOK*" "PARSE-OPTIONS" "PARSE-OPTIONS-FINISH" ;; Exit codes: "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" ;; "OPTION-KEYS" "OPTION-ARGUMENTS" "OPTION-DOCUMENTATION" "OPTION-FUNCTION" "OPTION-LIST") (:documentation " This package processes command line options. Example: (defvar *force-execution* nil) (define-option (\"-f\" \"--force\" \"force\") () \"Force execution\" (setf *force-execution* t)) (defun main (arguments) (parse-options arguments) (when *force-execution* (do-it)) (ext:exit ex-ok)) (main ext:*args*) License: AGPL3 Copyright Pascal J. Bourguignon 2012 - 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.COMMON-LISP.UNIX.OPTION") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (defvar *program-name* "unnamed" "Name of the program. If available we use the actual command line program name, otherwise we fallback to *PROGRAM-NAME*.") (defvar *debug-options* nil "Errors break into the debugger.") ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-condition parse-options-finish (condition) ((status-code :initarg :status-code :reader parse-options-finish-status-code)) (:report "PARSE-OPTIONS-FINISH must be called only in the dynamic context of a call to PARSE-OPTIONS") (:documentation "Condition signaled to finish the parsing of options early.")) (defun parse-options-finish (status-code) "Signals the PARSE-OPTIONS-FINISH condition, which terminates option parsing early." (error 'parse-options-finish :status-code status-code)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (defmacro redirecting-stdout-to-stderr (&body body) " Execute BODY with the *standard-output*, *error-output*, and *trace-output* redirected. If an error occurs in BODY, then all the redirected output is sent to *error-output*. " (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*) #-testing-script (parse-options-finish ex-software))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; From /usr/include/sysexits.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") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; OPTIONS PROCESSING ;;; (defun pname () "This function can be used to set *program-name* in the main script (setf script:*program-name* (script:pname)) " (file-namestring *program-name*)) (eval-when (:compile-toplevel :load-toplevel :execute) (defstruct option "An option structure." keys arguments documentation function) (setf (documentation 'option-keys 'function) "A list of option keys." (documentation 'option-arguments 'function) "A lambda-list of option arguments." (documentation 'option-documentation 'function) "The documentation of the option (a string)." (documentation 'option-function 'function) "The option function.") (defun q&d-parse-parameters (parameters) "Parses (mandatory &optional optionals... &rest rest &key key...)" (loop :with mandatories = '() :with optionals = '() :with rest = nil :with keys = '() :with state = :mandatory :with params = parameters :for param = (first params) :while params :do (ecase state ((:mandatory) (case param ((&optional) (setf state :optional)) ((&rest) (setf state :rest)) ((&key) (setf state :key)) (otherwise (push param mandatories))) (pop params)) ((:optional) (case param ((&optional) (error "&OPTIONAL given more than once in ~S" parameters)) ((&rest) (setf state :rest)) ((&key) (setf state :key)) (otherwise (push param optionals))) (pop params)) ((:rest) (case param ((&optional) (error "&OPTIONAL given after &REST in ~S" parameters)) ((&rest) (error "&REST given twice in ~S" parameters)) ((&key) (setf state :key)) (otherwise (setf state :after-rest rest param))) (pop params)) ((:after-rest) (case param ((&optional) (error "&OPTIONAL given after &REST in ~S" parameters)) ((&rest) (error "&REST given after &REST in ~S" parameters)) ((&key) (setf state :key)) (otherwise (error "Several &REST parameters given in ~S" parameters))) (pop params)) ((:key) (case param ((&optional) (error "&OPTIONAL given after &KEY in ~S" parameters)) ((&rest) (error "&REST given after &KEY in ~S" parameters)) ((&key) (setf state :key)) (otherwise (push param keys))) (pop params))) :finally (return (values (nreverse mandatories) (nreverse optionals) rest (nreverse keys))))) (defun q&d-arguments (mandatories optionals rest keys) " BUG: when the optionals or keys have a present indicator, we just ignore it and build a list that will pass the default value anyways... " (assert (every (function symbolp) mandatories)) (append mandatories (mapcar (lambda (opt) (etypecase opt (cons (first opt)) (symbol opt))) optionals) (when rest (list rest)) (mapcan (lambda (key) (etypecase key (cons (etypecase (first key) (symbol (list (keywordize (first key)) (first key))) (cons (list (second (first key)) (first (first key)))))) (symbol (list (keywordize key) key)))) keys))) (defun generate-wrap-option-function (keys option-arguments docstring option-function-name) (let ((vargs (gensym))) (multiple-value-bind (mandatories optionals rest keys-args) (q&d-parse-parameters option-arguments) `(make-option :keys ',keys :arguments ',option-arguments :function (lambda (,vargs) ,(flet ((generate-body () (cond (rest `(destructuring-bind ,option-arguments ,vargs (,option-function-name ,@(q&d-arguments mandatories optionals rest keys-args)) nil)) (keys-args (error "An option cannot have &key parameters without a &rest parameter. ~@ Invalid option parameters: ~S" option-arguments)) (t (let ((vremaining (gensym))) `(destructuring-bind (,@option-arguments &rest ,vremaining) ,vargs (,option-function-name ,@(q&d-arguments mandatories optionals rest keys-args)) ,vremaining)))))) (if (zerop (length mandatories)) (generate-body) `(if (<= ,(length mandatories) (length ,vargs)) ,(generate-body) (error "Missing arguments: ~{~A ~}" (subseq ',option-arguments (length ,vargs))))))) :documentation ',(split-string docstring (string #\newline))))))) ;;; --- ;;; The public API is: ;;; (register-option option warn-on-conflicts) ;;; (get-option key case-sensitive) (defparameter *options* '() "A list of all registered options.") (defparameter *case-sensitive-options-map* nil "A cached dictionary of options.") (defparameter *case-insensitive-options-map* nil "A cached dictionary of options.") (defun find-option (keys) (let* ((options (loop :for option :in *options* :append (loop :for key :in keys :if (member key (option-keys option)) :collect (list option "case sensitive" key) :else :if (member key (option-keys option) :test (function equalp)) :collect (list option "case insensitive" key)))) (option (remove-duplicates (mapcar (function first) options)))) (values option options))) (defun fill-option-map (table) (loop :for option :in (reverse *options*) :do (loop :for key :in (option-keys option) :do (setf (gethash key table) option))) table) (defun register-option (option warn-on-conflicts) (when warn-on-conflicts (multiple-value-bind (old-option conflicts) (find-option (option-keys option)) (when old-option (warn "~A" (let ((*print-circle* nil) (*print-escape* nil)) (format nil "There are already options for ~:{the ~A key ‘~A’~:^, ~}." (mapcar (function rest) conflicts))))))) (push option *options*)) (defun get-option (key case-sensitive) (let ((table (if case-sensitive *case-sensitive-options-map* *case-insensitive-options-map*))) (gethash key (or table (fill-option-map (if case-sensitive (setf *case-sensitive-options-map* (make-hash-table :test (function equal))) (setf *case-insensitive-options-map* (make-hash-table :test (function equalp))))))))) ;;; --- (defgeneric call-option-function (option arguments undefined-argument case-sensitive) (:documentation " DO: Call the option function with the ARGUMENTS. RETURN: The remaining list of arguments. UNDEFINED-ARGUMENT: A function taking an option key and the remaining list of arguments, called if an undefined argument is found in ARGUMENTS. It should return the new remaining list of arguments. ") (:method ((key string) arguments undefined-argument case-sensitive) (let* ((funopt (get-option key case-sensitive))) (cond (funopt (call-option-function funopt arguments undefined-argument case-sensitive)) (undefined-argument (funcall undefined-argument key arguments)) (t (error "Unknown option ~A ; try: ~A help" key (pname)))))) (:method ((option option) arguments undefined-argument case-sensitive) (declare (ignore undefined-argument case-sensitive)) (funcall (option-function option) arguments))) (defmacro define-option (names parameters &body body) " DO: Define a new option for the scirpt. NAMES: A list designator of option names (strings such as \"-a\" \"--always\"). PARAMETERS: A list of option parameters. The names of these parameters must be descriptive as they are used to build the usage help text. BODY: The code implementing this option. RETURN: The lisp-name of the option (this is a symbol named for the first option name). " (let* ((main-name (if (listp names) (first names) names)) (other-names (if (listp names) (rest names) '())) (lisp-name (intern (string-upcase main-name))) (docstring (if (and (stringp (first body)) (rest body)) (first body) nil)) (body (if (and (stringp (first body)) (rest body)) (rest body) body))) `(progn (register-option ,(generate-wrap-option-function (cons main-name other-names) parameters docstring `(lambda ,(remove '&rest parameters) ,docstring (block ,lisp-name ,@body))) t) ',lisp-name))) (defvar *documentation-text* "" "Some general documentation text issued by the --help command.") (defun option-list () " RETURN: The list of options defined. " (copy-list *options*)) (define-option ("help" "-h" "--help") () "Give this help." (let ((options (option-list))) (format t "~2%~A options:~2%" (pname)) (dolist (option (sort options (function string<) :key (lambda (option) (first (option-keys option))))) (format t " ~{~A~^ | ~} ~:@(~{~A ~}~)~%~@[~{~% ~A~}~]~2%" (option-keys option) (option-arguments option) (option-documentation option))) (format t "~A~%" *documentation-text*))) ;; TODO: See if we couldn't simplify it, perhaps with complete -C. (defun list-all-option-keys () (let ((keys '())) (dolist (option (option-list)) (dolist (key (option-keys option)) (push key keys))) keys)) (defun completion-option-prefix (prefix) (dolist (key (remove-if-not (lambda (key) (and (<= (length prefix) (length key)) (string= prefix key :end2 (length prefix)))) (list-all-option-keys))) (format t "~A~%" key)) (finish-output)) (defun completion-all-options () (dolist (key (list-all-option-keys)) (format t "~A~%" key)) (finish-output)) (defvar *bash-completion-hook* nil "A function (lambda (index words) ...) that will print the completion and return true, or do nothing and return nil.") (define-option ("--bash-completions") (index &rest words) "Implement the auto-completion of arguments. This option is designed to be invoked from the function generated by the '--bash-completion-function' option. There should be no need to use directly. " (let ((index (parse-integer index :junk-allowed t))) (unless (and *bash-completion-hook* (funcall *bash-completion-hook* index words)) (if index (completion-option-prefix (elt words index)) (completion-all-options)))) (parse-options-finish ex-ok)) (define-option ("--bash-completion-function") () "Write two bash commands (separated by a semi-colon) to create a bash function used to do auto-completion of command arguments. Use it with: eval $($COMMAND --bash-completion-function) and then typing TAB on the command line after the command name will autocomplete argument prefixes. " (format t "function completion_~A(){ ~ COMPREPLY=( $(~:*~A --bash-completions \"$COMP_CWORD\" \"${COMP_WORDS[@]}\") ) ; } ;~ complete -F completion_~:*~A ~:*~A~%" *program-name*) (parse-options-finish ex-ok)) (defun parse-options (arguments &optional default undefined-argument (case-sensitive t)) " DO: Parse the options in the ARGUMENTS list. DEFAULT: Thunk called if ARGUMENTS is empty. UNDEFINED-ARGUMENT: Thunk called if an undefined option is present in the ARGUMENTS. RETURN: NIL on success, status code when early exit is requested. " (handler-case (flet ((process-arguments () (cond (arguments (loop :while arguments :do (setf arguments (call-option-function (pop arguments) arguments undefined-argument case-sensitive))) nil) (default (funcall default))))) (if *debug-options* (process-arguments) (handler-case (process-arguments) ;; Somewhat arbitrary dispatching of lisp conditions to ;; linux sysexits: ((or arithmetic-error parse-error #-mocl print-not-readable type-error) (err) (format *error-output* "~%ERROR: ~A~%" err) (parse-options-finish ex-dataerr)) ((or cell-error control-error package-error program-error) (err) (format *error-output* "~%ERROR: ~A~%" err) (parse-options-finish ex-software)) (file-error (err) (format *error-output* "~%ERROR: ~A~%" err) (parse-options-finish ex-osfile)) (stream-error (err) (format *error-output* "~%ERROR: ~A~%" err) (parse-options-finish ex-ioerr)) (error (err) (format *error-output* "~%ERROR: ~A~%" err) (parse-options-finish ex-software))))) (parse-options-finish (condition) (return-from parse-options (parse-options-finish-status-code condition))))) ;;;; THE END ;;;;
24,702
Common Lisp
.lisp
534
35.685393
110
0.562918
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
15a1bb09332398462d3ad45ab5a84f9507fba37a7f6a15bdb5a6bde5f3c3b17b
5,164
[ -1 ]
5,165
com.informatimago.common-lisp.invoice.asd
informatimago_lisp/common-lisp/invoice/com.informatimago.common-lisp.invoice.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.invoice.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.invoice 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.invoice" ;; system attributes: :description "Informatimago Common Lisp Accounting and Invoicing" :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 . "Autumn 2010") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.invoice/") ((#: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 "invoice" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.invoice.test")))) ;;;; THE END ;;;;
2,534
Common Lisp
.lisp
53
44.622642
111
0.592981
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a3b8011d843612504a18ab91e488ca6e17fb046bace2c6679ee507ca8f25fd4a
5,165
[ -1 ]
5,166
invoice.lisp
informatimago_lisp/common-lisp/invoice/invoice.lisp
;;;; -*- mode:lisp; coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: invoices.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: Common-Lisp ;;;;DESCRIPTION ;;;; ;;;; This package exports classes and functions used for accounting: ;;;; invoices, customers/providers, movements, taxes... ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2004-10-17 <PJB> Completed conversion to Common-Lisp. ;;;; 2004-10-11 <PJB> Converted to Common-Lisp from emacs lisp. ;;;; 2002-09-09 <PJB> Added generate-invoice. ;;;; 199?-??-?? <PJB> Creation. ;;;;BUGS ;;;; Currencies are handled, but multicurrency accounting is not. ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 1990 - 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.INVOICE.INVOICE" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ISO4217") #+mocl (:shadowing-import-from "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING" "*TRACE-OUTPUT*" "*LOAD-VERBOSE*" "*LOAD-PRINT*" "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" "PRINT-NOT-READABLE" "PRINT-NOT-READABLE-OBJECT") (:export "LOAD-JOURNAL" "JOURNAL-ENTRY" "LINE" "PERSON" "GENERATE" "TRIMESTRE" "MAKE-BANK-REFERENCE" "JOURNAL" "MOVEMENT" "INVOICE-SET" "INVOICE" "INVOICE-LINE" "FISCAL-PERSON" "BANK-REFERENCE" "PJB-OBJECT" "*JOURNAL*" "*INVOICE-SET*" "*CURRENCY-READTABLE*") (:shadow "ABS" "ZEROP" "ROUND" "/=" "=" ">=" ">" "<=" "<" "/" "*" "-" "+") (:documentation " This package exports classes and functions used for accounting: invoices, customers/providers, movements, taxes... License: AGPL3 Copyright Pascal J. Bourguignon 1990 - 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.COMMON-LISP.INVOICE.INVOICE") ;;; parameters (defparameter *vat-rates* '(0/100 4/100 7/100 16/100) "The valid VAT rates in the country of the user.") (defparameter *invoice-directory-path* '(:absolute "HOME""PASCAL""JOBS""FREE-LANCE""INVOICES") "The directory where the generated invoices are stored.") (defparameter *invoice-set-file-path* (make-pathname :directory *invoice-directory-path* :name "INVOICES" :type "DATA") "Path to the file where invoices are stored.") ;;; global variables: (defparameter *default-currency* (find-currency :eur) "The currency used when no prefix currency code is given to #m") (defparameter *max-movement-amount* nil "The maximum movement amount (ht or ttc, expressed in the currency of the movement (weak, I know).") (defparameter *invoice-set* nil "Current Invoice Set (instance of INVOICE-SET).") ;;invoice-set (defparameter *journal* nil "Current Journal (instance of JOURNAL).") ;;;--------------------------------------------------------------------- (defgeneric abs (self)) (defgeneric add-entry (self entry)) (defgeneric add-invoice (self invoice)) (defgeneric add-line (self line)) (defgeneric add-person (self person &optional fisc)) (defgeneric amount-ht (self)) (defgeneric compute-totals (self)) (defgeneric credit-ht (self)) (defgeneric credit-vat (self)) (defgeneric currency (self)) (defgeneric amount-magnitude (self)) (defgeneric debit-ht (self)) (defgeneric debit-vat (self)) (defgeneric debit-vat-corriente (self)) (defgeneric debit-vat-inversion (self)) (defgeneric ensure-sorted (self)) (defgeneric extract (self year trimestre)) (defgeneric generate (invoice &key stream verbose language &allow-other-keys) (:documentation " DO: Generate this invoice into a file in the directory *INVOICE-DIRECTORY-PATH*. RETURN: The path to the file generated. ")) (defgeneric get-invoice-with-issuer-and-number (self issuer-fiscal-id invoice-number)) (defgeneric get-person-with-fiscal-id (self fiscal-id)) (defgeneric invoices (self)) (defgeneric is-credit (self)) (defgeneric is-refund (self)) (defgeneric negativep (self)) (defgeneric positivep (self)) (defgeneric reset (self)) (defgeneric round (self &optional divisor)) (defgeneric vat-rate (self)) (defgeneric write-invoice-file (self &key language)) (defgeneric zerop (self)) ;;;--------------------------------------------------------------------- ;;; Monetary Amounts & Currency Syntax ;;;--------------------------------------------------------------------- ;; Since floating point arithmetic is not adapted to accounting, ;; we will use integers for monetary amounts, and ;; percentages will be expressed as rationnals: 16 % = 16/100 ;; ;; 123.45 ¤ = 12345 ¢ = #978m123.45 ;; ;; In addition monetary amounts are tagged with a currency, and ;; arithmetic operations are type-restricted. ;; ;; The reader syntax is: # [currency-code] m|M [+|-] digit+ [ . digit* ] ;; The currency code must be a numeric code of a currency found ;; in (com.informatimago.common-lisp.cesarum.iso4217:get-currencies), ;; otherwise a read-time error is issued. ;; When the currency-code is not present, the currency designated ;; by *DEFAULT-CURRENCY* is used. ;; The number of digits after the decimal point must not be superior ;; to the minor unit attribute of the currency. ;; The value is converted to an integer number of minor unit and ;; the read result is an AMOUNT structure gathering the currency ;; and the value. ;; ;; The operations defined on AMOUNT values are: ;; ;; c: amount* --> boolean ;; with c in { <, <=, >, >=, =, /= }. ;; ;; +: amount* --> amount ;; -: amount* --> amount ;; *: amount X real* --> amount (commutatif and associatif) ;; /: amount X real* --> amount (not commutatif and not associatif) ;; ;; [ set* = Kleene closure of the set ] ;; ;; For now, all these operations work only when the currency of all amount ;; involved is the same. ;; ;; These Common-Lisp operators are shadowed, and functions are defined for ;; them, that extend the normal numeric functions for amounts. ;; ;; The AMOUNT structure has a printer that prints different format ;; depending on the *PRINT-READABLY*. It uses the reader syntax defined ;; above when *PRINT-READABLY* is true, or a "~V$ ~3A" format printing ;; the value followed by the alphabetic code of the currency. (defstruct (amount (:predicate amountp) #|(:PRINT-OBJECT PRINT-OBJECT)|#) "An amount of money." currency (value 0 :type integer)) (defmethod print-object ((self amount) stream) (if *print-readably* (format stream "#~DM~V$" (currency-numeric-code (amount-currency self)) (currency-minor-unit (amount-currency self)) (amount-magnitude self)) (format stream "~V$ ~A" (currency-minor-unit (amount-currency self)) (amount-magnitude self) (currency-alphabetic-code (amount-currency self)))) self) ;;PRINT-OBJECT (defmethod currency ((self number)) (declare (ignorable self)) nil) (defmethod currency ((self amount)) (amount-currency self)) (defmethod amount-magnitude ((self number)) self) (defmethod amount-magnitude ((self amount)) " RETURN: A real equal to the value of the amount. " (* (amount-value self) (aref #(1 1/10 1/100 1/1000 1/10000) (currency-minor-unit (amount-currency self))))) (defparameter *zero-amounts* (make-hash-table :test (function eq)) "A cache of 0 amount for the various currencies used.") (defun amount-zero (currency) " RETURN: A null amount of the given currency. " (let ((zero (gethash (find-currency currency) *zero-amounts*))) (unless zero (setf zero (setf (gethash (find-currency currency) *zero-amounts*) (make-amount :currency (find-currency currency) :value 0)))) zero)) ;;AMOUNT-ZERO (defmethod abs ((self number)) (common-lisp:abs self)) (defmethod abs ((self amount)) (make-amount :currency (amount-currency self) :value (common-lisp:abs (amount-value self)))) (defmethod zerop ((self number)) (common-lisp:zerop self)) (defmethod zerop ((self amount)) (common-lisp:zerop (amount-value self))) (defmethod positivep ((self number)) (common-lisp:<= 0 self)) (defmethod positivep ((self amount)) (common-lisp:<= 0 (amount-value self))) (defmethod negativep ((self number)) (common-lisp:> 0 self)) (defmethod negativep ((self amount)) (common-lisp:> 0 (amount-value self))) (defmethod round ((self real) &optional (divisor 1)) (common-lisp:round self divisor)) (defmethod round ((self amount) &optional (divisor 1)) (make-amount :currency (amount-currency self) :value (common-lisp:round (amount-value self) divisor))) (defun euro-round (magnitude currency) " MAGNITUDE: A REAL CURRENCY: The currency of the amount. RETURN: An integer in minor unit rounded according to the Euro rule." (let ((rounder (aref #(1 1/10 1/100 1/1000 1/10000) (currency-minor-unit currency)))) (round (+ magnitude (* (signum magnitude) (/ rounder 10))) rounder))) (defun euro-value-round (value) " VALUE: A REAL CURRENCY: The currency of the amount. RETURN: An integer in minor unit rounded according to the Euro rule." (round (+ value (* (signum value) 1/10)))) ;;EURO-VALUE-ROUND ;; (with-output-to-string (out) ;; (dolist (*print-readably* '(t nil)) ;; (print (make-amount :currency (find-currency :EUR) :value 12345) out))) (define-condition multi-currency-error (error) ((format-control :initarg :format-control :accessor format-control) (format-arguments :initarg :format-arguments :accessor format-arguments) (operation :initarg :operation :accessor multi-currency-error-operation) (amounts :initarg :amounts :accessor multi-currency-error-amounts)) (:report (lambda (self stream) (let ((*print-pretty* nil)) (format stream "~A: (~A ~{~A~^, ~})~%~A" (class-name (class-of self)) (multi-currency-error-operation self) (multi-currency-error-amounts self) (apply (function format) nil (format-control self) (format-arguments self))))))) (defun mcerror (operation amounts format-control &rest format-arguments) (error 'multi-currency-error :operation operation :amounts amounts :format-control format-control :format-arguments format-arguments)) (defun types-of-arguments (args) (labels ((display (item) (cond ((symbolp item) (symbol-name item)) ((atom item) item) (t (mapcar (function display) item))))) (mapcar (lambda (arg) (display (type-of arg))) args))) (defmacro make-comparison-method (name operator) " DO: Generate a comparison method. " `(defun ,name (&rest args) (cond ((every (function numberp) args) (apply (function ,operator) args)) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (apply (function ,operator) (mapcar (function amount-value) args)) (mcerror ',name args "Comparison not implemented yet.")))) (t (mcerror ',name args "Incompatible types: ~A" (types-of-arguments args)))))) (make-comparison-method < common-lisp:<) (make-comparison-method <= common-lisp:<=) (make-comparison-method > common-lisp:>) (make-comparison-method >= common-lisp:>=) (make-comparison-method = common-lisp:=) (make-comparison-method /= common-lisp:/=) (defun + (&rest args) " DO: A Generic addition with numbers or amounts. " (setf args (remove 0 args :key (lambda (x) (if (typep x 'amount) (amount-value x) x)) :test (function equal))) (cond ((every (function numberp) args) (apply (function common-lisp:+) args)) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (make-amount :currency currency :value (apply (function common-lisp:+) (mapcar (function amount-value) args))) (mcerror '+ args "Addtion not implemented yet.")))) (t (mcerror '+ args "Incompatible types: ~A" (types-of-arguments args))))) (defun - (&rest args) " DO: A Generic substraction with numbers or amounts. " (setf args (cons (car args) (remove 0 (cdr args) :key (lambda (x) (if (typep x 'amount) (amount-value x) x)) :test (function equal)))) (cond ((every (function numberp) args) (apply (function common-lisp:-) args)) ((zerop (first args)) (- (apply (function +) (rest args)))) ((every (function amountp) args) (let ((currency (find-currency (amount-currency (first args))))) (if (every (lambda (x) (eq currency (find-currency (amount-currency x)))) (cdr args)) (make-amount :currency currency :value (apply (function common-lisp:-) (mapcar (function amount-value) args))) (mcerror '- args "Substraction not implemented yet.")))) (t (mcerror '- args "Incompatible types: ~A" (types-of-arguments args))))) (defun * (&rest args) " DO: A Generic multiplication with numbers or amounts. " (if (every (function numberp) args) (apply (function common-lisp:*) args) (let ((p (position-if (function amountp) args))) (cond ((or (null p) (not (every (lambda (x) (or (amountp x)(realp x))) args))) (mcerror '* args "Incompatible types: ~A" (types-of-arguments args))) ((position-if (function amountp) args :start (1+ p)) (mcerror '* args "Cannot multiply moneys.")) (t (make-amount :currency (amount-currency (nth p args)) :value (euro-value-round (apply (function common-lisp:*) (mapcar (lambda (x) (if (amountp x) (amount-value x) x)) args))))))))) (defun / (&rest args) " DO: A Generic division with numbers or amounts. " (cond ((every (function numberp) args) (apply (function common-lisp:/) args)) ((and (cadr args) (not (cddr args)) ; two arguments (amountp (first args)) (amountp (second args))) ; both amounts ;; then return a number: (/ (amount-value (first args)) (amount-value (second args)))) ((and (amountp (car args)) (cdr args) ;; cannot take the inverse of an amount! (every (function realp) (cdr args))) (make-amount :currency (amount-currency (car args)) :value (euro-value-round (apply (function common-lisp:/) (amount-value (car args)) (cdr args))))) (t (mcerror '/ args "Incompatible types: ~A" (types-of-arguments args))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun currency-syntax (stream char infix) (declare (ignore char)) (let ((currency (or infix *default-currency*))) (setf currency (find-currency currency)) (unless currency (mcerror 'currency-syntax (or infix *default-currency*) "Invalid currency designator ~S" (or infix *default-currency*))) (assert (<= 0 (currency-minor-unit currency) 4) () "Unexpected minor unit for currency: ~S" currency) (let ((left '()) (right '()) (dot nil) (sign 1)) (let ((ch (read-char stream nil nil))) (cond ((null ch)) ((char= ch (character "-" )) (setf sign -1)) ((char= ch (character "+" ))) (t (unread-char ch stream)))) (loop for ch = (peek-char nil stream nil nil) while (and ch (digit-char-p ch)) do (push (read-char stream) left) finally (setf dot (and ch (char= (character ".") ch)))) (when (zerop (length left)) (mcerror 'currency-syntax currency "Missing an amount after #M")) (when dot (when (zerop (currency-minor-unit currency)) (mcerror 'currency-syntax currency "There is no decimal point in ~A" (currency-name currency))) (read-char stream) ;; eat the dot (loop for ch = (peek-char nil stream nil nil) while (and ch (digit-char-p ch)) do (push (read-char stream) right)) (when (< (currency-minor-unit currency) (length right)) (mcerror 'currency-syntax currency "Too many digits after the decimal point for ~A" (currency-name currency)))) (loop for i from (length right) below (currency-minor-unit currency) do (push (character "0") right)) (make-amount :currency currency ;; (WITH-STANDARD-IO-SYNTAX ;; (INTERN (CURRENCY-ALPHABETIC-CODE CURRENCY) "KEYWORD")) :value (* sign (parse-integer (map 'string (function identity) (nreverse (nconc right left))))) ;;:divisor (AREF #(1 10 100 1000 10000) ;; (CURRENCY-MINOR-UNIT CURRENCY)) )))) ;;currency-syntax (defparameter *currency-readtable* (copy-readtable *readtable*) "The readtable used to read currencies.") (set-dispatch-macro-character #\# #\M (function currency-syntax) *currency-readtable*) (set-dispatch-macro-character #\# #\M (function currency-syntax) *currency-readtable*) ) ;;eval-when ;; (let ((*readtable* *currency-readtable*)) ;; (mapcar ;; (lambda (s) ;; (let ((cnt 0)) ;; (list s ;; (handler-case (multiple-value-bind (r l) (read-from-string s) ;; (setf cnt l) r) ;; (error (err) ;; (apply (function format) nil #||*error-output*||# ;; (simple-condition-format-control err) ;; (simple-condition-format-arguments err)))) ;; (subseq s cnt)))) ;; '("#M123.45" "#840m123.45" "#548m123" "#788m123.456" ;; "#840m123" "#840m123.xyz" "#840m123.4" "#840m123.45" "#840m123.456" ;; "#197M123.45" "#548m123" "#548m123.xyz" "#548m123.4" "#548m123.45" ;; "#548m123.456" "#788m123" "#788m123.xyz" "#788m123.4" "#788m123.45" ;; "#788m123.456" "#788m123.4567" "#788m123.45678" ))) ;; ;; (let ((*readtable* *currency-readtable*)) (read-from-string "#197M123.45" )) ;; (let ((*readtable* *currency-readtable*)) (read-from-string "#M960" )) ;; (let ((*readtable* *currency-readtable*)) (read-from-string "#978M978" )) ;;;--------------------------------------------------------------------- ;;; DATE ;;;--------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +seconds-in-a-day+ (cl:* 24 3600) "Number of seconds in a day.") );;eval-when (defstruct (date #|(:PRINT-OBJECT PRINT-OBJECT)|#) year month day) (defmethod print-object ((self date) stream) (format stream "~4,'0D-~2,'0D-~2,'0D" (date-year self) (date-month self) (date-day self)) self) (defun date-from-string (yyyy-mm-dd) (let ((ymd (split-string yyyy-mm-dd "-"))) (make-date :year (parse-integer (nth 0 ymd)) :month (parse-integer (nth 1 ymd)) :day (parse-integer (nth 2 ymd))))) ;;DATE-FROM-STRING (defun date-after (a b) (or (> (date-year a) (date-year b)) (and (= (date-year a) (date-year b)) (or (> (date-month a) (date-month b)) (and (= (date-month a) (date-month b)) (> (date-day a) (date-day b))))))) ;;DATE-AFTER (defun date-in-year-trimestre (date year trimestre) " RETURN: Whether the given date is within the given YEAR and TRIMESTRE. " (and (= (date-year date) year) (member (date-month date) (elt '((1 2 3) (4 5 6) (7 8 9) (10 11 12)) (- trimestre 1))))) ;;DATE-IN-YEAR-TRIMESTRE (defun calendar-current-date () " RETURN: The date today. " (multiple-value-bind (se mi ho da mo ye dw ds zo) (get-decoded-time) (declare (ignore se mi ho dw ds zo)) (make-date :year ye :month mo :day da))) ;;CALENDAR-CURRENT-DATE (defun local-time-zone () " RETURN: The local time zone, as returned by GET-DECODED-TIME. " (multiple-value-bind (se mi ho da mo ye dw ds zone) (get-decoded-time) (declare (ignore se mi ho da mo ye dw ds)) zone)) ;;LOCAL-TIME-ZONE (defun universal-time-to-date (utime) " RETURN: the given universal time formated in the ISO8601 YYYY-MM-DD format. " (multiple-value-bind (se mi ho da mo ye dw ds zo) (decode-universal-time utime 0) (declare (ignore se mi ho dw ds zo)) (format nil "~4,'0D-~2,'0D--~2,'0D" ye mo da))) ;;UNIVERSAL-TIME-TO-DATE (defun date-to-universal-time (date-string) " DATE-STRING: A date in the ISO8601 format 'YYYY-MM-DD'. RETURN: A number of seconds since 1900-01-01 00:00:00 GMT. " (let ((ymd (split-string date-string "-"))) (encode-universal-time 0 0 0 (parse-integer (third ymd)) (parse-integer (second ymd)) (parse-integer (first ymd)) 0))) ;;DATE-TO-UNIVERSAL-TIME (defun date-format (utime &key (language :en)) (multiple-value-bind (se mi ho day month year dw ds zo) (decode-universal-time utime 0) (declare (ignore se mi ho dw ds zo)) (case language ((:fr) (format nil "~D~A ~A ~D" day (if (= 1 day) "er" "") (aref #("Janvier" "Février" "Mars" "Avril" "Mai" "Juin" "Juillet" "Août" "Septembre" "Octobre" "Novembre" "Décembre") (1- month)) year)) ((:es) (format nil "~D de ~A de ~D" day (aref #("Enero" "Febrero" "Marzo" "Abril" "Mayo" "Junio" "Julio" "Augosto" "Septiembre" "Octobre" "Noviembre" "Diciembre") (1- month)) year)) (otherwise (format nil "~A ~D~A, ~D" (aref #("January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December") (1- month)) day (case (mod day 10) ((1) "st") ((2) "nd") ((3) "rd") (otherwise "th")) year))))) ;;;--------------------------------------------------------------------- ;;; Pjb-Object ;;;--------------------------------------------------------------------- (defclass pjb-object () ((object-id :initform nil :initarg :object-id :accessor object-id :type (or null string) :documentation "The user-level ID of this object.")) (:documentation "This is a root class for my classes.")) ;;;--------------------------------------------------------------------- ;;; BANK-REFERENCE ;;;--------------------------------------------------------------------- (defclass bank-reference (pjb-object) ((bank-name :initform nil :initarg :bank-name :accessor bank-name :type (or null string) :documentation "The name of the bank.") (bank-address :initform nil :initarg :bank-address :accessor bank-address :type (or null string) :documentation "The address of the bank.") (branch-name :initform nil :initarg :branch-name :accessor branch-name :type (or null string) :documentation "The name of the branch.") (swift-code :initform nil :initarg :swift-code :accessor swift-code :type (or null string) :documentation "The swift-code of the bank.") (account-number :initform nil :initarg :account-number :accessor account-number :type (or null string) :documentation "The account number. It should be an IBAN in Europe.") (beneficiary-name :initform nil :initarg :beneficiary-name :accessor beneficiary-name :type (or null string) :documentation "The beneficiary's name.")) (:documentation "A bank account reference.")) ;;BANK-REFERENCE ;;;--------------------------------------------------------------------- ;;; FISCAL-PERSON ;;;--------------------------------------------------------------------- (defclass fiscal-person (pjb-object) ((fiscal-id :initform nil :initarg :fiscal-id :accessor fiscal-id :type (or null string) :documentation "The fiscal ID of the person, ie. the European fiscal ID.") (name :initform nil :initarg :name :accessor name :type (or null string) :documentation "The name of the person.") (address :initform nil :initarg :address :accessor address :type (or null string) :documentation "The address of the person.") (phone :initform nil :initarg :phone :accessor phone :type (or null string) :documentation "The phone number of the person.") (fax :initform nil :initarg :fax :accessor fax :type (or null string) :documentation "The fax number of the person.") (web :initform nil :initarg :web :accessor web :type (or null string) :documentation "The URL of the web site of this person.") (email :initform nil :initarg :email :accessor email :type (or null string) :documentation "The fax number of the person.") (bank-reference :initform nil :initarg :bank-reference :accessor bank-reference :type (or null bank-reference) :documentation "The bank reference of the person.") (language :initform :es :initarg :language :accessor language :type symbol ;; :es :en :fr :de :documentation "The language (two-letter code) used by this person.") (fisc :initform nil :initarg :fisc :accessor fisc :type boolean :documentation "Whether this person is the fiscal administration.")) (:documentation "A person (physical or moral) identified by a fiscal identification number." )) ;;FISCAL-PERSON (defmethod initialize-instance :after ((self fiscal-person) &rest arguments) (unless (getf arguments :object-id) (setf (object-id self) (or (fiscal-id self) (name self)))) self) ;;;--------------------------------------------------------------------- ;;; Invoice-Line ;;;--------------------------------------------------------------------- (defclass invoice-line (pjb-object) ((description :initform "" :initarg :description :accessor description :type string :documentation "The description of this line.") (currency :initform (find-currency :eur) :initarg :currency :accessor currency :type symbol :documentation "The currency of this line.") (amount-ht :initform (amount-zero *default-currency*) :initarg :amount-ht :accessor amount-ht :type amount :documentation "The amount excluding the taxes of this line.") (vat-rate :initform 0/100 :initarg :vat-rate :accessor vat-rate :type rational :documentation "The rate of VAT for this line (0.00 <= vat-rate <= 0.50).") (amount-vat :initform (amount-zero *default-currency*) :initarg :amount-vat :accessor amount-vat :type amount :documentation "The amount of VAT for this line. ( = amount-ht * (1+vat-rate) )") (amount-ttc :initform (amount-zero *default-currency*) :initarg :amount-ttc :accessor amount-ttc :type amount :documentation "The amount including the taxes of this line.")) (:documentation "An Invoice Line.")) ;;;--------------------------------------------------------------------- ;;; INVOICE ;;;--------------------------------------------------------------------- (defclass invoice (pjb-object) ((date :initform nil :initarg :date :accessor date :type (or null string) :documentation "'YYYY-MM-DD' The date of the invoice.") (issuer-fiscal-id :initform nil :initarg :issuer-fiscal-id :accessor issuer-fiscal-id :type (or null string) :documentation "The fiscal ID of the issuer of this invoice.") (invoice-number :initform nil :initarg :invoice-number :accessor invoice-number :type (or null string) :documentation "The invoice number.") (payer-fiscal-id :initform nil :initarg :payer-fiscal-id :accessor payer-fiscal-id :type (or null string) :documentation "The fiscal ID of the payer of this invoice.") (title :initform "" :initarg :title :accessor title :type (or null string) :documentation "The title of this invoice.") (currency :initform (find-currency :eur) :initarg :currency :accessor currency :type symbol :documentation "The currency of this invoice.") (lines :initform nil :accessor lines :type list :documentation "(list of Invoice-Line) The line items of this invoice.") (total-ht :initform (amount-zero *default-currency*) :accessor total-ht :type amount :documentation "The total excluding taxes of this invoice.") (total-vat :initform (amount-zero *default-currency*) :accessor total-vat :type amount :documentation "The total of VAT.") (total-ttc :initform (amount-zero *default-currency*) :accessor total-ttc :type amount :documentation "The total including taxes of this invoice.") ) (:documentation "An invoice, either outgoing or incoming. The amounts of the invoice may be negative when it's a refund.")) (defmethod initialize-instance :after ((self invoice) &rest arguments) (unless (getf arguments :object-id) (setf (object-id self) (concatenate 'string (issuer-fiscal-id self) ":" (invoice-number self)))) self) ;;;--------------------------------------------------------------------- ;;; INVOICE-SET ;;;--------------------------------------------------------------------- (defclass invoice-set (pjb-object) ((fiscal-id :initform nil :initarg :fiscal-id :accessor fiscal-id :type (or null string) :documentation "The fiscal id of the owner of this invoice set.") (fisc-fiscal-ids :initform nil :initarg :fisc-fiscal-ids :accessor fisc-fiscal-ids :type list :documentation "(list of string) List of fiscal-id of fisc entity. An invoice issued by on of these entities is actually a tax.") (persons :initform nil :initarg :persons :accessor persons :type list :documentation "The list of known Fiscal-Person.") (invoices :initform nil :initarg :invoices :accessor invoices :type list :documentation "The list of known Invoices.") ) (:documentation "This class gather all the data sets about invoices and fiscal persons.") ) ;;INVOICE-SET ;;;--------------------------------------------------------------------- ;;; INVOICE-LINE ;;;--------------------------------------------------------------------- ;; check = ( a-ttc | a-ht ) & ( a-vat | vat-rate ) ;; error = ~check | ( ~a-ttc & ~a-ht ) | ( ~a-vat & ~vat-rate ) ) ;; ;; (insert ;; (carnot '( a-ttc a-ht a-vat vat-rate check) ;; '((check . (lambda (a-ttc a-ht a-vat vat-rate check) ;; (and (or a-ttc a-ht) (or a-vat vat-rate)) ;; )) ;; (error . (lambda (a-ttc a-ht a-vat vat-rate check) ;; (or (not check) ;; (and (not a-ttc) (not a-ht)) ;; (and (not a-vat) (not vat-rate))) ))))) ;; ;; +-------+------+-------+----------+-------+-------+-------+ ;; | a-ttc | a-ht | a-vat | vat-rate | check | check | error | ;; +-------+------+-------+----------+-------+-------+-------+ ;; | OUI | OUI | OUI | OUI | OUI | X | . | ;; | OUI | OUI | OUI | OUI | NON | X | X | ;; | OUI | OUI | OUI | NON | OUI | X | . | ;; | OUI | OUI | OUI | NON | NON | X | X | ;; | OUI | OUI | NON | OUI | OUI | X | . | ;; | OUI | OUI | NON | OUI | NON | X | X | ;; | OUI | OUI | NON | NON | OUI | . | X | ;; | OUI | OUI | NON | NON | NON | . | X | ;; | OUI | NON | OUI | OUI | OUI | X | . | ;; | OUI | NON | OUI | OUI | NON | X | X | ;; | OUI | NON | OUI | NON | OUI | X | . | ;; | OUI | NON | OUI | NON | NON | X | X | ;; | OUI | NON | NON | OUI | OUI | X | . | ;; | OUI | NON | NON | OUI | NON | X | X | ;; | OUI | NON | NON | NON | OUI | . | X | ;; | OUI | NON | NON | NON | NON | . | X | ;; | NON | OUI | OUI | OUI | OUI | X | . | ;; | NON | OUI | OUI | OUI | NON | X | X | ;; | NON | OUI | OUI | NON | OUI | X | . | ;; | NON | OUI | OUI | NON | NON | X | X | ;; | NON | OUI | NON | OUI | OUI | X | . | ;; | NON | OUI | NON | OUI | NON | X | X | ;; | NON | OUI | NON | NON | OUI | . | X | ;; | NON | OUI | NON | NON | NON | . | X | ;; | NON | NON | OUI | OUI | OUI | . | X | ;; | NON | NON | OUI | OUI | NON | . | X | ;; | NON | NON | OUI | NON | OUI | . | X | ;; | NON | NON | OUI | NON | NON | . | X | ;; | NON | NON | NON | OUI | OUI | . | X | ;; | NON | NON | NON | OUI | NON | . | X | ;; | NON | NON | NON | NON | OUI | . | X | ;; | NON | NON | NON | NON | NON | . | X | ;; +-------+------+-------+----------+-------+-------+-------+ (defmethod initialize-instance ((self invoice-line) &key object-id description currency amount-ht vat-rate amount-vat amount-ttc &allow-other-keys) " DO: Checks that the values for the fields are within limits. " (when (or (and (not amount-ttc) (not amount-ht)) (and (not amount-vat) (not vat-rate))) (error "Not enought amount data defined for this line ~S." self)) (unless amount-ttc (setf amount-ttc (cond (amount-vat (+ amount-ht amount-vat)) (vat-rate (* amount-ht (+ 1 vat-rate))) ;; last case should not occur. (t (if (zerop vat-rate) amount-ht (/ (* amount-vat (+ 1 vat-rate)) vat-rate)))))) (unless amount-ht (setf amount-ht (cond (amount-vat (- amount-ttc amount-vat)) (vat-rate (/ amount-ttc (+ 1 vat-rate))) ;; last case should not occur. (t (if (zerop vat-rate) amount-ttc (/ amount-vat vat-rate)))))) (unless amount-vat (setf amount-vat (- amount-ttc amount-ht))) (unless vat-rate (setf vat-rate (if (zerop (amount-magnitude amount-ht)) 0 (/ (round (* (/ (amount-magnitude amount-vat) (amount-magnitude amount-ht)) 100)) 100)))) (when (null currency) (setf currency (currency amount-ttc))) ;; (check-vat amount-ttc amount-ht amount-vat vat-rate) (call-next-method self :object-id object-id :description description :currency currency :amount-ht amount-ht :vat-rate vat-rate :amount-vat amount-vat :amount-ttc amount-ttc)) ;;;--------------------------------------------------------------------- ;;; INVOICE ;;;--------------------------------------------------------------------- (defmethod compute-totals ((self invoice)) " DO: Compute the totals. " (let* ((th (amount-zero (currency self))) (tv th) (tt th)) (dolist (line (lines self)) (setf th (+ th (amount-ht line)) tv (+ tv (amount-vat line)) tt (+ tt (amount-ttc line)))) (setf (total-ht self) th (total-vat self) tv (total-ttc self) tt))) ;;COMPUTE-TOTALS (defmethod vat-rate ((self invoice)) " RETURN: A computed VAT rate for this invoice. " (if (zerop (amount-magnitude (total-ht self))) 0 (/ (round (* 100 (/ (amount-magnitude (total-vat self)) (amount-magnitude (total-ht self))))) 100))) (defmethod add-line ((self invoice) (line invoice-line)) " PRE: (eq (find-currency (currency self))(find-currency (currency line))) DO: Add the line. " (assert (eq (find-currency (currency self)) (find-currency (currency line)))) (setf (lines self) (append (lines self) (list line))) (compute-totals self)) ;;ADD-LINE (defmethod is-refund ((self invoice)) " RETURN: Whether this invoice is a refund invoice. " (negativep (total-ttc self))) ;;IS-REFUND (deftranslation *invoice-strings* "Phone:" :en :idem :fr "Téléphone :" :es "Teléfono :") (deftranslation *invoice-strings* "Fax:" :en :idem :fr "Télécopie :" :es "Telécopia :") (deftranslation *invoice-strings* "Email:" :en :idem :fr "Couriel :" :es "Email :") (deftranslation *invoice-strings* "VAT Immatriculation:" :en :idem :fr "TVA Intracommunautaire :" :es "Imatriculación IVA :") (deftranslation *invoice-strings* "INVOICE" :en :idem :fr "FACTURE" :es "FACTURA") (deftranslation *invoice-strings* "Date:" :en :idem :fr "Date :" :es "Fecha :") (deftranslation *invoice-strings* "Invoice no.:" :en :idem :fr "Facture nº :" :es "Nº de factura :") (deftranslation *invoice-strings* "Billing address:" :en :idem :fr "Adresse de facturation :" :es "Dirección de factura :") (deftranslation *invoice-strings* "Description" :en :idem :fr "Description" :es "Descripción") (deftranslation *invoice-strings* "Price" :en :idem :fr "Prix" :es "Precio") (deftranslation *invoice-strings* "Total" :en :idem :fr "Total HT" :es "Base imponible") (deftranslation *invoice-strings* "VAT ~5,1F %" :en :idem :fr "TVA ~5,1F %" :es "IVA ~5,1F %") (deftranslation *invoice-strings* "IRPF ~5,1F %" :en "" :fr "" :es :idem) (deftranslation *invoice-strings* "Total VAT Incl." :en :idem :fr "Total TTC" :es "Total factura") (deftranslation *invoice-strings* "PAYMENT-METHOD" :en "Method of Payment: Bank Transfer Please make your payment using the details below, before ~A." :fr "Mode de règlement : À régler par virement bancaire au compte suivant, avant le ~A." :es "Forma de pago : Transferencia bancaria a la cuenta siguiente, antes del ~A.") ;;*INVOICE-STRINGS* (deftranslation *invoice-strings* "Payment Bank" :en :idem :fr "Banque destinataire" :es "Banco") (deftranslation *invoice-strings* "Branch Name" :en :idem :fr "Agence" :es "Oficina") (deftranslation *invoice-strings* "Account Number (IBAN)" :en :idem :fr "Numéro de compte (IBAN)" :es "Número de cuenta (IBAN)") (deftranslation *invoice-strings* "Beneficiary" :en :idem :fr "Bénéficiaire" :es "Beneficiario") (deftranslation *invoice-strings* "SWIFT Code" :en :idem :fr "Code SWIFT" :es "Código SWIFT") (deftranslation *invoice-strings* "Currency change" :en :idem :fr "Change devises" :es "Cambio devisas") (defmacro longest-localized-length (table language fields) `(loop for fname in ,fields maximize (length (localize ,table ,language fname)) into increment finally (return increment))) ;;LONGEST-LOCALIZED-LENGTH (defparameter +line-chars+ (coerce #(#\LINEFEED #\RETURN #\NEWLINE #\PAGE) 'string) "A string containing the new-line characters.") (defun split-lines (text &key delete-empty-lines) " DELETE-EMPTY-LINES: When true, lines that are stripped empty are removed. RETURN: A list of stripped and splitted lines from the TEXT. " (let ((lines (split-string text +line-chars+))) (map-into lines (lambda (line) (string-trim " " line)) lines) (if delete-empty-lines (delete "" lines :test (function string=)) lines))) ;;SPLIT-LINES (defun align-following-lines (text left-margin) " DO: Format the TEXT inserting LEFT-MARGIN spaces before each line but the first. " (format nil (format nil "~~{~~A~~^~~%~VA~~}" left-margin "") (split-lines text))) ;;ALIGN-FOLLOWING-LINES (defun print-person-address (title left-margin person &key (language :fr) (stream t)) " DO: Insert into the current buffer at the current point the address and phone, fax and email of the given person, prefixed by the title and with a left-margin of `left-margin' characters. If the length of the title is greater than the `left-margin' then the length of the title is used instead. LANGUAGE: The default language is French (:FR), :EN and :ES are also available for English and Spanish. " (unless title (setf title "")) (when (< left-margin (length title)) (setf left-margin (length title))) ;; title / name (format stream "~A~A~%" (string-pad title left-margin) (name person)) ;; address (format stream (format nil "~~{~VA~~A~~%~~}" left-margin "") (split-lines (address person) :delete-empty-lines t)) ;; other fields (let* ((fields '("Phone:" "Fax:" "Email:" "VAT Immatriculation:")) (slots '(phone fax email fiscal-id)) (increment (loop for fname in fields for slot in slots when (slot-value person slot) maximize (length (localize *invoice-strings* language fname)) into increment finally (return increment)))) (loop for fname in fields for slot in slots when (slot-value person slot) do (format stream "~VA~A ~A~%" left-margin "" (string-pad (localize *invoice-strings* language fname) increment) (slot-value person slot))))) ;;PRINT-PERSON-ADDRESS (defun show-tva (montant-ht &key (stream t) (vat-rate 16/100 vat-rate-p) (irpf nil irpf-p) (language :es) (alt-language :es)) "Affiche le montant HT donné, la TVA, le montant TTC. En option le taux de TVA. La facture est dans la devise du montant. Une ou deux langues peuvent aussi être indiquées (:es, :fr, :en). Une option :irpf ou :no-irpf peut être indiquée pour forcer la déduction IRPF, sinon elle est appliquée par défaut uniquement dans le cas où le taux de TVA est 16% et la langue est 'es (sans langue secondaire) et la currency :EUR. (show-tva #978m750.00 :vat-rate 16/100 :language :en :alt-language :es) donne : ---------------------------------------------------- ----------------- (Base imponible ) Total : 750.00 EUR (IVA 16.0 % ) VAT 16.0 % : + 120.00 EUR (Total factura ) Total VAT Incl. : = 870.00 EUR ---------------------------------------------------- ----------------- " (let* ((line-form " ~52A ~17A~%") (desc-line (make-string 52 :initial-element (character "-"))) (pric-line (make-string 17 :initial-element (character "-"))) (base-lab-gau "") (tvat-lab-gau "") (irpf-lab-gau "") (tota-lab-gau "") (base-lab-dro) (tvat-lab-dro) (irpf-lab-dro) (tota-lab-dro) (taux-tva nil) (taux-tva-present nil) ;; empeze la actividad el 2000/07 entonces desde el 2003/07 es -18%. (taux-irpf (if (date-after (calendar-current-date) (make-date :year 2003 :month 6 :day 30)) -18/100 -9/100)) (show-irpf nil) (force-show-irpf nil) (montant-tva) (montant-irpf) (montant-ttc) (lang-pri nil) (lang-sec nil)) (when irpf-p (if irpf (setf show-irpf t force-show-irpf t) (setf show-irpf nil force-show-irpf t))) (setf lang-pri language lang-sec alt-language) (setf taux-tva vat-rate) (if vat-rate-p (setf taux-tva-present t) (setf taux-tva 0/100 taux-tva-present nil)) (when (equal lang-pri lang-sec) (setf lang-sec nil)) (if (and (null lang-sec) (not taux-tva-present) (string-equal lang-pri :es)) (setf taux-tva 16/100)) (unless force-show-irpf (setf show-irpf (and (eq (find-currency :eur) (currency montant-ht)) (string-equal lang-pri :es) (null lang-sec) (= taux-tva 16/100) ;; (equal (fiscal-id *invoice-set*) ;; (issuer-fiscal-id self)) ))) (setf montant-tva (* montant-ht taux-tva)) (setf montant-irpf (if show-irpf (* montant-ht taux-irpf) (amount-zero (currency montant-ht)))) (setf montant-ttc (+ montant-ht montant-tva montant-irpf)) (setf base-lab-dro (format nil "~16@A :" (localize *invoice-strings* lang-pri "Total"))) (setf tvat-lab-dro (format nil "~16@A :" (format nil (localize *invoice-strings* lang-pri "VAT ~5,1F %") (* 100 taux-tva)))) (setf irpf-lab-dro (format nil "~16@A :" (format nil (localize *invoice-strings* lang-pri "IRPF ~5,1F %") (* 100 taux-irpf)))) (setf tota-lab-dro (format nil "~16@A :" (localize *invoice-strings* lang-pri "Total VAT Incl."))) (when lang-sec (setf base-lab-gau (format nil "(~16@A) " (localize *invoice-strings* lang-sec "Total"))) (setf tvat-lab-gau (format nil "(~16@A) " (format nil (localize *invoice-strings* lang-sec "VAT ~5,1F %") (* 100 taux-tva)))) (setf irpf-lab-gau (format nil "(~16@A) " (format nil (localize *invoice-strings* lang-sec "IRPF ~5,1F %") (* 100 taux-irpf)))) (setf tota-lab-gau (format nil "(~16@A) " (localize *invoice-strings* lang-sec "Total VAT Incl.")))) (format stream "~%") (format stream line-form desc-line pric-line) (format stream line-form (concatenate 'string base-lab-gau base-lab-dro) (format nil " ~16@A" montant-ht)) (format stream line-form (concatenate 'string tvat-lab-gau tvat-lab-dro) (format nil "+~16@A" montant-tva)) (when show-irpf (format stream line-form (concatenate 'string irpf-lab-gau irpf-lab-dro) (format nil "-~16@A" (- montant-irpf)))) (format stream line-form (concatenate 'string tota-lab-gau tota-lab-dro) (format nil "=~16@A" montant-ttc)) (format stream line-form desc-line pric-line))) ;;SHOW-TVA (defun clean-title-for-file-name (title-string) " RETURN: A string containing the first word of title-string as plain ASCII. DO: Remove accents from the returned word. " ;;(STRING-REMOVE-ACCENTS (string-downcase (subseq title-string 0 (position-if-not (function alphanumericp) title-string)))) ;;CLEAN-TITLE-FOR-FILE-NAME (defmethod generate ((self invoice) &key (stream t) (verbose nil) (language :es language-p)) " DO: Generate this invoice into a file in the directory *INVOICE-DIRECTORY-PATH*. RETURN: The path to the file generated. " (let* ((payer (get-person-with-fiscal-id *invoice-set* (payer-fiscal-id self))) (issuer (get-person-with-fiscal-id *invoice-set* (issuer-fiscal-id self)))) (when verbose (format *trace-output* "Generating ~A ~A ~A ~A~%" (class-name (class-of self)) (date self) issuer (invoice-number self))) (unless language-p (setf language (or (language payer) :es))) (print-person-address "" 1 issuer :language language :stream stream) (format stream " ~%") (let* ((title (localize *invoice-strings* language "INVOICE")) (width (+ 8 (length title))) (title-b (concatenate 'string "|" (string-pad title width :justification :center) "|")) (line-b (concatenate 'string "+" (make-string width :initial-element (character "-")) "+"))) (format stream " ~A~%" (string-pad line-b 72 :justification :center)) (format stream " ~A~%" (string-pad title-b 72 :justification :center)) (format stream " ~A~%" (string-pad line-b 72 :justification :center))) (format stream " ~%") (let ((increment (longest-localized-length *invoice-strings* language '("Date:" "Invoice no.:" "Billing address:")))) (format stream " ~A ~A~%" (string-pad (localize *invoice-strings* language "Date:") increment) (date-format (date-to-universal-time (date self)) :language language)) (format stream " ~%") (format stream " ~A ~A~%" (string-pad (localize *invoice-strings* language "Invoice no.:") increment) (invoice-number self)) (format stream " ~%") (print-person-address (concatenate 'string " " (localize *invoice-strings* language "Billing address:")) (+ 2 increment) payer :language language) (format stream " ~%")) (let ((line-form " ~52@A ~17@A~%") (desc-line (make-string 52 :initial-element (character "-"))) (pric-line (make-string 17 :initial-element (character "-")))) (format stream line-form desc-line pric-line) (format stream line-form (localize *invoice-strings* language "Description") (localize *invoice-strings* language "Price")) (format stream line-form desc-line pric-line) (dolist (invo-line (lines self)) (let* ((desc (split-lines (description invo-line))) (last-length (length (car (last desc))))) (format stream "~{~% ~A~}" desc) (if (<= last-length 55) (format stream "~VA ~16@A" (- 55 last-length) "" (amount-ht invo-line)) (format stream "~% ~52@A ~16@A" "" (amount-ht invo-line))))) (format stream " ~%")) ;;let (show-tva (total-ht self) :language language :alt-language :es) (format stream " ~%") (let ((bankref (bank-reference issuer))) (when bankref (format stream "~{ ~A~%~}" (split-lines (format nil (localize *invoice-strings* language "PAYMENT-METHOD") (date-format (+ (* 30 +seconds-in-a-day+) (date-to-universal-time (date self))) :language language)))) (format stream " ~%") (let* ((fields '("Payment Bank" "" "Branch Name" "Account Number (IBAN)" "Beneficiary" "SWIFT Code")) (slots '(bank-name bank-address branch-name account-number beneficiary-name swift-code)) (increment (longest-localized-length *invoice-strings* language fields))) (loop for fname in fields for slot in slots when (slot-value bankref slot) do (format stream " ~A~A : ~A~%" (string-pad "" 8) (string-pad (localize *invoice-strings* language fname) increment) (align-following-lines (slot-value bankref slot) (+ increment 10)))) ))) (format stream " ~%") (format stream " ~%"))) ;;GENERATE (defmethod write-invoice-file ((self invoice) &key (language :en language-p)) (let* ((payer (get-person-with-fiscal-id *invoice-set* (payer-fiscal-id self))) (file-path (make-pathname :directory *invoice-directory-path* :name (format nil "~A-~A-~A" (delete (character "/") (invoice-number self)) (clean-title-for-file-name (object-id payer)) (clean-title-for-file-name (title self))) :type "txt"))) (unless language-p (setf language (or (language payer) :es))) (with-open-file (stream file-path :direction :output :if-does-not-exist :create :if-exists :supersede) (generate self :stream stream :language language)) file-path)) ;;WRITE-INVOICE-FILE ;;;--------------------------------------------------------------------- ;;; INVOICE-SET ;;;--------------------------------------------------------------------- (defmethod get-person-with-fiscal-id ((self invoice-set) fiscal-id) (car (member fiscal-id (persons self) :test (function string-equal) :key (function fiscal-id)))) (defmethod add-person ((self invoice-set) (person fiscal-person) &optional fisc) (let ((old (get-person-with-fiscal-id self (fiscal-id person)))) (if old (substitute person old (persons self) :count 1) (push person (persons self)))) (when (and fisc (not (member (fiscal-id person) (fisc-fiscal-ids self) :test (function string-equal)))) (push (fiscal-id person) (fisc-fiscal-ids self)))) ;;ADD-PERSON (defmethod get-invoice-with-issuer-and-number ((self invoice-set) issuer-fiscal-id invoice-number) (find-if (lambda (i) (and (equal issuer-fiscal-id (issuer-fiscal-id i)) (equal invoice-number (invoice-number i)))) (invoices self))) ;;GET-INVOICE-WITH-ISSUER-AND-NUMBER (defmethod add-invoice ((self invoice-set) (invoice invoice)) (let ((old (get-invoice-with-issuer-and-number self (issuer-fiscal-id invoice) (invoice-number invoice)))) (if old (substitute invoice old (invoices self) :count 1) (push invoice (invoices self))))) ;;ADD-INVOICE ;;;--------------------------------------------------------------------- ;;; MOVEMENT ;;;--------------------------------------------------------------------- (defclass movement (pjb-object) ((date :initform nil :initarg :date :accessor date :type (or null string) :documentation "'YYYY-MM-DD' Date of the movement.") (amount-ttc :initform (amount-zero *default-currency*) :initarg :amount-ttc :accessor amount-ttc :type amount :documentation "(number) The amount paid (including taxes).") (amount-vat :initform 0/100 :initarg :amount-vat :accessor amount-vat :type rational :documentation "(number) The VAT of the movement.") (description :initform "" :initarg :description :accessor description :type string :documentation "(string) A description of the movement.") (kind :initform nil :initarg :kind :accessor kind :type (or null symbol) :documentation "(symbol) A kind of movement, for tax reporting purpose. PRESTACION-NACIONAL, PRESTACION-INTRACOMUNITARIA, IMPUESTO, INVERSION, GASTO-CORRIENTE, ADQUISICION-INTRACOMUNITARIA") (invoice-fiscal-id :initform nil :initarg :invoice-fiscal-id :accessor invoice-fiscal-id :type (or null string) :documentation "The fiscal id of the common issuer of the following invoices related to this movement.") (invoice-numbers :initform nil :initarg :invoice-numbers :accessor invoice-numbers :type list :documentation "(list of string) The list of invoice numbers related to this entry. Note that one journal entry may relate to several invoices (grouped payment) and one invoice may relate to several movements (part payments, or corrections.") ) (:documentation "An entry in the journal. A movement with a positive amount is a credit, while a movement with a negative amount is a debit.")) ;;MOVEMENT (defmethod initialize-instance ((self movement) &key amount-ttc amount-ht invoice-fiscal-id &allow-other-keys) " DOES: Checks that the values for the fields are within limits. " (declare (ignorable self)) (when *max-movement-amount* (when amount-ttc (when (< *max-movement-amount* (abs amount-ttc)) (error "amount-ttc too big ~S." amount-ttc))) (when amount-ht (if (< *max-movement-amount* (abs amount-ht)) (error "amount-ht too big ~S." amount-ht)))) (when invoice-fiscal-id (unless (get-person-with-fiscal-id *invoice-set* invoice-fiscal-id) (warn "Unknown person (fiscal-id=~S)." invoice-fiscal-id))) (call-next-method)) ;;INITIALIZE-INSTANCE (defmethod amount-ht ((self movement)) (- (amount-ttc self) (amount-vat self))) (defparameter *movement-kinds* '(:prestacion-nacional :prestacion-intracomunitaria :impuesto :inversion :gasto-corriente :adquisicion-intracomunitaria)) ;;*MOVEMENT-KINDS* (defun make-movement-from-invoice (invoice) " RETURN: A new instance of MOVEMENT filled with data from invoice. " (let (kind amount-sign fiscal-id) (cond ((member (issuer-fiscal-id invoice) (fisc-fiscal-ids *invoice-set*) :test (function string-equal)) (setf kind :impuesto amount-sign -1 fiscal-id (issuer-fiscal-id invoice))) ((equalp (issuer-fiscal-id invoice) (fiscal-id *invoice-set*)) (setf kind (if (zerop (total-vat invoice)) :prestacion-intracomunitaria :prestacion-nacional) amount-sign 1 fiscal-id (payer-fiscal-id invoice))) (t (setf kind :gasto-corriente amount-sign -1 fiscal-id (issuer-fiscal-id invoice)))) (make-instance 'movement :date (date invoice) :amount-ttc (* (total-ttc invoice) amount-sign) :amount-vat (* (total-vat invoice) amount-sign) :description (title invoice) :kind kind :invoice-fiscal-id fiscal-id :invoice-numbers (list (invoice-number invoice))))) ;;MAKE-MOVEMENT-FROM-INVOICE (define-condition movement-error (simple-error) ((date :accessor movement-error-date :initarg :date) (amount-ttc :accessor movement-error-amount-ttc :initarg :amount-ttc) (vat-rate :accessor movement-error-vat-rate :initarg :vat-rate) (nif :accessor movement-error-nif :initarg :nif) (fac-l :accessor movement-error-fac-l :initarg :fac-l) (description :accessor movement-error-description :initarg :description) (kind :accessor movement-error-kind :initarg :kind))) (defun make-movement (date amount-ttc vat-rate nif fac-l description kind) " RETURN: A new instance of MOVEMENT filled with the given data ." (macrolet ((err (ctrl &rest args) `(error 'movement-error :format-control ,ctrl :format-arguments (list ,@args) :date date :amount-ttc amount-ttc :vat-rate vat-rate :nif nif :fac-l fac-l :description description :kind kind))) (unless (member kind *movement-kinds*) (err "Invalid kind ~A." kind)) (when (< vat-rate -2) (err "VAT-RATE must always be >= 0.")) (unless (eq kind :prestacion-intracomunitaria) (when (eq kind :prestacion-nacional) (unless (negativep amount-ttc) (err "AMOUNT-TTC must be > 0 for an entry of kind ~A." kind)))) (cond ((eq kind :prestacion-nacional) (when (<= vat-rate 0) (err "VAT-RATE must be > 0.00 for an entry of kind ~A." kind))) ((member kind '(:prestacion-intracomunitaria :impuesto)) (if (< 0 vat-rate) (err "VAT-RATE must be = 0 for an entry of kind ~A." kind)))) (make-instance 'movement :date date :amount-ttc amount-ttc :amount-vat (/ (* amount-ttc vat-rate) (+ 1 vat-rate)) :description description :kind kind :invoice-fiscal-id nif :invoice-numbers fac-l))) (defmethod is-credit ((self movement)) " RETURN: Whether the SELF is a credit movement. " (positivep (amount-ht self))) ;;IS-CREDIT (defmethod vat-rate ((self movement)) " RETURN: A computed VAT rate for this movement. " (if (zerop (amount-magnitude (amount-ht self))) 0 (/ (round (* 100 (/ (amount-magnitude (amount-vat self)) (amount-magnitude (amount-ht self))))) 100))) (defmethod credit-ht ((self movement)) (if (is-credit self) (amount-ht self) (amount-zero (currency (amount-ht self))))) (defmethod credit-vat ((self movement)) (if (is-credit self) (amount-vat self) (amount-zero (currency (amount-vat self))))) (defmethod debit-ht ((self movement)) (if (is-credit self) (amount-zero (currency (amount-ht self))) (- (amount-ht self)))) (defmethod debit-vat ((self movement)) (if (is-credit self) (amount-zero (currency (amount-vat self))) (- (amount-vat self)))) (defmethod debit-vat-inversion ((self movement)) (if (eq :inversion (kind self)) (debit-vat self) (amount-zero (currency (debit-vat self))))) (defmethod debit-vat-corriente ((self movement)) (if (eq :gasto-corriente (kind self)) (debit-vat self) (amount-zero (currency (debit-vat self))))) (defmethod invoices ((self movement)) " RETURN: A list of INVOICE instances related to this entry. " (let ((fiscal-id (if (and (is-credit self) (not (equal (kind self) :gasto-corriente))) (fiscal-id *invoice-set*) (invoice-fiscal-id self)))) (remove nil (mapcar (lambda (number) (get-invoice-with-issuer-and-number *invoice-set* fiscal-id number)) (invoice-numbers self))))) ;;INVOICES (defun trim-justify-and-split-text (text width) " DOES: Trim spaces on each line. justify each paragraph. RETURN: The justified text. " (let ((lines (split-lines text)) (paragraphs '()) (current-paragraph '())) (dolist (line lines ; group the paragraphs. (when current-paragraph (push (apply (function concatenate) 'string (nreverse current-paragraph)) paragraphs))) (if (string= line "") (when current-paragraph (push (apply (function concatenate) 'string (nreverse current-paragraph)) paragraphs)) (progn (push " " current-paragraph) (push line current-paragraph)))) (or (mapcan (lambda (para) (split-lines (string-justify-left para width 0))) (nreverse paragraphs)) (list " ")))) ;;TRIM-JUSTIFY-AND-SPLIT-TEXT (defmethod generate ((self movement) &key (stream t) (verbose nil) (language :en)) " DOES: format and insert this entry. " (let ((id (invoice-fiscal-id self)) person (name "") name-l (movement-sign (if (is-credit self) 1 -1)) (invoices-sign 1)) (when verbose (format *trace-output* "Generating ~A ~A ~A~%" (class-name (class-of self)) (date self) (amount-ttc self))) ;; first line: (if id (progn (setf person (get-person-with-fiscal-id *invoice-set* id)) (when person (setf name (name person)))) (setf id "")) (setf name-l (trim-justify-and-split-text name 38)) ;; === SEN FECHA IDENTIFICATION NOMBRE ============================= (format stream "~3A ~10A ~23@A ~A~%" (cond ((is-credit self) "ING") ((eq :impuesto (kind self)) "IMP") (t "GAS")) (date self) id (car name-l)) ;; === OPTIONAL NEXT LINES ========================================= ;; NOMBRE (continuación) (dolist (name (cdr name-l)) (format stream "~38A ~A~%" "" name)) ;; === INVOICE LINES =============================================== ;; IMPORTE IVA% +IVA TOTAL NUMERO FACTURA o DESCRIPCION ;; INVOICE TITLE (let* ((zero (amount-zero (currency (amount-ht self)))) (t-ht zero) (t-vat zero) (t-ttc zero)) (let ((t-ttc zero)) ; Let's find the invoices-sign (dolist (invoice (invoices self)) (setf t-ttc (+ t-ttc (total-ttc invoice)))) (setf invoices-sign (* movement-sign (if (negativep t-ttc) -1 1)))) (dolist (invoice (invoices self)) ; Let's print the invoices (let* ((title-l (trim-justify-and-split-text (title invoice) 38)) (i-ht (total-ht invoice)) (i-vat (total-vat invoice)) (i-ttc (total-ttc invoice))) (setf t-ht (+ t-ht i-ht) t-vat (+ t-vat i-vat) t-ttc (+ t-ttc i-ttc)) (format stream " ~2,,9$ ~4,1F% ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude (* i-ht invoices-sign)) (* 100 (vat-rate invoice)) (amount-magnitude (* i-vat invoices-sign)) (amount-magnitude (* i-ttc invoices-sign)) (invoice-number invoice)) (dolist (title title-l) (format stream "~38A ~A~%" "" title)))) ;; === DIFFERNCE LINE ============================================ ;; AMOUNT-HT AMOUNT-VAT AMOUNT-TTC Diferencia (unless (and (zerop t-ht) (zerop t-vat) (zerop t-ttc)) ;; Invoices, let's see if there's a difference. (handler-case (unless (= (amount-ttc self) (* t-ttc invoices-sign)) (let* ((diff-ht (- (amount-ht self) (* t-ht invoices-sign))) (diff-vat (- (amount-vat self) (* t-vat invoices-sign))) (diff-ttc (- (amount-ttc self) (* t-ttc invoices-sign)))) (format stream " ~2,,9$ ~5A ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude diff-ht) "" (amount-magnitude diff-vat) (amount-magnitude diff-ttc) "Diferencia"))) (multi-currency-error () (let ((cambio (if (zerop t-ttc) 0 (/ (amount-ttc self) (* t-ttc invoices-sign))))) (format stream " ~9A ~5A ~8A ~2,,9$ ~A ~A -> ~A~%" "" "" "" cambio (localize *invoice-strings* language "Currency change") (currency-alphabetic-code (currency t-ttc)) (currency-alphabetic-code (currency (amount-ttc self))))))) (format stream " --------- ----- -------- ---------~%"))) ;; === TOTAL ENTRY LINES =========================================== (let* ((desc-l (trim-justify-and-split-text (description self) 38)) (desc (pop desc-l))) (format stream " ~2,,9$ ~4,1F% ~2,,8$ ~2,,9$ ~A~%" (amount-magnitude (amount-ht self)) (* 100 (vat-rate self)) (amount-magnitude (amount-vat self)) (amount-magnitude (amount-ttc self)) desc) (dolist (desc desc-l) (format stream "~38A ~A~%" "" desc)))) (format stream "--- ---------- ----------------------- ~ ----------------------------------------~%")) ;;GENERATE ;;;--------------------------------------------------------------------- ;;; JOURNAL-ENTRY ;;;--------------------------------------------------------------------- ;; (defstruct (journal-entry (:type list)) ;; (date (calendar-current-date) :type date) ;; (amount-ht (amount-zero *default-currency*) :type amount) ;; (vat-rate 16/100 :type ratio) ;; (description "Default journal entry" :type string) ;; (kind :PRESTACION-NACIONAL :type keyword) ;; (nif "s/n" :type string) ;; (invoices '() :type list));;journal-entry ;; ;; (defmethod date ((self journal-entry)) (journal-entry-date self)) ;; (defmethod amount-ht ((self journal-entry)) (journal-entry-amount-ht self)) ;; (defmethod vat-rate ((self journal-entry)) (journal-entry-vat-rate self)) ;; (defmethod description ((self journal-entry)) (journal-entry-description self)) ;; (defmethod kind ((self journal-entry)) (journal-entry-kind self)) ;; (defmethod nif ((self journal-entry)) (journal-entry-nif self)) ;; (defmethod invoices ((self journal-entry)) (journal-entry-invoices self)) ;; ;; ;; (defmethod initialize-instance ((self journal-entry) ;; &key AMOUNT-HT VAT-RATE KIND &allow-other-keys) ;; (unless (MEMBER KIND ;; '(:PRESTACION-NACIONAL ;; :PRESTACION-INTRACOMUNITARIA ;; :IMPUESTO ;; :INVERSION :GASTO-CORRIENTE ;; :ADQUISICION-INTRACOMUNITARIA)) ;; (ERROR "Invalid kind ~A." KIND)) ;; (when (negativep VAT-RATE) ;; (ERROR "VAT-RATE must always be >= 0.00.")) ;; (unless (EQ KIND :PRESTACION-INTRACOMUNITARIA) ;; (unless (MEMBER KIND '(:PRESTACION-NACIONAL)) ;; ;; (when (>= 0.00 AMOUNT-HT) ;; (ERROR "AMOUNT-HT must be > 0.00 for an entry of kind ~A." KIND)))) ;; (COND ;; ((EQ KIND :PRESTACION-NACIONAL) ;; (when (negativep VAT-RATE) ;; (ERROR "VAT-RATE must be > 0.00 for an entry of kind ~A." KIND))) ;; ((MEMBER KIND '(:PRESTACION-INTRACOMUNITARIA :IMPUESTO)) ;; (when (positivep VAT-RATE) ;; (ERROR "VAT-RATE must be = 0.00 for an entry of kind ~A." KIND))) ;; (T ;; (IF (zerop VAT-RATE) ;; (ERROR "VAT-RATE must be > 0.00 for an entry of kind ~A." KIND)))) ;; ());;initialize-instance ;; ;; ;; (DEFMETHOD IS-CREDIT ((SELF JOURNAL-ENTRY)) ;; "RETURN: Whether the SELF is a credit." ;; (positivep (AMOUNT-HT SELF))) ;; ;; ;; (DEFMETHOD CREDIT-HT ((SELF JOURNAL-ENTRY)) ;; (IF (IS-CREDIT SELF) ;; (AMOUNT-HT SELF) ;; (amount-zero (currency (AMOUNT-HT SELF))))) ;; ;; ;; (DEFMETHOD CREDIT-VAT ((SELF JOURNAL-ENTRY)) ;; (* (CREDIT-HT SELF) (VAT-RATE SELF))) ;; ;; ;; (DEFMETHOD DEBIT-HT ((SELF JOURNAL-ENTRY)) ;; (IF (IS-CREDIT SELF) ;; (amount-zero (currency (AMOUNT-HT SELF))) ;; (- (AMOUNT-HT SELF)))) ;; ;; ;; (DEFMETHOD DEBIT-VAT ((SELF JOURNAL-ENTRY)) ;; (* (DEBIT-HT SELF) (VAT-RATE SELF))) ;; ;; ;; (DEFMETHOD DEBIT-VAT-INVERSION ((SELF JOURNAL-ENTRY)) ;; (IF (EQ :INVERSION (KIND SELF)) ;; (DEBIT-VAT SELF) ;; (amount-zero (currency (AMOUNT-HT SELF))))) ;; ;; ;; (DEFMETHOD DEBIT-VAT-CORRIENTE ((SELF JOURNAL-ENTRY)) ;; (IF (EQ :GASTO-CORRIENTE (KIND SELF)) ;; (DEBIT-VAT SELF) ;; (amount-zero (currency (AMOUNT-HT SELF))))) ;;;--------------------------------------------------------------------- ;;; JOURNAL ;;;--------------------------------------------------------------------- (defgeneric trimestre (journal) (:documentation "RETURN: The quarter of the journal (1 2 3 or 4).")) (defclass journal () ((sorted :initform nil :accessor sorted :type boolean :documentation "Indicates whether entries are sorted.") (entries :initform '() :initarg :entries :accessor entries :type list) (year :initform (date-year (calendar-current-date)) :initarg :year :accessor year :type (integer 1998 2070)) (trimestre :initform (1+ (truncate (1- (date-month (calendar-current-date))) 3)) :initarg :trimestre :accessor trimestre :type (member 1 2 3 4))) (:documentation "An account journal.")) (defmethod reset ((self journal)) " POST: (null (entries self)) " (setf (entries self) '() (sorted self) nil)) ;;RESET (defmethod add-entry ((self journal) (entry movement)) " DOES: Add the ENTRY into the journal. POST: (AND (MEMBER ENTRY (ENTRIES SELF)) (NOT (SORTED SELF))) " (push entry (entries self)) (setf (sorted self) nil)) ;;ADD-ENTRY (defmethod ensure-sorted ((self journal)) " POST: (sorted *journal*) " (unless (sorted self) (setf (entries self) (sort (entries self) (lambda (a b) (date-after (date b) (date a)))) (sorted self) t))) ;;ENSURE-SORTED (defmethod extract ((self journal) year trimestre) " RETURN: The entries of the journal corresponding to the given YEAR and TRIMESTRE. " (ensure-sorted self) (remove-if (lambda (entry) (not (date-in-year-trimestre (date entry) year trimestre))) (entries self))) ;;EXTRACT (defun journal-totals-of-entries (entries) "PRIVATE RETURN: a list containing the totals: credit-ht credit-vat debit-ht debit-vat-inversion debit-vat-corriente. " (if (null entries) (make-list 5 :initial-element (amount-zero *default-currency*)) (let* ((zero (amount-zero (currency (credit-ht (first entries))))) (credit-ht zero) (credit-vat zero) (debit-ht zero) (debit-vat-c zero) (debit-vat-i zero)) (mapcar (lambda (entry) (setf credit-ht (+ credit-ht (credit-ht entry)) credit-vat (+ credit-vat (credit-vat entry)) debit-ht (+ debit-ht (debit-ht entry)) debit-vat-c (+ debit-vat-c (debit-vat-corriente entry)) debit-vat-i (+ debit-vat-i (debit-vat-inversion entry)))) entries) (list credit-ht credit-vat debit-ht debit-vat-i debit-vat-c)))) (defun journal-split-and-justify-description (description width) "PRIVATE" (or (mapcan (lambda (line) (split-lines(string-justify-left line width 0))) (split-lines description)) (list " "))) (defun journal-print-header (year trimestre &key (stream t)) "PRIVATE" (format stream "----------------------------------------~ ---------------------------------------~%") (format stream "~36D - TRIMESTRE ~D~%" year trimestre) (format stream "--- ---------- ----------------------- ~ ----------------------------------------~%") (format stream "SEN FECHA IDENTIFICACION NOMBRE~%") (format stream "TID IMPORTE IVA% +IVA TOTAL ~ NUMERO FACTURA / DESCRIPTION~%") (format stream "--- --------- ----- -------- --------- ~ ---------------------------------------~%") (values)) (defun journal-print-trailer (&key (stream t)) "PRIVATE" (format stream " IMPORTE IVA TOTAL~%") (format stream "--- --------- ----- -------- --------- ~ ---------------------------------------~%") (values)) (defun journal-print-totals (totals &key (stream t)) "PRIVATE" (let ((credit-ht (nth 0 totals)) (credit-vat (nth 1 totals)) (debit-ht (nth 2 totals)) (debit-vat (+ (nth 3 totals) (nth 4 totals)))) (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude credit-ht) "" (amount-magnitude credit-vat) "" "Credito") (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude (- debit-ht)) "" (amount-magnitude (- debit-vat)) "" "Debido") (format stream " ~2,,9$ ~5A ~2,,8$ ~9A ~A~%" (amount-magnitude (- credit-ht debit-ht)) "" (amount-magnitude (- credit-vat debit-vat)) "" "Saldo") (values))) (defun kind-to-order (kind) (case kind ((:prestacion-nacional) 1) ((:prestacion-intracomunitaria) 2) ((:impuesto) 3) ((:inversion) 4) ((:gasto-corriente) 5) ((:adquisicion-intracomunitaria) 6) (otherwise 7))) (defmethod generate ((self journal) &key (stream t) (verbose nil) (language :en)) " DOES: Prints the formated entries of the journal onto the stream. " (ensure-sorted self) (let* ((entries (sort (extract self (year self) (trimestre self)) (lambda (a b) (cond ((= (kind-to-order (kind a)) (kind-to-order (kind b))) (not (date-after (date a) (date b)))) (t (< (kind-to-order (kind a)) (kind-to-order (kind b)))))))) (totals (journal-totals-of-entries entries))) (format stream "~2%") (journal-print-header (year self) (trimestre self) :stream stream) (mapcar (lambda (entry) (generate entry :stream stream :verbose verbose :language language)) entries) (journal-print-trailer :stream stream) (journal-print-totals totals :stream stream) (format stream "~2%") (values))) ;;;--------------------------------------------------------------------- ;;; Reading Journal File. ;;;--------------------------------------------------------------------- (defmacro person (&rest args) " DO: Add to the *INVOICE-SET* a new FISCAL-PERSON instance created with the give initargs. " `(add-person *invoice-set* (make-instance 'fiscal-person ,@args))) (defmacro make-bank-reference (&rest args) " RETURN: A new instance of BANK-REFERENCE with the given initargs. " `(make-instance 'bank-reference ,@args)) (defmacro invoice (&rest args) (do ((args args) (attributes '()) (lines '()) (vinst (gensym))) ((null args) `(let ((,vinst (make-instance 'invoice ,@(nreverse attributes)))) ,@(mapcar (lambda (line) `(add-line ,vinst (make-instance 'invoice-line ,@line))) (nreverse lines)) (add-invoice *invoice-set* ,vinst))) (cond ((keywordp (car args)) (push (pop args) attributes) (push (pop args) attributes)) ((atom (car args)) (error "Invalid invoice attribute ~S" (pop args))) ((eql 'line (caar args)) (push (list* :object-id (string (gensym "L")) (cdr (pop args))) lines)) (t (error "Invalid invoice attribute ~S" (pop args)))))) ;;INVOICE (defmacro journal-entry (date amount-ttc vat-rate nif fac description kind) " DOES: Add a new journal entry. AMOUNT-TTC is the total paid (including VAT) expressed in Euros. VAT-RATE is the V.A.T percentage. " `(add-entry *journal* (make-movement (date-from-string ',date) ',amount-ttc ',vat-rate ',nif (if (listp ',fac) ',fac (list ',fac)) ',description ',kind))) ;;JOURNAL-ENTRY (defun load-journal (path &key (verbose *load-verbose*) (print *load-print*)) " DO: Load the journal at PATH. " (let ((*readtable* *currency-readtable*))) (load path :verbose verbose :print print)) ;; (in-package :common-lisp-user) ;; (cd "/home/pascal/jobs/free-lance/accounting/") ;; (load "invoice") ;;;; THE END ;;;;
84,266
Common Lisp
.lisp
2,026
34.122902
86
0.556063
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
247245a901d9686cb4b01ccfb2f19355f68aceb75e91c70ca6f9a62f88eaca7a
5,166
[ -1 ]
5,167
com.informatimago.common-lisp.invoice.test.asd
informatimago_lisp/common-lisp/invoice/com.informatimago.common-lisp.invoice.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.invoice.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.invoice.test system. ;;;; Tests the com.informatimago.common-lisp.invoice 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.invoice.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.invoice 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.common-lisp.invoice.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.invoice" "com.informatimago.common-lisp.cesarum") :components () #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) ;; (let ((*package* (find-package "TESTED-PACKAGE"))) ;; (uiop:symbol-call "TESTED-PACKAGE" ;; "TEST/ALL")) )) ;;;; THE END ;;;;
2,976
Common Lisp
.lisp
67
38.238806
87
0.550052
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2fd29705e9bc3ae09d8cc35b6a7a7e23e2259016ba87bbb245a3ae3cfdc28f5a
5,167
[ -1 ]
5,168
tree-to-diagram.lisp
informatimago_lisp/common-lisp/diagram/tree-to-diagram.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: tree-to-Diagram.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This module generates a Diagram text file drawing a tree. ;;;; The tree drawn is a list whose car is the node displayed, and ;;;; whose cdr is the list of children. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 199?-??-?? <PJB> Creation. ;;;;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.COMMON-LISP.DIAGRAM.TREE-TO-DIAGRAM" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST") (:export "TREE-GENERATE-RANDOM" "TREE-SIZE" "TREE-DEPTH" "TREE-TO-DIAGRAM") (:documentation " This package generates a Diagram! text file drawing a tree. The tree drawn is a list whose car is the node displayed, and whose cdr is the list of children. License: AGPL3 Copyright Pascal J. Bourguignon 1994 - 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.COMMON-LISP.DIAGRAM.TREE-TO-DIAGRAM") (defun tree-diagram-generate-node (n l x y node) "PRIVATE. DOES: Generates the Diagram text for a node. n: the Diagram symbol number (may be used in Diagram links). l: the Diagram layer. x,y: the coordinates. node: the text in the node rectangle. RETURN: a list (n' l' x' y') for the following brother node. " (format t "symbol ~s~%" n) (format t " layer ~s~%" l) (format t " shape ~aRectangle~a~%" (code-char 34) (code-char 34)) (format t " location ~s.00 ~s.00~%" x y) (format t " size 126.00 18.00~%") (format t " framed~%") (format t " fillColor colorIndex 0~%") (format t " frameColor colorIndex 1~%") (format t " shadowColor colorIndex 2~%") (format t " lineWidth 1.00~%") (format t " filled~%") (format t " rtfText {\\rtf0\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\margl40\\margr40\\pard\\tx960\\tx1920\\tx2880\\tx3840\\tx4800\\tx5760\\tx6720\\tx7680\\tx8640\\tx9600\\f0\\b\\i0\\ulnone\\qc\\fs20\\fc0\\cf0 ~s}~%" node) (format t " textPlacement middle~%") (format t "end~%~%") (list (1+ n) (1+ l) x (+ 27 y))) (defun tree-diagram-generate-inherit (n l x y) "PRIVATE. DOES: Generates the Diagram text for a 'inherit' symbol (vertical triangle). n: the Diagram symbol number (may be used in Diagram links). l: the Diagram layer. x,y: the coordinates. RETURN: a list (n' l' x' y') for the first child node. " (format t "symbol ~s~%" n) (format t " layer ~s~%" l) (format t " shape ~aVertical Triangle~a~%" (code-char 34) (code-char 34)) (format t " location ~s.00 ~s.00~%" (+ 52 x) (+ 10 y)) (format t " size 21.00 11.00~%") (format t " framed~%") (format t " fillColor colorIndex 0~%") (format t " frameColor colorIndex 1~%") (format t " shadowColor colorIndex 2~%") (format t " lineWidth 1.00~%") (format t " filled~%") (format t " textPlacement top~%") (format t "end~%") (list (1+ n) (1+ l) (+ 81 x) (+ 27 y))) (defun tree-diagram-generate-adjust-x (inc) "PRIVATE. inc: a list (n l x y) corresponding to the after last brother. RETURN: a list (n' l' x' y') for the next uncle node. " (list (car inc) (cadr inc) (- (caddr inc) 81) (car (cdddr inc)))) (defun tree-diagram-generate-tree (n l x y tree) "PRIVATE. DOES: writes to the *standard-output* the Diagram text for the subtree 'tree'. RETURN: a list (n' l' x' y') for the next brother subtree. " (if (null (cdr tree)) (tree-diagram-generate-node n l x y (car tree)) (let ((inc (apply (function tree-diagram-generate-inherit) (tree-diagram-generate-node n l x y (car tree))))) (do ((subtrees (cdr tree) (cdr subtrees))) ((null subtrees)) (setq inc (apply (function tree-diagram-generate-tree) (append inc (list (car subtrees)))))) (tree-diagram-generate-adjust-x inc)))) (defun tree-to-diagram (tree) " PRE: tree is a cons of the node and the list of children. DOES: writes to the *standard-output* the Diagram file text. " (tree-diagram-generate-tree 1000 60 45 27 tree)) (defun tree-depth (tree) " PRE: tree is a cons of the node and the list of children. RETURN: the depth of the tree. " (if (null tree) 0 (1+ (reduce (function max) (cdr tree) :key (function tree-depth) :initial-value 0)))) (defun tree-size (tree) " PRE: tree is a cons of the node and the list of children. RETURN: The size of the tree (number of nodes) " (loop with count = 0 for item in tree do (if (listp item) (setq count (+ count (tree-size item))) (setq count (1+ count))) finally (return count))) (defun tree-generate-random (depth width) " RETURN: A random tree with random number as node, of maximal depth `depth' and where each node has a maximum of `width` children. NOTE: The result can easily be degenreate (a single node, or a much smaller tree). " (if (>= 1 depth) (random most-positive-fixnum) (loop for i from 0 below (random (1+ width)) collect (tree-generate-random (1- depth) width) into children finally (return (cons (random most-positive-fixnum) children))))) ;; (insert (tree-to-ascii (generate-random-tree 7 3))) ;;; (let ((tree (generate-random-tree 3 50)) ;;; (*trace-output* (current-buffer))) ;;; (printf *trace-output* "recursive-count: ") ;;; (time (loop repeat 10 do (recursive-count tree))) ;;; (printf *trace-output* "tree-size: ") ;;; (time (loop repeat 10 do (tree-size tree))) ;;; ) ;;;; THE END ;;;;
7,424
Common Lisp
.lisp
177
38.40678
224
0.641768
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b0a8df2723ac26afeb74230d8733571500a5948138a81b49ab4ff895d98d263f
5,168
[ -1 ]
5,169
com.informatimago.common-lisp.diagram.test.asd
informatimago_lisp/common-lisp/diagram/com.informatimago.common-lisp.diagram.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.diagram.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.diagram.test system. ;;;; Tests the com.informatimago.common-lisp.diagram 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.diagram.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.diagram 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.common-lisp.diagram.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.diagram" "com.informatimago.common-lisp.cesarum") :components () #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) ;; (let ((*package* (find-package "TESTED-PACKAGE"))) ;; (uiop:symbol-call "TESTED-PACKAGE" ;; "TEST/ALL")) )) ;;;; THE END ;;;;
2,976
Common Lisp
.lisp
67
38.238806
87
0.550052
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
304bdeed90d251aeb7fcfe45b0751862d8488e9293a13eaf0c17caf78f5e4ad9
5,169
[ -1 ]
5,170
com.informatimago.common-lisp.diagram.asd
informatimago_lisp/common-lisp/diagram/com.informatimago.common-lisp.diagram.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.diagram.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.diagram 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.diagram" ;; system attributes: :description "Informatimago Common Lisp (NeXTSTEP) Diagram! file generator." :long-description " This package generates a Diagram text file drawing a tree. The tree drawn is a list whose car is the node displayed, and whose cdr is the list of children. " :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 . "Autumn 2010") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.diagram/") ((#: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 "tree-to-diagram" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.diagram.test")))) ;;;; THE END ;;;;
2,736
Common Lisp
.lisp
58
44.103448
111
0.605834
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c547e22b5fa9f9e4935d38e8c77a0e90562ba3a2328d53e3ad8a8da34fc8e3fb
5,170
[ -1 ]
5,171
rib.lisp
informatimago_lisp/common-lisp/bank/rib.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: rib.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; See defpackage documentation string. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2008-05-12 <PJB> Added setters (setf bank-code), etc. ;;;; 2004-08-28 <PJB> Converted from C++. ;;;; 1994-12-28 <PJB> Creation. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 1994 - 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.BANK.RIB" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.BANK.IBAN") (:export "CHECK-DIGITS" "SET-ACCOUNT-NUMBER" "ACCOUNT-NUMBER" "SET-BRANCH-CODE" "BRANCH-CODE" "SET-BANK-CODE" "BANK-CODE" "SET-RIB" "GET-RIB" "RIB") (:documentation " This package provides a class representing a French \"Relevé d'Identité Banquaire\", composed of three codes and a control key value: (banque, branch-code, account-number, check-digits). See also: COM.INFORMATIMAGO.COMMON-LISP.BANK.IBAN -- the new European bank account numbers. License: Copyright Pascal J. Bourguignon 1994 - 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.COMMON-LISP.BANK.RIB") (define-condition rib-error (iban-error) () (:documentation "A RIB error")) (defgeneric bank-code (rib) (:documentation " RETURN: The bank code of the RIB. ")) (defgeneric branch-code (rib) (:documentation " RETURN: The branch code of the RIB. ")) (defgeneric account-number (rib) (:documentation " RETURN: The account number of the RIB. ")) (defgeneric check-digits (rib) (:documentation " RETURN: The check digits of the RIB. ")) (defgeneric check-digits-changed (rib) (:documentation " RETURN: The check digits changed flag. NOTE: The check-digits are updated lazily when other slots are changed. This flag indicates that check-digits need to be recomputed. ")) (defgeneric get-rib (rib &key with-spaces) (:documentation " RETURN: A string containing the RIB. When WITH-SPACES is true, spaces are used to separate the various fields of the RIB. ")) (defgeneric set-bank-code (rib bank-code) (:documentation " DO: Sets the bank-code of the RIB. RETURN: RIB ")) (defgeneric set-branch-code (rib branch-code) (:documentation " DO: Sets the branch-code of the RIB. RETURN: RIB ")) (defgeneric set-account-number (rib account-number) (:documentation " DO: Sets the account-number of the RIB. RETURN: RIB ")) (defgeneric set-rib (rib new-rib &key with-check-digits) (:documentation " DO: Replace the RIB fields with the data obtained from the NEW-RIB string. NEW-RIB: A string containing the new rib numbers. RETURN: RIB ")) (defgeneric (setf bank-code) (bank-code rib) (:documentation " DO: Sets the bank-code of the RIB. RETURN: RIB ")) (defgeneric (setf branch-code) (branch-code rib) (:documentation " DO: Sets the branch-code of the RIB. RETURN: RIB ")) (defgeneric (setf account-number) (account-number rib) (:documentation " DO: Sets the account-number of the RIB. RETURN: RIB ")) (defclass rib (iban) ((bank-code :reader bank-code :initform "00000" :initarg :bank-code :type (string 5)) (branch-code :reader branch-code :initform "00000" :initarg :branch-code :type (string 5)) (account-number :reader account-number :initform "00000000000" :initarg :account-number :type (string 11)) (check-digits :initform "00" :initarg :check-digits :type (string 2)) (check-digits-changed :reader check-digits-changed :initform t :type boolean)) (:documentation " INVARIANT: (length banque)=5, (length branch-code)=5, (length account-number)=11, (length check-digits)=2, for each attribute in {banque,branch-code,account-number,check-digits}, foreach i in [0,strlen(attribute)-1], attribute()[i] in {'0',...,'9','A',...,'Z'}. check-digits=f(banque,branch-code,account-number). ")) (defparameter +alphabet-value+ "012345678912345678912345678923456789") (defparameter +alphabet-from+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") (defun compute-check-digits (bank-code branch-code account-number) (let ((k (mod (parse-integer (map 'string (lambda (ch) (aref +alphabet-value+ (position (char-upcase ch) +alphabet-from+))) (concatenate 'string bank-code branch-code account-number "00")) :junk-allowed nil) 97))) (format nil "~2,'0D" (if (= 0 k) 0 (- 97 k))))) (defmethod initialize-instance ((self rib) &rest args) (declare (ignore args)) (call-next-method) (setf (slot-value self 'bank-code) (get-and-check-alphanum 5 (bank-code self)) (slot-value self 'branch-code) (get-and-check-alphanum 5 (branch-code self)) (slot-value self 'account-number) (get-and-check-alphanum 11 (account-number self)) (slot-value self 'check-digits) (compute-check-digits (bank-code self) (branch-code self) (account-number self)) (slot-value self 'check-digits-changed) nil) self) (defmethod check-digits ((self rib)) (when (check-digits-changed self) (setf (slot-value self 'check-digits) (compute-check-digits (bank-code self) (branch-code self) (account-number self))) (setf (slot-value self 'check-digits-changed) nil)) (slot-value self 'check-digits)) (defmethod get-rib ((self rib) &key (with-spaces nil)) (format nil (if with-spaces "~5S ~5S ~11S ~2S" "~5S~5S~11S~2S") (bank-code self) (branch-code self) (account-number self) (check-digits self))) (defmethod set-bank-code ((self rib) (bank-code string)) (setf (slot-value self 'bank-code) (get-and-check-alphanum 5 bank-code) (slot-value self 'check-digits-changed) t) self) (defmethod set-branch-code ((self rib) (branch-code string)) (setf (slot-value self 'branch-code) (get-and-check-alphanum 5 branch-code) (slot-value self 'check-digits-changed) t) self) (defmethod set-account-number ((self rib) (account-number string)) (setf (slot-value self 'account-number) (get-and-check-alphanum 11 account-number) (slot-value self 'check-digits-changed) t) self) (defmethod set-rib ((self rib) (rib string) &key (with-check-digits nil)) (setf rib (get-and-check-alphanum (if with-check-digits 23 21) rib)) (let* ((b (subseq rib 0 5)) (g (subseq rib 5 5)) (c (subseq rib 10 11)) (k (when with-check-digits (subseq rib 21 23))) (ck (compute-check-digits b g c))) (when (and with-check-digits (string/= k ck)) (signal 'rib-error "Invalid key, given=~S, computed=~S." k ck)) (setf (slot-value self 'bank-code) b (slot-value self 'branch-code) g (slot-value self 'account-number) c (slot-value self 'check-digits) ck (slot-value self 'check-digits-changed) nil) self)) (defmethod (setf bank-code) (bank-code (self rib)) (set-bank-code self bank-code)) (defmethod (setf branch-code) (branch-code (self rib)) (set-branch-code self branch-code)) (defmethod (setf account-number) (account-number (self rib)) (set-account-number self account-number)) (defun test () (every (lambda (test) (let ((rib (make-instance 'rib :bank-code (first test) :branch-code (second test) :account-number (third test)))) (string= (fourth test) (check-digits rib)))) '(("10011" "00020" "1202196212N" "93") ("10011" "00020" "0335091570T" "41") ("11899" "05900" "00014503740" "69") ("11899" "05900" "00014503760" "09") ("30003" "03083" "00051102516" "52") ("30003" "03083" "00021000041" "89") ("10278" "05900" "00030094740" "14") ("10278" "05900" "00014503740" "02") ("10278" "05900" "00014503760" "39")))) ;;;; THE END ;;;;
10,004
Common Lisp
.lisp
231
38.038961
101
0.640564
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a7fad03cd49357bb2815f522f8428c99b6d99fecc9d488739dec058d542dad9c
5,171
[ -1 ]
5,172
com.informatimago.common-lisp.bank.asd
informatimago_lisp/common-lisp/bank/com.informatimago.common-lisp.bank.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.bank.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.bank 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.bank" ;; system attributes: :description "Informatimago Common Lisp Banking Utilities" :long-description "Various bank data formats (IBAN, RIB)." :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 . "Autumn 2010") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.bank/") ((#: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 "iban" :depends-on ()) (:file "rib" :depends-on ("iban"))) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.bank.test")))) ;;;; THE END ;;;;
2,621
Common Lisp
.lisp
55
44.236364
108
0.588924
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
62405038d7ccd001de5a8564a4e576b387e6e4e8dc8cde43ae8ec63f21e839b3
5,172
[ -1 ]
5,173
iban.lisp
informatimago_lisp/common-lisp/bank/iban.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: iban.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; See defpackage documentation string. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-11-29 <PJB> Added a PRINT-OBJECT method, corrected ERROR calls, ;;;; added examples to the package comment. ;;;; 2004-10-10 <PJB> Created. ;;;;BUGS ;;;; The verification of the country code accepts all existing countries ;;;; as defined by iso-3166. Some of these country code are not used ;;;; (GP --> FR for example). So an incorrect use of GP is not detected. ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 1994 - 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.BANK.IBAN" (: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.ISO3166") (:export "GET-AND-CHECK-ALPHANUM" "COMPUTE-IBAN-KEY" "CHECK-IBAN-KEY" "GET-IBAN" "GET-KEY" "GET-COUNTRY-CODE" "SET-IBAN" "CHECK-COUNTRY" "BASIC-FORM" "IBAN" "IBAN-ERROR") (:documentation " This class is an Internationnal Bank Account Number, according to the European standard: IBAN Format: <http://www.ecbs.org/iban/iban.htm> To create find the IBAN given an account number with a country-code: (make-instance 'iban :basic-form (remove #\\space (format nil \"~2A00~A\" country-code account))) this will compute the IBAN key, and print the IBAN instance. To get the IBAN as a string with groups separated by spaces: (com.informatimago.common-lisp.bank.iban:get-iban iban :with-spaces t) License: AGPL3 Copyright Pascal J. Bourguignon 1994 - 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.COMMON-LISP.BANK.IBAN") (defgeneric basic-form (iban) (:documentation "RETURN: The basic form of the IBAN.")) (defgeneric get-and-check-alphanum (self string &optional length) (:documentation "Check that STRING contains only alphanumeric character valid in an IBAN.")) (defgeneric check-country (self) (:documentation " DO: Checks the country code in the basic-form, and raises an error if not valid. RAISE: IBAN-ERROR RETURN: SELF ")) (defgeneric get-country-code (self) (:documentation " RETURN: The country code in the IBAN. ")) (defgeneric get-key (self) (:documentation " RETURN: The computed key of the IBAN. ")) (defgeneric get-iban (self &key with-spaces) (:documentation " RETURN: The IBAN as a string, with spaces inserted when WITH-SPACES is true, else in basic form. ")) (defgeneric set-iban (self iban &key with-key) (:documentation " DO: Change the IBAN. If WITH-KEY is true then the IBAN key is checked and an error raised if it is not valid, else the IBAN key is computed and substituted. RETURN: SELF SIGNAL: An IBAN-ERROR when with-key and the key in the IBAN is incorrect. ")) (define-condition iban-error (simple-error) () (:documentation "An IBAN error.")) (defclass iban () ((basic-form :reader basic-form :initform "FR00000000000000000000000" :initarg :basic-form :type string :documentation "The basic form of the IBAN.")) (:documentation "The Internationnal Bank Account Number class.")) (defmethod initialize-instance ((self iban) &rest args) (declare (ignore args)) (call-next-method) (when (basic-form self) (set-iban self (basic-form self))) self) (defmethod print-object ((self iban) stream) (print-unreadable-object (self stream :identity t :type t) (princ (basic-form self) stream)) self) (defmethod get-country-code ((self iban)) " RETURN: The country code in the IBAN. " (subseq (basic-form self) 0 2)) (defmethod get-key ((self iban)) " RETURN: The computed key of the IBAN. " (subseq (slot-value self 'basic-form) 2 4)) (defmethod get-iban ((self iban) &key (with-spaces nil)) " RETURN: The IBAN, with spaces inserted when WITH-SPACES is true, else in basic form. " (if with-spaces (do ((iban (basic-form self)) (res '()) (i 0 (+ i 4))) ((>= (+ i 4) (length iban)) (progn (push (subseq iban i) res) (apply (function concatenate) 'string (nreverse res)))) (push (subseq iban i (+ i 4)) res) (push " " res)) (copy-seq (basic-form self)))) ;; We test and convert to upper case letters, because ;; the RIB and IBAN may contain only the following characters: ;; 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ (defparameter +alphabet-from+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") (defmethod get-and-check-alphanum ((self iban) string &optional length) (when (and length (/= length (length string))) (error 'iban-error :format-control "For IBAN ~S:~% Bad length, expected ~D, got ~D: ~S" :format-arguments (list self length (length string) string))) (map 'string (lambda (ch) (let ((index (position ch +alphabet-from+))) (unless index (error 'iban-error :format-control "For IBAN ~S:~% Bad character '~C' in ~S, ~ should be alphanumeric." :format-arguments (list self ch string))) (aref +alphabet-from+ (if (< index 36) index (- index 26))))) string)) (defun country-codes () "Returns a list of 2-letter country codes." (mapcar (function first) (get-countries :only-existing t))) (defparameter *country-codes* (country-codes) "List of 2-letter country codes.") (defmethod check-country ((self iban)) " DO: Checks the country code in the basic-form, and raises an error if not valid. RAISE: IBAN-ERROR RETURN: SELF " (let ((cc (get-country-code self))) (unless (member cc *country-codes* :test (function string-equal)) (error 'iban-error :format-control "For IBAN ~S:~% Bad country code: ~S" :format-arguments (list self cc)))) self) (defun check-iban-key (iban) " DO: Check the IBAN KEY The IBAN string must be in basic format, all non alphanumeric characters removed. 0- move the first four characters of the IBAN to the end. 1- convert the letters into numerics. 2- apply MOD 97-10 (ISO 7064) : remainder of n by 97 must be 1 3- return T when the IBAN key checks. RETURN: Whether the IBAN key checks. " (= 1 (mod (loop :for ch :across (concatenate 'string (subseq iban 4) (subseq iban 0 4)) :with n = 0 :do (setf n (+ (* (if (alpha-char-p ch) 100 10) n) (parse-integer (string ch) :radix 36 :junk-allowed nil))) :finally (return n)) 97))) (defun compute-iban-key (country account) " DO: Compute the IBAN key for the given ACCOUNT. ACCOUNT must be in basic format, all non alphanumeric characters removed. 0- create artificial IBAN with 00 check sum. 1- move the first four characters of the IBAN to the end. 2- convert the letters into numerics. 3- apply MOD 97-10 (ISO 7064): check sum is 98 - n mod 97. 4- return the complete IBAN. RETURN: The new complete IBANA. " (format nil "~2A~2,'0D~A" country (- 98 (mod (loop for ch across (concatenate 'string account country "00") with n = 0 do (setf n (+ (* (if (alpha-char-p ch) 100 10) n) (parse-integer (string ch) :radix 36 :junk-allowed nil))) finally (return n)) 97)) account)) (defmethod set-iban ((self iban) (iban string) &key (with-key nil)) " DO: Change the IBAN. If WITH-KEY is true then the IBAN key is checked and an error raised if it is not valid, else the IBAN key is computed and substituted. RETURN: SELF RAISE: An IBAN-ERROR when with-key and the key in the IBAN is incorrect. " (setf iban (get-and-check-alphanum self (remove-if (complement (function alphanumericp)) iban))) (setf (slot-value self 'basic-form) (if with-key (if (check-iban-key iban) iban (error 'iban-error :format-control "For IBAN ~S~% Invalid key, given=~S, computed=~S." :format-arguments (list iban (subseq iban 2 4) (subseq (compute-iban-key (subseq iban 0 2) (subseq iban 4)) 2 4)))) (compute-iban-key (subseq iban 0 2) (subseq iban 4)))) (check-country self) self) ;;;; THE END ;;;;
10,867
Common Lisp
.lisp
253
36.217391
97
0.62564
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
24828a1c850b4d9c57775960d0127286efb41c81900bbc035fe32e4169f071d2
5,173
[ -1 ]
5,174
com.informatimago.common-lisp.bank.test.asd
informatimago_lisp/common-lisp/bank/com.informatimago.common-lisp.bank.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.bank.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.bank.test system. ;;;; Tests the com.informatimago.common-lisp.bank 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.bank.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.bank 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.common-lisp.bank.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.common-lisp.bank") :components () #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) ;; (let ((*package* (find-package "TESTED-PACKAGE"))) ;; (uiop:symbol-call "TESTED-PACKAGE" ;; "TEST/ALL")) )) ;;;; THE END ;;;;
2,955
Common Lisp
.lisp
67
37.925373
84
0.546778
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2931c5cc374b3677d0e28ba5386e74a2df2a8bee3f91269f34193bf3fded25da
5,174
[ -1 ]
5,175
com.informatimago.common-lisp.rfc1035.asd
informatimago_lisp/common-lisp/rfc1035/com.informatimago.common-lisp.rfc1035.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.common-lisp.rfc1035.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to load the com.informatimago.common-lisp.rfc1035 library. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-08-15 <PJB> Created this .asd file. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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/ ;;;;************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.rfc1035" :description "Informatimago Common Lisp RFC1035 Zone File Parser." :long-description " A RFC1035 Zone File Parser. " :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "AGPL3" ;; component attributes: :version "1.0.0" :properties ((#:author-email . "[email protected]") (#:date . "Summer 2018") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.rfc1035/") ((#: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 "rfc1035" :depends-on ())) #+adsf3 :in-order-to #+adsf3 ((asdf:test-op (asdf:test-op "com.informatimago.common-lisp.rfc1035.test")))) ;;;; THE END ;;;;
2,565
Common Lisp
.lisp
55
43.490909
111
0.594573
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9819c22eac605f0e38abea38fe73444ec27711ae0ef4235e061938784ff1101f
5,175
[ -1 ]
5,176
com.informatimago.common-lisp.rfc1035.test.asd
informatimago_lisp/common-lisp/rfc1035/com.informatimago.common-lisp.rfc1035.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.common-lisp.rfc1035.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.common-lisp.rfc1035.test system. ;;;; Tests the com.informatimago.common-lisp.rfc1035 system. ;;;; ;;;;USAGE: ;;;; ;;;;AUTHORS: ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-08-15 <PJB> Created. ;;;;BUGS: ;;;; ;;;;LEGAL: ;;;; ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.common-lisp.rfc1035.test" ;; system attributes: :description "Tests the com.informatimago.common-lisp.rfc1035 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 . "Summer 2018") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.rfc1035.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.common-lisp.rfc1035") :components ((:file "rfc1035-test")) #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) (let ((*package* (find-package "COM.INFORMATIMAGO.COMMON-LISP.RFC1035.RFC1035"))) (uiop:symbol-call "COM.INFORMATIMAGO.COMMON-LISP.RFC1035.RFC1035" "TEST/ALL")))) ;;;; THE END ;;;;
3,013
Common Lisp
.lisp
66
39.484848
109
0.566384
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c0f5be39dbdb5f38819297f5adf124076d733dd9dc7e97c32c46818c07faac93
5,176
[ -1 ]
5,177
rfc1035-test.lisp
informatimago_lisp/common-lisp/rfc1035/rfc1035-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: rfc1035-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test rfc1035. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2018-08-15 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2018 - 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.COMMON-LISP.RFC1035.RFC1035") (eval-when (:compile-toplevel :load-toplevel :execute) (use-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST")) (defun test-read-zone () (with-input-from-string (stream " $TTL 30m $ORIGIN example.com. @ 1D IN SOA ns1.example.com. admin.example.com. ( 2018080200 ; serial (d. adams) 1H ; refresh 15M ; retry 14D ; expiry 1H ) ; negative cache @ 1H IN NS ns1.domain.com. @ 1H IN NS ns2.domain.com. @ IN 1H NS ns3.domain.com. @ 1H NS ns4.domain.com. @ IN NS ns5.domain.com. @ NS ns6.domain.com. ns1 3600 IN A 127.1.0.1 ns1 3600 IN AAAA ::ffff:127.1.0.1 ns2 3600 IN A 127.1.0.2 ns3 3600 IN A 127.1.0.3 ns4 3600 IN A 127.1.0.4 ns5 3600 IN A 127.1.0.5 ns6 3600 IN A 127.1.0.6 mx1 A 127.2.0.1 mx2 A 127.2.0.2 host A 127.0.0.1 host AAAA ::ffff:127.1.0.1 host TXT \"v=spf1 include:_spf.google.com ipv4:127.0.0.1 ipv6:::ffff:127.1.0.1 -all\" host SPF v=spf1 include:_spf.google.com ipv4:127.0.0.1 ipv6:::ffff:127.1.0.1 -all host.example.com. TXT \"google-site-verification=H-AnQ4Mc58qDb2fLBqHXrllwKCSfkl6d1YR9eCj_SyM\" www CNAME host ftp 1H CNAME host ; MX Records @ MX 0 mx1 @ MX 10 mx2.example.com. ;; THE END ") (read-zone stream (make-zone)))) (defun test-include () (setf (com.informatimago.common-lisp.cesarum.file:text-file-contents "/tmp/zone.inc") " @ 1H IN NS ns1.domain.com. @ 1H IN NS ns2.domain.com. @ IN 1H NS ns3.domain.com. @ 1H NS ns4.domain.com. @ IN NS ns5.domain.com. @ NS ns6.domain.com. ns1 3600 IN A 127.1.0.1 ns1 3600 IN AAAA ::ffff:127.1.0.1 ns2 3600 IN A 127.1.0.2 ns3 3600 IN A 127.1.0.3 ns4 3600 IN A 127.1.0.4 ns5 3600 IN A 127.1.0.5 ns6 3600 IN A 127.1.0.6 ") (with-input-from-string (stream " $TTL 30m $ORIGIN example.com. @ 1D IN SOA ns1.example.com. admin.example.com. ( 2018080200 ; serial (d. adams) 1H ; refresh 15M ; retry 14D ; expiry 1H ) ; negative cache $INCLUDE /tmp/zone.inc mx1 A 127.2.0.1 mx2 A 127.2.0.2 host A 127.0.0.1 host AAAA ::ffff:127.1.0.1 host TXT \"v=spf1 include:_spf.google.com ipv4:127.0.0.1 ipv6:::ffff:127.1.0.1 -all\" host SPF v=spf1 include:_spf.google.com ipv4:127.0.0.1 ipv6:::ffff:127.1.0.1 -all host.example.com. TXT \"google-site-verification=H-AnQ4Mc58qDb2fLBqHXrllwKCSfkl6d1YR9eCj_SyM\" www CNAME host ftp 1H CNAME host ; MX Records @ MX 0 mx1 @ MX 10 mx2.example.com. ;; THE END ") (read-zone stream (make-zone)))) (define-test test/read-simple-zone-file () (test equalp (test-read-zone) (make-zone :ttl 3600 :origin "example.com." :class :in :includes nil :current-domain "example.com." :records '(("example.com." 3600 :in :mx 10 "mx2.example.com.") ("example.com." 3600 :in :mx 0 "mx1") ("ftp.example.com." 3600 :in :cname "host") ("www.example.com." 3600 :in :cname "host") ("host.example.com." 3600 :in :txt "google-site-verification=H-AnQ4Mc58qDb2fLBqHXrllwKCSfkl6d1YR9eCj_SyM") ("host.example.com." 3600 :in :spf "v=spf1" "include:_spf.google.com" "ipv4:127.0.0.1" "ipv6:::ffff:127.1.0.1" "-all") ("host.example.com." 3600 :in :txt "v=spf1 include:_spf.google.com ipv4:127.0.0.1 ipv6:::ffff:127.1.0.1 -all") ("host.example.com." 3600 :in :aaaa "::ffff:127.1.0.1") ("host.example.com." 3600 :in :a "127.0.0.1") ("mx2.example.com." 3600 :in :a "127.2.0.2") ("mx1.example.com." 3600 :in :a "127.2.0.1") ("ns6.example.com." 3600 :in :a "127.1.0.6") ("ns5.example.com." 3600 :in :a "127.1.0.5") ("ns4.example.com." 3600 :in :a "127.1.0.4") ("ns3.example.com." 3600 :in :a "127.1.0.3") ("ns2.example.com." 3600 :in :a "127.1.0.2") ("ns1.example.com." 3600 :in :aaaa "::ffff:127.1.0.1") ("ns1.example.com." 3600 :in :a "127.1.0.1") ("example.com." 3600 :in :ns "ns6.domain.com.") ("example.com." 3600 :in :ns "ns5.domain.com.") ("example.com." 3600 :in :ns "ns4.domain.com.") ("example.com." 3600 :in :ns "ns3.domain.com.") ("example.com." 3600 :in :ns "ns2.domain.com.") ("example.com." 3600 :in :ns "ns1.domain.com.") ("example.com." 86400 :in :soa "ns1.example.com." "admin.example.com." 2018080200 3600 900 1209600 3600))))) (define-test test/read-zone-file-with-include () (test equalp (test-include) (make-zone :ttl 3600 :origin "example.com." :class :in :includes nil :current-domain "example.com." :records '(("example.com." 3600 :in :mx 10 "mx2.example.com.") ("example.com." 3600 :in :mx 0 "mx1") ("ftp.example.com." 3600 :in :cname "host") ("www.example.com." 3600 :in :cname "host") ("host.example.com." 3600 :in :txt "google-site-verification=H-AnQ4Mc58qDb2fLBqHXrllwKCSfkl6d1YR9eCj_SyM") ("host.example.com." 3600 :in :spf "v=spf1" "include:_spf.google.com" "ipv4:127.0.0.1" "ipv6:::ffff:127.1.0.1" "-all") ("host.example.com." 3600 :in :txt "v=spf1 include:_spf.google.com ipv4:127.0.0.1 ipv6:::ffff:127.1.0.1 -all") ("host.example.com." 3600 :in :aaaa "::ffff:127.1.0.1") ("host.example.com." 3600 :in :a "127.0.0.1") ("mx2.example.com." 3600 :in :a "127.2.0.2") ("mx1.example.com." 3600 :in :a "127.2.0.1") ("ns6.example.com." 3600 :in :a "127.1.0.6") ("ns5.example.com." 3600 :in :a "127.1.0.5") ("ns4.example.com." 3600 :in :a "127.1.0.4") ("ns3.example.com." 3600 :in :a "127.1.0.3") ("ns2.example.com." 3600 :in :a "127.1.0.2") ("ns1.example.com." 3600 :in :aaaa "::ffff:127.1.0.1") ("ns1.example.com." 3600 :in :a "127.1.0.1") ("example.com." 3600 :in :ns "ns6.domain.com.") ("example.com." 3600 :in :ns "ns5.domain.com.") ("example.com." 3600 :in :ns "ns4.domain.com.") ("example.com." 3600 :in :ns "ns3.domain.com.") ("example.com." 3600 :in :ns "ns2.domain.com.") ("example.com." 3600 :in :ns "ns1.domain.com.") ("example.com." 86400 :in :soa "ns1.example.com." "admin.example.com." 2018080200 3600 900 1209600 3600))))) (define-test test/all () (test/read-simple-zone-file) (test/read-zone-file-with-include) :success) ;;;; THE END ;;;;
9,951
Common Lisp
.lisp
186
41.123656
148
0.466982
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
28453fec6d5b6393ced4aa2dba158d6017b907795acde043fc830eda6406a22e
5,177
[ -1 ]
5,178
driver.lisp
informatimago_lisp/driver/driver.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: driver.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A lisp driver similar to gcc. ;;;; ;;;; Right, that's silly. But some non-lispers may be lured into ;;;; lisp by it. ;;;; ;;;;USAGE: ;;;; ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-07-01 <PJB> Created. ;;;;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.DRIVER" (:use "COMMON-LISP") (:export "COMPILE-FILES" "GENERATE-LIBRARY" "GENERATE-EXECUTABLE")) (in-package "COM.INFORMATIMAGO.DRIVER") " plc -c -Iincludes_dir -o file.o file.lisp… Compiles the possibly multiple source files file.lisp into an object file.o. The directories specified with -I are searched by LOAD, REQUIRE, and ASDF. The object files generated by plc are not necessarily compatible with gcc or ld. plc -o libfile.a -static file.lisp|file.o … plc -o executable file.lisp|file.o … Loads the files specified (sources or object), link-edit them, and generate an executable. In all those files, there should be a function named CL-USER::MAIN, which will be called when the executable is run, with as arguments all the command line arguments (as strings). The environment variables are accessible thru the accessor CL-USER::GETENV. CL-USER::EXIT is a function taking 0 or 1 argument, a status code to be returned by the command. -c Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file. -o file Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o. -v Print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper. -version, --version Display the version number and copyrights of the invoked plc. -ansi Ensures that strict Ansi Common Lisp is used. This is the default. -traditional Do not enfore strict Ansi Common Lisp. -g Produce debugging information. You can use -g with -O, but this may give strange results. speed space debug safety -O, -O0, -O1, -O2, -O3 Optimize. -O is equivalent to -O1 no -Os ==> (space 0) -Os ==> (space 3) (speed 2) -O# ==> (speed #) no -Ofast ==> (safety 3) -Ofast ==> (safety 0) -g ==> (debug 3) no -g ==> (debug 0) -fsingle-precision-constant ==> (setf *read-default-float-format* 'single-float) no -fsingle-precision-constant ==> (setf *read-default-float-format* 'double-float) -Dname ==> (push :name *features*) -Dname=definition ==> (define-symbol-macro cl-user::name definition) (-D-register 'cl-user::name 'definition) -Uname ==> (setf *features* (remove :name *features*)) (-D-unregister 'cl-user::name) (unintern 'cl-user::name) -Idir, -I dir Add the directory dir to the list of directories to be searched for lisp files. Directories named by -I are searched before the standard system include directories. -dM Dumps *features* -dD Prints the -Dname=definition definitions. (-D-definitions) -Ldir, -L dir Add directory dir to the list of directories to be searched for -l. -llibrary, -l library library names a lisp library, created with lpc -static, which will be loaded before compiling or linking the program. -static produces a library containing the compiled code of all the input source files. library is the name of an asdf or quicklisp system, which is loaded before compiling. -Bimplementation Specifies what implementation to use. It is the name of a Common Lisp implementation executable, or its full path. Examples: -Bclisp -B/opt/local/bin/sbcl --sysroot=dir Specifies the quicklisp directory. -print-search-dirs Print the name of the configured installation directory and a list of program and library directories plc will search---and don't do anything else. -print-sysroot Print the target sysroot directory that will be used during compilation. This is the target sysroot specified either at configure time or using the --sysroot option. If no target sysroot is specified, the default is ~/quicklisp/. -dumpmachine Print the compiler's target machine (for example, i686-pc-linux-gnu)---and don't do anything else. (machine-type) -dumpversion Print the compiler version (for example, 3.0)---and don't do anything else. (lisp-implementation-version) -A predicate=answer Evaluates: (assert (equal predicate answer)) " (in-package "COMMON-LISP-USER") (setf #+clisp ext:*load-echo* #+clisp *verbose* *load-verbose* *verbose* *compile-verbose* *verbose*) (when *ansi* (dolist (used-package (package-use-list "COMMON-LISP-USER")) (unless (eq (package-name used-package (find-package "COMMON-LISP"))) (unuse-package package "COMMON-LISP-USER")))) (in-package "COMMON-LISP-USER") (defpackage "COM.INFORMATIMAGO.DRIVER.SCRIPT" (:use "COMMON-LISP") (:export "*VERBOSE*" "*DEBUG*" "*DEFAULT-PROGRAM-NAME*" "*PROGRAM-NAME*" "*PROGRAM-PATH*" "*ARGUMENTS*" "WITHOUT-OUTPUT" "WITH-PAGER" "REDIRECTING-STDOUT-TO-STDERR" "RELAUCH-WITH-KFULL-LINKSET-IF-NEEDED" ;; I/O "PERROR" "PMESSAGE" "PQUERY" ;; Options "DEFINE-OPTION" "CALL-OPTION-FUNCTION" "PARSE-OPTIONS" "MAIN" "SET-DOCUMENTATION-TEXT" "*BASH-COMPLETION-HOOK*" ;; Utilities: "FIND-DIRECTORIES" "CONCAT" "MAPCONCAT" "GETPID" "SHELL-QUOTE-ARGUMENT" "SHELL" "EXECUTE" "RUN-PROGRAM" "UNAME" "COPY-FILE" "MAKE-SYMBOLIC-LINK" "MAKE-DIRECTORY" ;; Exit codes: "EX--BASE" "EX--MAX" "EX-CANTCREAT" "EX-CONFIG" "EX-DATAERR" "EX-IOERR" "EX-NOHOST" "EX-NOINPUT" "EX-NOPERM" "EX-NOUSER" "EX-OK" "EX-OSERR" "EX-OSFILE" "EX-PROTOCOL" "EX-SOFTWARE" "EX-TEMPFAIL" "EX-UNAVAILABLE" "EX-USAGE" "EXIT")) (in-package "COM.INFORMATIMAGO.DRIVER.SCRIPT") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (defvar *default-program-name* "untitled") (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*)))) (defvar *program-path* (program-path) "A namestring of the path to the program. This may be a relative pathname, when it's obtained from argv[0]. If available we use the actual program name (from (EXT:ARGV) or *LOAD-TRUENAME*), otherwise we fallback to *DEFAULT-PROGRAM-NAME*.") (defvar *program-name* (file-namestring *program-path*) "Name of the program.") (defvar *arguments* ext:*args* "A list of command line arguments (strings).") (defvar *verbose* nil "Adds some trace output.") (defvar *debug* nil "Errors break into the debugger.") #-(or use-ppcre use-regexp) (push #-(and) :use-ppcre #+(and) :use-regexp *features*) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (defun relauch-with-kfull-linkset-if-needed (thunk) ;; If the version of clisp requires -Kfull to have linux, then let's call it with -Kfull… (multiple-value-bind (res err) (ignore-errors (funcall thunk)) (when err (if (find "-Kfull" (ext:argv) :test (function string=)) (error err) (ext:exit (or (ext:run-program "/usr/bin/clisp" :arguments (append '("-ansi" "-q" "-E" "utf-8" "-Kfull") (cons *program-path* *arguments*)) :wait t #+linux :may-exec #+linux t #+win32 :indirectp #+win32 nil) 0)))))) #-linux (when (find "linux" *modules* :test (function string=)) (push :linux *features*)) #-(or linux macos win32 #|what else is not linux?|#) (relauch-with-kfull-linkset-if-needed (lambda () (require "linux"))) (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*) #-testing-script (exit ex-software))))) (defun getpid () (or (ignore-errors (find-symbol "getpid" "LINUX")) (ignore-errors (find-symbol "PROCESS-ID" "OS")) (ignore-errors (find-symbol "PROCESS-ID" "SYSTEM")))) (defun report-the-error (err string-stream) (let ((log-path (format nil "/tmp/~A.~D.errors" *program-name* (let ((getpid (getpid))) (if getpid (funcall getpid) "nopid"))))) (with-open-file (log-stream log-path :direction :output :if-exists :supersede :if-does-not-exist :create) (format log-stream "~A GOT AN ERROR: ~A~%~80,,,'-<~>~%~A~%" *program-name* err (get-output-stream-string string-stream))) (format *error-output* "~A: ~A~% See ~A~%" *program-name* err log-path) (finish-output *error-output*) (exit ex-software))) (defmacro without-output (&body body) `(prog1 (values) (with-output-to-string (net) (handler-case (let ((*standard-output* net) (*error-output* net) (*trace-output* net)) ,@body) (error (err) (report-the-error err net)))))) (defmacro with-pager ((&key lines) &body body) " Executes the BODY, redirecting *STANDARD-OUTPUT* to a pager. If no option is given, use the system pager obtained from the environment variable PAGER. If none is defined, then no pager is used. The following is NOT IMPLEMENTED YET: If an option is given, then it defines a local pager. LINES Number of line to output in a single chunk. After this number of line has been written, some user input is required to further display lines. " (when lines (error "~S: Sorry :LINES is not implemented yet." 'with-pager)) ;; (print (list (version:clisp-version) ;; (version:rt-version<= "2.48" (version:clisp-version)))) #+#.(version:rt-version<= "2.44" (version:clisp-version)) `(progn ,@body) #-#.(version:rt-version<= "2.44" (version:clisp-version)) (let ((pager (ext:getenv "PAGER"))) (if pager (let ((pager-stream (gensym))) `(let ((,pager-stream (ext:make-pipe-output-stream ,pager :external-format charset:utf-8 :buffered nil) ;; (ext:run-program ,pager ;; :input :stream ;; :output :terminal ;; :wait nil) )) (unwind-protect (let ((*standard-output* ,pager-stream)) ,@body) (close ,pager-stream)))) `(progn ,@body)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (defun shell-quote-argument (argument) "Quote ARGUMENT for passing as argument to an inferior shell." #+(or MSWINDOWS WIN32) ;; Quote using double quotes, but escape any existing quotes in ;; the argument with backslashes. (let ((result "") (start 0) (end) (match-beginning) (match-end)) (when (or (null (setf match-end (position #\" argument))) (< match-end (length argument))) (loop :while (setf match-beginning (position #\" argument :start start)) :do (setf end (1+ match-beginning) result (concatenate 'string result (subseq argument start end) "\\" (subseq argument end (1+ end))) start (1+ end)))) (concatenate 'string "\"" result (subseq argument start) "\"")) #-(or MSWINDOWS WIN32) (if (equal argument "") "''" ;; Quote everything except POSIX filename characters. ;; This should be safe enough even for really weird shells. (let ((result "") (start 0) (end) (match-beginning) (match-end)) (loop :while (setf match-end (position-if-not (lambda (ch) (or (alphanumericp ch) (position ch "-_./"))) argument :start start)) :do (setf end match-end result (concatenate 'string result (subseq argument start end) "\\" (subseq argument end (1+ end))) start (1+ end))) (concatenate 'string result (subseq argument start))))) (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))) #+linux ;; Should probably move away. (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))) #+linux ;; Should probably move away. (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* "/")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun perror (format-string &rest args) " DO: Writes a message on the error output in the name of the script. " (format *error-output* "~&~A: ~?" *program-name* 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: ~?" *program-name* 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: ~?" *program-name* format-string args) (finish-output *query-io*) (read-line *query-io*)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; From /usr/include/sysexits.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.") ;;EX-USAGE (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.") ;;EX-DATAERR (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).") ;;EX-NOINPUT (defconstant ex-nouser 67 "addressee unknown The user specified did not exist. This might be used for mail addresses or remote logins. ") ;;EX-NOUSER (defconstant ex-nohost 68 "host name unknown The host specified did not exist. This is used in mail addresses or network requests.") ;;EX-NOHOST (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.") ;;EX-UNAVAILABLE (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.") ;;EX-SOFTWARE (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.") ;;EX-OSERR (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).") ;;EX-OSFILE (defconstant ex-cantcreat 73 "can't create (user) output file A (user specified) output file cannot be created.") ;;EX-CANTCREAT (defconstant ex-ioerr 74 "input/output error An error occurred while doing I/O on some file.") ;;EX-IOERR (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.") ;;EX-TEMPFAIL (defconstant ex-protocol 76 "remote error in protocol the remote system returned something that was \"not possible\" during a protocol exchange.") ;;EX-PROTOCOL (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.") ;;EX-NOPERM (defconstant ex-config 78 "configuration error") (defconstant ex--max 78 "maximum listed value") (defun exit (&optional (code ex-ok)) (ext:exit code)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; OPTIONS PROCESSING ;;; (defparameter *options* (make-hash-table :test (function equal)) "The dictionary of options.") (defstruct option keys arguments documentation function) (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))) (push (subseq string position nextpos) chunks) (setf position (1+ nextpos) nextpos position)) (nreverse chunks))) (defun q&d-parse-parameters (parameters) "Parses (mandatory &optional optionals... &rest rest &key key...)" (loop :with mandatories = '() :with optionals = '() :with rest = nil :with keys = '() :with state = :mandatory :with params = parameters :for param = (first params) :while params :do (ecase state ((:mandatory) (case param ((&optional) (setf state :optional)) ((&rest) (setf state :rest)) ((&key) (setf state :key)) (otherwise (push param mandatories))) (pop params)) ((:optional) (case param ((&optional) (error "&OPTIONAL given more than once in ~S" parameters)) ((&rest) (setf state :rest)) ((&key) (setf state :key)) (otherwise (push param optionals))) (pop params)) ((:rest) (case param ((&optional) (error "&OPTIONAL given after &REST in ~S" parameters)) ((&rest) (error "&REST given twice in ~S" parameters)) ((&key) (setf state :key)) (otherwise (setf state :after-rest rest param))) (pop params)) ((:after-rest) (case param ((&optional) (error "&OPTIONAL given after &REST in ~S" parameters)) ((&rest) (error "&REST given after &REST in ~S" parameters)) ((&key) (setf state :key)) (otherwise (error "Several &REST parameters given in ~S" parameters))) (pop params)) ((:key) (case param ((&optional) (error "&OPTIONAL given after &KEY in ~S" parameters)) ((&rest) (error "&REST given after &KEY in ~S" parameters)) ((&key) (setf state :key)) (otherwise (push param keys))) (pop params))) :finally (return (values (nreverse mandatories) (nreverse optionals) rest (nreverse keys))))) (defun keywordize (string-designator) (intern (string string-designator) (load-time-value (find-package "KEYWORD")))) (defun q&d-arguments (mandatories optionals rest keys) " BUG: when the optionals or keys have a present indicator, we just ignore it and build a list that will pass the default value anyways... " (assert (every (function symbolp) mandatories)) (append mandatories (mapcar (lambda (opt) (etypecase opt (cons (first opt)) (symbol opt))) optionals) (when rest (list rest)) (mapcan (lambda (key) (etypecase key (cons (etypecase (first key) (symbol (list (keywordize (first key)) (first key))) (cons (list (second (first key)) (first (first key)))))) (symbol (list (keywordize key) key)))) keys))) (defun wrap-option-function (keys option-arguments docstring option-function) (let ((vargs (gensym))) (multiple-value-bind (mandatories optionals rest keys-args) (q&d-parse-parameters option-arguments) (setf *print-circle* nil) (make-option :keys keys :arguments option-arguments :function (compile (make-symbol (format nil "~:@(~A-WRAPPER~)" (first keys))) `(lambda (option-key ,vargs) (let ((nargs (length ,vargs))) (if (<= ,(length mandatories) nargs) ,(cond (rest `(destructuring-bind ,option-arguments ,vargs (funcall ',option-function ,@(q&d-arguments mandatories optionals rest keys-args)) nil)) (keys-args (error "An option cannot have &key parameters without a &rest parameter. ~@ Invalid option parameters: ~S" option-arguments)) (t (let ((vremaining (gensym))) `(destructuring-bind (,@option-arguments &rest ,vremaining) ,vargs (funcall ',option-function ,@(q&d-arguments mandatories optionals rest keys-args)) ,vremaining)))) (let ((missing-count (- ,(length mandatories) nargs)) (missing-args (subseq ',mandatories nargs))) (error "option ~A is missing ~:[an ~*~;~A ~]argument~:*~p: ~{~A ~}" option-key (< 1 missing-count) missing-count missing-args)))))) :documentation (split-string docstring (string #\newline)))))) (defun call-option-function (option-key arguments &optional undefined-argument) (let* ((option (gethash option-key *options*))) (cond (option (funcall (option-function option) option-key arguments)) (undefined-argument (funcall undefined-argument option-key arguments)) (t (error "Unknown option ~A ; try: ~A help" option-key *program-name*))))) (defmacro define-option (names parameters &body body) " DO: Define a new option for the scirpt. NAMES: A list designator of option names (strings such as \"-a\" \"--always\"). PARAMETERS: A list of option parameters. The names of these parameters must be descriptive as they are used to build the usage help text. BODY: The code implementing this option. RETURN: The lisp-name of the option (this is a symbol named for the first option name). " (let* ((main-name (if (listp names) (first names) names)) (other-names (if (listp names) (rest names) '())) (lisp-name (intern (string-upcase main-name))) (docstring (if (and (stringp (first body)) (rest body)) (first body) nil)) (body (if (and (stringp (first body)) (rest body)) (rest body) body))) `(progn (setf (gethash ',main-name *options*) (wrap-option-function ',(cons main-name other-names) ',parameters ',docstring (lambda ,(remove '&rest parameters) ,docstring (block ,lisp-name ,@body)))) ,@(mapcar (lambda (other-name) `(setf (gethash ',other-name *options*) (gethash ',main-name *options*))) other-names) ',lisp-name))) (defvar *documentation-text* "") (defun set-documentation-text (text) (setf *documentation-text* text)) (defun option-list () (let ((options '())) (maphash (lambda (key option) (declare (ignore key)) (pushnew option options)) *options*) options)) (define-option ("help" "-h" "--help") () "Give this help." (with-pager () (let ((options (option-list))) (format t "~2%~A options:~2%" *program-name*) (dolist (option (sort options (function string<) :key (lambda (option) (first (option-keys option))))) (format t " ~{~A~^ | ~} ~:@(~{~A ~}~)~%~@[~{~% ~A~}~]~2%" (option-keys option) (option-arguments option) (option-documentation option))) (format t "~A~%" *documentation-text*)))) ;; TODO: See if we couldn't simplify it, perhaps with complete -C. (defun list-all-option-keys () (let ((keys '())) (dolist (option (option-list)) (dolist (key (option-keys option)) (push key keys))) keys)) (defun completion-option-prefix (prefix) (dolist (key (remove-if-not (lambda (key) (and (<= (length prefix) (length key)) (string= prefix key :end2 (length prefix)))) (list-all-option-keys))) (format t "~A~%" key)) (finish-output)) (defun completion-all-options () (dolist (key (list-all-option-keys)) (format t "~A~%" key)) (finish-output)) (defvar *bash-completion-hook* nil "A function (lambda (index words) ...) that will print the completion and return true, or do nothing and return nil.") (define-option ("--bash-completions") (index &rest words) "Implement the auto-completion of arguments. This option is designed to be invoked from the function generated by the '--bash-completion-function' option. There should be no need to use directly. " (let ((index (parse-integer index :junk-allowed t))) (unless (and *bash-completion-hook* (funcall *bash-completion-hook* index words)) (if index (completion-option-prefix (elt words index)) (completion-all-options)))) (exit 0)) (define-option ("--bash-completion-function") () "Write two bash commands (separated by a semi-colon) to create a bash function used to do auto-completion of command arguments. Use it with: eval $($COMMAND --bash-completion-function) and then typing TAB on the command line after the command name will autocomplete argument prefixes. " (format t "function completion_~A(){ ~ COMPREPLY=( $(~:*~A --bash-completions \"$COMP_CWORD\" \"${COMP_WORDS[@]}\") ) ; } ;~ complete -F completion_~:*~A ~:*~A~%" *program-name*) (exit 0)) (defun parse-options (arguments &optional default undefined-argument) (flet ((process-arguments () (cond (arguments (loop :while arguments :do (setf arguments (call-option-function (pop arguments) arguments undefined-argument)))) (default (funcall default))))) (if *debug* (process-arguments) (handler-case (process-arguments) (error (err) (format *error-output* "~%ERROR: ~A~%" err) ;; TODO: select different sysexits codes depending on the error class. (return-from parse-options ex-software))))) 0) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defun not-implemented-here (function-name) (error "How to implement ~S in ~S" function-name (lisp-implementation-type))) (defun prepare-options (options) (mapcar (lambda (option) (typecase option (keyword (format nil "-~(~A~)" option)) (symbol (string-downcase option)) (string option) (t (prin1-to-string option)))) options)) (defun shell (command &rest arguments) #+clisp (ext:shell (format nil command arguments)) #-clisp (not-implemented-here 'shell)) (defun run-program (program arguments &key (input :terminal) (output :terminal) (if-output-exists :error) (wait t)) " RETURN: The status returned by the command. SEE ALSO: SHELL " #+clisp (ext:run-program program :arguments arguments :input input :output output :if-output-exists if-output-exists :wait wait) #-clisp (not-implemented-here 'run-program)) (defun uname (&rest options) "Without OPTIONS, return a keyword naming the system (:LINUX, :DARWIN, etc). With options, returns the first line output by uname(1)." (with-open-stream (uname (run-program "uname" (prepare-options options) :input nil :output :stream :wait t)) (values (if options (read-line uname) (intern (string-upcase (read-line uname)) "KEYWORD"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Some emacs style functions. ;;; (defun find-directories (rootpath) "Return a list of recursive subdirectories starting from ROOTPATH that are accessible by the user." (directory (merge-pathnames (make-pathname :directory '(:relative :wild-inferiors) :name nil :type nil :version nil) rootpath nil))) (defun concat (&rest items) (with-output-to-string (*standard-output*) (dolist (item items) (typecase item (string (write-string item *standard-output*)) (sequence (write-sequence item *standard-output*)) (t (with-standard-io-syntax (format *standard-output* "~A" item))))))) (defun mapconcat (function sequence separator) (etypecase sequence (list (if sequence (let* ((items (mapcar (lambda (item) (let ((sitem (funcall function item))) (if (stringp sitem) sitem (princ-to-string sitem)))) sequence)) (ssepa (if (stringp separator) separator (princ-to-string separator))) (size (+ (reduce (function +) items :key (function length)) (* (length ssepa) (1- (length items))))) (result (make-array size :element-type 'character)) (start 0)) (replace result (first items) :start1 start) (incf start (length (first items))) (dolist (item (rest items)) (replace result ssepa :start1 start) (incf start (length ssepa)) (replace result item :start1 start) (incf start (length item))) result) "")) (vector (if (plusp (length sequence)) (let* ((items (map 'vector (lambda (item) (let ((sitem (funcall function item))) (if (stringp sitem) sitem (princ-to-string sitem)))) sequence)) (ssepa (if (stringp separator) separator (princ-to-string separator))) (size (+ (reduce (function +) items :key (function length)) (* (length ssepa) (1- (length items))))) (result (make-array size :element-type 'character)) (start 0)) (replace result (aref items 0) :start1 start) (incf start (length (aref items 0))) (loop :for i :from 1 :below (length items) :do (replace result ssepa :start1 start) (incf start (length ssepa)) (replace result (aref items i) :start1 start) (incf start (length (aref items i)))) result) "")))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; ;; ;;; The main program, definition of the options ;; ;;; ;; ;; ;; (in-package "COMMON-LISP-USER") ;; (load (make-pathname :name "SCRIPT" :type "LISP" :version NIL :case :common ;; :defaults *load-pathname*)) ;; (use-package "SCRIPT") ;; ;; ;; (redirecting-stdout-to-stderr (load #p"/etc/gentoo-init.lisp")) ;; (redirecting-stdout-to-stderr ;; (let ((*load-verbose* nil) ;; (*compile-verbose* nil)) ;; (load (make-pathname :name ".clisprc" :type "lisp" :case :local ;; :defaults (user-homedir-pathname))) ;; ;; (setf *features* (delete :testing-script *features*)) ;; )) ;; (redirecting-stdout-to-stderr (asdf:oos 'asdf:load-op :split-sequence) ;; (asdf:oos 'asdf:load-op :cl-ppcre)) ;; ;; ;; #-testing-script ;; (exit (main ext:*args*)) ;;;; THE END ;;;;
40,445
Common Lisp
.lisp
899
35.126808
134
0.565573
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
93a50a10d7525c391c1f5c3a6309e62afeae5f69e1d5755813831bef8020c7b4
5,178
[ -1 ]
5,179
hello.lisp
informatimago_lisp/driver/test-ll/hello.lisp
(defpackage "H" (:use "CL") (:export "ELLO")) (in-package "H") (defun ello () (prin1 'hello))
100
Common Lisp
.lisp
6
14.666667
19
0.585106
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
38e23951fa2c712dcf2d4f2573349cf9fd33b17da1f972184e578decced45939
5,179
[ -1 ]
5,180
word.lisp
informatimago_lisp/driver/test-ll/word.lisp
(defpackage "W" (:use "CL") (:export "ORD")) (in-package "W") (defun ord () (prin1 'ord))
96
Common Lisp
.lisp
6
14
18
0.566667
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6d7a0ee05e81e0bf3d85459ad8163793bd1787c1a87c71475dc90fbc8b382ce9
5,180
[ -1 ]
5,181
package.lisp
informatimago_lisp/lispdoc/package.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: packages.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines the packages. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-04 <PJB> Extracted from lispdoc.lisp ;;;;BUGS ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.LISPDOC.UTILITY" (:use "COMMON-LISP") (:export "APPENDF") (:documentation " A few utility operators. License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.URI" (:use "COMMON-LISP" "CL-PPCRE") (:export "URI" "URI-REFERENCE") (:documentation " Exports cl-ppcre scanners for URI and URI-REFERENCE. License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.DOC" (:use "COMMON-LISP") (:export "CLASSDOC" "CLASSDOC-INITARGS" "CLASSDOC-P" "CLASSDOC-PRECEDENCE-LIST" "COPY-CLASSDOC" "COPY-DOC" "COPY-FUNDOC" "COPY-PACKDOC" "COPY-VARDOC" "DOC" "DOC-KIND" "DOC-NAME" "DOC-P" "DOC-STRING" "DOC-SYMBOL" "FUNDOC" "FUNDOC-LAMBDA-LIST" "FUNDOC-P" "MAKE-CLASSDOC" "MAKE-DOC" "MAKE-FUNDOC" "MAKE-PACKDOC" "MAKE-VARDOC" "PACKDOC" "PACKDOC-EXTERNAL-SYMBOL-DOCS" "PACKDOC-NICKNAMES" "PACKDOC-P" "VARDOC" "VARDOC-INITIAL-VALUE" "VARDOC-P") (:documentation " The documentation is stored in DOC objects (various subclasses). License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 Copyright (C) 2003 Sven Van Caekenberghe. You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC" (:use "COMMON-LISP" "COM.INFORMATIMAGO.LISPDOC.DOC") (:export "LISPDOC") (:documentation " LISPDOC scans in-image packages and return a list of filled PACKDOC structures. License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 Copyright (C) 2003 Sven Van Caekenberghe. You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.TREE" (:use "COMMON-LISP" "SPLIT-SEQUENCE" "COM.INFORMATIMAGO.LISPDOC.UTILITY") (:export "*HIERARCHICAL-PACKAGE-SEPARATOR*" "PACKAGE-PATH" "TREE" "MAKE-TREE" "TREE-P" "TREE-COPY" "TREE-PARENT" "TREE-NODE" "TREE-PACKAGE" "TREE-CHILDREN" "TREE-CHILDREN-NAMED" "TREE-ADD-NODE-AT-PATH" "MAKE-INDEX-TREE" "TREE-NODE-AT-PATH" "TREE-PATH") (:documentation " A package tree index, for hierarchical packages index. License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.GENERATE" (:use "COMMON-LISP" "SPLIT-SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.LISPDOC" "COM.INFORMATIMAGO.LISPDOC.DOC" "COM.INFORMATIMAGO.LISPDOC.TREE" "COM.INFORMATIMAGO.LISPDOC.UTILITY") (:export "DOCUMENTATION-GENERATOR" "DOCUMENTATION-TITLE" "COPYRIGHT" "AUTHOR" "EMAIL" "KEYWORDS" "PACKDOCS" "PAGES" "INDEX-TREE" "RENDER" "NAVIGATION" "GENERATE-LISPDOC" "GENERATE-BEGIN" "GENERATE-END" "GENERATE-INTRODUCTION" "GENERATE-SYMBOL-INDEX" "GENERATE-PERMUTED-SYMBOL-INDEX" "GENERATE-FLAT-SYMBOL-INDEX" "GENERATE-FLAT-PACKAGE-INDEX" "GENERATE-HIERARCHICAL-PACKAGE-INDEX" "GENERATE-PACKAGE-DOCUMENTATION-PAGES" "GENERATE-NAVIGATION-MENU" "PACKAGE-NAVIGATION-MENU" "BUILD-PERMUTED-SYMBOL-INDEX-GROUPS" "BUILD-FLAT-SYMBOL-INDEX-GROUPS" "FIRST-LETTER" "RIGHT-CASE" "COLLECT-ALL-SYMBOLS") (:documentation " A generator class shall have methods defined for all the generic functions exported from this package. License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.GENERATE.HTML" (:use "COMMON-LISP" "CL-PPCRE" "SPLIT-SEQUENCE" "COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML" "COM.INFORMATIMAGO.LISPDOC.URI" "COM.INFORMATIMAGO.LISPDOC.DOC" "COM.INFORMATIMAGO.LISPDOC.TREE" "COM.INFORMATIMAGO.LISPDOC.GENERATE" "COM.INFORMATIMAGO.LISPDOC.UTILITY") (:shadowing-import-from "COMMON-LISP" "MAP") ; in html-generator too. (:shadowing-import-from "CL-PPCRE" "SCAN") ; in html-generator too. (:export "HTML-DOCUMENTATION") (:documentation " License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 Copyright (C) 2003 Sven Van Caekenberghe. You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.GENERATE.RST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.LISPDOC.URI" "COM.INFORMATIMAGO.LISPDOC.DOC" "COM.INFORMATIMAGO.LISPDOC.GENERATE" "COM.INFORMATIMAGO.LISPDOC.UTILITY") (:export "RST-DOCUMENTATION") (:documentation " Generate a single-file reStructuredText documentation. The docstrings may contain reStructuredText markups, which is taken as-is, but title and subtitles need to marked up consistently across all the packages documented in a single document. The RST-DOCUMENTATION generator will generate only double-line (above and below) document and chapter title markups, reserving single-line (below) title markups to the docstrings. It would be advised to use the following title markups in docstrings: docstring section ******************** docstring subsection ==================== sub-subsection -------------------- sub-sub-subsection .................... License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.GENERATE.TEXT" (:use "COMMON-LISP" "COM.INFORMATIMAGO.LISPDOC.URI" "COM.INFORMATIMAGO.LISPDOC.DOC" "COM.INFORMATIMAGO.LISPDOC.GENERATE" "COM.INFORMATIMAGO.LISPDOC.UTILITY") (:export "TEXT-DOCUMENTATION") (:documentation " Generate a single-file plain-text documentation. The docstrings are copied as-is, surrounded by some formatted titles. License: LLGPL Copyright Pascal J. Bourguignon 2015 - 2015 You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) (defpackage "COM.INFORMATIMAGO.LISPDOC.RUN" (:use "COMMON-LISP" "COM.INFORMATIMAGO.LISPDOC.DOC" "COM.INFORMATIMAGO.LISPDOC.GENERATE" "COM.INFORMATIMAGO.LISPDOC.GENERATE.RST" "COM.INFORMATIMAGO.LISPDOC.GENERATE.HTML") (:export "DOC") (:documentation " Automatically generate documentation for properly documented symbols exported from packages. This is tool automatically generates documentation for Common Lisp code based on symbols that exported from packages and properly documented. This code was written for OpenMCL <http://openmcl.clozure.com> There are generators for HTML and reStructuredText formats. Other generators classes can be written by the user. License: LLGPL Copyright Pascal J. Bourguignon 2012 - 2015 Copyright (C) 2003 Sven Van Caekenberghe. You are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License <http://opensource.franz.com/preamble.html> also known as the LLGPL. ")) ;;;; THE END ;;;;
10,329
Common Lisp
.lisp
249
36.714859
78
0.696948
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
86782ce0313c504fde63d9a1ae424714eceb8446d3053c7f1c0f44f327550acb
5,181
[ -1 ]
5,182
tree.lisp
informatimago_lisp/lispdoc/tree.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: tree.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Implements a package tree index, for hierarchical package index. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-04 <PJB> Extracted from lispdoc.lisp. ;;;;BUGS ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LISPDOC.TREE") (defvar *hierarchical-package-separator* #\. "The character used to separate package 'components' in hierarchical package names. It's usually a dot, but some may use a different character such as a slash.") (defun package-path (package) " RETURN: A list of component strings representing the name of the PACKAGE, assuming it is structured as a list of components joined by the *HIERARCHICAL-PACKAGE-SEPARATOR*. EXAMPLE: (package-path \"COM.INFORMATIMAGO.LISPDOC.TREE\") --> (\"COM\" \"INFORMATIMAGO\" \"LISPDOC\" \"TREE\") " (split-sequence *hierarchical-package-separator* (etypecase package (string package) (package (package-name package))))) (defstruct (tree (:copier tree-copy)) " A node in the package hierarchical naming tree. PARENT: a reference to the parent node, or NIL for the root. NODE: the string component naming this node. PACKAGE: the joined hierarchical package name of the package designated by this node, or NIL if none. CHILDREN: the subtrees. " parent node package (children '())) (defmethod print-object ((tree tree) stream) (print-unreadable-object (tree stream :identity t :type t) (format stream "~S" (list :node (tree-node tree) :package (tree-package tree) :children (length (tree-children tree))))) tree) (defun tree-children-named (tree node) " RETURN: the child in the TREE named by NODE. " (find node (tree-children tree) :key (function tree-node) :test (function equal))) (defun tree-add-node-at-path (tree path pname) " DO: Add a new tree node in the TREE for the package named PNAME at the given relative PATH. RETURN: tree. " (if (endp path) (progn (setf (tree-package tree) pname) tree) (let ((child (tree-children-named tree (first path)))) (if child (tree-add-node-at-path child (rest path) pname) (let ((new-child (make-tree :parent tree :node (first path) :package (when (endp (rest path)) pname)))) (appendf (tree-children tree) (list new-child)) (tree-add-node-at-path new-child (rest path) pname)))))) (defun make-index-tree (package-names) " RETURN: a new tree filled with nodes for all the PACKAGE-NAMES. " (let ((root (make-tree))) (dolist (pname package-names root) (tree-add-node-at-path root (package-path pname) pname)))) (defun tree-node-at-path (tree path) " RETURN: The tree node found at the given PATH. " (if (endp path) tree (let ((child (tree-children-named tree (first path)))) (when child (tree-node-at-path child (rest path)))))) (defun tree-path (tree) " RETURN: The path from TREE to the root. " (cons (tree-node tree) (when (and (tree-parent tree) (tree-node (tree-parent tree))) (tree-path (tree-parent tree))))) ;;;; THE END ;;;;
4,898
Common Lisp
.lisp
127
33.055118
102
0.611298
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ef54f943cc8ddf78daa7f5217ec9d1456a6c019754a70b859720060ba1001f24
5,182
[ -1 ]
5,183
lispdoc.lisp
informatimago_lisp/lispdoc/lispdoc.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: lispdoc.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Generate HTML documentation of a set of CL packages. ;;;; ;;;; Originally: ;;;; Id: lispdoc.lisp,v 1.8 2004/01/13 14:03:41 sven Exp ;;;;AUTHORS ;;;; Sven Van Caekenberghe. ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-04-29 <PJB> ;;;;BUGS/TODO ;;;; ;;;; - improve class documentation (slots, accessors). ;;;; ;;;; - improve navigation menu (symbol lists, tree). ;;;; ;;;; - make it run on clisp, sbcl, etc. ;;;; ;;;; - deal with re-exported symbol, whose home is not one of the ;;;; documented packages. ;;;; ;;;; - make it merge documentations (tree, navigation), since some ;;;; packages can only be loaded in a specific implementation. ;;;; ;;;; - make links from symbols and packages to source files (eg. gitorious). ;;;; ;;;; - It would be nice to have a reST parser for the docstrings. ;;;; Check cl-docutils for its reST parser? ;;;; http://www.jarw.org.uk/lisp/cl-docutils.html ;;;; ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2012 - 2016 ;;;; Copyright (C) 2003 Sven Van Caekenberghe. ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LISPDOC") ;;;---------------------------------------------------------------------- ;;; ;;; documentation portability layer ;;; (defun function-lambda-list (funame) " FUNAME: A function name. RETURN: The function lambda list. " (let ((le (function-lambda-expression (if (consp funame) (fdefinition funame) (or (macro-function funame) (symbol-function funame)))))) (if le (second le) (or #+swank (swank/backend:arglist funame) #+openmcl (ccl:arglist funame) #+lispworks (lw:function-lambda-list funame) '())))) (defun class-precedence-list (class-name) " CLASS-NAME: A class name. RETURN: The class precedence list. " (let ((class (find-class class-name))) (closer-mop:ensure-finalized class) (closer-mop:class-precedence-list class))) (defun class-slot-initargs (class-name) " CLASS-NAME: A class name. RETURN: The initargs of the class slots. " (let ((class (find-class class-name))) (closer-mop:ensure-finalized class) (mapcan (lambda (slot) (copy-seq (closer-mop:slot-definition-initargs slot))) (closer-mop:class-slots class)))) (defun has-meaning (symbol) (or (boundp symbol) (fboundp symbol) (ignore-errors (fdefinition `(setf ,symbol))) (ignore-errors (find-class symbol)))) ;;;---------------------------------------------------------------------- ;;; ;;; lispdoc ;;; (defun lispdoc-symbol (symbol) " RETURN: A list of doc structures for the SYMBOL. " (let ((doc '())) (when (documentation symbol 'variable) (push (make-vardoc :kind (if (constantp symbol) :constant :variable) :symbol symbol :string (documentation symbol 'variable) :initial-value (if (boundp symbol) (symbol-value symbol) :unbound)) doc)) (let ((spec `(setf ,symbol))) (when (and (documentation spec 'function) (fboundp spec)) (push (make-fundoc :kind (cond ((typep (fdefinition spec) 'standard-generic-function) :generic-function) (t :function)) :symbol `(setf ,symbol) :string (documentation spec 'function) :lambda-list (function-lambda-list spec)) doc))) (when (and (documentation symbol 'function) (fboundp symbol)) (push (make-fundoc :kind (cond ((macro-function symbol) :macro) ((typep (fdefinition symbol) 'standard-generic-function) :generic-function) (t :function)) :symbol symbol :string (documentation symbol 'function) :lambda-list (function-lambda-list symbol)) doc)) (when (documentation symbol 'type) (cond ((not (ignore-errors (find-class symbol))) (push (make-doc :kind :type :symbol symbol :string (documentation symbol 'type)) doc)) ((subtypep (find-class symbol) (find-class 'structure-object)) (push (make-classdoc :kind :structure :symbol symbol :string (documentation symbol 'type)) doc)) (t (block :ignore (push (make-classdoc :kind (cond ((subtypep (find-class symbol) (find-class 'condition)) :condition) ((subtypep (find-class symbol) (find-class 'standard-object)) :class) (t (return-from :ignore))) :symbol symbol :string (documentation symbol 'type) :precedence-list (mapcar (function class-name) (class-precedence-list symbol)) :initargs (class-slot-initargs symbol)) doc))))) (unless doc (push (make-doc :kind (if (has-meaning symbol) :undocumented :skip) :symbol symbol) doc)) doc)) (defun lispdoc-package (package) " RETURN: packdoc structure for the package. " (make-packdoc :kind :package :symbol package :string (or (documentation package t) :undocumented) :nicknames (package-nicknames package) :external-symbol-docs (mapcan (function lispdoc-symbol) (let ((symbols '())) (do-external-symbols (x package) (push x symbols)) (sort symbols (function string-lessp)))))) (defun lispdoc (packages) "Generate a lispdoc sexp documenting the exported symbols of each package" (mapcar (lambda (package) (lispdoc-package (if (packagep package) package (find-package package)))) packages)) ;;;; THE END ;;;;
8,533
Common Lisp
.lisp
205
29.912195
112
0.494879
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
908e470af3a348a7de6ff9902412c1733ca4b2f8b7bd6c8bd3ee175b46649610
5,183
[ -1 ]
5,184
doc.lisp
informatimago_lisp/lispdoc/doc.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: doc.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines the doc classes. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-03 <PJB> Extracted from lispdoc. ;;;;BUGS ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LISPDOC.DOC") (defstruct doc symbol kind string) (defstruct (packdoc (:include doc)) nicknames external-symbol-docs) (defstruct (vardoc (:include doc)) initial-value) (defstruct (fundoc (:include doc)) lambda-list) (defstruct (classdoc (:include doc)) precedence-list initargs) (defun doc-name (doc) (let ((name (doc-symbol doc))) (etypecase name (package (package-name name)) (symbol name) (cons (second name))))) ;;;; THE END ;;;;
2,146
Common Lisp
.lisp
64
31.6875
78
0.614382
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
446dd15b2fe3943dc5734367158aa78777b2723d55a842e3b8c941261ddaa4e4
5,184
[ -1 ]
5,185
utility.lisp
informatimago_lisp/lispdoc/utility.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: utility.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Exports a few utility operators. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-04 <PJB> Extracted from lispdoc.lisp ;;;;BUGS ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LISPDOC.UTILITY") (define-modify-macro appendf (&rest args) append "Append onto list") ;;;; THE END ;;;;
1,787
Common Lisp
.lisp
46
37.608696
78
0.604263
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6cf06ac9e84e6e471001759e13fd6ab8fbf41339030076316e65f6d5a5401388
5,185
[ -1 ]
5,186
lispdoc-run.lisp
informatimago_lisp/lispdoc/lispdoc-run.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: lispdoc-run.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Generates the com.informatimago documentation. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-04-28 <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 "COM.INFORMATIMAGO.LISPDOC.RUN") (defun doc (&key (target-class 'html-documentation) (doc-directory (merge-pathnames #P"public_html/sites/com.informatimago.www/develop/lisp/doc/" (user-homedir-pathname)))) (let ((*print-length* 10) (*print-level* 4) (*print-right-margin* 80)) (mapc 'delete-file (directory (merge-pathnames #P"*.html" doc-directory))) (com.informatimago.lispdoc.generate:generate-lispdoc target-class doc-directory (remove-if-not (lambda (p) (and (search "COM.INFORMATIMAGO" (package-name p)) (not (search "COM.INFORMATIMAGO.PJB" (package-name p))))) (list-all-packages)) :title "Informatimago CL Software" ; "Informatimago Common Lisp Packages Documentation" :copyright "Copyright Pascal J. Bourguignon 2012 - 2015" :author "Pascal J. Bourguignon" :email "[email protected]" :keywords "Informatimago, Common Lisp, Lisp, Library"))) ;;;; THE END ;;;;
2,551
Common Lisp
.lisp
57
40
107
0.601766
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
72dd22d60c722e940635e34b1b671f7cb4c3002a24c9e1c4894b56f377318b6a
5,186
[ -1 ]
5,187
genrst.lisp
informatimago_lisp/lispdoc/genrst.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: genrst.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Generate reStructuredText documentation. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-04 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LISPDOC.GENERATE.RST") (defclass rst-documentation (documentation-generator) ()) ;;;; THE END ;;;;
1,766
Common Lisp
.lisp
46
37.217391
78
0.605478
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7cb05245c7bd500a9453b8363434dc6efab4d1e6f0a1cfc7e70e9f32781148e0
5,187
[ -1 ]
5,188
genhtml.lisp
informatimago_lisp/lispdoc/genhtml.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: genhtml.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; HTML generator for the documentation. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-03 <PJB> Extracted from lispdoc. ;;;;BUGS ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LISPDOC.GENERATE.HTML") ;;;---------------------------------------------------------------------- ;;; ;;; processing pjb docstrings. ;;; (defun replace-urls (text) " Search all the urls in the text, and replace them with an A tag. " (let ((start 0)) (loop (multiple-value-bind (wbegin wend begins ends) (scan '(:sequence #\< (:register uri) #\>) text :start start) (declare (ignore wbegin wend)) (if begins (let ((begin (aref begins 0)) (end (aref ends 0))) (pcdata "~A" (subseq text start begin)) (let ((url (subseq text begin end))) (a (:href url) (pcdata "~A" url))) (setf start end)) (progn (pcdata "~A" (subseq text start (length text))) (return))))))) (defun pjb-docstring (docstring) (if (eq :undocumented docstring) (p (:class "undocumented") (i - (pcdata "undocumented"))) (pre (:class "docstring") (replace-urls docstring)))) ;;;---------------------------------------------------------------------- ;;; ;;; Documentation HTML generation ;;; (defun report-file (path) (format *trace-output* "~&;; Writing file ~A~%" path) path) (defun style-sheet () (link (:rel "stylesheet" :type "text/css" :href "style.css"))) (defun create-style-sheet () (with-open-file (css (report-file "style.css") :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (format css " body { margin: 10px; padding: 10px; } pre.docstring { margin: 20px; } div.symbol { padding:2px; background-color:#ddeeee; } div.kind { padding:2px; background-color:#ddeeee; } .undocumented { foreground-color:#ff0000; } .menu a { background-color:#80a0a0; border:1px solid #308080; padding:2px; } .menu input { color:#000000; background-color:#80a0a0; border:1px solid #308080; padding:2px; } .menu a:link {color:#000000;} /* unvisited link */ .menu a:visited {color:#004444;} /* visited link */ .menu a:hover {color:#FFFFFF;} /* mouse over link */ .menu a:active {color:#00FFFF;} /* selected link */ .header p { font-size:80%; } .footer p { font-size:80%; } "))) (defun doc-title (name arglist kind) (a (:name (if (atom name) (format nil "~A" (symbol-name name)) (format nil "(SETF ~A)" (symbol-name (second name)))))) (table (:border "0" :width "100%") (tr - (td (:valign "top" :align "left") (div (:class "symbol") (cond ((not (member kind '(:function :generic-function :macro))) (b - (pcdata "~A" (right-case name)))) ((and (consp name) (eq (car name) 'setf)) (pcdata "(setf (") (b - (pcdata "~A" (right-case (second name)))) (pcdata "~{ ~A~}) ~A)" (right-case (rest arglist)) (right-case (first arglist)))) (t (pcdata "(") (b - (pcdata "~A" (right-case name))) (pcdata "~{ ~A~}" (right-case arglist)) (pcdata ")"))))) (td (:valign "top" :align "right" :width "200px") (div (:class "kind") (i - (pcdata "~(~A~)" kind))))))) (defun generate-head (target &optional (title nil titlep)) (head () (title () (pcdata "~A" (if titlep title (documentation-title target)))) (link (:rel "shortcut icon" :href "/favicon.ico")) (link (:rel "icon" :href "/favicon.ico" :type "image/vnd.microsoft.icon")) (link (:rel "icon" :href "/favicon.png" :type "image/png")) (meta (:http-equiv "Content-Type" :content "text/html; charset=utf-8")) (when (author target) (meta (:name "Author" :content (author target)))) (when (email target) (meta (:name "Reply-To" :content (email target)))) (when (keywords target) (meta (:name "Keywords" :content (keywords target)))) (style-sheet))) ;;;--------------------------------------------------------------------- ;;; ;;; HTML Documentation render ;;; (defclass html-documentation (documentation-generator) ()) (defmethod initialize-instance :after ((target html-documentation) &key &allow-other-keys) ;; TODO: this ../index link is specific to informatimago; it should be moved to .lispdoc.run (setf (navigation target) `(("../index" ,(documentation-title target)) ("index" "Documentation Index") ("hierarchical-package-index" "Hierarchical Package Index") ("flat-package-index" "Flat Package Index") ("symbol-index" "Symbol Indices")))) (defgeneric header (target page-name)) (defgeneric footer (target page-name)) (defun make-url (page) (format nil "~(~A.html~)" page)) (defmethod generate-introduction ((target html-documentation)) (create-style-sheet) (let ((page-name "index")) (with-open-file (html (report-file (make-url page-name)) :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (with-html-output (html :encoding :utf-8) (doctype :transitional (html () (generate-head target) (body () (header target page-name) (h1 () (pcdata "~A" (documentation-title target))) (ul - (loop :for (fn text) :in (navigation target) :unless (equalp fn page-name) :do (li - (a (:href (make-url fn)) (pcdata "~A" text))))) (footer target page-name)))))))) (defvar *navigation* nil "The current navigation menu.") (defmethod generate-navigation-menu ((target html-documentation) &optional (entries nil entriesp)) " ENTRIES: A list of (list url text). Usually, some variant of (navigation target). " (div (:class "menu") (p - (loop :for (filename text) :in (if entriesp entries (navigation target)) :do (pcdata "   ") ;; (form (:action (make-url filename) :method "GET") ;; (input (:type "submit" :value text))) (a (:href (make-url filename)) (pcdata "~A" text)))))) (defmethod header ((target html-documentation) page-name) (div (:class "header") (generate-navigation-menu target (remove page-name (navigation target) :test (function string=) :key (function first)))) (hr) (br)) (defmethod footer ((target html-documentation) page-name) (br) (hr) (div (:class "footer") (generate-navigation-menu target (remove page-name (navigation target) :test (function string=) :key (function first))) (p - (pcdata (copyright target))))) ;;;--------------------------------------------------------------------- ;;; ;;; HTML rendering ;;; (defmethod render ((doc doc) (target html-documentation)) (ecase (doc-kind doc) (:type (doc-title (doc-symbol doc) nil (doc-kind doc)) (pjb-docstring (doc-string doc))) (:skip (format t "~&;; warning: lispdoc skipping ~s~%" (doc-symbol doc))) (:undocumented (p - (b - (pcdata "~A" (doc-symbol doc))) "    " (i (:class "undocumented") "undocumented"))))) (defmethod render ((doc packdoc) (target html-documentation)) (let ((page-name (doc-name doc))) (with-open-file (html (report-file (make-url page-name)) :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (let ((title (format nil "Package ~A" (doc-name doc))) (*navigation* (package-navigation-menu target page-name (or *navigation* (navigation target))))) (with-html-output (html :encoding :utf-8) (doctype :transitional (html () (generate-head target) (body () (header target page-name) (h1 () (pcdata "~A" title)) (when (packdoc-nicknames doc) (blockquote - (pcdata "Nicknames: ") (tt - (pcdata "~{ ~A~}" (packdoc-nicknames doc))))) (pjb-docstring (doc-string doc)) (mapc (lambda (doc) (render doc target)) (packdoc-external-symbol-docs doc)) (footer target page-name)))))) (pathname html)))) (defmethod render ((doc vardoc) (target html-documentation)) (doc-title (doc-symbol doc) nil (doc-kind doc)) (pjb-docstring (doc-string doc)) (if (eq (vardoc-initial-value doc) :unbound) (blockquote - (pcdata "Initially unbound")) (blockquote - (pcdata "Initial value: ") (tt - (pcdata "~A" (vardoc-initial-value doc)))))) (defmethod render ((doc fundoc) (target html-documentation)) (doc-title (doc-symbol doc) (fundoc-lambda-list doc) (doc-kind doc)) (pjb-docstring (doc-string doc))) (defmethod render ((doc classdoc) (target html-documentation)) (doc-title (doc-symbol doc) nil (doc-kind doc)) (pjb-docstring (doc-string doc)) (when (classdoc-precedence-list doc) (blockquote - (pcdata "Class precedence list: ") (tt - (pcdata "~{ ~A~}" (classdoc-precedence-list doc))))) (when (classdoc-initargs doc) (blockquote - (pcdata "Class init args: ") (tt - (pcdata "~{ ~A~}" (classdoc-initargs doc)))))) ;;;--------------------------------------------------------------------- (defmethod generate-hierarchical-package-index ((target html-documentation) tree &optional (filename "hierindex")) (loop ;; find the first node from the root that has more than one child or designate an actual package. :while (and (= 1 (length (tree-children tree))) (null (tree-package tree)) (null (tree-package (first (tree-children tree))))) :do (setf tree (first (tree-children tree)))) (flet ((filename (path) (format nil "~{~A~^.~}" (reverse path)))) (let ((title (filename (tree-path tree)))) (with-open-file (html (report-file (make-url filename)) :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (with-html-output (html :encoding :utf-8) (doctype :transitional (html () (generate-head target title) (body () (header target filename) (h1 () (pcdata "~A" title)) (ul - (dolist (child (tree-children tree)) (let ((childfile (filename (tree-path child)))) (li - (a (:href (make-url childfile)) (if (tree-package child) (pcdata "Package ~A" (tree-package child)) (progn (pcdata "System ~A" childfile) (generate-hierarchical-package-index target child childfile)))))))) (footer target filename))))))))) (defmethod generate-flat-package-index ((target html-documentation) pages &optional (filename "flatindex")) (let ((title "Flat Package Index")) (with-open-file (html (report-file (make-url filename)) :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (with-html-output (html :encoding :utf-8) (doctype :transitional (html () (generate-head target title) (body () (header target filename) (h1 () (pcdata "~A" title)) (ul - (dolist (page pages) (li - (a (:href (make-url page)) (pcdata "~A" page))))) (footer target filename)))))))) (defmethod generate-flat-symbol-index ((target html-documentation) syms &optional (filename "flatsymindex")) " RETURN: A list of (first-letter filename) " (let ((groups (build-flat-symbol-index-groups syms)) (indices '())) ;; Generate each group index: (dolist (group groups (nreverse indices)) (let* ((group (sort group (function string-lessp) :key (lambda (x) (symbol-name (doc-name x))))) (first-letter (first-letter (first group))) (filename (format nil "~A-~A" filename first-letter)) (title (format nil "Alphabetical Symbol Index -- ~A" first-letter)) (width (reduce (function max) group :key (lambda (x) (length (princ-to-string (doc-symbol x))))))) (push (list first-letter filename) indices) (with-open-file (html (report-file (make-url filename)) :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (with-html-output (html :encoding :utf-8) (doctype :transitional (html () (generate-head target title) (body () (header target filename) (h1 () (pcdata "~A" title)) (pre - (dolist (sym group) (let ((packname (package-name (symbol-package (doc-name sym))))) (a (:href (with-standard-io-syntax (format nil "~A#~A" (make-url packname) (doc-symbol sym)))) (pcdata "~A" (doc-symbol sym))) (pcdata "~V<~>" (- width -4 (length (princ-to-string (doc-symbol sym))))) (a (:href (make-url packname)) (pcdata "~(~A~)" packname)) (pcdata "~%")))) (footer target filename)))))))))) (defmethod generate-permuted-symbol-index ((target html-documentation) syms &optional (filename "permsymindex")) " RETURN: A list of (first-letter filename) " (let ((groups (build-permuted-symbol-index-groups syms)) (indices '())) ;; Generate each group index: (dolist (group groups (nreverse indices)) (let ((first-letter (pop group))) (labels ((compute-offset (name index) (if (equalp first-letter (aref name index)) index (loop :for previous :from index :for i :from (1+ index) :below (length name) :while (not (and (not (alpha-char-p (aref name previous))) (equalp first-letter (aref name i)))) :finally (return (if (< i (length name)) i nil))))) (offset (doc) (if (consp (doc-symbol doc)) (compute-offset (princ-to-string (doc-symbol doc)) (length "(setf ")) (compute-offset (symbol-name (doc-name doc)) 0)))) (let* ((group (sort group (function string-lessp) :key (lambda (doc) (let ((name (princ-to-string (doc-symbol doc))) (offset (offset doc))) (concatenate 'string (subseq name offset) (subseq name 0 offset)))))) (filename (format nil "~A-~A" filename first-letter)) (title (format nil "Permuted Symbol Index -- ~A" first-letter)) (indent (reduce (lambda (a b) (cond ((null a) b) ((null b) a) (t (max a b)))) group :key (function offset))) (width (reduce (function max) group :key (lambda (x) (length (princ-to-string (doc-symbol x))))))) (push (list first-letter filename) indices) (with-open-file (html (report-file (make-url filename)) :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (with-html-output (html :encoding :utf-8) (doctype :transitional (html () (generate-head target title) (body () (header target filename) (h1 () (pcdata "~A" title)) (pre - (dolist (sym group) (let ((packname (package-name (symbol-package (doc-name sym)))) (offset (offset sym))) (when offset (pcdata (make-string (- indent (offset sym)) :initial-element #\space)) (a (:href (with-standard-io-syntax (format nil "~A#~A" (make-url packname) (doc-symbol sym)))) (pcdata "~A" (doc-symbol sym))) (pcdata "~V<~>" (- (+ width 4) (- (length (princ-to-string (doc-symbol sym))) offset))) (a (:href (make-url packname)) (pcdata "~(~A~)" packname)) (pcdata "~%"))))) (footer target filename)))))))))))) (defmethod generate-symbol-index ((target html-documentation) flat-indices permuted-indices symbol-count &optional (filename "symindex")) (flet ((gen-index (indices) (div (:class "menu") (loop :for sep = "" :then "   " :for (first-letter initial-filename) :in indices :do (progn (pcdata sep) (a (:href (make-url initial-filename)) (pcdata "~A" (if (eq :other first-letter) "Non-Alphabebtic" first-letter)))))))) (let ((title "Symbol Indices")) (with-open-file (html (report-file (make-url filename)) :direction :output :if-does-not-exist :create :if-exists :supersede :external-format :utf-8) (with-html-output (html :encoding :utf-8) (doctype :transitional (html () (generate-head target title) (body () (header target filename) (h1 - (pcdata "Alphabetical Symbol Index")) (p - (pcdata "There are ~A symbols exported from the Informatimago Common Lisp packages." symbol-count)) (gen-index flat-indices) (p - (a (:href "") (pcdata "Click here to see all the symbols on one page, alphabetically."))) (h1 - (pcdata "Permuted Symbol Index")) (p - (pcdata "A permuted index includes each ") (i - (pcdata "n")) (pcdata "-word entry up to ") (i - (pcdata "n")) (pcdata " times, at points corresponding to the use of each word in the entry") (pcdata " as the sort key. For example, a symbol ") (tt - (pcdata "FOO-BAR")) (pcdata " would occur twice, once under ") (tt - (pcdata "FOO")) (pcdata " and ") (tt - (pcdata "BAR")) (pcdata ". This allows you to use any") (pcdata " word in th symbol's name to search for that symbol.")) (gen-index permuted-indices) (footer target filename))))))))) #-(and) (setf *index-tree* (make-index-tree (mapcar (function doc-name) (lispdoc (sort (mapcar (lambda (package) (if (packagep package) package (find-package package))) (remove-if-not (lambda (p) (and (search "COM.INFORMATIMAGO" (package-name p)) (not (search "COM.INFORMATIMAGO.PJB" (package-name p))))) (list-all-packages))) (function string<) :key (function package-name)))))) ;;;; THE END ;;;;
23,928
Common Lisp
.lisp
504
32.986111
137
0.480317
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4d46d785e59aa8c522ca83d77232ca71fde2fd0b100a332fec39848473847ea6
5,188
[ -1 ]
5,189
uri.lisp
informatimago_lisp/lispdoc/uri.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: uri.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; URI parser. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-08-03 <PJB> Extracted from lispdoc.lisp ;;;;BUGS ;;;;LEGAL ;;;; LLGPL ;;;; ;;;; Copyright Pascal J. Bourguignon 2015 - 2016 ;;;; ;;;; This library is licenced under the Lisp Lesser General Public ;;;; License. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 2 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 ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LISPDOC.URI") ;;; URIs: ;;; http://www.ietf.org/rfc/rfc3986.txt (define-parse-tree-synonym digit (:char-class (:range #\0 #\9))) (define-parse-tree-synonym alpha (:char-class (:range #\A #\Z) (:range #\a #\z))) (define-parse-tree-synonym alphanum (:char-class (:range #\A #\Z) (:range #\a #\z) (:range #\0 #\9))) (define-parse-tree-synonym hexdig (:char-class (:range #\A #\F) (:range #\a #\f) (:range #\0 #\9))) ;; dec-octet = DIGIT ; 0-9 ;; / %x31-39 DIGIT ; 10-99 ;; / "1" 2DIGIT ; 100-199 ;; / "2" %x30-34 DIGIT ; 200-249 ;; / "25" %x30-35 ; 250-255 (define-parse-tree-synonym dec-octet (:alternation digit (:sequence (:char-class (:range #\1 #\9)) digit) (:sequence #\1 digit digit) (:sequence #\2 (:char-class (:range #\0 #\4)) digit) (:sequence #\2 #\5 (:char-class (:range #\0 #\5))))) ;; IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet (define-parse-tree-synonym ipv4address (:sequence dec-octet #\. dec-octet #\. dec-octet #\. dec-octet)) ;; h16 = 1*4HEXDIG (define-parse-tree-synonym h16 (:greedy-repetition 1 4 hexdig)) ;; ls32 = ( h16 ":" h16 ) / IPv4address (define-parse-tree-synonym ls32 (:alternation (:sequence h16 #\: h16) ipv4address)) ;; IPv6address = 6( h16 ":" ) ls32 ;; / "::" 5( h16 ":" ) ls32 ;; / [ h16 ] "::" 4( h16 ":" ) ls32 ;; / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 ;; / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 ;; / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 ;; / [ *4( h16 ":" ) h16 ] "::" ls32 ;; / [ *5( h16 ":" ) h16 ] "::" h16 ;; / [ *6( h16 ":" ) h16 ] "::" (define-parse-tree-synonym ipv6address (:alternation (:sequence (:greedy-repetition 6 6 (:sequence h16 #\:)) ls32) (:sequence #\: #\: (:greedy-repetition 5 5 (:sequence h16 #\:)) ls32) (:sequence (:alternation :void h16) #\: #\: (:greedy-repetition 4 4 (:sequence h16 #\:)) ls32) (:sequence (:alternation :void (:sequence (:greedy-repetition 0 1 (:sequence h16 #\:)) h16)) #\: #\: (:greedy-repetition 3 3 (:sequence h16 #\:)) ls32) (:sequence (:alternation :void (:sequence (:greedy-repetition 0 2 (:sequence h16 #\:)) h16)) #\: #\: (:greedy-repetition 2 2 (:sequence h16 #\:)) ls32) (:sequence (:alternation :void (:sequence (:greedy-repetition 0 3 (:sequence h16 #\:)) h16)) #\: #\: (:sequence h16 #\:) ls32) (:sequence (:alternation :void (:sequence (:greedy-repetition 0 4 (:sequence h16 #\:)) h16)) #\: #\: ls32) (:sequence (:alternation :void (:sequence (:greedy-repetition 0 5 (:sequence h16 #\:)) h16)) #\: #\: h16) (:sequence (:alternation :void (:sequence (:greedy-repetition 0 6 (:sequence h16 #\:)) h16)) #\: #\:))) ;; IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) (define-parse-tree-synonym ipvfuture (:sequence #\v (:greedy-repetition 1 nil hexdig) #\. (:greedy-repetition 1 nil (:alternation unreserved sub-delims #\:)))) ;; IP-literal = "[" ( IPv6address / IPvFuture ) "]" (define-parse-tree-synonym ip-literal (:sequence #\[ (:alternation unreserved ipv6address ipvfuture) #\])) ;; gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" (define-parse-tree-synonym gen-delims (:char-class #\: #\/ #\? #\# #\[ #\] #\@)) ;; sub-delims = "!" / "$" / "&" / "'" / "(" / ")" ;; / "*" / "+" / "," / ";" / "=" (define-parse-tree-synonym sub-delims (:char-class #\! #\$ #\& #\' #\( #\) #\* #\+ #\, #\; #\=)) ;; reserved = gen-delims / sub-delims (define-parse-tree-synonym reserved (:alternation gen-delims sub-delims)) ;; unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" (define-parse-tree-synonym unreserved (:alternation alpha digit #\- #\. #\_ #\~)) ;; pct-encoded = "%" HEXDIG HEXDIG (define-parse-tree-synonym pct-encoded (:sequence #\% hexdig hexdig)) ;; pchar = unreserved / pct-encoded / sub-delims / ":" / "@" (define-parse-tree-synonym pchar (:alternation unreserved pct-encoded sub-delims #\" #\@)) ;; segment = *pchar ;; segment-nz = 1*pchar ;; segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) ;; ; non-zero-length segment without any colon ":" (define-parse-tree-synonym segment (:greedy-repetition 0 nil pchar)) (define-parse-tree-synonym segment-nz (:greedy-repetition 1 nil pchar)) (define-parse-tree-synonym segment-nz-nc (:greedy-repetition 1 nil (:alternation unreserved pct-encoded sub-delims #\@))) ;; path-abempty = *( "/" segment ) ;; path-absolute = "/" [ segment-nz *( "/" segment ) ] ;; path-noscheme = segment-nz-nc *( "/" segment ) ;; path-rootless = segment-nz *( "/" segment ) ;; path-empty = 0<pchar> (define-parse-tree-synonym path-abempty (:greedy-repetition 0 nil (:sequence #\/ segment))) (define-parse-tree-synonym path-absolute (:greedy-repetition 0 nil (:alternation :void (:sequence segment-nz (:greedy-repetition 0 nil (:sequence #\/ segment)))))) (define-parse-tree-synonym path-noscheme (:sequence segment-nz-nc (:greedy-repetition 0 nil (:sequence #\/ segment)))) (define-parse-tree-synonym path-rootless (:sequence segment-nz (:greedy-repetition 0 nil (:sequence #\/ segment)))) (define-parse-tree-synonym path-empty :void) ;; path = path-abempty ; begins with "/" or is empty ;; / path-absolute ; begins with "/" but not "//" ;; / path-noscheme ; begins with a non-colon segment ;; / path-rootless ; begins with a segment ;; / path-empty ; zero characters (define-parse-tree-synonym path (:alternation path-abempty path-absolute path-noscheme path-rootless path-empty)) ;; reg-name = *( unreserved / pct-encoded / sub-delims ) (define-parse-tree-synonym reg-name (:greedy-repetition 0 nil (:alternation unreserved pct-encoded sub-delims))) ;; scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) (define-parse-tree-synonym scheme (:sequence alpha (:greedy-repetition 0 nil (:alternation alpha digit #\+ #\- #\.)))) ;; userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) (define-parse-tree-synonym userinfo (:greedy-repetition 0 nil (:alternation unreserved pct-encoded sub-delims #\:))) ;; host = IP-literal / IPv4address / reg-name (define-parse-tree-synonym host (:alternation ip-literal ipv4address reg-name)) ;; port = *DIGIT (define-parse-tree-synonym port (:greedy-repetition 0 nil digit)) ;; authority = [ userinfo "@" ] host [ ":" port ] (define-parse-tree-synonym authority (:sequence (:alternation :void (:sequence userinfo #\@)) host (:alternation :void (:sequence #\: port)))) ;; query = *( pchar / "/" / "?" ) (define-parse-tree-synonym query (:greedy-repetition 0 nil (:alternation pchar #\/ #\?))) ;; fragment = *( pchar / "/" / "?" ) (define-parse-tree-synonym fragment (:greedy-repetition 0 nil (:alternation pchar #\/ #\?))) ;; relative-part = "//" authority path-abempty ;; / path-absolute ;; / path-noscheme ;; / path-empty (define-parse-tree-synonym relative-part (:alternation (:sequence #\/ #\/ authority path-abempty) path-absolute path-noscheme path-empty)) ;; relative-ref = relative-part [ "?" query ] [ "#" fragment ] (define-parse-tree-synonym relative-ref (:sequence relative-part (:alternation :void (:sequence #\? query)) (:alternation :void (:sequence #\# fragment)))) ;; hier-part = "//" authority path-abempty ;; / path-absolute ;; / path-rootless ;; / path-empty (define-parse-tree-synonym hier-part (:alternation (:sequence #\/ #\/ authority path-abempty) path-absolute path-rootless path-empty)) ;; absolute-URI = scheme ":" hier-part [ "?" query ] (define-parse-tree-synonym absolute-uri (:sequence scheme #\: hier-part (:alternation :void (:sequence #\? query)))) ;; URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] (define-parse-tree-synonym uri (:sequence scheme #\: hier-part (:alternation :void (:sequence #\? query)) (:alternation :void (:sequence #\# fragment)))) ;; URI-reference = URI / relative-ref (define-parse-tree-synonym uri-reference (:alternation uri relative-ref)) ;;;; THE END ;;;;
11,151
Common Lisp
.lisp
220
45.790909
156
0.538085
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2d53030c52c2e3800b5d11d2e5f95b593c5f69c3fa113edd83399341a3852373
5,189
[ -1 ]
5,190
com.informatimago.lispdoc.test.asd
informatimago_lisp/lispdoc/com.informatimago.lispdoc.test.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;*************************************************************************** ;;;;FILE: com.informatimago.lispdoc.test.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: None ;;;;USER-INTERFACE: None ;;;;DESCRIPTION: ;;;; ;;;; This file defines the com.informatimago.lispdoc.test system. ;;;; Tests the com.informatimago.lispdoc 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/> ;;;; ;;;;*************************************************************************** (asdf:defsystem "com.informatimago.lispdoc.test" ;; system attributes: :description "Tests the com.informatimago.lispdoc 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.lispdoc.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.lispdoc") :components () #+asdf3 :perform #+asdf3 (asdf:test-op (operation system) (declare (ignore operation system)) ;; (let ((*package* (find-package "TESTED-PACKAGE"))) ;; (uiop:symbol-call "TESTED-PACKAGE" ;; "TEST/ALL")) )) ;;;; THE END ;;;;
2,893
Common Lisp
.lisp
67
36.985075
83
0.541622
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
87b4595711b5bba4163214c0c5d0466f20a462b20e4de31100ad5a84516f6c32
5,190
[ -1 ]
5,191
com.informatimago.lispdoc.asd
informatimago_lisp/lispdoc/com.informatimago.lispdoc.asd
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: com.informatimago.lispdoc.asd ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; ASD file to generate the documentation of the com.informatimago lisp packages. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2010-10-31 <PJB> Created this .asd file. ;;;;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/ ;;;;************************************************************************** #+mocl (asdf:defsystem "com.informatimago.lispdoc" ;; system attributes: :description "Dummy Informatimago Common Lisp Documentation Generator" :long-description " This system would use closer-mop which is not available for MOCL. " :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "LLGPL" ;; component attributes: :version "1.2.0" :properties ((#:author-email . "[email protected]") (#:date . "Spring 2012") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.lispdoc/") ((#: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 ()) #-mocl (asdf:defsystem "com.informatimago.lispdoc" ;; system attributes: :description "Informatimago Common Lisp Documentation Generator" :author "Pascal J. Bourguignon <[email protected]>" :maintainer "Pascal J. Bourguignon <[email protected]>" :licence "LLGPL" ;; component attributes: :version "1.2.0" :properties ((#:author-email . "[email protected]") (#:date . "Spring 2012") ((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.lispdoc/") ((#:albert #:formats) . ("docbook")) ((#:albert #:docbook #:template) . "book") ((#:albert #:docbook #:bgcolor) . "white") ((#:albert #:docbook #:textcolor) . "black")) :depends-on ( ;; Dependencies: "cl-ppcre" "closer-mop" "split-sequence" "com.informatimago.common-lisp.cesarum" "com.informatimago.common-lisp.html-generator" ;; The documented systems: TODO: we shouldn't depend on them. "com.informatimago.common-lisp" "com.informatimago.clext" "com.informatimago.clmisc" "com.informatimago.rdp" #+(and ccl darwin) "com.informatimago.objcl") :components ((:file "package") (:file "utility" :depends-on ("package")) (:file "uri" :depends-on ("package")) (:file "doc" :depends-on ("package")) (:file "tree" :depends-on ("package" "utility")) (:file "lispdoc" :depends-on ("package" "doc")) (:file "generate" :depends-on ("package" "doc" "lispdoc" "utility" "tree")) (:file "gentext" :depends-on ("package" "doc" "generate" "utility" "tree" "uri")) (:file "genrst" :depends-on ("package" "doc" "generate" "utility" "tree" "uri")) (:file "genhtml" :depends-on ("package" "doc" "generate" "utility" "tree" "uri")) (:file "lispdoc-run" :depends-on ("package" "lispdoc" "genhtml" "genrst" "gentext"))) #+asdf-unicode :encoding #+asdf-unicode :utf-8) ;;;; THE END ;;;;
4,746
Common Lisp
.lisp
97
41.783505
101
0.556752
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b9c011bc6188ce478150cc6797be8c5899fb404820e3ff1dc2a4d78925eb56bc
5,191
[ -1 ]
5,192
mxarc.lisp
informatimago_lisp/multics/mxarc.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: mxarc.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Tool to extract multics archives. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-03-28 <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.MULTICS.MXARC" (:use "COMMON-LISP") (:export "MXARC")) (in-package "COM.INFORMATIMAGO.MULTICS.MXARC") (defconstant +sep+ 15) (defconstant +eof+ 0) (defparameter *spaces* #(#\space #\tab #\newline #\return)) (defun spacep (ch) (find ch *spaces*)) (defun skip-to-next-record (stream) (loop :for byte = (read-byte stream) :until (eql +sep+ byte))) (defun read-record (stream) (map 'string (function code-char) (loop :for byte = (read-byte stream) :until (eql +sep+ byte) :collect byte))) (defun read-blob (stream) (loop :with data = (make-array 4096 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0) :for byte = (loop :for byte = (read-byte stream) :while (eql +sep+ byte) :finally (return byte)) :then (read-byte stream nil stream) :until (or (eql +eof+ byte) (eql stream byte)) :do (vector-push-extend byte data 4096) :finally (return data))) (defun parse-date (string) (let ((mo (parse-integer string :start 0 :end 2)) (da (parse-integer string :start 3 :end 5)) (ye (parse-integer string :start 6 :end 8)) (ho (parse-integer string :start 10 :end 12)) (mi (parse-integer string :start 12 :end 14)) (s (parse-integer string :start 15 :end 16))) (encode-universal-time (* 60 (/ s 10)) mi ho da mo (+ ye (if (< ye 50) 2000 1900)) 0))) (defun parse-header (header) (let* ((start (position-if-not (function spacep) header)) (name (string-trim " " (subseq header start (+ start 32)))) (creation-date (parse-date (subseq header (+ start 32) (+ start 48)))) (modification-date (parse-date (subseq header (+ start 52) (+ start 68)))) (access-rights (subseq header (+ start 48) (+ start 51))) (size (parse-integer (subseq header (+ start 68))))) (values name creation-date access-rights modification-date size))) (defun save (path data &key (access-rights "r w") (creation-date (get-universal-time)) (modification-date (get-universal-time))) (declare (ignore access-rights creation-date modification-date)) (with-open-file (out path :direction :output :element-type '(unsigned-byte 8) :if-does-not-exist :create :if-exists :rename) (write-sequence data out))) (defun extract (path &key (output-directory #P"") (verbose nil)) (ensure-directories-exist path) (with-open-file (arc path :direction :input :element-type '(unsigned-byte 8)) (handler-case (loop (skip-to-next-record arc) (let ((header (read-record arc))) (when verbose (write-line (string-trim *spaces* header))) (multiple-value-bind (name creation-date access-rights modification-date size) (parse-header header) (declare (ignore size)) (let ((data (read-blob arc))) (save (merge-pathnames name output-directory nil) data :access-rights access-rights :creation-date creation-date :modification-date modification-date))))) (end-of-file () (return-from extract))))) ;; (extract #P"~/Downloads/bound_multics_emacs_.s.archive") #-(and) (progn (let ((archive-dir #P"~/Downloads/") (out-dir-root #P"/tmp/multics/")) (dolist (archive '("bound_emacs_ctls_.s.archive" "bound_emacs_full_.s.archive" "bound_emacs_macros_.s.archive" "bound_emacs_packages_.s.archive" "bound_emacs_rmail_.s.archive" "bound_multics_emacs_.s.archive")) (let* ((name (subseq archive (length "bound_") (1- (position #\. archive)))) (outdir (merge-pathnames (make-pathname :directory (list :relative name)) out-dir-root))) (extract (merge-pathnames archive archive-dir) :output-directory outdir) #-(and) (map nil 'print (directory (merge-pathnames "*.*" outdir)))))) (extract #P"~/Downloads/bound_multics_emacs_.s.archive" :output-directory #P"/tmp/me/" :verbose t) (directory #P"/tmp/me/*.*") ) ;;;; THE END ;;;;
6,079
Common Lisp
.lisp
133
36.932331
93
0.562363
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
59823c4b5609ad76fc03f04a6bea6ed92fa15a60282b6969a7df95ba36f04181
5,192
[ -1 ]
5,193
xlisp.lisp
informatimago_lisp/languages/xlisp/xlisp.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: xlisp.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This is an implementation of xlisp 3.0 (1997) written as a ;;;; Common Lisp package. ;;;; ;;;; To keep it simple, we don't support continuations and ;;;; environments, but they could be added in a later version. We ;;;; don't export internal functions either (whose names start with %). ;;;; ;;;; ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-03-15 <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.XLISP" (:nickname "XLISP") (:use) (:import-from "COMMON-LISP" "T" "NIL" "*PACKAGE*" "*READTABLE*" "*STANDARD-INPUT*" "*STANDARD-OUTPUT*" "*ERROR-OUTPUT*" "*PRINT-CASE*" ) (:export "T" "NIL" "*PACKAGE*" "*READTABLE*" "*STANDARD-INPUT*" "*STANDARD-OUTPUT*" "*ERROR-OUTPUT*" "*PRINT-CASE*" "*ERROR-HANDLER*" "*UNBOUND-HANDLER*" "*LOAD-PATH*" "*FIXNUM-FORMAT*" "*HEXNUM-FORMAT*" "*FLONUM-FORMAT*" "*SOFTWARE-TYPE*" "WIN95" "DOS32" "UNIX" "MAC" "OBJECT" "CLASS" )) (defpackage "COM.INFORMATIMAGO.XLISP.IMPLEMENTATION" (:use "COMMON-LISP")) (in-package "COM.INFORMATIMAGO.XLISP.IMPLEMENTATION") (eval-when (:compile-toplevel :load-toplevel :execute) (defun sharp-f (stream ch) (declare (ignore stream ch)) 'nil) (defun sharp-t (stream ch) (declare (ignore stream ch)) 't) (defun sharp-exclaim (stream ch) (declare (ignore ch)) (let ((*package* (find-package "KEYWORD"))) (ecase (read stream) (:true 't) (:false 'nil) (:optional '&optional) (:rest '&rest)))) );;eval-when (defmacro enable-xlisp-readtable () `(eval-when (:compile-toplevel :load-toplevel :execute) (set-dispatch-macro-character #\# #\f 'sharp-f) (set-dispatch-macro-character #\# #\t 'sharp-t) (set-dispatch-macro-character #\# #\! 'sharp-exclaim))) (define-condition xlisp-error (error) ((function :initarg :function :reader xlisp-error-function) (environment :initarg :environment :reader xlisp-error-environment)) (:report (lambda (condition stream) (format stream "XLISP ERROR in function ~S, environment ~S" (xlisp-error-function condition) (xlisp-error-environment condition))))) (defun default-error-handler (erroneous-function error-environment) (error 'xlisp-error :function erroneous-function :environment error-environment)) (defvar xlisp:*error-handler* (function default-error-handler) "Bound to a function to handle errors. The function should take two arguments, the function where the error occured and the environment at the time of the error. It shouldn't return.") (defun default-unbound-handler (symbol continuation) (error "~S NOT IMPLEMENTED YET" 'default-unbound-handler)) (defvar xlisp:*unbound-handler* (function default-unbound-handler) "Bound to a function to handle unbound symbol errors. The function should take two arguments, the symbol that is unbound and a continuation to call after correcting the error.") ;; TODO: See what format environment variable XLISP has? (defvar xlisp:*load-path* (or (when (getenv "XLISP") (read-from-string (getenv "XLISP"))) (when *load-pathname* (list *load-pathname*)) '(".")) "Bound to the path used by the LOAD function. This is initialized to the contents of the XLISP environment variable or, if that is not defined, to the path where the XLISP executable was found. The value consists of a list of strings that should be paths to directories XLISP should search for files being loaded. Each string should end with an appropriate directory terminator (the backslash under MS-DOS, the slash under UNIX or a colon on the Macintosh.") (defvar xlisp:*FIXNUM-FORMAT* "%ld" "A printf style format string for printing fixed point numbers. FIXNUMs are generally represented by long integers so this should usually be set to \"%ld\".") (defvar xlisp:*HEXNUM-FORMAT* "%lx" "A printf style format string for printing fixed point numbers in hexadecimal. FIXNUMs are generally represented by long integers so this should usually be set to \"%lx\".") (defvar xlisp:*FLONUM-FORMAT* "%.15g" "A printf style format string for printing floating point numbers. This is usually set to \"%.15g\".")
5,928
Common Lisp
.lisp
144
35.583333
89
0.630692
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
50e1c9fd51ed3c6c933f0c49ce5d5b8c399be7c54c4abbeb350779ff539c05a8
5,193
[ -1 ]
5,194
xlisp.txt
informatimago_lisp/languages/xlisp/xlisp.txt
XLISP: An Object-Oriented Lisp Version 3.0 January 28, 1997 David Michael Betz 18 Garrison Drive Bedford, NH 03110 (603) 472-2389 (home) Copyright (c) 1984-2002, by David Michael Betz All Rights Reserved See the included file 'license.txt' for the full license. Introduction XLISP is a dialect of the Lisp programming language with extensions to support object-oriented programming. Over the years I have released many versions of XLISP with differing goals. The original XLISP was written to run on tiny machines like the Z80 under CP/M and hence was a small language. When Common Lisp came around, I made an attempt to bring XLISP into conformance with that standard. Later I learned about Scheme, an elegant dialect of Lisp designed by Gerald Sussman and Guy Steele Jr. and realized that it more closely matched my desire for a small but powerful language. This version of XLISP is mostly based on Scheme with my own object system and some Common Lispish extensions. It is derived from XScheme, my earlier implementation of Scheme. Unlike the original XLISP, this version compiles to bytecodes instead of directly interpreting the source s-expressions. This makes it somewhat faster than the old XLISP for normal functions and much faster for macros since they are expanded at compile time not run time. There are currently implementations of XLISP running on the IBM-PC and clones under MS-DOS, on the Macintosh and under OS/2. It is completely written in ANSI C and is easily extended with user written built-in functions and classes. It is available in source form to non-commercial users. This document is a brief description of XLISP. XLISP follows the "Revised^3 Report on the Algorithmic Language Scheme" with extensions. It assumes some knowledge of Scheme or LISP and some understanding of the concepts of object-oriented programming. I recommend the book "Structure and Interpretation of Computer Programs" by Harold Abelson and Gerald Jay Sussman and published by MIT Press and the McGraw-Hill Book Company for learning Scheme (and programming in general). You might also find "The Scheme Programming Language" by R. Kent Dybvig and "The Little Lisper" by Daniel P. Friedman and Matthias Felleisen to be helpful. A Note from the Author If you have any problems with XLISP, feel free to contact me for help or advice. Please remember that since XLISP is available in source form in a high level language many users have been making versions available on a variety of machines. If you call to report a problem with a specific version, I may not be able to help you if that version runs on a machine I don't have access to. Please have the version number of XLISP that you are running readily accessible before calling me. If you find a bug in XLISP, first try to fix the bug yourself using the source code provided. If you are successful in fixing the bug, send the bug report along with the fix to me. If you don't have access to a C compiler or are unable to fix a bug, please send the bug report to me and I'll try to fix it. Any suggestions for improvements will be welcomed. Feel free to extend the language in whatever way suits your needs. However, PLEASE DO NOT RELEASE ENHANCED VERSIONS WITHOUT CHECKING WITH ME FIRST!! I would like to be the clearing house for new features added to XLISP. If you want to add features for your own personal use, go ahead. But, if you want to distribute your enhanced version, contact me first. Constants #T #!TRUE The true value. Where boolean expressions are required, any value other than #F is interpreted as a true value. #F #!FALSE The false value. In XLISP, false and the empty list are the same value. Built-In Variables *PACKAGE* Bound to the default package. *READTABLE* Bound to the current read table. *ERROR-HANDLER* Bound to a function to handle errors. The function should take two arguments, the function where the error occured and the environment at the time of the error. It shouldn't return. *UNBOUND-HANDLER* Bound to a function to handle unbound symbol errors. The function should take two arguments, the symbol that is unbound and a continuation to call after correcting the error. *LOAD-PATH* Bound to the path used by the LOAD function. This is initialized to the contents of the XLISP environment variable or, if that is not defined, to the path where the XLISP executable was found. The value consists of a list of strings that should be paths to directories XLISP should search for files being loaded. Each string should end with an appropriate directory terminator (the backslash under MS-DOS, the slash under UNIX or a colon on the Macintosh. *STANDARD-INPUT* Bound to the standard input port. *STANDARD-OUTPUT* Bound to the standard output port. *ERROR-OUTPUT* Bound to the error output port. *FIXNUM-FORMAT* A printf style format string for printing fixed point numbers. FIXNUMs are generally represented by long integers so this should usually be set to "%ld". *HEXNUM-FORMAT* A printf style format string for printing fixed point numbers in hexadecimal. FIXNUMs are generally represented by long integers so this should usually be set to "%lx". *FLONUM-FORMAT* A printf style format string for printing floating point numbers. This is usually set to "%.15g". *PRINT-CASE* Bound to a symbol that controls the case in which symbols are printed. Can be set to UPCASE or DOWNCASE. *SOFTWARE-TYPE* Bound to a symbol that indicates the host software. The following types are defined currently: win95 Windows 95 dos32 Command line DOS under Windows 95 unix Unix or Linux mac Macintosh T Bound to #t. NIL Bound to the empty list. OBJECT Bound to the class "Object". CLASS Bound to the class "Class". Expressions variable An expression consisting of a variable is a variable reference. The value of the variable reference is the value stored in the location to which the variable is bound. It is an error to reference an unbound variable. (QUOTE datum) 'datum (QUOTE datum) evaluates to datum. Datum may be any external representation of an XLISP value. This notation is used to include literal constants in XLISP code. (QUOTE datum) may be abbreviated as 'datum. The two notations are equivalent in all respects. constant Numeric constants, string constants, character constants and boolean constants evaluate "to themselves"; they need not be quoted. (operator operand...) A procedure call is written by simply enclosing in parentheses expressions for the procedure to be called and the arguments to be passed to it. The operator and operand expressions are evaluated and the resulting procedure is passed the resulting arguments. (object selector operand...) A message sending form is written by enclosing in parentheses expressions for the receiving object, the message selector, and the arguments to be passed to the method. The receiver, selector, and argument expressions are evaluated, the message selector is used to select an appropriate method to handle the message, and the resulting method is passed the resulting arguments. (LAMBDA formals body) Formals should be a formal argument list as described below, and body should be a sequence of one or more expressions. A lambda expression evaluates to a procedure. The environment in effect when the lambda expression is evaluated is remembered as part of the procedure. When the procedure is later called with some actual arguments, the environment in which the lambda expression was evaluated will be extended by binding the variables in the formal argument list to fresh locations, the corresponding actual argument values will be stored in those locations, and the expressions in the body of the lambda expression will be evaluated sequentially in the extended environment. The result of the last expression in the body will be returned as the result of the procedure call. Formals should have the following form: (var... [#!OPTIONAL ovar...] [. rvar]) or (var... [#!OPTIONAL ovar...] [#!REST rvar]) where: var is a required argument ovar is an optional argument rvar is a "rest" argument There are three parts to a formals list. The first lists the required arguments of the procedure. All calls to the procedure must supply values for each of the required arguments. The second part lists the optional arguments of the procedure. An optional argument may be supplied in a call or omitted. If it is omitted, a special value is given to the argument that satisfies the default-object? predicate. This provides a way to test to see if an optional argument was provided in a call or omitted. The last part of the formals list gives the "rest" argument. This argument will be bound to the rest of the list of arguments supplied to a call after the required and optional arguments have been removed. Alternatively, you can use Common Lisp syntax for the formal parameters: (var... [&optional {ovar | (ovar [init [svar]])}... [&rest rvar] [&key {kvar | ({kvar | (key kvar)} [init [svar]])}... [&aux {avar | (avar [init])}]) where: var is a required argument ovar is an optional argument rvar is a "rest" argument kvar is a keyword argument avar is an aux variable svar is a "supplied-p" variable See "Common Lisp, the Language" by Guy Steele Jr. for a description of this syntax. (NAMED-LAMBDA name formals body) NAMED-LAMBDA is the same as LAMBDA except that the specified name is associated with the procedure. (IF test consequent [alternate]) An if expression is evaluated as follows: first, test is evaluated. If it yields a true value, then consequent is evaluated and its value is returned. Otherwise, alternate is evaluated and its value is returned. If test yields a false value and no alternate is specified, then the result of the expression is unspecified. A false value is nil or the empty list. Every other value is a true value. (SET! variable expression) Expression is evaluated, and the resulting value is stored in the location to which variable is bound. Variable must be bound in some region or at the top level. The result of the set! expression is unspecified. (COND clause...) Each clause should be of the form (test expression...) where test is any expression. The last clause may be an "else clause," which has the form (ELSE expression...) A cond expression is evaluated by evaluating the test expressions of successive clauses in order until one of them evaluates to a true value. When a test evaluates to a true value, then the remaining expressions in its clause are evaluated in order, and the result of the last expression in the clause is returned as the result of the entire cond expression. If the selected clause contains only the test and no expressions, then the value of the test is returned as the result. If all tests evaluate to false values, and there is no else clause, then the result of the conditional expression is unspecified; if there is an else clause, then its expressions are evaluated, and the value of the last one is returned. (AND test...) The test expressions are evaluated from left to right, and the value of the first expression that evaluates to a false value is returned. Any remaining expressions are not evaluated. If all the expressions evaluate to true values, the value of the last expression is returned. If there are no expressions then #t is returned. (OR test...) The test expressions are evaluated from left to right, and the value of the first expression that evaluates to a true value is returned. Any remaining expressions are not evaluated. If all expressions evaluate to false values, the value of the last expression is returned. If there are no expressions then #f is returned. Multiple Values (VALUES expr...) The results of evaluating this expression are the values of the expressions given as arguments. It is legal to pass no values as in (VALUES) to indicate no values. (VALUES-LIST list) The results of evaluating this expression are the values in the specified list. (MULTIPLE-VALUE-BIND (var...) vexpr expr...) The multiple values produced by vexpr are bound to the specified variables and the remaining expressions are evaluated in an environment that includes those variables. (MULTIPLE-VALUE-CALL function expr) The multiple values of expr are passed as arguments to the specified function. Non-Local Exits (CATCH tag expr...) Evaluate the specified expressions in an environment where the specified tag is visible as a target for THROW. If no throw occurs, return the value(s) of the last expression. If a throw occurs that matches the tag, return the value(s) specified in the THROW form. (THROW tag expr...) Throw to a tag established by the CATCH form. In the process of unwinding the stack, evaluate any cleanup forms associated with UNWIND-PROTECT forms established between the target CATCH and the THROW form. (THROW-ERROR arg) Throw an error. This is basically equivilent to (THROW ERROR arg) except that care is taken to make sure that recursive errors are not produced if there is no corresponding CATCH for the ERROR tag. (UNWIND-PROTECT pexpr expr...) Evaluate pexpr (the protected expression) and then the other expressions and return the value(s) of pexpr. If an error or a THROW occurs during the evaluation of the protected form, the other expressions (known as cleanup forms) are evaluated during the unwind process. Binding Forms (LET [name] bindings body) Bindings should have the form ((variable init)...) where each init is an expression, and body should be a sequence of one or more expressions. The inits are evaluated in the current envirnoment, the variables are bound to fresh locations holding the results, the body is evaluated in the extended environment, and the value of the last expression of body is returned. Each binding of a variable has body as its region. If a name is supplied, a procedure that takes the bound variables as its arguments and has the body of the LET as its body is bound to that name. (LET* bindings body) Same as LET except that the bindings are done sequentially from left to right and the bindings to the left are visible while evaluating the initialization expressions for each variable. (LETREC bindings body) Bindings should have the form ((variable init)...) and body should be a sequence of one or more expressions. The variables are bound to fresh locations holding undefined values; the inits are evaluated in the resulting environment; each variable is assigned to the result of the corresponding init; the body is evaluated in the resulting environment; and the value of the last expression in body is returned. Each binding of a variable has the entire letrec expression as its region, making it possible to define mutually recursive procedures. One restriction of letrec is very important: it must be possible to evaluate each init without referring to the value of any variable. If this restriction is violated, then the effect is undefined, and an error may be signalled during evaluation of the inits. The restriction is necessary because XLISP passes arguments by value rather than by name. In the most common uses of letrec, all the inits are lambda expressions and the restriction is satisfied automatically. Sequencing (BEGIN expression...) (SEQUENCE expression...) The expressions are evaluated sequentially from left to right, and the value of the last expression is returned. This expression type is used to sequence side effects such as input and output. Delayed Evaluation (CONS-STREAM expr1 expr2) Create a cons stream whose head is expr1 (which is evaluated immediately) and whose tail is expr2 (whose evaluation is delayed until TAIL is called). (HEAD expr) Returns the head of a stream. (TAIL expr) Returns the tail of a stream by calling FORCE on the promise created by CONS-STREAM. (DELAY expression) Evaluating this expression creates a "promise" to evaluate expression at a later time. (FORCE promise) Applying FORCE to a promise generated by DELAY requests that the promise produce the value of the expression passed to DELAY. The first time a promise is FORCEed, the DELAY expression is evaluated and the value stored. On subsequent calls to FORCE with the same promise, the saved value is returned. Iteration (WHILE test expression...) While is an iteration construct. Each iteration begins by evaluating test; if the result is false, then the loop terminates and the value of test is returned as the value of the while expression. If test evaluates to a true value, then the expressions are evaluated in order for effect and the next iteration begins. Definitions (DEFINE variable expression) Define a variable and give it an initial value. (DEFINE (variable . formals) body) Define a procedure. Formals should be specified in the same way as with LAMBDA. (DEFINE-MACRO (name . formals) body) Defines a macro with the specified name. The Object System XLISP provides a fairly simple single inheritance object system. Each object is an instance of a class and classes themselves are objects. Each object has a set of instance variables where it stores its private data and in addition has access to a set of class variables that are shared amongst all instances of the same class. Each class has a set of methods with which it responds to messages sent to its instances. A message is sent using a syntax similar to a function call: (object selector expr...) Where object is the object receiving the message, selector is a symbol used to select the appropriate method for handling the message and the expressions are arguments to pass to the method. A method may return zero or more values. Within a method, the object's instance variables and class variables are bound as if they were lexical variables. (DEFINE-CLASS name decl...) Creates a class with the specified class name and binds the global variable with that name to the new class. Decl is: (SUPER-CLASS super) Specifies the single superclass. If not specified, the superclass is Object. (INSTANCE-VARIABLES ivar...) (IVARS ivar...) Specifies the instance variables of the new class. (CLASS-VARIABLES {cvar | (cvar init)}...) (CVARS {cvar | (cvar init)}...) Specifies the class variables of the new class. (DEFINE-METHOD (class selector formals) expr...) Defines a method for the specified class with the specified selector. Within a method, the symbol self refers to the object receiving the message. Also, all instance variables and class variables are available as if they were lexical variables. (DEFINE-CLASS-METHOD (class selector formals) expr...) Defines a class method for the specified class with the specified selector. Within a method, the symbol self refers to the class receiving the message. Also class variables are available as if they were lexical variables. (SUPER selector expr...) When used within a method, sends a message to the superclass of the class where the current method was found. Methods for the Built-In Classes Class: (Class 'make-instance) Make an uninitialize instance of a class. (Class 'new &rest args) Make and initialize an instance of a class. The new instance is initialized by sending it the 'initialize message with the arguments passed to 'new. The result of the 'initialize method is returned as the result of 'new. The 'initialize method should return self as its value. (Class 'initialize ivars &optional cvars super name) Default class initialization method. (Class 'answer selector formals body) Add a method to a class. (Class 'show &optional port) Display information about a class. Object: (Object 'initialize) Default initialization method. (Object 'class) Return the class of an object. (Object 'get-variable var) Get the value of an instance variable. (Object 'set-variable! var expr) Set the value of an instance variable. (Object 'show &optional port) Display information about an object. List Functions (CONS expr1 expr2) Create a new pair whose car is expr1 and whose cdr is expr2. (ACONS key data alist) Is equivilent to (CONS (CONS key data) alist) and is used to add a pair to an association list. (CAR pair) (FIRST pair) Extract the car of a pair. (CDR pair) (REST pair) Extract the cdr of a pair. (CxxR pair) (CxxxR pair) (CxxxxR pair) These functions are short for combinations of CAR and CDR. Each 'x' is stands for either 'A' or 'D'. An 'A' stands for the CAR function and a 'D' stands for the CDR function. For instance, (CADR x) is the same as (CAR (CDR x)). (SECOND list) (THIRD list) (FOURTH list) Extract the specified elements of a list. (LIST expr...) Create a list whose elements are the arguments to the function. This function can take an arbitrary number of arguments. Passing no arguments results in the empty list. (LIST* expr...) Create a list whose elements are the arguments to the function except that the last argument is used as the tail of the list. This means that the call (LIST* 1 2 3) produce the result (1 2 . 3). (APPEND list...) Append lists to form a single list. This function takes an arbitrary number of arguments. Passing no arguments results in the empty list. (REVERSE list) Create a list whose elements are the same as the argument except in reverse order. (LAST-PAIR list) Return the last pair in a list. (LENGTH list) Compute the length of a list. (PAIRLIS keys data &optional alist) Creates pairs from corresponding elements of keys and data and pushes these onto alist. For instance: (pairlis '(x y) '(1 2) '((z . 3))) => ((x . 1) (y . 2) (z . 3)) (COPY-LIST list) Makes a top level copy of the list. (COPY-TREE list) Make a deep copy of a list. (COPY-ALIST alist) Copy an association list by copying each top level pair in the list. (END? list) Returns #f for a pair, #t for the empty list and signals an error for all other types. (MEMBER expr list) (MEMV expr list) (MEMQ expr list) Find an element in a list. Each of these functions searches the list looking for an element that matches expr. If a matching element is found, the remainder of the list starting with that element is returned. If no matching element is found, the empty list is returned. The functions differ in the test used to determine if an element matches expr. The MEMBER function uses EQUAL?, the MEMV function uses EQV? and the MEMQ function uses EQ?. (ASSOC expr alist) (ASSV expr alist) (ASSQ expr alist) Find an entry in an association list. An association list is a list of pairs. The car of each pair is the key and the cdr is the value. These functions search an association list for a pair whose key matches expr. If a matching pair is found, it is returned. Otherwise, the empty list is returned. The functions differ in the test used to determine if a key matches expr. The ASSOC function uses EQUAL?, the ASSV function uses EQV? and the ASSQ function uses EQ?. (LIST-REF list n) Return the nth element of a list (zero based). (LIST-TAIL list n) Return the sublist obtained by removing the first n elements of list. Destructive List Functions (SET-CAR! pair expr) Set the car of a pair to expr. The value returned by this procedure is unspecified. (SET-CDR! pair expr) Set the cdr of a pair to expr. The value returned by this procedure is unspecified. (APPEND! list...) Append lists destructively. Sequence Functions At the moment these sequence functions work only with lists. (MAPCAR) (MAPC) (MAPCAN) (MAPLIST) (MAPL) (MAPCON) (SOME) (EVERY) (NOTANY) (NOTEVERY) (FIND) (FIND-IF) (FIND-IF-NOT) (MEMBER) (MEMBER-IF) (MEMBER-IF-NOT) (ASSOC) (ASSOC-IF) (ASSOC-IF-NOT) (RASSOC) (RASSOC-IF) (RASSOC-IF-NOT) (REMOVE) (REMOVE-IF) (REMOVE-IF-NOT) (DELETE) (DELETE-IF) (DELETE-IF-NOT) (COUNT) (COUNT-IF) (COUNT-IF-NOT) (POSITION) (POSITION-IF) (POSITION-IF-NOT) Symbol Functions (BOUND? sym [ env]) Returns #t if a global value is bound to the symbol and #f otherwise. (SYMBOL-NAME sym) Get the print name of a symbol. (SYMBOL-VALUE sym [env]) Get the global value of a symbol. (SET-SYMBOL-VALUE! sym expr [env]) Set the global value of a symbol. The value returned by this procedure is unspecified. (SYMBOL-PLIST sym) Get the property list associated with a symbol. (SET-SYMBOL-PLIST! sym plist) Set the property list associate with a symbol. The value returned by this procedure is unspecified. (SYMBOL-PACKAGE sym) Returns the package containing the symbol. (GENSYM &optional sym | str | num) Generate a new, uninterned symbol. The print name of the symbol will consist of a prefix with a number appended. The initial prefix is "G" and the initial number is 1. If a symbol is specified as an argument, the prefix is set to the print name of that symbol. If a string is specified, the prefix is set to that string. If a number is specified, the numeric suffix is set to that number. After the symbol is generated, the number is incremented so subsequent calls to GENSYM will generate numbers in sequence. (GET sym prop) Get the value of a property of a symbol. The prop argument is a symbol that is the property name. If a property with that name exists on the symbols property list, the value of the property is returned. Otherwise, the empty list is returned. (PUT sym prop expr) Set the value of a property of a symbol. The prop argument is a symbol that is the property name. The property/value combination is added to the property list of the symbol. (REMPROP sym prop) Remove the specified property from the property list of the symbol. Package Functions (MAKE-PACKAGE name &key uses) (FIND-PACKAGE name) (LIST-ALL-PACKAGES) (PACKAGE-NAME pack) (PACKAGE-NICKNAMES pack) (IN-PACKAGE pack) (USE-PACKAGE name [pack]) (UNUSE-PACKAGE name [pack]) (PACKAGE-USE-LIST pack) (PACKAGE-USED-BY-LIST pack) (EXPORT sym [pack]) (UNEXPORT sym [pack]) (IMPORT sym [pack]) (INTERN pname [pack]) (UNINTERN sym [pack]) (MAKE-SYMBOL pname) (FIND-SYMBOL sym [pack]) Vector Functions (VECTOR expr...) Create a vector whose elements are the arguments to the function. This function can take an arbitrary number of arguments. Passing no arguments results in a zero length vector. (MAKE-VECTOR len) Make a vector of the specified length. (VECTOR-LENGTH vect) Get the length of a vector. (VECTOR-REF vect n) Return the nth element of a vector (zero based). (VECTOR-SET! vect n expr) Set the nth element of a vector (zero based). Array Functions (MAKE-ARRAY d1 d2...) Make an array (vector of vectors) with the specified dimensions. At least one dimension must be specified. (ARRAY-REF array s1 s2...) Get an array element. The sn arguments are integer subscripts (zero based). (ARRAY-SET! array s1 s2... expr) Set an array element. The sn arguments are integer subscripts (zero based). Table Functions (MAKE-TABLE &optional size) Make a table with the specified size. The size defaults to something useful hopefully. (TABLE-REF table key) Find the value in the table associated with the specified key. (TABLE-SET! table key value) Set the value in the table associated with the specified key. (TABLE-REMOVE! table key) Remove the entry with the specified key from the table. Return the old value associated with the key or nil if the key is not found. (EMPTY-TABLE! table) Remove all entries from a table. (MAP-OVER-TABLE-ENTRIES table fun) Apply the specified function to each entry in the table and return the list of values. The function should take two arguments. The first is the key and the second is the value associated with that key. Conversion Functions (SYMBOL->STRING sym) Convert a symbol to a string. Returns the print name of the symbol as a string. (STRING->SYMBOL str) Convert a string to a symbol. Returns a symbol with the string as its print name. This can either be a new symbol or an existing one with the same print name. (VECTOR->LIST vect) Convert a vector to a list. Returns a list of the elements of the vector. (LIST->VECTOR list) Convert a list to a vector. Returns a vector of the elements of the list. (STRING->LIST str) Convert a string to a list. Returns a list of the characters in the string. (LIST->STRING list) Convert a list of character to a string. Returns a string whose characters are the elements of the list. (CHAR->INTEGER char) Convert a character to an integer. Returns the ASCII code of the character as an integer. (INTEGER->CHAR n) Convert an integer ASCII code to a character. Returns the character whose ASCII code is the integer. (STRING->NUMBER str &optional base) Convert a string to a number. Returns the value of the numeric interpretation of the string. The base argument must be 2, 8, 10 or 16 and defaults to 10. (NUMBER->STRING n &optional base) Convert a number to a string. Returns the string corresponding to the number. The base argument must be 2, 8, 10 or 16 and defaults to 10. Logical Functions (NOT expr) Returns #t if the expression is #f and #t otherwise. Type Predicates (NULL? expr) Returns #t if the expression is the empty list and #f otherwise. (ATOM? expr) Returns #f if the expression is a pair and #t otherwise. (LIST? expr) Returns #t if the expression is either a pair or the empty list and #f otherwise. (NUMBER? expr) Returns #t if the expression is a number and #f otherwise. (BOOLEAN? expr) Returns #t if the expression is either #t or #f and #f otherwise. (PAIR? expr) Returns #t if the expression is a pair and #f otherwise. (SYMBOL? expr) Returns #t if the expression is a symbol and #f otherwise. (COMPLEX? expr) Returns #t if the expression is a complex number and #f otherwise. Note: Complex numbers are not yet supported by XLISP. (REAL? expr) Returns #t if the expression is a real number and #f otherwise. (RATIONAL? expr) Returns #t if the expression is a rational number and #f otherwise. Note: Rational numbers are not yet supported by XLISP. (INTEGER? expr) Returns #t if the expression is an integer and #f otherwise. (CHAR? expr) Returns #t if the expression is a character and #f otherwise. (STRING? expr) Returns # if the expression is a string and #f otherwise. (VECTOR? expr) Returns #t if the expression is a vector and #f otherwise. (TABLE? expr) Returns #t if the expression is a table and #f otherwise. (PROCEDURE? expr) Returns #t if the expression is a procedure (closure) and #f otherwise. (PORT? expr) Returns #t if the expression is a port and #f otherwise. (INPUT-PORT? expr) Returns #t if the expression is an input port and #f otherwise. (OUTPUT-PORT? expr) Returns #t if the expression is an output port and #f otherwise. (OBJECT? expr) Returns #t if the expression is an object and #f otherwise. (EOF-OBJECT? expr) Returns #t if the expression is the object returned by READ upon detecting an end of file condition and #f otherwise. (DEFAULT-OBJECT? expr) Returns #t if the expression is the object passed as the default value of an optional parameter to a procedure when that parameter is omitted from a call and #f otherwise. (ENVIRONMENT? expr) Returns #t if the expression is an environment and #f otherwise. Equality Predicates (EQUAL? expr1 expr2) Recursively compares two objects to determine if their components are the same and returns #t if they are the same and #f otherwise. (EQV? expr1 expr2) Compares two objects to determine if they are the same object. Returns #t if they are the same and #f otherwise. This function does not compare the elements of lists or vectors but will compare strings and all types of numbers. (EQ? expr1 expr2) Compares two objects to determine if they are the same object. Returns #t if they are the same and #f otherwise. This function performs a low level address compare on two objects and may return #f for objects that appear on the surface to be the same. This is because the objects are not stored uniquely in memory. For instance, numbers may appear to be equal, but EQ? will return #f when comparing them if they are stored at different addresses. The advantage of this function is that it is faster than the others. Symbols are guaranteed to compare correctly, so EQ? can safely be used to compare them. Arithmetic Functions (IDENTITY expr) Returns the value of expr. This is the identity function. (ZERO? n) Returns #t if the number is zero and #f otherwise. (POSITIVE? n) Returns #t if the number is positive and #f otherwise. (NEGATIVE? n) Returns #t if the number is negative and #f otherwise. (ODD? n) Returns #t if the integer is odd and #f otherwise. (EVEN? n) Returns #t if the integer is even and #f otherwise. (EXACT? n) Returns #t if the number is exact and #f otherwise. Note: This function always returns #f in XLISP since exact numbers are not yet supported. (INEXACT? n) Returns #t if the number is inexact and #f otherwise. Note: This function always returns #t in XLISP since exact numbers are not yet supported. (TRUNCATE n) Truncates a number to an integer and returns the resulting value. (FLOOR n) Returns the largest integer not larger than n. (CEILING n) Returns the smallest integer not smaller than n. (ROUND n) Returns the closest integer to n, rounding to even when n is halfway between two integers. (1+ n) Returns the result of adding one to the number. (-1+ n) Returns the result of subtracting one from the number. (ABS n) Returns the absolute value of the number. (GCD n1 n2...) Returns the greatest common divisor of the specified numbers. (LCM n1 n2...) Returns the least common multiple of the specified numbers. (RANDOM n) Returns a random number between zero and n-1 (n must be an integer). (SET-RANDOM-SEED! n) Sets the seed of the random number generator to n. (+ n1 n2...) Returns the sum of the numbers. (- n) Negates the number and returns the resulting value. (- n1 n2...) Subtracts each remaining number from n1 and returns the resulting value. (* n1 n2...) Multiplies the numbers and returns the resulting value. (/ n) Returns 1/n. (/ n1 n2...) Divides n1 by each of the remaining numbers and returns the resulting value. (QUOTIENT n1 n2...) Divides the integer n1 by each of the remaining numbers and returns the resulting integer quotient. This function does integer division. (REMAINDER n1 n2) Divides the integer n1 by the integer n2 and returns the remainder. (MODULO n1 n2) Returns the integer n1 modulo the integer n2 . (MIN n1 n2...) Returns the number with the minimum value. (MAX n1 n2...) Returns the number with the maximum value. (SIN n) Returns the sine of the number. (COS n) Returns the cosine of the number. (TAN n) Returns the tangent of the number. (ASIN n) Returns the arc-sine of the number. (ACOS n) Returns the arc-cosine of the number. (ATAN x) Returns the arc-tangent of x. (ATAN y x) Returns the arc-tangent of y/x. (EXP n) Returns e raised to the n. (SQRT n) Returns the square root of n. (EXPT n1 n2) Returns n1 raised to the n2 power. (LOG n) Returns the natural logarithm of n. Comparison Functions (< n1 n2...) (= n1 n2...) (> n1 n2...) (<= n1 n2...) (/= n1 n2...) (>= n1 n2...) These functions compare numbers and return #t if the numbers match the predicate and #f otherwise. For instance, (< x y z) will return #t if x is less than y and y is less than z. Bitwise Logical Functions (LOGAND n1 n2...) Returns the bitwise AND of the integer arguments. (LOGIOR n1 n2...) Returns the bitwise inclusive OR of the integer arguments. (LOGXOR n1 n2...) Returns the bitwise exclusive OR of the integer arguments. (LOGNOT n) Returns the bitwise complement of n. (ASH n shift) Arithmetically shift n left by the specified number of places (or right if shift is negative) (LSH n shift) Logically shift n left by the specified number of places (or right if shift is negative). String Functions (MAKE-STRING size) Makes a string of the specified size initialized to nulls. (STRING-LENGTH str) Returns the length of the string. (STRING-NULL? str) Returns #t if the string has a length of zero and #f otherwise. (STRING-APPEND str1...) Returns the result of appending the string arguments. If no arguments are supplied, it returns the null string. (STRING-REF str n) Returns the nth character in a string. (STRING-SET! str n c) Sets the nth character of the string to c. (SUBSTRING str &optional start end) Returns the substring of str starting at start and ending at end (integers). The range is inclusive of start and exclusive of end. (STRING-UPCASE str &key start end) Return a copy of the specified string with lowercase letters converted to uppercase letters in the specified range (which defaults to the whole string). (STRING-DOWNCASE str &key start end) Return a copy of the specified string with uppercase letters converted to lowercase letters in the specified range (which defaults to the whole string). (STRING-UPCASE! str &key start end) Like STRING-UPCASE but modifies the input string. (STRING-DOWNCASE! str &key start end) Like STRING-DOWNCASE but modifies the input string. (STRING-TRIM bag str) Return a string with characters that are in bag (which is also a string) removed from both the left and right ends. (STRING-LEFT-TRIM bag str) Return a string with characters that are in bag (which is also a string) removed from the left end. (STRING-RIGHT-TRIM bag str) Return a string with characters that are in bag (which is also a string) removed from right end. (STRING-SEARCH str1 str2 &key start1 end1 start2 end2 from-end?) Search for the specified substring of str1 in the specified substring of str2 and return the starting offset when a match is found or nil if no match is found. (STRING-CI-SEARCH str1 str2 &key start1 end1 start2 end2 from-end?) Like STRING-SEARCH but case insensitive. String Comparison Functions (STRING<? str1 str2 &key start1 end1 start2 end2) (STRING=? str1 str2 &key start1 end1 start2 end2) (STRING>? str1 str2 &key start1 end1 start2 end2) (STRING<=? str1 str2 &key start1 end1 start2 end2) (STRING/=? str1 str2 &key start1 end1 start2 end2) (STRING>=? str1 str2 &key start1 end1 start2 end2) These functions compare strings and return #t if the strings match the predicate and #f otherwise. For instance, (STRING< x y) will return #t if x is less than y. Case is significant. #A does not match #a. (STRING-CI<? str1 str2 &key start1 end1 start2 end2) (STRING-CI=? str1 str2 &key start1 end1 start2 end2) (STRING-CI>? str1 str2 &key start1 end1 start2 end2) (STRING-CI<=? str1 str2 &key start1 end1 start2 end2) (STRING-CI/=? str1 str2 &key start1 end1 start2 end2) (STRING-CI>=? str1 str2 &key start1 end1 start2 end2) These functions compare strings and return #t if the strings match the predicate and #f otherwise. For instance, (STRING-CI< x y) will return #t if x is less than y. Case is not significant. #A matches #a. Character Functions (CHAR-UPPER-CASE? ch) Is the specified character an upper case letter? (CHAR-LOWER-CASE? ch) Is the specifed character a lower case letter? (CHAR-ALPHABETIC? ch) Is the specified character an upper or lower case letter? (CHAR-NUMERIC? ch) Is the specified character a digit? (CHAR-ALPHANUMERIC? ch) Is the specified character a letter or a digit? (CHAR-WHITESPACE? ch) Is the specified character whitespace? (STRING ch) Return a string containing just the specified character. (CHAR str [n]) Return the nth character of the string (n defaults to zero). (CHAR-UPCASE ch) Return the uppercase equivilent to the specified character if it is a letter. Otherwise, just return the character. (CHAR-DOWNCASE ch) Return the lowercase equivilent to the specified character if it is a letter. Otherwise, just return the character. (DIGIT->CHAR n) Return the character associated with the specified digit. The argument must be in the range of zero to nine. Character Comparison Functions (CHAR<? ch1 ch2) (CHAR=? ch1 ch2) (CHAR>? ch1 ch2) (CHAR<=? ch1 ch2) (CHAR/=? ch1 ch2) (CHAR>=? ch1 ch2) These functions compare characters and return #t if the characters match the predicate and #f otherwise. For instance, (CHAR< x y) will return #t if x is less than y. Case is significant. #A does not match #a. (CHAR-CI<? ch1 ch2) (CHAR-CI=? ch1 ch2) (CHAR-CI>? ch1 ch2) (CHAR-CI<=? ch1 ch2) (CHAR-CI>=? ch1 ch2) These functions compare characters and return #t if the characters match the predicate and #f otherwise. For instance, (CHAR-CI< x y) will return #t if x is less than y. Case is not significant. #A matchs #a. (READ &optional port) Reads an expression from the specified port. If no port is specified, the current input port is used. Returns the expression read or an object that satisfies the eof-object? predicate if it reaches the end of file on the port. (READ-DELIMITED-LIST ch &optional port) Read expressions building a list until the first occurance of the specified character. Return the resulting list. (SET-MACRO-CHARACTER! ch fun &optional non-terminating? table) (GET-MACRO-CHARACTER ch &optional table) (MAKE-DISPATCH-MACRO-CHARACTER ch &optional non-terminating? table) (SET-DISPATCH-MACRO-CHARACTER dch ch fun &optional table) (GET-DISPATCH-MACRO-CHARACTER dch ch &optional table) (WRITE expr &optional port) Writes an expression to the specified port. If no port is specified, the current output port is used. The expression is written such that the READ function can read it back. This means that strings will be enclosed in quotes and characters will be printed with # notation. (WRITE-SIZE expr) Returns the number of characters in the printed representation of the specified object when printed by the function WRITE. (DISPLAY-SIZE expr) Returns the number of characters in the printed representation of the specified object when printed by the function DISPLAY. (DISPLAY expr &optional port) Writes an expression to the specified port. If no port is specified, the current output port is used. The expression is written without any quoting characters. No quotes will appear around strings and characters are written without the # notation. (PRINT expr &optional port) The same as (NEWLINE port) followed by (WRITE expr port). Input/Output Functions (READ-LINE &optional port) Read a line from the specified port (which defaults to the current input port). Returns the line read as a string or nil if it reaches end of file on the port. (READ-CHAR &optional port) Reads a character from the specified port. If no port is specified, the current input port is used. Returns the character read or an object that satisfies the default-object? predicate if it reaches the end of file on the port. (UNREAD-CHAR ch &optional port) Unread the specified character. This causes it to be the next character read from the port. Only one character can be "unread" at a time. This allows for a one character look ahead for parsers. (PEEK-CHAR &optional port) Peek at the next character without actually reading it. (CHAR-READY? &optional port) Returns #t if a character is ready on the specified port, #f if not. (CLEAR-INPUT &optional port) Clears any buffered input on the specified port. (READ-BYTE &optional port) Reads a byte from the specified port. If no port is specified, the current input port is used. Returns the byte read or an object that satisfies the default- object? predicate if it reaches the end of file on the port. (READ-SHORT &optional port) (READ-SHORT-HIGH-FIRST &optional port) (READ-SHORT-LOW-FIRST &optional port) Read signed 16 bit value from the specified port in whatever byte order is native to the host machine. Returns the 16 bit value or an object that satisfies the eof-object? predicate if it reaches the end of file on the port. The -HIGH-FIRST and -LOW-FIRST forms read the high and low byte first respectively. (READ-LONG &optional port) (READ-LONG-HIGH-FIRST &optional port) (READ-LONG-LOW-FIRST &optional port) Read signed 32 bit value from the specified port in whatever byte order is native to the host machine. Returns the 32 bit value or an object that satisfies the eof-object? predicate if it reaches the end of file on the port. . The -HIGH-FIRST and -LOW-FIRST forms read the high and low byte first respectively. (WRITE-CHAR ch &optional port) Writes a character to the specified port. If no port is specified, the current output port is used. (WRITE-BYTE ch &optional port) Writes a byte to the specified port. If no port is specified, the current output port is used. (WRITE-SHORT n &optional port) (WRITE-SHORT-HIGH-FIRST n &optional port) (WRITE-SHORT-LOW-FIRST n &optional port) Write a signed 16 bit integer to the specified port. If no port is specified, the current output port is used. The -HIGH-FIRST and -LOW-FIRST forms write the high and low byte first respectively. (WRITE-LONG n &optional port) (WRITE-LONG-HIGH-FIRST n &optional port) (WRITE-LONG-LOW-FIRST n &optional port) Write a signed 32 bit integer to the specified port. If no port is specified, the current output port is used. . The -HIGH-FIRST and -LOW-FIRST forms write the high and low byte first respectively. (NEWLINE &optional port) Starts a new line on the specified port. If no port is specified, the current output port is used. (FRESH-LINE &optional port) Starts a fresh line on the specified port. If the output position is already at the start of the line, FRESH-LINE does nothing. If no port is specified, the current output port is used. Format (FORMAT port str &rest args) If port is #f, FORMAT collects its output into a string and returns the string. If port is #t, FORMAT sends its output to the current output port. Otherwise, port should be an output port. ~S print argument as if with WRITE ~A print argument as if with DISPLAY ~X print argument as a hexadecimal number ~% print as if with NEWLINE ~& print as if with FRESH-LINE Output Control Functions (PRINT-BREADTH [n]) Controls the maximum number of elements of a list that will be printed. If n is an integer, the maximum number is set to n. If it is #f, the limit is set to infinity. This is the default. If n is omitted from the call, the current value is returned. (PRINT-DEPTH [n]) Controls the maximum number of levels of a nested list that will be printed. If n is an integer, the maximum number is set to n. If it is #f, the limit is set to infinity. This is the default. If n is omitted from the call, the current value is returned. File I/O Functions All four of the following OPEN functions take an optional argument to indicate that file I/O is to be done in binary mode. For binary files, this argument should be the symbol BINARY. For text files, the argument can be left out or the symbol TEXT can be supplied. (OPEN-INPUT-FILE str ['binary]) Opens the file named by the string and returns an input port. (OPEN-OUTPUT-FILE str ['binary]) Creates the file named by the string and returns an output port. (OPEN-APPEND-FILE str ['binary]) Opens the file named by the string for appending returns an output port. (OPEN-UPDATE-FILE str ['binary]) Opens the file named by the string for input and output and returns an input/output port. (FILE-MODIFICATION-TIME str) Returns the time the file named by the string was last modified. (PARSE-PATH-STRING str) Parses a path string and returns a list containing each path entry terminated by a path separator. (GET-FILE-POSITION port) Returns the current file position as an offset in bytes from the beginning of the file. (SET-FILE-POSITION! port offset whence) Sets the current file position as an offset in bytes from the beginning of the file (when whence equals 0), the current file position (when whence equals 1) or the end of the file (when whence equals 2). Returns the new file position as an offset from the start of the file. (CLOSE-PORT port) Closes any port. (CLOSE-INPUT-PORT port) Closes an input port. (CLOSE-OUTPUT-PORT port) Closes an output port. (CALL-WITH-INPUT-FILE str proc) Open the file whose name is specifed by str and call proc passing the resulting input port as an argument. When proc returns, close the file and return the value returned by proc as the result. (CALL-WITH-OUTPUT-FILE str proc) Create the file whose name is specifed by str and call proc passing the resulting output port as an argument. When proc returns, close the file and return the value returned by proc as the result. (CURRENT-INPUT-PORT) Returns the current input port. (CURRENT-OUTPUT-PORT) Returns the current output port. (CURRENT-ERROR-PORT) Returns the current error port. String Stream Functions (MAKE-STRING-INPUT-STREAM str) Make a stream that can be used to retrieve the characters in the specified string. The returned stream can be used as an input port in any function that takes an input port as an argument. (MAKE-STRING-OUTPUT-STREAM) Make a stream that can be used as an output port in any function that takes an output port as an argument. The stream accumulates characters until the GET-OUTPUT-STREAM-STRING function is called to retrieve them. (GET-OUTPUT-STREAM-STRING stream) Returns the contents of a string output stream as a string and clears the output stream. Control Features (EVAL expr [env]) Evaluate the expression in the global environment and return its value. (APPLY proc args) Apply the procedure to the list of arguments and return the result. (MAP proc list...) Apply the procedure to argument lists formed by taking corresponding elements from each list. Form a list from the resulting values and return that list as the result of the MAP call. (FOR-EACH fun list...) Apply the procedure to argument lists formed by taking corresponding elements from each list. The values returned by the procedure applications are discarded. The value returned by FOR-EACH is unspecified. (CALL-WITH-CURRENT-CONTINUATION proc) (CALL/CC proc) Form an "escape procedure" from the current continuation and pass it as an argument to proc. Calling the escape procedure with a single argument will cause that argument to be passed to the continuation that was in effect when the CALL-WITH-CURRENT-CONTINUATION procedure was called. Environment Functions (THE-ENVIRONMENT) Returns the current environment. (PROCEDURE-ENVIRONMENT proc) Returns the environment from a procedure closure. (ENVIRONMENT-BINDINGS env) Returns an association list corresponding to the top most frame of the specified environment. (ENVIRONMENT-PARENT env) Returns the parent environment of the specified environment. (BOUND? symbol [env]) Returns #t if the symbol is bound in the environment. (SYMBOL-VALUE symbol [env]) Returns the value of a variable in an environment. (SET-SYMBOL-VALUE! symbol value [env]) Sets the value of a symbol in an environment. The result of the set-symbol-value! expression is unspecified. (EVAL expr [env]) Evaluate the expression in the specified environment and return its value. Utility Functions (LOAD str) Read and evaluate each expression from the specified file. (LOAD-NOISILY str) Read and evaluate each expression from the specified file and print the results to the current output port. (LOAD-FASL-FILE str) Load a fasl file produced by COMPILE-FILE. (TRANSCRIPT-ON str) Opens a transcript file with the specified name and begins logging the interactive session to that file. (TRANSCRIPT-OFF) Closes the current transcript file. (COMPILE expr &optional env) Compiles an expression in the specified environment and returns a thunk that when called causes the expression to be evaluated. The environment defaults to the top level environment if not specified. (SAVE name) Saves the current workspace to a file with the specified name. The workspace can later be reloaded using RESTORE. (RESTORE name) Restores a previously saved workspace from the file with the specified name. (GETARG n) Get the nth argument from the command line. If there were fewer than n arguments, return nil. (GET-TIME) Get the current time in seconds. (GET-ENVIRONMENT-VARIABLE name) Get the value of the environment variable with the specified name. The name should be a string. Returns the value of the environment variable if it exists. Otherwise, returns nil. (EXIT) (QUIT) Exits from XLISP back to the operating system. (GC [ni vi]) Invokes the garbage collector and returns information on memory usage. If ni and vi are specified, they must be integers. Node and vector space are expanded by those amounts respectively and no garbage collection is triggered. GC returns an array of six values: the number of calls to the garbage collector, the total number of nodes, the current number of free nodes, the number of node segments, the number of vector segments and the total number of bytes allocated to the heap. (ROOM) Returns the same information as GC without actually invoking the garbage collector. (LOAD-FASL-FILE name) (FASL-WRITE-PROCEDURE proc &optional port) (FASL-READ-PROCEDURE &optional port) (DEFINE-CRECORD name (field-definition...)) Field definition: (field-name type &optional size) Where type is: char, uchar, short, ushort, int, uint, long, ulong, str (ALLOCATE-CMEMORY type size) (FREE-CMEMORY ptr) (FOREIGN-POINTER? ptr) (FOREIGN-POINTER-TYPE ptr) (SET-FOREIGN-POINTER-TYPE! ptr type) (FOREIGN-POINTER-TYPE? ptr type) (FOREIGN-POINTER-EQ? ptr1 ptr2) (GET-CRECORD-FIELD ptr offset type) (GET-CRECORD-FIELD-ADDRESS ptr offset type) (SET-CRECORD-FIELD! ptr offset type val) (GET-CRECORD-STRING ptr offset length) (SET-CRECORD-STRING! ptr offset length str) (GET-CRECORD-TYPE-SIZE type) (DECOMPILE proc &optional port) Decompiles the specified bytecode procedure and displays the bytecode instructions to the specified port. If not specified, the port defaults to the current output port. (INSTRUCTION-TRACE &rest body) Enables bytecode level instruction tracing during the evaluation of the expressions in the body. (TRACE-ON) Starts bytecode instruction level tracing. (TRACE-OFF) Stops bytecode instruction level tracing. (SHOW-STACK &optional n) Shows the call stack leading up to an error when invoked from a debug prompt. Each line represents a procedure waiting for a value. The line is displayed in the form of a function call with the procedure first followed by the actual values of the arguments that were passed to the procedure. For method invocations, the method is first followed by the object receiving the message followed by the arguments. N is the number of stack levels to display. If unspecified, it defaults to 20. (SHOW-CONTROL-STACK &optional n) Shows frames on the continuation stack. N is the number of stack levels to display. If unspecified, it defaults to 20. (SHOW-VALUE-STACK &optional n) Shows frames on the value stack. N is the number of stack levels to display. If unspecified, it defaults to 20. (RESET) Returns to the top level read/eval/print loop. System Functions (%CAR pair) (%CDR pair) (%SET-CAR! pair expr) (%SET-CDR! pair expr) (%VECTOR-LENGTH vect) (%VECTOR-REF vect n) (%VECTOR-SET! vect n expr) These functions do the same as their counterparts without the leading '%' character. The difference is that they don't check the type of their first argument. This makes it possible to examine data structures that have the same internal representation as pairs and vectors. It is *very* dangerous to modify objects using these functions and there is no guarantee that future releases of XLISP will represent objects in the same way that the current version does. (%VECTOR-BASE vect) Returns the address of the base of the vector storage. (%ADDRESS-OF expr) Returns the address of the specified object in the heap. (%FORMAT-ADDRESS addr) Returns the address of an object as a string formated for output as a hex number. Object Representations This version of XLISP uses the following object representations: Closures are represented as pairs. The car of the pair is the compiled function and the cdr of the pair is the saved environment. Compiled functions are represented as vectors. The element at offset 0 is the bytecode string. The element at offset 1 is the function name. The element at offset 2 is a list of names of the function arguments. The elements at offsets above 2 are the literals refered to by the compiled bytecodes. Environments are represented as lists of vectors. Each vector is an environment frame. The element at offset 0 is a list of the symbols that are bound in that frame. The symbol values start at offset 1. Objects are represented as vectors. The element at offset 0 is the class of the object. The remaining elements are the object's instance variable values. --------------------------------- ------------- .
57,025
Common Lisp
.lisp
1,327
41.154484
99
0.796295
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
74d013fe1de0dbddb9c81dbf95dc3662eb69def3fa35011c41c02ed55c2ea83e
5,194
[ -1 ]
5,195
package.lisp
informatimago_lisp/languages/lua/package.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: package.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines the package for the LUA system. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-07-15 <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.LANGUAGES.LUA.SCANNER" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER") (:export "LUA-TOKEN" "TOKEN-VALUE" "TOK-COMMENT" "TOK-IDENTIFIER" "TOK-KEYWORD" "TOK-NUMBER" "TOK-SPECIAL" "TOK-STRING" "LUA-SCANNER" "LUA-SCANNER-KEEP-COMMENTS") (:documentation " Implements a LUA scanner. The LUA-SCANNER is a subclass of COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER:SCANNER. The LUA-TOKEN is a subclass of COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER:TOKEN. Copyright Pascal J. Bourguignon 2012 - 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. ")) (defpackage "COM.INFORMATIMAGO.LANGUAGES.LUA.PARSER" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER" "COM.INFORMATIMAGO.LANGUAGES.LUA.SCANNER" "COM.INFORMATIMAGO.RDP") (:export ) (:documentation " Implements a LUA parser. The parser is generated with COM.INFORMATIMAGO.RDP. Copyright Pascal J. Bourguignon 2012 - 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. ")) ;;;; THE END ;;;;
2,944
Common Lisp
.lisp
78
35.538462
80
0.674508
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
daf7512c42ab1fee322f77711324746423f96f56a4c7654a31d7b13f633b0028
5,195
[ -1 ]
5,196
lua-scanner-test.lisp
informatimago_lisp/languages/lua/lua-scanner-test.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: lua-scanner-test.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Test lua-scanner.lisp ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-02-24 <PJB> Extracted tests from lua-scanner.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.LANGUAGES.LUA.SCANNER.TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER" "COM.INFORMATIMAGO.LANGUAGES.LUA.SCANNER") (:export "TEST/ALL")) (in-package "COM.INFORMATIMAGO.LANGUAGES.LUA.SCANNER.TEST") (defun test/scan-stream (src) (loop :with scanner = (make-instance 'lua-scanner :source src) :for token = (scan-next-token scanner) :while token :do (progn (format t "~&~20A ~32S ~32S ~A~%" (token-kind (scanner-current-token scanner)) (token-value (scanner-current-token scanner)) (token-text (scanner-current-token scanner)) (type-of (scanner-current-token scanner))) (finish-output)))) (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))) ;; (test/scan-file #P "~/mission.lua") (define-test test/lua-scanner () (assert-true (with-output-to-string (*standard-output*) (test/scan-file (load-time-value (merge-pathnames #P"test-1.lua" *load-truename* nil)))))) (define-test test/all/lua-scanner () (test/lua-scanner)) (defun test/all () (test/all/lua-scanner)) ;;;; THE END ;;;;
2,938
Common Lisp
.lisp
71
36.577465
83
0.60273
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e8267fc99146380c88ce7ec027cfda44e1ff5d9b2a86022e496d366df3316e64
5,196
[ -1 ]
5,197
lua-scanner.lisp
informatimago_lisp/languages/lua/lua-scanner.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: lua-scanner.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports a LUA scanner and parser. ;;;; http://www.lua.org/manual/5.2/manual.html#3.1 ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-07-14 <PJB> Created. Implemented the scanner. ;;;;BUGS ;;;; ;;;; Implemented the parser of 5.1; ;;;; in 5.2 we miss :: and "\z", "\xHH"; 0XHH (we implement 0xHH), ;;;; and hexadecimal floating points. 0x1.921FBP+1 0xA23p-4 ;;;; ;;;; #x = (length x) ;;;; ;;;;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 "COM.INFORMATIMAGO.LANGUAGES.LUA.SCANNER") ;; We need to write a specific scanner because of long brackets. :-( ;; Lua is a case-sensitive language: and is a reserved word, but And ;; and AND are two different, valid names. As a convention, names ;; starting with an underscore followed by uppercase letters (such as ;; _VERSION) are reserved for internal global variables used by Lua. (defparameter *lua-keywords* (loop :with h = (make-hash-table :test (function equal)) :for kw :in '("and" "break" "do" "else" "elseif" "end" "false" "for" "function" "if" "in" "local" "nil" "not" "or" "repeat" "return" "then" "true" "until" "while") :do (setf (gethash kw h) (intern kw :keyword)) :finally (return h))) ;; (com.informatimago.common-lisp.cesarum.utility:print-hashtable *lua-keywords*) (defparameter *lua-special-tokens* '("+" "-" "*" "/" "%" "^" "#" "==" "~=" "<=" ">=" "<" ">" "=" "(" ")" "{" "}" "[" "]" ";" ":" "," "." ".." "...")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; LUA Tokens ;;; (defclass lua-token (token) ()) (defclass tok-special (lua-token) ()) (defclass tok-keyword (lua-token) ()) (defclass tok-identifier (lua-token) ()) (defgeneric token-value (token) (:method ((token token)) (token-kind token))) (defclass tok-string (lua-token) ((value :accessor token-value :initarg :value :initform "" :type string))) (defclass tok-number (lua-token) ((value :accessor token-value :initarg :value :initform 0.0d0 :type real))) (defclass tok-comment (lua-token) ()) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; LUA Scanner ;;; (defclass lua-scanner (buffered-scanner) ((keep-comments :accessor lua-scanner-keep-comments :initform nil :initarg :keep-comments :type boolean :documentation "When T, comments are returned as tokens, when NIL, comments are skipped as spaces.")) (:documentation "A scanner for LUA.")) (defgeneric process-escape (scanner text value)) (defgeneric scan-string-starting-with (scanner delimiter)) (defgeneric scan-string-starting-with-long-bracket (scanner bracket)) (defgeneric scan-identifier (scanner)) (defgeneric scan-number (scanner)) (defmethod process-escape ((scanner lua-scanner) text value) (let ((ch (getchar scanner))) (write-char ch text) (let ((ch (case ch ((#\a) #+bell #\Bell ;; assume ASCII: #-bell (ignore-errors (code-char 7))) ((#\b) #+backspace #\Backspace ;; assume ASCII: #-backspace (ignore-errors (code-char 8))) ((#\f) #+page #\Page ;; assume ASCII: #-page (ignore-errors (code-char 12))) ((#\n #\Newline) #\Newline) ((#\r) #+return #\Return ;; assume ASCII: #-return (ignore-errors (code-char 13))) ((#\t) #+tab #\Tab ;; assume ASCII: #-tab (ignore-errors (code-char 9))) ((#\v) #+vt #\vt ;; assume ASCII: #-vt (ignore-errors (code-char 11))) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (let ((digits (list ch))) (when (digit-char-p (nextchar scanner)) (let ((ch (getchar scanner))) (write-char ch text) (push ch digits)) (when (digit-char-p (nextchar scanner)) (let ((ch (getchar scanner))) (write-char ch text) (push ch digits)))) (let ((code (parse-integer (coerce (nreverse digits) 'string)))) ;; Note: we should ;; catch the errors ;; and continue ;; scanning the ;; string, before ;; resignaling the ;; error. (if (<= 0 code 255) (handler-case (code-char code) (error () (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Invalid character code in escape: ~A (unsupported character code) in string ~S." :format-arguments (list code (get-output-stream-string text))))) (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Invalid character code in escape \\~A in string ~S." :format-arguments (list code (get-output-stream-string text))))))) (otherwise ch)))) (when ch (write-char ch value))))) (defmethod scan-string-starting-with ((scanner lua-scanner) delimiter) ;; "('([^'\\]|\\([abfnrtv\\\"']|[0-9]([0-9][0-9]?)?)*') ;; |(\"([^'\\]|\\([abfnrtv\\\"']|[0-9]([0-9][0-9]?)?)*\")" (let (text value) (setf text (with-output-to-string (text) (write-char delimiter text) (setf value (with-output-to-string (value) (loop :for ch = (getchar scanner) :while ch :do (write-char ch text) :until (char= ch delimiter) :do (case ch ((#\\) (process-escape scanner text value)) ((#\Newline) (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Unescaped newline in string: ~S." :format-arguments (list (get-output-stream-string text)))) (otherwise (write-char ch value))) :finally (unless ch (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Reached end-of-file with unterminated string starting with: ~S." :format-arguments (list (get-output-stream-string text))))))))) (values text value))) (defmethod scan-string-starting-with-long-bracket ((scanner lua-scanner) bracket) (let (text value) (setf text (with-output-to-string (text) (write-char bracket text) (setf value (with-output-to-string (value) (loop :named scan-string :with olevel = (loop :for ch = (nextchar scanner) :while (char= ch #\=) :do (write-char (getchar scanner) text) :count 1 :into level :finally (write-char (getchar scanner) text) (unless (char= ch #\[) (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Invalid token: ~S (missing a '['?)" :format-arguments (list (get-output-stream-string text)))) (return level)) :for ch = (getchar scanner) :while ch :do (write-char ch text) :do (case ch ((#\\) (process-escape scanner text value)) ((#\]) (loop :for ch = (nextchar scanner) :while (char= ch #\=) :do (write-char (getchar scanner) text) :count 1 :into level :finally (write-char (getchar scanner) text) (if (and (char= ch #\]) (= olevel level)) (return-from scan-string) (format value "]~V,,,'=<~>~C" level ch)))) (otherwise (write-char ch value))) :finally (unless ch (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Reached end-of-file with unterminated string starting with: ~S." :format-arguments (list (get-output-stream-string text))))))))) (values text value))) (defun make-extensible-string (&optional (default-allocation 32)) (make-array default-allocation :element-type 'character :adjustable t :fill-pointer 0)) (defmethod scan-identifier ((scanner lua-scanner)) (with-output-to-string (name) (write-char (getchar scanner) name) (loop :for ch = (nextchar scanner) :while (and ch (or (alphanumericp ch) (char= ch #\_))) :do (write-char (getchar scanner) name)))) (defmethod scan-number ((scanner lua-scanner)) (flet ((invalid-char (ch what number) (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Invalid ~A character ~S in number starting with: ~S." :format-arguments (list what ch number))) (incomplete-floating-point-number (number) (error 'scanner-error :line (scanner-line scanner) :column (scanner-column scanner) :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Incomplete floating-point number starting with: ~S." :format-arguments (list number)))) (let ((ch (getchar scanner))) (if (char= #\x (nextchar scanner)) ;; hexadecimal integer (let ((text (with-output-to-string (number) (loop :for ch = (nextchar scanner) :while (and ch (digit-char-p ch 16.)) :do (write-char (getchar scanner) number) :finally (when (and ch (alphanumericp ch)) (invalid-char ch "hexadecimal" (concatenate 'string "0x" (get-output-stream-string number)))))))) (values text (parse-integer text :radix 16))) ;; integer or floating-point (let* ((*read-default-float-format* 'double-float) (*read-base* 10.) (*read-eval* nil) (text (with-output-to-string (number) (write-char ch number) (loop :with state = :before-dot :for ch = (nextchar scanner) :while ch :do (case state (:before-dot (case ch ((#\.) (setf state :after-dot) (write-char (getchar scanner) number)) ((#\e #\E) (setf state :after-exponent) (write-char (getchar scanner) number)) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (write-char (getchar scanner) number)) (otherwise (when (and ch (alphanumericp ch)) (invalid-char ch "integer" (get-output-stream-string number))) #-mocl (loop-finish) #+mocl (case state ((:after-dot :after-exponent :after-exponent-sign) (incomplete-floating-point-number (get-output-stream-string number))))))) (:after-dot (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf state :in-fraction) (write-char (getchar scanner) number)) (otherwise (invalid-char ch (if (char-equal ch #\e) "floating-point (missing a 0 before the exponent?)" "floating-point") (get-output-stream-string number))))) (:in-fraction (case ch ((#\e #\E) (setf state :after-exponent) (write-char (getchar scanner) number)) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (write-char (getchar scanner) number)) (otherwise (when (and ch (alphanumericp ch)) (invalid-char ch "floating-point" (get-output-stream-string number))) #-mocl (loop-finish) #+mocl (case state ((:after-dot :after-exponent :after-exponent-sign) (incomplete-floating-point-number (get-output-stream-string number))))))) (:after-exponent (case ch ((#\- #\+) (setf state :after-exponent-sign) (write-char (getchar scanner) number)) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf state :in-exponent) (write-char (getchar scanner) number)) (otherwise (when (and ch (alphanumericp ch)) (invalid-char ch "floating-point exponent" (get-output-stream-string number))) #-mocl (loop-finish) #+mocl (case state ((:after-dot :after-exponent :after-exponent-sign) (incomplete-floating-point-number (get-output-stream-string number))))))) (:after-exponent-sign (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf state :in-exponent) (write-char (getchar scanner) number)) (otherwise (when (alphanumericp ch) (invalid-char ch "floating-point exponent" (get-output-stream-string number))) #-mocl (loop-finish) #+mocl (case state ((:after-dot :after-exponent :after-exponent-sign) (incomplete-floating-point-number (get-output-stream-string number))))))) (:in-exponent (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (write-char (getchar scanner) number)) (otherwise (when (alphanumericp ch) (invalid-char ch "floating-point exponent" (get-output-stream-string number))) #-mocl (loop-finish) #+mocl (case state ((:after-dot :after-exponent :after-exponent-sign) (incomplete-floating-point-number (get-output-stream-string number)))))))) :finally (case state ((:after-dot :after-exponent :after-exponent-sign) (incomplete-floating-point-number (get-output-stream-string number)))))))) (values text (read-from-string text))))))) (defmethod scan-next-token ((scanner lua-scanner) &optional parser-data) (declare (ignore parser-data)) (skip-spaces scanner) (setf (scanner-current-token scanner) (let ((column (scanner-column scanner)) (line (scanner-column scanner)) (ch (getchar scanner))) (flet ((invalid-char (ch) (error 'scanner-error :line line :column column :state (scanner-state scanner) :current-token (scanner-current-token scanner) :scanner scanner :format-control "Invalid character ~S" :format-arguments (list ch)))) (case ch ((nil) nil) ((#\' #\") (multiple-value-bind (text value) (scan-string-starting-with scanner ch) (make-instance 'tok-string :column column :line line :kind :string :text text :value value))) ((#\[) ;; [ [[…]] [=[…]=] [=…=[…]=…=] (let ((next (nextchar scanner))) (case next ((#\[ #\=) (multiple-value-bind (text value) (scan-string-starting-with-long-bracket scanner ch) (make-instance 'tok-string :column column :line line :kind :string :text text :value value))) (otherwise (make-instance 'tok-special :column column :line line :kind :left-bracket :text "["))))) ((#\< #\= #\> #\~) (let ((next (nextchar scanner))) (case next ((#\=) (let ((name (make-array 2 :element-type 'character :initial-contents (list ch (getchar scanner))))) (make-instance 'tok-special :column column :line line :kind (case ch (#\< :le) (#\= :eq) (#\> :ge) (#\~ :ne)) :text name))) (otherwise (when (char= ch #\~) (invalid-char ch)) (let ((name (string ch))) (make-instance 'tok-special :column column :line line :kind (case ch (#\< :lt) (#\= :assign) (#\> :gt)) :text name)))))) ((#\-) ;; - -- --[[…]] --[=[…]=] --[=…=[…]=…=] (let ((next (nextchar scanner))) (if (char= next #\-) (progn (getchar scanner) (if (char= (nextchar scanner) #\[) (multiple-value-bind (text value) (scan-string-starting-with-long-bracket scanner ch) (if (lua-scanner-keep-comments scanner) (make-instance 'tok-string :column column :line line :kind :string :text text :value value) (scan-next-token scanner))) (let ((comment (progn (ungetchar scanner ch) (ungetchar scanner ch) (readline scanner)))) (if (lua-scanner-keep-comments scanner) (make-instance 'tok-comment :column column :line line :kind :comment :text comment) (scan-next-token scanner))))) (make-instance 'tok-special :column column :line line :kind :minus :text "-")))) ((#\+ #\* #\/ #\% #\^ #\# #\( #\) #\{ #\} #\] #\; #\: #\,) (make-instance 'tok-special :column column :line line :kind (case ch (#\+ :plus) (#\* :times) (#\/ :divide) (#\% :modulo) (#\^ :power) (#\# :sharp) (#\( :left-paren) (#\) :right-paren) (#\{ :left-brace) (#\} :right-brace) (#\] :right-bracket) (#\; :semicolon) (#\: :colon) (#\, :comma)) :text (string ch))) ((#\.) ;; . .. ... (if (char= (nextchar scanner) #\.) (progn (getchar scanner) (if (char= (nextchar scanner) #\.) (progn (getchar scanner) (make-instance 'tok-special :column column :line line :kind :tridot :text "...")) (make-instance 'tok-special :column column :line line :kind :duodot :text ".."))) (make-instance 'tok-special :column column :line line :kind :unidot :text "."))) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (ungetchar scanner ch) (multiple-value-bind (text value) (scan-number scanner) (make-instance 'tok-number :column column :line line :kind :number :text text :value value))) (otherwise ;; LUA alpha chars depend on the locale (isalpha). ;; We assume the CL implementation uses the locale for alpha-char-p. (if (and ch (or (alpha-char-p ch) (char= #\_ ch))) (progn (ungetchar scanner ch) (let* ((name (scan-identifier scanner)) (kw (gethash name *lua-keywords*))) (make-instance (if kw 'tok-keyword 'tok-identifier) :column column :line line :kind (or kw :identifier) :text name))) (invalid-char ch)))))))) ;;;; THE END ;;;;
29,250
Common Lisp
.lisp
557
29.639138
136
0.390641
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
306043192be8576a3e5ecda7e03bb97e34f691231dd671b285910b8f3e8ea952
5,197
[ -1 ]
5,198
lua-parser.lisp
informatimago_lisp/languages/lua/lua-parser.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: lua-parser.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines the LUA 5.2 Parser. ;;;; http://www.lua.org/manual/5.2/manual.html#9 ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-07-15 <PJB> Created. ;;;;BUGS ;;;; ;;;; This is unfinished. ;;;; ;;;;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 "COM.INFORMATIMAGO.LANGUAGES.LUA.PARSER") (defgrammar lua :trace nil :scanner lua-scanner :terminals ((number "[0-9]+") (string "\"[^\"]*\"") (name "[_A-Za-z][_A-Za-z0-9]*")) :start chunk :rules ( ;; (--> chunk ;; block) (--> chunk exp) (--> block (seq (rep stat) (opt retstat))) (--> stat (alt ";" (seq varlist "=" explist) (seq functioncall) (seq label) (seq "break") (seq "goto" Name) (seq "do" block "end") (seq "while" exp "do" block "end") (seq "repeat" block "until" exp) (seq "if" exp "then" block (rep "elseif" exp "then" block) (opt "else" block) "end") (seq "for" Name (alt for-name-= for-namelist)) (seq "function" funcname funcbody) (seq "local" (alt (seq "function" Name funcbody) (seq namelist (opt "=" explist)))))) (--> for-name-= (seq "=" exp "," exp (opt "," exp) "do" block "end")) (--> for-namelist (seq namelist-cont "in" explist "do" block "end")) (--> retstat (seq "return" (opt explist) (opt ";"))) (--> label (seq "::" Name "::")) (--> funcname (seq Name (rep (seq "." Name)) (opt (seq ":" Name)))) (--> varlist (seq var (rep (seq "," var)))) (--> namelist (seq Name namelist-cont)) (--> namelist-cont (rep (seq "," Name))) (--> explist (seq exp (rep (seq "," exp)))) #-(and) (--> exp (alt "nil" "false" "true" Number String "..." functiondef prefixexp tableconstructor (seq exp binop exp) (seq unop exp))) (--> exp disjonction) (--> disjonction (seq conjonction (rep "or" conjonction))) (--> conjonction (seq comparaison (rep "and" comparaison))) (--> comparaison (seq concatenation (rep (alt "<" ">" "<=" ">=" "~=" "==") concatenation))) (--> concatenation (seq summation (rep ".." summation))) (--> summation (seq term (rep (alt "+" "-") term))) (--> term (seq factor (rep (alt "*" "/" "%") factor))) (--> factor (seq (opt (alt "not" "#" "-")) exponentiation)) (--> exponentiation (seq simple (rep "^" simple))) (--> simple (alt "nil" "false" "true" Number String "…" functiondef prefixexp tableconstructor)) #-(and) (--> prefixexp (alt var functioncall "(" exp ")")) #-(and) (--> var (alt Name (seq prefixexp "[" exp "]") (seq prefixexp "." Name)) ) #-(and) (--> functioncall (alt (seq prefixexp args) (seq prefixexp ":" Name args))) #-(and) (--> callpart (seq (opt (seq ":" name)) args)) (--> indexpart (alt (seq "[" exp "]") (seq "." Name))) #-(and) (--> prefixexp (alt (seq (alt Name (seq "(" exp ")")) (rep (alt callpart indexpart))))) ;; TODO: (--> prefixexp "prefix") ;; TODO: (--> var Name) ;; TODO: (--> functioncall (seq "funcall" Name "(" exp ")")) (--> args (alt (seq "(" (opt explist) ")" ) tableconstructor String) ) (--> functiondef "function" funcbody) (--> funcbody (seq "(" (opt parlist) ")" block "end")) (--> parlist (alt (seq namelist (opt "," "...")) "...")) (--> tableconstructor (seq "{" (opt fieldlist) "}")) (--> fieldlist (seq field (rep fieldsep field) (opt fieldsep))) (--> field (alt (seq "[" exp "]" "=" exp ) (seq Name "=" exp) exp)) (--> fieldsep (alt "," ";")) #-(and) (--> binop (alt "+" "-" "*" "/" "^" "%" ".." "<" "<=" ">" ">=" "==" "~=" "and" "or")) #-(and) (--> unop (alt "-" "not" "#")))) ;; Operator precedence in Lua follows the table below, from lower to ;; higher priority: ;; ;; or ;; and ;; < > <= >= ~= == ;; .. ;; + - ;; * / % ;; not # - (unary) ;; ^ ;; ;; As usual, you can use parentheses to change the precedences of an ;; expression. The concatenation ('..') and exponentiation ('^') ;; operators are right associative. All other binary operators are left ;; associative. ;;;; THE END ;;;;
7,677
Common Lisp
.lisp
227
21.422907
104
0.385842
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
069b71d9a3a424b2f87dc64f354ec5560d1fe824038e4b662c16bb99f17d6d1f
5,198
[ -1 ]
5,199
cxx.lisp
informatimago_lisp/languages/cxx/cxx.lisp
;;;; -*- coding:utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: cxx.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: none ;;;;DESCRIPTION ;;;; ;;;; Parsing C++ sources. ;;;; This is a restricted parser, used just to analyze ;;;; the call graph of C++ functions and methods. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2005-01-07 <PJB> Updated. ;;;; 1996-10-23 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 1996 - 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.LANGUAGES.CXX.CXX" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.GRAPH" ) (:export "BUILD-METHOD-CALL-GRAF" "PARSE" "C++PROGRAM") (:documentation " Parsing C++ sources. This is a restricted parser, used just to analyze the call graph of C++ functions and methods. License: AGPL3 Copyright Pascal J. Bourguignon 1996 - 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.LANGUAGES.CXX.CXX") ;; (defclass Char-Filter () ;; (defclass File-Filter (Char-Filter) ;; (defclass Look-ahead-Char-Filter (Char-Filter) ;; ;; (defclass Token-Filter () ;; (defclass C++Token-Filter (Token-Filter) ;; (defclass C++NoNLToken-Filter (C++Token-Filter) ;; (defclass Look-ahead-Token-Filter (Token-Filter) ;; (defclass C++Comment-Filter (Token-Filter) ;; (defclass CPreprocessor-Filter (Token-Filter) ;; (defclass CComment-Filter (Token-Filter) ;;---------------------------------------------------------------------- ;; method-header ::= [ type ] class-name '::' method-name '(' arguments ')' . ;; body ::= '{' { statement | body } '}' . ;; statement ::= { token } (defgeneric set-file (self f)) (defgeneric read-a-char (self)) (defgeneric dump (self)) (defgeneric do-quotes (self flag)) (defgeneric set-source (self input)) (defgeneric push-on-filter (self f)) (defgeneric read-a-token (self)) (defgeneric parse-statement-list (self filter)) (defgeneric c++class-name (self)) (defgeneric name (self)) (defgeneric res-type (self)) (defgeneric arguments (self)) (defgeneric called-methods (self)) (defgeneric parse (program file-name-list) (:documentation " DO: Parse the files given into the program. PROGRAM: An instance of C++PROGRAM. FILE-NAME-LIST: A list of file pathnames, C++ sources and headers.")) (defgeneric add-c++method (self method)) (defgeneric unify-methods-by-name (self)) (defgeneric build-method-call-graf (program) (:documentation "Builds the method call graph of the program.")) (defgeneric print-c++method-names (self)) ;;---------------------------------------------------------------------- (defclass char-filter () ((previous :accessor previous :initform nil))) (defmethod push-on-filter ((self char-filter) f) (setf (previous self) f)) (defmethod read-a-char ((self char-filter)) (if (null (previous self)) 'eof (read-a-char (previous self)))) (defmethod dump ((self char-filter)) (let ((c (read-a-char self))) (loop while (not (equal 'eof c)) do (write-char c) (setq c (read-a-char self))))) ;;---------------------------------------------------------------------- (defclass file-filter (char-filter) ((file :accessor file :initform nil))) (defmethod set-file ((self file-filter) f) (setf (file self) f)) (defmethod read-a-char ((self file-filter)) (if (null (file self)) 'eof (read-char (file self) nil 'eof))) ;;---------------------------------------------------------------------- (defclass look-ahead-char-filter (char-filter) ((next-char :accessor next-char :initform nil))) (defmethod push-on-filter :before ((self look-ahead-char-filter) f) (declare (ignore f)) (setf (next-char self) nil)) (defmethod read-a-char ((self look-ahead-char-filter)) (if (null (previous self)) 'eof (let ((res nil)) (if (null (next-char self)) (setf (next-char self) (read-a-char (previous self)))) (setq res (next-char self)) (setf (next-char self) (read-a-char (previous self))) res))) ;;---------------------------------------------------------------------- (defclass token-filter () ((previous :accessor previous :initform nil))) (defmethod do-quotes ((self token-filter) flag) (if (null (previous self)) nil (do-quotes (previous self) flag))) (defmethod push-on-filter ((self token-filter) (f token-filter)) (setf (previous self) f)) (defmethod read-a-token ((self token-filter)) (if (null (previous self)) 'eof (read-a-token (previous self)))) (defmethod dump ((self token-filter)) (let ((c (read-a-token self))) (loop while (not (equal 'eof c)) do (print c) (setq c (read-a-token self))))) ;;---------------------------------------------------------------------- (defun char-kind (c) (cond ((equal c 'eof) 'eof) ((or (char= c (code-char 9)) (char= c (character " "))) 'space) ((or (char= c (code-char 10)) (char= c (code-char 13))) 'new-line) ((or (char= (character "_") c) (char= (character "~") c) (alpha-char-p c)) 'letter) ((digit-char-p c) 'digit) ((or (char= (character "'") c) (char= (character "\"") c)) 'quote) (t 'special))) (defun token-member (tok liste) (cond ((null liste) nil) ((equal tok (car liste)) t) (t (token-member tok (cdr liste))))) (defun token-kind (tok) (let* ((c (char tok 0)) (kind (char-kind c))) (cond ((equal kind 'letter) (if (token-member tok '("sizeof" "delete" "this" "friend" "typedef" "auto" "register" "static" "extern" "inline" "virtual" "const" "volatile" "char" "short" "int" "long" "signed" "unsigned" "float" "double" "void" "enum" "class" "struct" "union" "asm" "private" "protected" "public" "operator" "new" "case" "default" "if" "else" "switch" "while" "do" "for" "break" "continue" "return" "goto" "template" "try" "catch" "throw")) 'keyword 'identifier)) ((equal kind 'digit) 'number) ((equal kind 'quote) 'string) ((equal kind 'new-line) 'new-line) (t 'special)))) ;;---------------------------------------------------------------------- (defclass c++token-filter (token-filter) ((c++source :accessor c++source :initform nil) (doquotes :accessor doquotes :initform t) (dotrace :accessor dotrace :initform nil))) (defmethod do-quotes ((self c++token-filter) flag) (let ((old (doquotes self))) (setf (doquotes self) flag) old)) (defmethod set-source ((self c++token-filter) (input look-ahead-char-filter)) (setf (c++source self) input)) (defmethod read-a-token ((self c++token-filter)) ;; * '::' ( ) { } ;; '->' "<char>*" CR '/*' '*/' '//' (let ((r (let ((s nil) (c (read-a-char (c++source self)))) ;; skip spaces;; note we don't skip new-lines here. (loop while (equal (char-kind c) 'space) do (setq c (read-a-char (c++source self)))) (if (equal 'eof c) 'eof (let ((kind (char-kind c))) (setq s (cons c s)) (cond ((equal kind 'letter) (setq c (next-char (c++source self))) (setq kind (char-kind c)) (loop while (or (equal kind 'letter) (equal kind 'digit)) do (setq c (read-a-char (c++source self))) (setq s (cons c s)) (setq c (next-char (c++source self))) (setq kind (char-kind c)))) ((equal kind 'digit) (setq c (next-char (c++source self))) (setq kind (char-kind c)) (loop while (or (equal kind 'digit) (equal c (character ".")) (and (char<= (character "a") c) (char<= c (character "g"))) (and (char<= (character "A") c) (char<= c (character "G"))) (equal c (character "x")) (equal c (character "X")) ) do (setq c (read-a-char (c++source self))) (setq s (cons c s)) (setq c (next-char (c++source self))) (setq kind (char-kind c)))) ((and (doquotes self) (equal kind 'quote)) (let ((term c)) (setq c (read-a-char (c++source self))) (loop while (not (or (equal 'eof c) (equal (char-kind c) 'new-line) (equal term c))) do (setq s (cons c s)) (if (char= (character "\\") c) (progn (setq c (read-a-char (c++source self))) (setq s (cons c s)))) (setq c (read-a-char (c++source self)))) (if (equal term c) (setq s (cons c s))))) ((equal kind 'new-line) (setq c (next-char (c++source self))) (loop while (equal (char-kind c) 'new-line) do (setq c (read-a-char (c++source self))) (setq s (cons c s)) (setq c (next-char (c++source self))))) ((char= (character "-") c) (if (char= (character ">") (next-char (c++source self))) (progn (setq c (read-a-char (c++source self))) (setq s (cons c s))))) ((char= (character "/") c) (if (or (char= (character "/") (next-char (c++source self))) (char= (character "*") (next-char (c++source self)))) (progn (setq c (read-a-char (c++source self))) (setq s (cons c s))))) ((char= (character "*") c) (if (char= (character "/") (next-char (c++source self))) (progn (setq c (read-a-char (c++source self))) (setq s (cons c s))))) ((char= (character ":") c) (if (char= (character ":") (next-char (c++source self))) (progn (setq c (read-a-char (c++source self))) (setq s (cons c s)))))) (concatenate 'string (reverse s))))))) (if (dotrace self) (format t "~a " r)) r)) ;;---------------------------------------------------------------------- (defclass c++nonltoken-filter (c++token-filter) ()) (defmethod read-a-token ((self c++nonltoken-filter)) (let ((tok (read-a-token (previous self)))) (cond ((equal tok 'eof) 'eof) ((equal (token-kind tok) 'new-line) (read-a-token self)) (t tok)))) ;;---------------------------------------------------------------------- (defclass look-ahead-token-filter (token-filter) ((dotrace :accessor dotrace :initform nil) (next-token :accessor next-token :initform nil))) (defmethod push-on-filter :before ((self look-ahead-token-filter) (f token-filter)) (declare (ignore f)) (setf (next-token self) nil)) (defmethod read-a-token ((self look-ahead-token-filter)) (if (null (previous self)) 'eof (let ((res nil)) (if (null (next-token self)) (setf (next-token self) (read-a-token (previous self)))) (setq res (next-token self)) (setf (next-token self) (read-a-token (previous self))) (if (dotrace self) (format t "~a " res)) res))) ;;---------------------------------------------------------------------- (defun skip-comment (self start-string stop-lambda) (if (null (previous self)) 'eof (let ((cur-token (read-a-token (previous self)))) (loop while (equal cur-token start-string) do (let ((saved (do-quotes self nil))) (setq cur-token (read-a-token (previous self))) (loop while (not (or (equal cur-token 'eof) (apply stop-lambda (list cur-token)))) do (setq cur-token (read-a-token (previous self)))) (do-quotes self saved) (unless (equal cur-token 'eof) (setq cur-token (read-a-token (previous self)))))) cur-token))) ;;---------------------------------------------------------------------- (defclass cpreprocessor-filter (token-filter) ()) (defmethod read-a-token ((self cpreprocessor-filter)) (skip-comment self "#" (lambda (x) (equal (token-kind x) 'new-line)))) ;;---------------------------------------------------------------------- (defclass ccomment-filter (token-filter) ()) (defmethod read-a-token ((self ccomment-filter)) (skip-comment self "/*" (lambda (x) (equal x "*/")))) ;;---------------------------------------------------------------------- (defclass c++comment-filter (token-filter) ()) (defmethod read-a-token ((self c++comment-filter)) (skip-comment self "//" (lambda (x) (equal (token-kind x) 'new-line)))) ;;---------------------------------------------------------------------- (defclass c++header () ((res-type :accessor res-type :initform nil) (c++class-name :accessor c++class-name :initform nil) (c++method-name :accessor c++method-name :initform nil) (arguments :accessor arguments :initform nil) (header-kind :accessor header-kind :initform nil) (bad-token-list :accessor bad-token-list :initform nil))) (defun range (s from end) (subseq s from end)) (defmethod parse ((self c++header) (filter token-filter)) (let ((l nil) (tok (read-a-token filter)) (i 0)) (loop while (not (or (equal tok 'eof) (equal tok ")") (equal tok ";;"))) do (setq l (cons tok l)) (setq tok (read-a-token filter))) (when (not (equal tok 'eof)) (setq l (cons tok l))) (setq l (reverse l)) (setq i (search "::" l)) (if (null i) (progn (setf (header-kind self) 'function) (setq i (search "(" l)) (if (or (null i) (= 0 i)) (progn (setf (bad-token-list self) l) nil) (progn (setf (c++class-name self) nil) (setf (res-type self) (range l 0 (- i 2))) (setf (c++method-name self) (car (range l (1- i) (1- i)))) (setf (arguments self) (range l i nil)) t))) (progn (setf (header-kind self) 'method) (setf (c++class-name self) (car (range l (1- i) (1- i)))) (setf (res-type self) (range l 0 (- i 2))) (if (equal (nth (1+ i) l) "~") (progn (setf (c++method-name self) (car (range l (1+ i) (+ i 2)))) (setf (arguments self) (range l (+ i 3) nil))) (progn (setf (c++method-name self) (car (range l (1+ i) (1+ i)))) (setf (arguments self) (range l (+ i 2) nil)))) t)))) ;;---------------------------------------------------------------------- ;; body ::= '{' { statement | body } '}' . ;; statement ::= { token } (defclass c++body () ((initializer :accessor initializer :initform nil) (statements :accessor statements :initform nil))) (defmethod parse ((self c++body) (filter token-filter)) (let ((tok (read-a-token filter)) (i nil)) (if (equal tok ":") (loop while (not (token-member tok '("{" "}" 'eof))) do (setq i (cons tok i)) (setq tok (read-a-token filter)))) (setf (initializer self) (reverse i)) (if (equal tok "{") (block nil (setf (statements self) (parse-statement-list self filter)) t) nil))) (defmethod parse-statement-list ((self c++body) (filter token-filter)) (let ((tok (read-a-token filter)) (s nil)) (loop while (not (or (equal 'eof tok) (equal tok "}"))) do (if (equal tok "{") (setq s (cons (parse-statement-list self filter) s)) (setq s (cons tok s))) (setq tok (read-a-token filter))) (if (equal tok "}") (reverse s) nil))) (defun search-method-calls (statements) (cond ((or (null statements) (null (cdr statements))) nil) ((listp (car statements)) (append (search-method-calls (car statements)) (search-method-calls (cdr statements)))) ((equal "(" (cadr statements)) (if (equal 'identifier (token-kind (car statements))) (cons (car statements) (search-method-calls (cdr statements))) (search-method-calls (cdr statements)))) (t (search-method-calls (cdr statements))))) (defmethod called-methods ((self c++body)) (search-method-calls (statements self))) ;;---------------------------------------------------------------------- ;; Some methods are merely functions, that is methods without a class. ;; In that case: (null (c++class-name method)) (defclass c++method () ((header :accessor header :initform nil) (body :accessor body :initform nil))) (defmethod parse ((self c++method) (filter token-filter)) (setf (header self) (make-instance 'c++header)) (setf (body self) (make-instance 'c++body)) (and (parse (header self) filter) (parse (body self) filter))) ;;SEE: We should have a TokenFilter class to test here for a "{" token. (defmethod c++class-name ((self c++method)) (c++class-name (header self))) (defmethod name ((self c++method)) (c++method-name (header self))) (defmethod res-type ((self c++method)) (res-type (header self))) (defmethod arguments ((self c++method)) (arguments (header self))) (defmethod called-methods ((self c++method)) (called-methods (body self))) ;;---------------------------------------------------------------------- (defclass c++class () ((methods :accessor methods :initform nil))) (defmethod parse ((self c++class) (filter token-filter)) (let ((m (make-instance 'c++method))) (when (parse m filter) (add-c++method self m) (parse self filter)))) (defmethod add-c++method ((self c++class) method) (push method (methods self))) ;;---------------------------------------------------------------------- (defclass c++program () ((methods :accessor methods :initform nil) (dotrace :accessor dotrace :initform nil)) (:documentation "Represents the C++ program.")) (defmethod parse ((self c++program) file-name-list) (cond ((stringp file-name-list) (parse self (list file-name-list))) ((null file-name-list) t) (t (let ((source (make-instance 'file-filter)) (lasource (make-instance 'look-ahead-char-filter)) (tokens (make-instance 'c++token-filter)) (skip-ccomments (make-instance 'ccomment-filter)) (skip-c++comments (make-instance 'c++comment-filter)) (preprocess (make-instance 'cpreprocessor-filter)) (nonltokens (make-instance 'c++nonltoken-filter)) (analysis (make-instance 'look-ahead-token-filter))) (set-file source (open (car file-name-list))) (push-on-filter lasource source) (set-source tokens lasource) (push-on-filter skip-ccomments tokens) (push-on-filter skip-c++comments skip-ccomments) (push-on-filter preprocess skip-c++comments) (push-on-filter nonltokens preprocess) (push-on-filter analysis nonltokens) (setf (dotrace analysis) (dotrace self)) (loop until (equal 'eof (next-token analysis)) do (let ((method (make-instance 'c++method))) (if (parse method analysis) (progn (if (dotrace self) (format t "~%--------------------------~%")) (add-c++method self method) (format t "Added method ~a::~a~%" (c++class-name method) (name method)) (when (dotrace self) (format t "~%--------------------------~%"))) (progn (when (dotrace self) (format t "~%--------------------------~%")) (format t "Could not parse a method. ") (format t "Bad tokens:~a~%" (bad-token-list (header method))) (when (dotrace self) (format t "~%--------------------------~%"))))))) (parse self (cdr file-name-list))))) (defmethod add-c++method ((self c++program) method) (push method (methods self))) (defun search-unif-meth-named (name umlist) (cond ((null umlist) nil) ((equal name (name (caar umlist))) umlist) (t (search-unif-meth-named name (cdr umlist))))) (defmethod unify-methods-by-name ((self c++program)) (let ((umlist nil) (um nil)) (do ((meth (methods self) (cdr meth))) ((null meth) umlist) (setq um (search-unif-meth-named (name (car meth)) umlist)) (if (null um) (setq umlist (cons (list (car meth)) umlist)) (rplaca um (cons (car meth) (car um))))))) (defmethod build-method-call-graf ((self c++program)) (let ( (unif-meth-list (unify-methods-by-name self)) (g (make-instance 'graf))) (add-nodes g unif-meth-list) (do ((unifmeth unif-meth-list (cdr unifmeth))) ((null unifmeth) g) (do ((meth (car unifmeth) (cdr meth))) ((null meth) nil) (do ((name (called-methods (car meth)) (cdr name))) ((null name) nil) (add-edge g (list (car unifmeth) (car (search-unif-meth-named (car name) unif-meth-list))))))))) (defmethod print-c++method-names ((self c++program)) (do ((meth (methods self) (cdr meth))) ((null meth) nil) (format t "~a::~a~%" (c++class-name (car meth)) (name (car meth))))) ;;---------------------------------------------------------------------- (defun build-c++method-name-list (mlist) (if (null mlist) nil (cons (concatenate 'string (c++class-name (car mlist)) "::" (name (car mlist))) (build-c++method-name-list (cdr mlist))))) (defun build-unif-meth-name-list (umlist) (if (null umlist) nil (cons (build-c++method-name-list (car umlist)) (build-unif-meth-name-list (cdr umlist))))) (defun name-methods (l) (cond ((null l) nil) ((listp l) (cons (name-methods (car l)) (name-methods (cdr l)))) (t (concatenate 'string (c++class-name l) "::" (name l))))) (defun node-named (g n) (car (search-unif-meth-named n (nodes g)))) ;;---------------------------------------------------------------------- #|| (use-package "COM.INFORMATIMAGO.LANGUAGES.CXX.CXX") (setq source (make-instance 'File-Filter)) (set-File source (open "/home/pascal/firms/bauhaus/hermstedt/cme_stutel/generic/CME.cpp")) (set-File source (open "/home/pascal/firms/hbedv/src-HEAD/avmailgate/avmailgate/bcstring.h")) (setq skipccomments (make-instance 'CCommentFilter)) (push-on-filter skipccomments source) (setq skipcxxcomments (make-instance 'CxxCommentFilter)) (push-on-filter skipcxxcomments skipccomments) (setq preprocess (make-instance 'CPreprocessorFilter)) (push-on-filter preprocess skipcxxcomments) (setq lookahead (make-instance 'LookaheadFilter)) (push-on-filter lookahead preprocess) (setq analysis lookahead) (setq p (make-instance 'CxxProgram)) (parse p (mapcar (lambda (file) (sconc "/home/pascal/firms/bauhaus/hermstedt/cme_stutel/" file)) '("generic/AL.cpp" "generic/Buffer.cpp" "generic/CME.cpp" "generic/CME_Result.cpp" "generic/Directory.cpp" "generic/EmptyBuffer.cpp" "generic/EmptyTLVBuffer.cpp" "generic/File.cpp" "generic/FtpReason.cpp" "generic/FullBuffer.cpp" "generic/FullTLVBuffer.cpp" "generic/ISDN_Cause.cpp" "generic/Item.cpp" "generic/List.cpp" "generic/PCI_Status.cpp" "generic/StutelReason.cpp" "generic/TLV_Buffer.cpp" "generic/TOrigin.cpp" "generic/TResult.cpp" "generic/VCO.cpp" "generic/V_PRIMITIVE.cpp" "generic/X213_CauseOrigin.cpp" "generic/X25_CauseDiag.cpp" "generic/debug.cpp" "generic/util.cpp" "acme/AnticipationWindow.cpp" "acme/FileHeader.cpp" "acme/NAF.cpp" "acme/N_SDU.cpp" "acme/PCIMessage.cpp" "acme/PciAL.cpp" "acme/SBV_Command.cpp" "acme/StutelCME.cpp" "acme/StutelVCO.cpp" "acme/T_DU.cpp" "acme/T_Response_neg.cpp" "acme/T_Response_pos.cpp" )))  (print (methods p)) ||# ;;;; cxx.lisp -- -- ;;;;
28,319
Common Lisp
.lisp
630
35.514286
93
0.505783
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bd3b588e50d20c20a6a2bb6ea7071f309990f63890f7d00cfa222bda8521fd83
5,199
[ -1 ]
5,200
read-yacc.lisp
informatimago_lisp/languages/c11/read-yacc.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: read-yacc.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Parses yacc files, to generate the grammar in sexp form. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-02 <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 "COM.INFORMATIMAGO.LANGUAGES.YACC.PARSER") (defun remove-comments (text &key (single-line-comments t)) (flet ((concatenate-chunks (chunks) (mapconcat (function identity) chunks " "))) (declare (inline concatenate-chunks)) (loop :with length := (length text) :with state := :top :with chunks := '() :with start := 0 :with i := 0 :while (< i length) :do (let ((ch (aref text i))) (ecase state (:top (case ch ((#\") (incf i) (setf state :in-string)) ((#\') (incf i) (setf state :in-character)) ((#\/) (incf i) (when (< i length) (let ((ch (aref text i))) (case ch ((#\/) ;;single line comment (when single-line-comments (return-from remove-comments (values (concatenate-chunks (nreverse (cons (subseq text start (1- i)) chunks))) state)))) ((#\*) (incf i) (push (subseq text start (- i 2)) chunks) (setf state :in-multiline-comment start length)))))) (otherwise (incf i)))) (:in-multiline-comment (case ch ((#\*) (incf i) (when (< i length) (let ((ch (aref text i))) (when (char= ch #\/) (incf i) (setf start i) (setf state :top))))) (otherwise (incf i)))) (:in-string (case ch ((#\\) (incf i) (if (< i length) (incf i) (progn (cerror "Continue" "backslash in string literal at the end of the line") (setf state :top)))) ((#\") (incf i) (setf state :top)) (otherwise (incf i)))) (:in-character (case ch ((#\\) (incf i) (if (< i length) (incf i) (progn (cerror "Continue" "backslash in character literal at the end of the line") (setf state :top)))) ((#\') (incf i) (setf state :top)) (otherwise (incf i)))))) :finally (return (case state (:in-string (cerror "Continue" "unterminated string literal at the end of the line") (values (concatenate-chunks (nreverse chunks)) :top)) (:in-character (cerror "Continue" "unterminated character literal at the end of the line") (values (concatenate-chunks (nreverse chunks)) :top)) (:top (values (concatenate-chunks (nreverse (if (< start length) (cons (subseq text start) chunks) chunks))) state)) (:in-multiline-comment (values (concatenate-chunks (nreverse chunks)) state))))))) (defun test/remove-comments () (assert (equal (multiple-value-list (remove-comments "hello \"world/*\" /*comment*/ /*another/*comment*/ boy // the end */ really")) '("hello \"world/*\" boy " :top))) :success) (defun read-delimited-string (stream ch) (let ((buffer (make-array 80 :element-type 'character :initial-element #\space :fill-pointer 0 :adjustable t))) (flet ((save (ch) (vector-push-extend ch buffer (length buffer)))) (declare (inline save)) (loop :with terminator = ch :for ch = (read-char stream nil nil) :while ch :do (cond ((char= terminator ch) (loop-finish)) ((char= #\\ ch) (let ((ch (read-char stream nil nil))) (unless ch (error "unterminated ~:[string~;character~] literal ending with incomplete escape" (char= terminator #\'))) (save ch))) (t (save ch))) :finally (return buffer))))) (defparameter *yacc-readtable* (let ((rt (copy-readtable nil))) (setf (readtable-case rt) :preserve) (remove-all-macro-characters rt) (set-macro-character #\" 'read-delimited-string nil rt) (set-macro-character #\' 'read-delimited-string nil rt) (set-macro-character #\: 'read-colon nil rt) rt)) (defun read-header (stream) (let ((*readtable* *yacc-readtable*)) (loop :with tokens := '() :with start := nil :for line = (let ((line (read-line stream nil nil))) (when line (string-trim *whitespaces* (remove-comments line)))) :while (and line (string/= "%%" line)) :when (plusp (length line)) :do (with-input-from-string (in line) (let ((directive (read in))) (case directive ((|%token|) (setf tokens (nconc (loop :for token := (read in nil nil) :while token :do (check-type token symbol) :collect token) tokens))) ((|%start|) (setf start (read in nil nil)) (check-type start symbol)) (otherwise (format *error-output* "Unexpected yacc directive: ~S~%" directive))))) :finally (return (list :start start :tokens tokens))))) (define-parser *Yacc-parser* (:start-symbol rules) (:terminals (lchar \: \| identifier \;)) (rules (rule) (rule rules #'cons)) (rule (identifier \: alternatives \; (lambda (i c as s) (declare (ignore c s)) (cons i (mapcar (lambda (a) (if (and (listp a) (= 1 (length a))) (first a) a)) as))))) (alternatives (rhs) (rhs \| alternatives (lambda (r p a) (declare (ignore p)) (if r (cons r a) a)))) (rhs () (term rhs #'cons)) (term lchar identifier)) (defun make-lexer (scanner) (lambda () (let ((token (scan-next-token scanner))) (if (eq (token-kind token) 'com.informatimago.common-lisp.parser.scanner::<END\ OF\ SOURCE>) (values nil nil) (values (token-kind token) token))))) (defun read-rules (stream) (let* ((lines (remove "" (mapcar (lambda (line) (string-trim *whitespaces* line)) (stream-to-string-list stream)) :test (function string=))) (end (member "%%" lines :test (function string=))) (scanner (make-instance 'c11-scanner :source (remove-comments (mapconcat (function identity) (ldiff lines end) " ")))) (lexer (make-lexer scanner))) #-(and) (parse-with-lexer lexer *yacc-parser*) (maptree (lambda (token) (ecase (token-kind token) ((identifier) (intern (token-text token))) ((lchar) (intern (string (code-char (character-value (token-text token)))))))) (print (parse-with-lexer lexer *yacc-parser*))))) (defun read-footer (stream) (declare (ignore stream)) (values)) (defun read-yacc (stream name) (let* ((header (read-header stream)) (rules (read-rules stream))) (pprint `(define-parser ,name (:start-symbol ,(getf header :start (first (first rules)))) (:terminals ,(getf header :tokens)) ,@rules)))) #-(and) (progn (in-package "COM.INFORMATIMAGO.LANGUAGES.YACC.PARSER") (with-open-file (stream #P"~/src/public/lisp/languages/c11/c11-parser.yacc") (read-yacc stream "c11")) ) ;;;; THE END ;;;;
10,588
Common Lisp
.lisp
239
29.07113
133
0.450305
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d9ac3bf4c7f283f042007e8f05d91f0de6a9c0ed35a3695e53794762112c6523
5,200
[ -1 ]
5,201
c11-yacc.lisp
informatimago_lisp/languages/c11/c11-yacc.lisp
(DEFINE-PARSER *C11-PARSER* (:START-SYMBOL |translation_unit|) (:TERMINALS ( |identifier| |typedef_name| |func_name| |string_literal| |i_constant| |f_constant| |enum_name| |alignas| |alignof| |atomic| |generic| |noreturn| |static_assert| |thread_local| |case| |default| |if| |else| |switch| |while| |do| |for| |goto| |continue| |break| |return| |struct| |union| |enum| |...| |complex| |imaginary| |bool| |char| |short| |int| |long| |signed| |unsigned| |float| |double| |void| |const| |restrict| |volatile| |typedef| |extern| |static| |auto| |register| |inline| |sizeof| ^= \|= -= <<= >>= &= && |\|\|| *= /= %= += -> ++ -- << >> <= >= == !=)) ;; renaming terminals: (IDENTIFIER |identifier|) (TYPEDEF_NAME |typedef_name|) (FUNC_NAME |func_name|) (STRING_LITERAL |string_literal|) (I_CONSTANT |i_constant|) (F_CONSTANT |f_constant|) (|constant| I_CONSTANT F_CONSTANT ) ;ENUMERATION_CONSTANT (|string| STRING_LITERAL FUNC_NAME) (ALIGNAS |alignas|) (ALIGNOF |alignof|) (ATOMIC |atomic|) (GENERIC |generic|) (NORETURN |noreturn|) (STATIC_ASSERT |static_assert|) (THREAD_LOCAL |thread_local|) (CASE |case|) (DEFAULT |default|) (IF |if|) (ELSE |else|) (SWITCH |switch|) (WHILE |while|) (DO |do|) (FOR |for|) (GOTO |goto|) (CONTINUE |continue|) (BREAK |break|) (RETURN |return|) (STRUCT |struct|) (UNION |union|) (ENUM |enum|) (ELLIPSIS |...|) (COMPLEX |complex|) (IMAGINARY |imaginary|) (BOOL |bool|) (CHAR |char|) (SHORT |short|) (INT |int|) (LONG |long|) (SIGNED |signed|) (UNSIGNED |unsigned|) (FLOAT |float|) (DOUBLE |double|) (VOID |void|) (CONST |const|) (RESTRICT |restrict|) (VOLATILE |volatile|) (TYPEDEF |typedef|) (EXTERN |extern|) (STATIC |static|) (AUTO |auto|) (REGISTER |register|) (INLINE |inline|) (SIZEOF |sizeof|) (XOR_ASSIGN |^=|) (OR_ASSIGN \|=) (SUB_ASSIGN |-=|) (LEFT_ASSIGN |<<=|) (RIGHT_ASSIGN |>>=|) (AND_ASSIGN |&=|) (AND_OP |&&|) (OR_OP \|\|) (MUL_ASSIGN |*=|) (DIV_ASSIGN |/=|) (MOD_ASSIGN |%=|) (ADD_ASSIGN |+=|) (PTR_OP |->|) (INC_OP |++|) (DEC_OP |--|) (LEFT_OP |<<|) (RIGHT_OP |>>|) (LE_OP |<=|) (GE_OP |>=|) (EQ_OP |==|) (NE_OP |!=|) ;; productions: (|primary_expression| IDENTIFIER |constant| |string| (\( |expression| \)) |generic_selection|) (|generic_selection| (GENERIC \( |assignment_expression| \, |generic_assoc_list| \))) (|generic_assoc_list| |generic_association| (|generic_assoc_list| \, |generic_association|)) (|generic_association| (|type_name| \: |assignment_expression|) (DEFAULT \: |assignment_expression|)) (|postfix_expression| |primary_expression| (|postfix_expression| [ |expression| ]) (|postfix_expression| \( \)) (|postfix_expression| \( |argument_expression_list| \)) (|postfix_expression| |.| IDENTIFIER) (|postfix_expression| PTR_OP IDENTIFIER) (|postfix_expression| INC_OP) (|postfix_expression| DEC_OP) (\( |type_name| \) { |initializer_list| }) (\( |type_name| \) { |initializer_list| \, })) (|argument_expression_list| |assignment_expression| (|argument_expression_list| \, |assignment_expression|)) (|unary_expression| |postfix_expression| (INC_OP |unary_expression|) (DEC_OP |unary_expression|) (|unary_operator| |cast_expression|) (SIZEOF |unary_expression|) (SIZEOF \( |type_name| \)) (ALIGNOF \( |type_name| \))) (|unary_operator| & * + - ~ !) (|cast_expression| |unary_expression| (\( |type_name| \) |cast_expression|)) (|multiplicative_expression| |cast_expression| (|multiplicative_expression| * |cast_expression|) (|multiplicative_expression| / |cast_expression|) (|multiplicative_expression| % |cast_expression|)) (|additive_expression| |multiplicative_expression| (|additive_expression| + |multiplicative_expression|) (|additive_expression| - |multiplicative_expression|)) (|shift_expression| |additive_expression| (|shift_expression| LEFT_OP |additive_expression|) (|shift_expression| RIGHT_OP |additive_expression|)) (|relational_expression| |shift_expression| (|relational_expression| < |shift_expression|) (|relational_expression| > |shift_expression|) (|relational_expression| LE_OP |shift_expression|) (|relational_expression| GE_OP |shift_expression|)) (|equality_expression| |relational_expression| (|equality_expression| EQ_OP |relational_expression|) (|equality_expression| NE_OP |relational_expression|)) (|and_expression| |equality_expression| (|and_expression| & |equality_expression|)) (|exclusive_or_expression| |and_expression| (|exclusive_or_expression| ^ |and_expression|)) (|inclusive_or_expression| |exclusive_or_expression| (|inclusive_or_expression| \| |exclusive_or_expression|)) (|logical_and_expression| |inclusive_or_expression| (|logical_and_expression| AND_OP |inclusive_or_expression|)) (|logical_or_expression| |logical_and_expression| (|logical_or_expression| OR_OP |logical_and_expression|)) (|conditional_expression| |logical_or_expression| (|logical_or_expression| ? |expression| \: |conditional_expression|)) (|assignment_expression| |conditional_expression| (|unary_expression| |assignment_operator| |assignment_expression|)) (|assignment_operator| = MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN ADD_ASSIGN SUB_ASSIGN LEFT_ASSIGN RIGHT_ASSIGN AND_ASSIGN XOR_ASSIGN OR_ASSIGN) (|expression| |assignment_expression| (|expression| \, |assignment_expression|)) (|constant_expression| |conditional_expression|) (|declaration| (|declaration_specifiers| \;) (|declaration_specifiers| |init_declarator_list| \;) |static_assert_declaration|) (|declaration_specifiers| (|storage_class_specifier| |declaration_specifiers|) |storage_class_specifier| (|type_specifier| |declaration_specifiers|) |type_specifier| (|type_qualifier| |declaration_specifiers|) |type_qualifier| (|function_specifier| |declaration_specifiers|) |function_specifier| (|alignment_specifier| |declaration_specifiers|) |alignment_specifier|) (|init_declarator_list| |init_declarator| (|init_declarator_list| \, |init_declarator|)) (|init_declarator| (|declarator| = |initializer|) |declarator|) (|storage_class_specifier| TYPEDEF EXTERN STATIC THREAD_LOCAL AUTO REGISTER) (|type_specifier| VOID CHAR SHORT INT LONG FLOAT DOUBLE SIGNED UNSIGNED BOOL COMPLEX IMAGINARY |atomic_type_specifier| |struct_or_union_specifier| |enum_specifier| TYPEDEF_NAME) (|struct_or_union_specifier| (|struct_or_union| { |struct_declaration_list| }) (|struct_or_union| IDENTIFIER { |struct_declaration_list| }) (|struct_or_union| IDENTIFIER)) (|struct_or_union| STRUCT UNION) (|struct_declaration_list| |struct_declaration| (|struct_declaration_list| |struct_declaration|)) (|struct_declaration| (|specifier_qualifier_list| \;) (|specifier_qualifier_list| |struct_declarator_list| \;) |static_assert_declaration|) (|specifier_qualifier_list| (|type_specifier| |specifier_qualifier_list|) |type_specifier| (|type_qualifier| |specifier_qualifier_list|) |type_qualifier|) (|struct_declarator_list| |struct_declarator| (|struct_declarator_list| \, |struct_declarator|)) (|struct_declarator| (\: |constant_expression|) (|declarator| \: |constant_expression|) |declarator|) (|enum_specifier| (ENUM { |enumerator_list| }) (ENUM { |enumerator_list| \, }) (ENUM IDENTIFIER { |enumerator_list| }) (ENUM IDENTIFIER { |enumerator_list| \, }) (ENUM IDENTIFIER)) (|enumerator_list| |enumerator| (|enumerator_list| \, |enumerator|)) (|enumeration_constant| IDENTIFIER) (|enumerator| (|enumeration_constant| = |constant_expression|) |enumeration_constant|) (|declarator| (|pointer| |direct_declarator|) |direct_declarator|) (|direct_declarator| IDENTIFIER (\( |declarator| \)) (|direct_declarator| [ ]) (|direct_declarator| [ * ]) (|direct_declarator| [ STATIC |type_qualifier_list| |assignment_expression| ]) (|direct_declarator| [ STATIC |assignment_expression| ]) (|direct_declarator| [ |type_qualifier_list| * ]) (|direct_declarator| [ |type_qualifier_list| STATIC |assignment_expression| ]) (|direct_declarator| [ |type_qualifier_list| |assignment_expression| ]) (|direct_declarator| [ |type_qualifier_list| ]) (|direct_declarator| [ |assignment_expression| ]) (|direct_declarator| \( |parameter_type_list| \)) (|direct_declarator| \( \)) (|direct_declarator| \( |identifier_list| \))) (|pointer| (* |type_qualifier_list| |pointer|) (* |type_qualifier_list|) (* |pointer|) *) (|type_qualifier_list| |type_qualifier| (|type_qualifier_list| |type_qualifier|)) (|parameter_type_list| (|parameter_list| \, ELLIPSIS) |parameter_list|) (|parameter_list| |parameter_declaration| (|parameter_list| \, |parameter_declaration|)) (|parameter_declaration| (|declaration_specifiers| |declarator|) (|declaration_specifiers| |abstract_declarator|) |declaration_specifiers|) (|identifier_list| IDENTIFIER (|identifier_list| \, IDENTIFIER)) (|type_name| (|specifier_qualifier_list| |abstract_declarator|) |specifier_qualifier_list|) (|abstract_declarator| (|pointer| |direct_abstract_declarator|) |pointer| |direct_abstract_declarator|) (|direct_abstract_declarator| (\( |abstract_declarator| \)) ([ ]) ([ * ]) ([ STATIC |type_qualifier_list| |assignment_expression| ]) ([ STATIC |assignment_expression| ]) ([ |type_qualifier_list| STATIC |assignment_expression| ]) ([ |type_qualifier_list| |assignment_expression| ]) ([ |type_qualifier_list| ]) ([ |assignment_expression| ]) (|direct_abstract_declarator| [ ]) (|direct_abstract_declarator| [ * ]) (|direct_abstract_declarator| [ STATIC |type_qualifier_list| |assignment_expression| ]) (|direct_abstract_declarator| [ STATIC |assignment_expression| ]) (|direct_abstract_declarator| [ |type_qualifier_list| |assignment_expression| ]) (|direct_abstract_declarator| [ |type_qualifier_list| STATIC |assignment_expression| ]) (|direct_abstract_declarator| [ |type_qualifier_list| ]) (|direct_abstract_declarator| [ |assignment_expression| ]) (\( \)) (\( |parameter_type_list| \)) (|direct_abstract_declarator| \( \)) (|direct_abstract_declarator| \( |parameter_type_list| \))) (|initializer| ({ |initializer_list| }) ({ |initializer_list| \, }) |assignment_expression|) (|initializer_list| (|designation| |initializer|) |initializer| (|initializer_list| \, |designation| |initializer|) (|initializer_list| \, |initializer|)) (|designation| (|designator_list| =)) (|designator_list| |designator| (|designator_list| |designator|)) (|designator| ([ |constant_expression| ]) (|.| IDENTIFIER)) (|static_assert_declaration| (STATIC_ASSERT \( |constant_expression| \, STRING_LITERAL \) \;)) (|statement| |labeled_statement| |compound_statement| |expression_statement| |selection_statement| |iteration_statement| |jump_statement|) (|labeled_statement| (IDENTIFIER \: |statement|) (CASE |constant_expression| \: |statement|) (DEFAULT \: |statement|)) (|compound_statement| ({ }) ({ |block_item_list| })) (|block_item_list| |block_item| (|block_item_list| |block_item|)) (|block_item| |declaration| |statement|) (|expression_statement| \; (|expression| \;)) (|selection_statement| (IF \( |expression| \) |statement| ELSE |statement|) (IF \( |expression| \) |statement|) (SWITCH \( |expression| \) |statement|)) (|iteration_statement| (WHILE \( |expression| \) |statement|) (DO |statement| WHILE \( |expression| \) \;) (FOR \( |expression_statement| |expression_statement| \) |statement|) (FOR \( |expression_statement| |expression_statement| |expression| \) |statement|) (FOR \( |declaration| |expression_statement| \) |statement|) (FOR \( |declaration| |expression_statement| |expression| \) |statement|)) (|jump_statement| (GOTO IDENTIFIER \;) (CONTINUE \;) (BREAK \;) (RETURN \;) (RETURN |expression| \;)) (|translation_unit| |external_declaration| (|translation_unit| |external_declaration|)) (|external_declaration| |function_definition| |declaration|) (|function_definition| (|declaration_specifiers| |declarator| |declaration_list| |compound_statement|) (|declaration_specifiers| |declarator| |compound_statement|)) (|declaration_list| |declaration| (|declaration_list| |declaration|)) ) #-(and) (let ((*PRINT-PRETTY* nil) (*PRINT-LEVEL* nil) (*PRINT-LENGTH* nil) (*PRINT-CIRCLE* nil) (*PRINT-CASE* :upcase) (*PRINT-READABLY*) (*PRINT-GENSYM* T) (*PRINT-BASE* 10 ) (*PRINT-RADIX* nil) (*PRINT-ARRAY* T) (*PRINT-LINES* nil) (*PRINT-ESCAPE* T) (*PRINT-RIGHT-MARGIN* 110)) (pprint (mapcar (lambda (prod) `(--> ,(first prod) ,(case (length (rest prod)) ((0) '(seq)) ((1) (if (listp (second prod)) `(seq ,@(second prod)) (second prod))) (otherwise `(alt ,@(mapcar (lambda (rhs) (if (listp rhs) `(seq ,@rhs) rhs)) (rest prod))))))) '())))
14,123
Common Lisp
.lisp
451
26.405765
90
0.632602
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8a7b1d2d40b38b21e6211b5660a0217e3fa5221ad1ff36b7c69d714a55bd401b
5,201
[ -1 ]
5,202
graph.lisp
informatimago_lisp/languages/c11/graph.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.LANGUAGES.C11.GRAPH" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.GRAPH" "COM.INFORMATIMAGO.COMMON-LISP.GRAPHVIZ.GRAPH-DOT")) (in-package "COM.INFORMATIMAGO.LANGUAGES.C11.GRAPH") (defparameter *graph* (let ((graph (make-instance 'graph-class :edge-class 'directed-edge-class)) (elements (make-hash-table))) (destructuring-bind ((terminal (&rest terminals)) &rest non-terminals) (cdddr (find 'define-parser (sexp-list-file-contents "parser.lisp") :key (function first))) (declare (ignore terminal)) (dolist (item (remove-duplicates (append terminals (loop :for (non-terminal . productions) :in non-terminals :collect non-terminal :append (loop :for production :in productions :if (atom production) :collect production :else :append (loop :for item :in production :unless (and (listp item) (eql 'function (first item))) :collect item)))))) (let ((node (make-instance 'element-class))) (set-property node :dot-label item) (add-node graph node) (setf (gethash item elements) node))) (loop :for (non-terminal . productions) :in non-terminals :for from := (gethash non-terminal elements) :do (let ((to-nodes '())) (loop :for production :in productions :do (if (listp production) (appendf to-nodes (let ((last (first (last production)))) (if (and (listp last) (eql 'function (first last))) (butlast production) production))) (push production to-nodes))) (dolist (to (mapcar (lambda (item) (gethash item elements)) (remove-duplicates to-nodes))) (add-edge-between-nodes graph from to))))) graph)) (setf (text-file-contents "c11.dot") (generate-dot *graph*)) ;; ;; dot -Kfdp -Tps c11.dot> c11.ps && open c11.ps ;; (uiop:run-program "bash -c 'dot -Kfdp -Tps c11.dot> c11.ps && open c11.ps'") ;; ;; (cardinal (nodes *graph*)) ;; (cardinal (edges *graph*)) ;; 419 ;; 248
3,244
Common Lisp
.lisp
64
30.125
99
0.452711
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d5b85b57822e563755f4c98d095f7cb65520040cdb58601761c1e72b293d0932
5,202
[ -1 ]
5,203
scratch.lisp
informatimago_lisp/languages/c11/scratch.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (ql:quickload :com.informatimago.languages.c11) (in-package "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER") (defun emacs-c-tokens () (reduce (function append) (reverse (com.informatimago.languages.cpp::context-output-lines (let ((*identifier-package* (load-time-value (find-package "COM.INFORMATIMAGO.LANGUAGES.C11.C")))) (cpp-e "/Users/pjb/src/public/lisp/languages/cpp/tests/emacs.c" :trace-includes t :defines '( ;; "__GNUC__" "4" "__STDC__" "1" "__x86_64__" "1") :includes '("/Users/pjb/src/macosx/emacs-24.5/src/") :include-bracket-directories '("/Users/pjb/src/macosx/emacs-24.5/src/" "/Users/pjb/src/macosx/emacs-24.5/lib/" "/Users/pjb/src/macosx/gcc-4.9.2/gcc/ginclude/" "/usr/include/") :write-processed-lines nil)))) :initial-value '())) ;; 7 seconds. #-(and) (defparameter *tc* (emacs-c-tokens)) (defun gen-p () (with-open-file (out "p.lisp" :direction :output :if-exists :supersede :if-does-not-exist :create) (pprint '(in-package "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER") out) (destructuring-bind (grammar &rest rest) (cdr (macroexpand-1 *c*)) (let ((*print-circle* t) (*print-right-margin* 200)) (pprint grammar out)) (let ((*print-circle* nil) (*print-right-margin* 200)) (dolist (form rest) (pprint form out))))) (load "p.lisp")) (defvar *tokens* nil) (defvar *scanner* nil) (defvar *context* nil) (defvar *cpp-context* nil) (defun test/parse-stream (&key tokens source-file) (declare (stepper disable)) (let ((tokens (or tokens (reduce (function append) (reverse (com.informatimago.languages.cpp::context-output-lines (let ((*identifier-package* (load-time-value (find-package "COM.INFORMATIMAGO.LANGUAGES.C11.C")))) (setf *cpp-context* (cpp-e (or source-file "/Users/pjb/src/public/lisp/languages/cpp/tests/emacs.c") :trace-includes t :defines '( ;; "__GNUC__" "4" "__STDC__" "1" "__x86_64__" "1") :includes '("/Users/pjb/src/macosx/emacs-24.5/src/") :include-bracket-directories '("/Users/pjb/src/macosx/emacs-24.5/src/" "/Users/pjb/src/macosx/emacs-24.5/lib/" "/Users/pjb/src/macosx/gcc-4.9.2/gcc/ginclude/" "/usr/include/") :write-processed-lines nil))))) :initial-value '())))) (setf *tokens* tokens) (setf *scanner* (make-instance 'pre-scanned-scanner :tokens tokens)) (setf *context* (make-instance 'context)) (loop :until (scanner-end-of-source-p *scanner*) :collect (handler-bind ((parser-end-of-source-not-reached ;; #'continue #'invoke-debugger)) (parse-c11 *scanner*))))) (defun print-tokens (tokens &key (start 0) (end nil)) (dolist (token (subseq tokens start end) (values)) (princ (token-text token)) (if (find (token-text token) '("{" "}" ";") :test (function string=)) (terpri) (princ " ")))) (defun print-typedefs (&optional (context *context*)) (com.informatimago.common-lisp.cesarum.utility:print-hashtable (context-typedefs context))) (defun print-enum-constants (&optional (context *context*)) (com.informatimago.common-lisp.cesarum.utility:print-hashtable (context-enumeration-constants context))) (defun print-func-names (&optional (context *context*)) (com.informatimago.common-lisp.cesarum.utility:print-hashtable (context-functions context))) #-(and) (progn (ql:quickload :com.informatimago.rdp) (ql:quickload :com.informatimago.languages.c11) (gen-p) (pprint (remove-unary (test/parse-stream :source-file "tests/expressions.c"))) (untrace compute-token-kind) (untrace typedef-name-p function-name-p enumeration-constant-name-p enter-typedef enter-function enter-enumeration-constant push-declaration-specifiers pop-declaration-specifiers register-declarator scan-next-token) (progn (print-typedefs) (terpri) (print-enum-constants) (terpri) (print-func-names) (terpri)) (print-tokens *tokens* :start (- (length (pre-scanned-tokens *scanner*)) 40) :end (length (pre-scanned-tokens *scanner*))) void unblock_tty_out_signal ( void ) ; extern void init_sys_modes ( struct tty_display_info * ) ; extern void reset_sys_modes ( struct tty_display_info * ) ; extern void init_all_sys_modes ( void ) ; extern void reset_all_sys_modes ( void ) ; extern void ) #-(and) (progn (defparameter *c* (quote )) #.*c* (pprint (macroexpand-1 *c*)) (with-open-file (out "p.lisp" :direction :output :if-exists :supersede :if-does-not-exist :create) (dolist (form (cdr (macroexpand-1 *c*))) (pprint form out))) ) #-(and) (progn (map nil 'print (subseq *tc* 0 30)) (let ((*context* (make-instance 'context))) (values (parse-with-lexer (make-list-lexer *tc*) *c11-parser*) *context*)) ) #-(and) ( ;; yacc (defun make-list-lexer (tokens) (lambda () (if tokens (let ((token (pop tokens))) (values (token-kind token) token)) (values nil nil)))) (let ((*context* (make-instance 'context))) (values (parse-with-lexer (make-list-lexer *tc*) *c11-parser*) *context*)) ) #-(and) ( ;; rdp: (defun test/parse-stream (src) (let ((*scanner* (make-instance '-scanner :source src))) (loop :until (typep (scanner-current-token *scanner*) 'tok-eof) :collect (lse-parser *scanner*)))) ) #-(and) ( (mapcar 'compute-token-kind (subseq *tc* 0 100)) (|typedef| |unsigned| |int| identifier \; |typedef| |signed| |char| identifier \; |typedef| |unsigned| |char| identifier \; |typedef| |short| identifier \; |typedef| |unsigned| |short| identifier \; |typedef| |int| identifier \; |typedef| |unsigned| |int| identifier \; |typedef| |long| |long| identifier \; |typedef| |unsigned| |long| |long| identifier \; |typedef| |long| identifier \; |typedef| |unsigned| |int| identifier \; |typedef| |int| identifier \; |typedef| |union| { |char| identifier [ dec ] \; |long| |long| identifier \; } identifier \; |typedef| identifier identifier \; |typedef| |int| identifier \; |typedef| |unsigned| |long| identifier \; |typedef| |__builtin_va_list| identifier \; |typedef| identifier identifier \; |typedef| identifier identifier \; |typedef| identifier) ("typedef" "unsigned" "int" "bool_bf" ";" "typedef" "signed" "char" "__int8_t" ";" "typedef" "unsigned" "char" "__uint8_t" ";" "typedef" "short" "__int16_t" ";" "typedef" "unsigned" "short" "__uint16_t" ";" "typedef" "int" "__int32_t" ";" "typedef" "unsigned" "int" "__uint32_t" ";" "typedef" "long" "long" "__int64_t" ";" "typedef" "unsigned" "long" "long" "__uint64_t" ";" "typedef" "long" "__darwin_intptr_t" ";" "typedef" "unsigned" "int" "__darwin_natural_t" ";" "typedef" "int" "__darwin_ct_rune_t" ";" "typedef" "union" "{" "char" "__mbstate8" "[" "128" "]" ";" "long" "long" "_mbstateL" ";" "}" "__mbstate_t" ";" "typedef" "__mbstate_t" "__darwin_mbstate_t" ";" "typedef" "int" "__darwin_ptrdiff_t" ";" "typedef" "unsigned" "long" "__darwin_size_t" ";" "typedef" "__builtin_va_list" "__darwin_va_list" ";" "typedef" "__darwin_ct_rune_t" "__darwin_wchar_t" ";" "typedef" "__darwin_wchar_t" "__darwin_rune_t" ";" "typedef" "__darwin_ct_rune_t") (let ((*readtable* vacietis:c-readtable) (vacietis:*compiler-state* (vacietis:make-compiler-state))) (with-open-file (src #P"~/src/lisp/c/duff-device.c") (read src))) (defparameter *s* (make-instance 'c11-scanner :source (com.informatimago.common-lisp.cesarum.file:text-file-contents #P"~/src/public/lisp/languages/cpp/tests/out.c"))) (defparameter *t* (let ((scanner (make-instance 'c11-scanner :source (com.informatimago.common-lisp.cesarum.file:text-file-contents #P"~/src/public/lisp/languages/cpp/tests/out.c")))) (loop for token = (scan-next-token scanner) until (eq (token-kind token) 'com.informatimago.common-lisp.parser.scanner::<END\ OF\ SOURCE>) collect (print token)))) (defparameter *tc* (mapcar (lambda (token) (setf (token-kind token) (compute-token-kind token)) token) (reduce (function append) (reverse (com.informatimago.languages.cpp::context-output-lines (let ((*identifier-package* (load-time-value (find-package "COM.INFORMATIMAGO.LANGUAGES.C11.C")))) (cpp-e "/Users/pjb/src/public/lisp/languages/cpp/tests/emacs.c" :trace-includes t :defines '("__GNUC__" "4" "__STDC__" "1" "__x86_64__" "1") :includes '("/Users/pjb/src/macosx/emacs-24.5/src/") :include-bracket-directories '("/Users/pjb/src/macosx/emacs-24.5/src/" "/Users/pjb/src/macosx/emacs-24.5/lib/" "/Users/pjb/src/macosx/gcc-4.9.2/gcc/ginclude/" "/usr/include/") :write-processed-lines nil)))) :initial-value '()))) (dolist (token *tc*) (setf (token-kind token) (compute-token-kind token))) (defparameter *yacc* (let ((scanner (make-instance 'c11-scanner :source (com.informatimago.common-lisp.cesarum.file:text-file-contents #P"scanner.yacc")))) (loop for token = (scan-next-token scanner) until (eq (token-kind token) 'com.informatimago.common-lisp.parser.scanner::<END\ OF\ SOURCE>) collect (print token)))) ) #-(and) (let (ss) (do-symbols (s "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER" ss) (when (prefixp "C11/PARSE-" (string s)) (push s ss)))) #-(and) (untrace c11/parse-alignment-specifier-1-1 c11/parse-static-assert-declaration-1 c11/parse-exclusive-or-expression-1-1-1 c11/parse-compound-statement c11/parse-external-declaration-1 c11/parse-right-assign c11/parse-external-declaration-1-2-1 c11/parse-declaration-specifiers-1 c11/parse-enum-specifier c11/parse-struct-declaration-1-1 c11/parse-simple-type-specifier-1-1-1 c11/parse-sizeof-argument-1-1-2 c11/parse-sizeof-argument-1-1-1 c11/parse-postfix-expression-item-1 c11/parse-external-declaration-1-2 c11/parse-parameter-declaration-1-1 c11/parse-iteration-statement-1-1 c11/parse-block-item-1 c11/parse-sizeof-argument-1-1 c11/parse-cast-expression-1-3-1-2-1-2 c11/parse-struct-declarator c11/parse-simple-type-specifier-1-1-8 c11/parse-initializer-1-1-1 c11/parse-simple-type-specifier-1-1-3 c11/parse-struct-or-union-specifier-1-1-1 c11/parse-mul-assign-1 c11/parse-iteration-statement-1-2 c11/parse-eq-op c11/parse-simple-unary-expression-1-1 c11/parse-storage-class-specifier-1-2 c11/parse-parameter-declaration-1-2 c11/parse-abstract-declarator-1 c11/parse-inc-op-1 c11/parse-le-op-1 c11/parse-and-expression-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-2-1-1-1-1-1 c11/parse-initializer-list-1-1 c11/parse-cast-expression-1-1 c11/parse-identifier-list-1-1-1 c11/parse-bracket-direct-abstract-declarator c11/parse-initializer-1-1 c11/parse-simple-type-specifier c11/parse-enum-specifier-1-2-1 c11/parse-or-assign-1 c11/parse-expression-1 c11/parse-simple-unary-expression c11/parse-inclusive-or-expression-1-1-1 c11/parse-declaration c11/parse-jump-statement-1-3 c11/parse-direct-declarator--or--direct-abstract-declarator c11/parse-add-assign c11/parse-specifier-qualifier-1 c11/parse-type-name-1-1 c11/parse-selection-statement-1 c11/parse-equality-expression-1-1 c11/parse-simple-direct-declarator c11/parse-pointer c11/parse-simple-type-specifier-1-1-2 c11/parse-declaration-specifier-1 c11/parse-exclusive-or-expression-1 c11/parse-argument-expression-list-1-1-1 c11/parse-struct-declaration-1-1-1 c11/parse-struct-declaration-1 c11/parse-simple-labeled-statement c11/parse-relational-expression-1-1-1 c11/parse-initializer-list-1 c11/parse-mod-assign-1 c11/parse-struct-declaration-list-1-1 c11/parse-storage-class-specifier-1-1 c11/parse-alignment-specifier-1-1-1 c11/parse-cast-expression-1-3-1 c11/parse-ge-op c11/parse-generic-assoc-list-1 c11/parse-pointer-1-2-1 c11/parse-direct-declarator-in-brackets-1-3 c11/parse-multiplicative-expression-1-1-1-1 c11/parse-direct-declarator-item c11/parse-simple-unary-expression-1-2 c11/parse-unary-expression-1 c11/parse-right-op c11/parse-enum-specifier-1-1 c11/parse-pointer-1-2-1-1 c11/parse-sizeof-argument c11/parse-postfix-expression-head-1 c11/parse-direct-declarator-item-1-1 c11/parse-direct-declarator-item-1-1-1 c11/parse-enumerator c11/parse-direct-declarator-in-brackets-1-2-1 c11/parse-generic-association c11/parse-declarator-1-2 c11/parse-designator-1 c11/parse-direct-abstract-declarator c11/parse-selection-statement-1-1 c11/parse-exclusive-or-expression-1-1 c11/parse-cast-expression-1-3-1-2-1-1 c11/parse-type-qualifier-list-1-1 c11/parse-declaration-1-1 c11/parse-postfix-expression-item-1-2-1 c11/parse-multiplicative-expression-1 c11/parse-parameter-list c11/parse-simple-direct-abstract-declarator c11/parse-expression-statement-or-label-1-1 c11/parse-string c11/parse-simple-type-specifier-1-1-7 c11/parse-expression-1-1-1 c11/parse-external-declaration-1-2-2 c11/parse-div-assign c11/parse-parameter-type-list-1-1 c11/parse-external-declaration-1-2-2-2-1-2-1 c11/parse-direct-abstract-declarator-item-1 c11/parse-storage-class-specifier-1-3 c11/parse-simple-type-specifier-1-1-6 c11/parse-block-item-list c11/parse-type-qualifier c11/parse-simple-unary-expression-1 c11/parse-external-declaration-1-2-2-2-1-1-1 c11/parse-ne-op c11/parse-designator-list c11/parse-function-specifier-1-1 c11/parse-logical-or-expression c11/parse-simple-type-specifier-1-1-5 c11/parse-expression-statement-or-label-1-1-1-2 c11/parse-initializer-list-1-1-2 c11/parse-primary-expression-1-1 c11/parse-equality-expression c11/parse-init-declarator-list c11/parse-external-declaration-1-2-2-2-1-1-2-1 c11/parse-sizeof-argument-1-1-1-1 c11/parse-struct-declarator-1-2-1 c11/parse-direct-abstract-declarator-in-parentheses-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator c11/parse-primary-expression-1 c11/parse-simple-type-specifier-1 c11/parse-enumerator-list-1 c11/parse-alignment-specifier c11/parse-postfix-expression-head c11/parse-equality-expression-1-1-1-1 c11/parse-function-specifier-1 c11/parse-selection-statement c11/parse-identifier-list-1-1 c11/parse-init-declarator-1-1 c11/parse-specifier-qualifier-list-1 c11/parse-constant c11/parse-generic-selection c11/parse-enum-specifier-1-2 c11/parse-struct-declarator-list-1-1 c11/parse-constant-expression c11/parse-type-qualifier-list c11/parse-cast-expression-1-3-1-2 c11/parse-relational-expression-1-1-1-1 c11/parse-abstract-declarator-1-1-1 c11/parse-expression-statement c11/parse-storage-class-specifier c11/parse-argument-expression-list-1-1 c11/parse-initializer c11/parse-direct-declarator-in-brackets-1-3-1-1-1 c11/parse-inclusive-or-expression-1-1 c11/parse-direct-abstract-declarator-in-parentheses-1-1 c11/parse-bracket-direct-abstract-declarator-1-1-1-2 c11/parse-exclusive-or-expression c11/parse-mul-assign c11/parse-direct-abstract-declarator-1 c11/parse-assignment-operator-1 c11/parse-assignment-expression-1 c11/parse-simple-direct-declarator-1-2 c11/parse-simple-primary-expression c11/parse-specifier-qualifier-1-1 c11/parse-cast-expression-1 c11/parse-enumerator-list c11/parse-init-declarator c11/parse-simple-type-qualifier-1-1 c11/parse-logical-or-expression-1-1 c11/parse-struct-or-union c11/parse-multiplicative-expression-1-1-1 c11/parse-storage-class-specifier-1 c11/parse-sizeof-argument-1-1-1-1-1-2 c11/parse-declaration-specifier c11/parse-simple-type-qualifier-1-1-3 c11/parse-specifier-qualifier-list-1-1 c11/parse-postfix-expression-head-1-1-1-2 c11/parse-direct-declarator-in-parentheses c11/parse-specifier-qualifier c11/parse-direct-abstract-declarator-in-parentheses-1-2 c11/parse-abstract-declarator-1-2 c11/parse-and-expression c11/parse-additive-expression-1-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-2-1-1-2 c11/parse-direct-declarator-in-brackets-1-1 c11/parse-selection-statement-1-2 c11/parse-enum-specifier-1-2-1-1 c11/parse-direct-abstract-declarator-item-1-1 c11/parse-cast-expression-1-3-1-2-1-1-1 c11/parse-conditional-expression-1-1-1 c11/parse-struct-or-union-specifier-1 c11/parse-generic-selection-1 c11/parse-external-declaration-1-2-2-2 c11/parse-string-1 c11/parse-logical-and-expression c11/parse-inclusive-or-expression c11/parse-bracket-direct-abstract-declarator-1-1-1-1 c11/parse-assignment-operator c11/parse-initializer-list-1-2 c11/parse-block-item-list-1 c11/parse-bracket-direct-abstract-declarator-1-1-1 c11/parse-struct-declaration-list c11/parse-external-declaration-1-2-2-2-1-2 c11/parse-additive-expression c11/parse-simple-type-specifier-1-1-10 c11/parse-storage-class-specifier-1-4 c11/parse-postfix-expression-item-1-6 c11/parse-designator-1-1 c11/parse-direct-declarator-item--or--direct-abstract-declarator-item-1-1-1 c11/parse-direct-declarator-item-1 c11/parse-struct-declaration-list-1 c11/parse-abstract-declarator c11/parse-direct-declarator-1 c11/parse-function-specifier-1-2 c11/parse-pointer-1-1 c11/parse-struct-or-union-specifier-1-1-2 c11/parse-inc-op c11/parse-cast-expression c11/parse-cast-expression-1-3 c11/parse-initializer-list c11/parse-generic-association-1 c11/parse-iteration-statement-1-3-1 c11/parse-and-op c11/parse-initializer-list-1-2-1 c11/parse-init-declarator-list-1 c11/parse-div-assign-1 c11/parse-declarator--or--abstract-declarator c11/parse-direct-declarator-in-parentheses-1-2 c11/parse-struct-or-union-specifier c11/parse-jump-statement-1-4-1 c11/parse-unary-expression c11/parse-specifier-qualifier-1-1-1-1 c11/parse-inclusive-or-expression-1 c11/parse-postfix-expression-1 c11/parse-simple-primary-expression-1 c11/parse-left-assign c11/parse-enumeration-constant c11/parse-equality-expression-1-1-1 c11/parse-external-declaration-1-2-2-2-1-1 c11/parse-declaration-specifiers c11/parse-init-declarator-list-1-1-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-2-1-1 c11/parse-relational-expression-1 c11/parse-type-specifier c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-2-1-1-1 c11/parse-iteration-statement-1-3-1-2-1 c11/parse-additive-expression-1 c11/parse-cast-expression-1-3-1-3 c11/parse-simple-type-specifier-1-1-4 c11/parse-logical-and-expression-1-1 c11/parse-bracket-direct-abstract-declarator-1 c11/parse-type-qualifier-list-1 c11/parse-simple-type-qualifier-1 c11/parse-postfix-expression-item-1-2 c11/parse-external-declaration-1-2-2-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-1 c11/parse-external-declaration-1-2-2-2-1-1-1-1 c11/parse-struct-declarator-list c11/parse-jump-statement-1 c11/parse-type-qualifier-1-1 c11/parse-jump-statement-1-2 c11/parse-specifier-qualifier-list c11/parse-shift-expression-1-1-1-1 c11/parse-initializer-1 c11/parse-simple-labeled-statement-1-2 c11/parse-dec-op-1 c11/parse-sub-assign-1 c11/parse-expression c11/parse-direct-declarator-in-brackets-1-3-1 c11/parse-declarator-1-1 c11/parse-shift-expression-1-1-1 c11/parse-translation-unit c11/parse-struct-declarator-list-1-1-1 c11/parse-declaration-1-1-1 c11/parse-logical-and-expression-1 c11/parse-direct-declarator-in-parentheses-1-1 c11/parse-simple-labeled-statement-1 c11/parse-type-specifier-1 c11/parse-sizeof-argument-1-1-1-1-1-2-1 c11/parse-storage-class-specifier-1-6 c11/parse-direct-declarator c11/parse-parameter-list-1-1 c11/parse-relational-expression-1-1 c11/parse-left-op-1 c11/parse-declaration-1 c11/parse-jump-statement c11/parse-type-name-1 c11/parse-expression-statement-1 c11/parse-type-name c11/parse-init-declarator-list-1-1 c11/parse-postfix-expression-item-1-1 c11/parse-storage-class-specifier-1-5 c11/parse-external-declaration-1-2-2-2-1-1-2 c11/parse-expression-1-1 c11/parse-iteration-statement-1-3 c11/parse-struct-or-union-specifier-1-1-2-1-1 c11/parse-direct-declarator--or--direct-abstract-declarator-1-1 c11/parse-declarator--or--abstract-declarator-1-1-1 c11/parse-generic-assoc-list c11/parse-generic-association-1-1 c11/parse-direct-abstract-declarator-in-parentheses c11/parse-declarator-1 c11/parse-simple-direct-abstract-declarator-1-1-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-2 c11/parse-iteration-statement-1-3-1-2 c11/parse-assignment-operator-1-1 c11/parse-and-expression-1-1-1 c11/parse-multiplicative-expression c11/parse-relational-expression c11/parse-sizeof-argument-1-1-1-1-1-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-2-1 c11/parse-simple-direct-abstract-declarator-1-1 c11/parse-multiplicative-expression-1-1 c11/parse-jump-statement-1-1 c11/parse-simple-direct-declarator-1 c11/parse-additive-expression-1-1-1 c11/parse-struct-or-union-specifier-1-1 c11/parse-designation c11/parse-jump-statement-1-4 c11/parse-simple-type-specifier-1-1 c11/parse-assignment-expression c11/parse-pointer-1 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1 c11/parse-struct-declarator-1-2-1-1 c11/parse-struct-declaration c11/parse-cast-expression-1-3-1-2-1 c11/parse-direct-declarator-in-brackets-1 c11/parse-argument-expression-list c11/parse-declaration-specifiers-1-1 c11/parse-ge-op-1 c11/parse-postfix-expression-item c11/parse-declaration-1-1-2 c11/parse-sizeof-argument-1-1-1-1-1 c11/parse-struct-or-union-1 c11/parse-direct-abstract-declarator-item-1-1-1 c11/parse-direct-abstract-declarator-item c11/parse-right-op-1 c11/parse-eq-op-1 c11/parse-iteration-statement-1-3-1-1-1 c11/parse-direct-declarator-item-1-2-1-1-1 c11/parse-statement-1 c11/parse-postfix-expression-head-1-1 c11/parse-direct-declarator--or--direct-abstract-declarator-1 c11/parse-dec-op c11/parse-ne-op-1 c11/parse-block-item c11/parse-parameter-list-1-1-1 c11/parse-sub-assign c11/parse-iteration-statement-1 c11/parse-and-assign-1 c11/parse-simple-type-specifier-1-1-11 c11/parse-simple-type-qualifier-1-1-2 c11/parse-specifier-qualifier-1-1-1 c11/parse-right-assign-1 c11/parse-simple-type-qualifier-1-1-1 c11/parse-translation-unit-1-1 c11/parse-struct-declarator-1-2 c11/parse-atomic-type-specifier-1 c11/parse-iteration-statement-1-3-1-1 c11/parse-direct-declarator-in-parentheses-1 c11/parse-enumerator-1-1 c11/parse-assignment-expression-1-1 c11/parse-init-declarator-1-1-1 c11/parse-generic-assoc-list-1-1-1 c11/parse-shift-expression-1 c11/parse-direct-declarator-item--or--direct-abstract-declarator-item-1-1 c11/parse-external-declaration-1-1 c11/parse-identifier-list c11/parse-function-specifier c11/parse-le-op c11/parse-sizeof-argument-1-1-1-1-1-2-1-1-1 c11/parse-and-assign c11/parse-simple-type-specifier-1-1-9 c11/parse-direct-declarator-item--or--direct-abstract-declarator-item-1 c11/parse-sizeof-argument-1-1-1-1-1-2-1-1 c11/parse-alignment-specifier-1 c11/parse-postfix-expression-head-1-1-1 c11/parse-or-assign c11/parse-parameter-declaration c11/parse-logical-or-expression-1-1-1 c11/parse-enum-specifier-1-2-1-1-1 c11/parse-designator-list-1 c11/parse-designator-1-2 c11/parse-designator c11/parse-constant-1 c11/parse-direct-declarator-in-brackets-1-2 c11/parse-statement c11/parse-argument-expression-list-1 c11/parse-shift-expression-1-1 c11/parse-postfix-expression-1-1 c11/parse-expression-statement-or-label c11/parse-external-declaration c11/parse-init-declarator-1 c11/parse-primary-expression c11/parse-assignment-expression-1-1-1 c11/parse-selection-statement-1-1-1 c11/parse-postfix-expression-head-1-1-1-3 c11/parse-unary-operator c11/parse-static-assert-declaration c11/parse-simple-labeled-statement-1-1 c11/parse-enum-specifier-1 c11/parse-conditional-expression-1 c11/parse-postfix-expression-item-1-4 c11/parse-postfix-expression-head-1-1-1-1 c11/parse-generic-assoc-list-1-1 c11/parse-parameter-list-1 c11/parse-conditional-expression c11/parse-direct-declarator-1-1 c11/parse-expression-statement-or-label-1-1-1 c11/parse-xor-assign c11/parse-type-qualifier-1 c11/parse-postfix-expression-head-1-1-1-2-1 c11/parse-pointer-1-2 c11/parse-additive-expression-1-1-1-1 c11/parse-simple-unary-expression-1-4 c11/parse-unary-operator-1 c11/parse-logical-and-expression-1-1-1 c11/parse-mod-assign c11/parse-sizeof-argument-1-1-1-1-1-3 c11/parse-conditional-expression-1-1 c11/parse-simple-unary-expression-1-5 c11/parse-compound-statement-1-1 c11/parse-enumerator-list-1-1 c11/parse-generic-association-1-2 c11/parse-iteration-statement c11/parse-struct-declarator-1 c11/parse-direct-declarator-in-brackets-1-3-1-1 c11/parse-cast-expression-1-2 c11/parse-parameter-type-list c11/parse-simple-direct-declarator-1-1 c11/parse-direct-declarator-in-brackets c11/parse-initializer-list-1-1-1 c11/parse-designation-1 c11/parse-struct-or-union-specifier-1-1-2-1 c11/parse-simple-type-qualifier c11/parse-shift-expression c11/parse-simple-unary-expression-1-3 c11/parse-direct-declarator-item--or--direct-abstract-declarator-item c11/parse-postfix-expression-item-1-5 c11/parse-simple-direct-declarator--or--simple-direct-abstract-declarator-1-2-1-1-1-1 c11/parse-translation-unit-1 c11/parse-left-op c11/parse-direct-declarator-item-1-2-1 c11/parse-expression-statement-or-label-1 c11/parse-direct-declarator-item-1-2-1-1 c11/parse-atomic-type-specifier c11/parse-simple-direct-abstract-declarator-1 c11/parse-struct-declarator-list-1 c11/parse-left-assign-1 c11/parse-postfix-expression c11/parse-cast-expression-1-3-1-1 c11/parse-ptr-op c11/parse-postfix-expression-item-1-3 c11/parse-external-declaration-1-2-2-2-1 c11/parse-or-op-1 c11/parse-or-op c11/parse-simple-type-specifier-1-1-12 c11/parse-ptr-op-1 c11/parse-parameter-type-list-1-1-1 c11/parse-parameter-declaration-1 c11/parse-add-assign-1 c11/parse-identifier-list-1 c11/parse-sizeof-argument-1 c11/parse-declarator c11/parse-enumerator-1-1-1 c11/parse-direct-declarator-item-1-2 c11/parse-compound-statement-1 c11/parse-bracket-direct-abstract-declarator-1-1 c11/parse-and-expression-1-1 c11/parse-expression-statement-or-label-1-1-1-1 c11/parse-equality-expression-1 c11/parse-struct-declarator-1-1 c11/parse-enum-specifier-1-1-1 c11/parse-direct-abstract-declarator-1-1 c11/parse-xor-assign-1 c11/parse-expression-statement-1-1 c11/parse-abstract-declarator-1-1 c11/parse-and-op-1 c11/parse-declarator--or--abstract-declarator-1-1 c11/parse-selection-statement-1-1-1-1 c11/parse-logical-or-expression-1 c11/parse-enumerator-1 c11/parse-enumerator-list-1-1-1 c11/parse-declarator--or--abstract-declarator-1 c11/parse-parameter-type-list-1) ;;;; THE END ;;;;
29,191
Common Lisp
.lisp
186
137.247312
16,893
0.682596
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0f4da3d97a2d9ff42c86538f0495d4237b758cdb38a031fb4ebbb264f6c59c93
5,203
[ -1 ]
5,204
actions.lisp
informatimago_lisp/languages/c11/actions.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: actions.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; The actions of the C11 parser. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-02 <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 "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER") (defun c-declaration (specifiers init-declarators semicolon) (print (list 'specifiers specifiers)) (print (list 'init-declarators init-declarators)) (finish-output) (list specifiers init-declarators semicolon)) (defun c-trace (&rest sentence) (print sentence) (finish-output) sentence) ;;;; THE END ;;;;
1,812
Common Lisp
.lisp
46
37.956522
83
0.621453
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
493cc26eea8184f2937c42bb894f8b8e050980e703c769a69959c9dd8099ec73
5,204
[ -1 ]
5,205
c11-scanner.lisp
informatimago_lisp/languages/c11/c11-scanner.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: c11-scanner.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; C11 Scanner. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-02 <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 "COM.INFORMATIMAGO.LANGUAGES.C11.SCANNER") (define-scanner c11-scanner ;; This scanner is not used by c11-parser, but by read-yacc. :terminals ( "_Alignas" "_Alignof" "_Atomic" "_Bool" "_Complex" "_Generic" "_Imaginary" "_Noreturn" "_Static_assert" "_Thread_local" "auto" "break" "case" "char" "const" "continue" "default" "do" "double" "else" "enum" "extern" "float" "for" "goto" "if" "inline" "int" "long" "register" "restrict" "return" "short" "signed" "sizeof" "static" "struct" "switch" "typedef" "union" "unsigned" "void" "volatile" "while" "^=" "|=" "-=" "<<=" ">>=" "&=" "&&" "||" "*=" "/=" "%=" "+=" "->" "++" "--" "<<" ">>" "<=" ">=" "==" "!=" "(" ")" "," ":" ";" "." "..." "[" "]" "{" "}" "&" "*" "/" "+" "-" "~" "!" "%" "<" ">" "=" "^" "|" "?" (identifier "[a-zA-Z_$][a-zA-Z_$0-9]*") (hex "0[xX][0-9A-Fa-f]+[uUlL]*") (oct "0[0-7]+[uUlL]*") (dec "[0-9]+[uUlL]*") (lchar "L?'(\\.|[^\\'])+'") (flt1 "[0-9]+[Ee][-+]?[0-9]+[fFlL]?") (flt2 "[0-9]*\\.[0-9]+([Ee][-+]?[0-9]+)?[fFlL]?") (flt3 "[0-9]+\\.[0-9]*([Ee][-+]?[0-9]+)?[fFlL]?") (str "L?\"(\\.|[^\\\"])*\"")) :alphanumerics "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$" :spaces (load-time-value (coerce (remove-duplicates '(#\Space #\Newline #+has-tab #\Tab #+has-page #\Page #+has-null #\Null #+(and has-return (not newline-is-return)) #\Return #+(and has-linefeed (not newline-is-linefeed)) #\Linefeed)) 'string))) (defparameter *parser-package* (load-time-value (find-package "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER")) "Package where the token kinds are interned.") (defparameter *symbol-package* (load-time-value (find-package "COM.INFORMATIMAGO.LANGUAGES.C11.C")) "Package where the identifiers of the C program are interned.") (defparameter *c11-literal-tokens* '("_Alignas" "_Alignof" "_Atomic" "_Bool" "_Complex" "_Generic" "_Imaginary" "_Noreturn" "_Static_assert" "_Thread_local" "auto" "break" "case" "char" "const" "continue" "default" "do" "double" "else" "enum" "extern" "float" "for" "goto" "if" "inline" "int" "long" "register" "restrict" "return" "short" "signed" "sizeof" "static" "struct" "switch" "typedef" "union" "unsigned" "void" "volatile" "while" "^=" "|=" "-=" "<<=" ">>=" "&=" "&&" "||" "*=" "/=" "%=" "+=" "->" "++" "--" "<<" ">>" "<=" ">=" "==" "!=" "(" ")" "," ":" ";" "." "..." "[" "]" "{" "}" "&" "*" "/" "+" "-" "~" "!" "%" "<" ">" "=" "^" "|" "?")) (defparameter *c11-literal-tokens-map* (load-time-value (let ((table (make-hash-table :test 'equal))) (dolist (token *c11-literal-tokens* table) (setf (gethash token table) (let ((name (string-upcase token))) (when (char= (aref name 0) #\_) (setf name (substitute #\- #\_ (subseq name 1)))) (intern name *parser-package*))))))) (defparameter *c11-regexp-tokens* ;; order matters '((string-literal (str "^L?\"(\\.|[^\\\"])*\"$")) (i-constant (lchar "^L?'(\\.|[^\\'])+'$")) (identifier (identifier "^[a-zA-Z_$][a-zA-Z_$0-9]*$")) (f-constant (flt1 "^[0-9]+[Ee][-+]?[0-9]+[fFlL]?$") (flt2 "^[0-9]*\\.[0-9]+([Ee][-+]?[0-9]+)?[fFlL]?$") (flt3 "^[0-9]+\\.[0-9]*([Ee][-+]?[0-9]+)?[fFlL]?$")) (i-constant (hex "^0[xX][0-9A-Fa-f]+[uUlL]*$") (oct "^0[0-7]+[uUlL]*$") (dec "^[0-9]+[uUlL]*$")))) (defvar *context*) (defun upgrade-c11-token (token) (let* ((text (token-text token)) (literal (gethash text *c11-literal-tokens-map*))) (if literal (setf (token-kind token) literal) (let ((kind (first (find-if (lambda (entry) (some (lambda (regexp) (string-match (second regexp) text)) (rest entry))) *c11-regexp-tokens*)))) (if (eq kind 'identifier) (setf (token-symbol token) (intern (token-text token) *symbol-package*) (token-kind token) (cond ((typedef-name-p *context* token) 'typedef-name) ((function-name-p *context* token) 'func-name) ((enumeration-constant-name-p *context* token) 'enumeration-constant) (t 'identifier))) (setf (token-kind token) kind)))) token)) ;;;; THE END ;;;;
6,736
Common Lisp
.lisp
135
39.481481
112
0.451951
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
77a191ba74930a1960dfb6fd881ee80a43d2269beb9d078062d8c8fb7cda57dd
5,205
[ -1 ]
5,206
context.lisp
informatimago_lisp/languages/c11/context.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: context.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; C11 compilation context. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-12 <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 "COM.INFORMATIMAGO.LANGUAGES.C11.CONTEXT") (defclass context () ((c-identifiers-package :initarg :c-identifiers-package :initform (load-time-value (find-package "COM.INFORMATIMAGO.LANGUAGES.C11.C")) :accessor context-c-identifiers-package) (typedefs :initarg :typedefs :initform (make-hash-table :test (function equal)) :documentation "Maps identifier symbols to typedef declarations. The scanner uses it to detect typedef_name tokens." :reader context-typedefs) (functions :initarg :functions :initform (make-hash-table :test (function equal)) :documentation "Maps identifier symbols to function declarations. The scanner uses it to detect func_name tokens." :reader context-functions) (enumeration-constants :initarg :enum-constants :initform (make-hash-table :test (function equal)) :documentation "Maps identifier symbols to enumeration constant declarations. The scanner uses it to detect enumeration_constant tokens." :reader context-enumeration-constants) (declaration-specifiers :initform '() :accessor context-declaration-specifiers))) (defvar *context* nil "The C11 parser context.") (defgeneric typedef-name-p (context token) (:method ((context null) token) (declare (ignorable context token)) nil)) (defgeneric function-name-p (context token) (:method ((context null) token) (declare (ignorable context token)) nil)) (defgeneric enumeration-constant-name-p (context token) (:method ((context null) token) (declare (ignorable context token)) nil)) (defun identifier-in-table-p (context table name) (declare (ignore context)) (and (eq 'identifier (token-kind name)) (gethash (token-symbol name) table))) (defun enter-into-table (context table kind name definition) (declare (ignore context kind)) (assert (eq 'identifier (token-kind name)) (name)) (setf (gethash (token-symbol name) table) definition)) (defmethod typedef-name-p ((context context) token) (identifier-in-table-p context (context-typedefs context) token)) (defmethod function-name-p ((context context) token) (identifier-in-table-p context (context-functions context) token)) (defmethod enumeration-constant-name-p ((context context) token) (identifier-in-table-p context (context-enumeration-constants context) token)) (defgeneric enter-typedef (context name &optional definition) (:method ((context context) name &optional (definition t)) (enter-into-table context (context-typedefs context) 'typedef-name name definition))) (defgeneric enter-function (context name &optional definition) (:method ((context context) name &optional (definition t)) (enter-into-table context (context-functions context) 'func-name name definition))) (defgeneric enter-enumeration-constant (context name &optional definition) (:method ((context context) name &optional (definition t)) (enter-into-table context (context-enumeration-constants context) 'enum-name name definition))) ;;;; THE END ;;;;
4,739
Common Lisp
.lisp
95
44.473684
104
0.659607
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bd58d3e06db4f3c7cc83e4141416ddd3c9c3854b0f375427e58123c5dbc67573
5,206
[ -1 ]
5,207
packages.lisp
informatimago_lisp/languages/c11/packages.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: packages.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Defines the packages for the C11 parser. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-02 <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.LANGUAGES.C11.TOKENS" (:use) (:import-from "COMMON-LISP" "*" ">=" "/" "-" "++" "+" ">" "=" "<" "<=" "/=") (:import-from "COM.INFORMATIMAGO.LANGUAGES.CPP" "IDENTIFIER" "STRING-LITERAL" ;; "TYPEDEF-NAME" "FUNC-NAME" ;; "I-CONSTANT" "F-CONSTANT" "ENUM-NAME" ) (:export "IDENTIFIER" "TYPEDEF-NAME" "FUNC-NAME" "STRING-LITERAL" "I-CONSTANT" "F-CONSTANT" "ENUM-NAME" "STAR" ;; - "_Alignas" "_Alignof" "_Atomic" "_Bool" "_Complex" "_Generic" "_Imaginary" "_Noreturn" "_Static_assert" "_Thread_local" "auto" "break" "case" "char" "const" "continue" "default" "do" "double" "else" "enum" "extern" "float" "for" "goto" "if" "inline" "int" "long" "register" "restrict" "return" "short" "signed" "sizeof" "static" "struct" "switch" "typedef" "union" "unsigned" "void" "volatile" "while" "^=" "|=" "-=" "<<=" ">>=" "&=" "&&" "||" "*=" "/=" "%=" "+=" "->" "++" "--" "<<" ">>" "<=" ">=" "==" "!=" "(" ")" "," ":" ";" "." "..." "[" "]" "{" "}" "&" "*" "/" "+" "-" "~" "!" "%" "<" ">" "=" "^" "|" "?") (:documentation "This package exports the token-kinds of the C11 terminal symbols.")) (defpackage "COM.INFORMATIMAGO.LANGUAGES.C11.CONTEXT" (:use "COMMON-LISP" "COM.INFORMATIMAGO.LANGUAGES.CPP" "COM.INFORMATIMAGO.LANGUAGES.C11.TOKENS" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER") (:export "CONTEXT" "CONTEXT-C-IDENTIFIERS-PACKAGE" "CONTEXT-TYPEDEFS" "CONTEXT-FUNCTIONS" "CONTEXT-ENUMERATION-CONSTANTS" "CONTEXT-DECLARATION-SPECIFIERS" "*CONTEXT*" "TYPEDEF-NAME-P" "FUNCTION-NAME-P" "ENUMERATION-CONSTANT-NAME-P" "IDENTIFIER-IN-TABLE-P" "ENTER-TYPEDEF" "ENTER-FUNCTION" "ENTER-ENUMERATION-CONSTANT")) (defpackage "COM.INFORMATIMAGO.LANGUAGES.C11.SCANNER" (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER" "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP" "COM.INFORMATIMAGO.LANGUAGES.C11.TOKENS" "COM.INFORMATIMAGO.LANGUAGES.C11.CONTEXT" "COM.INFORMATIMAGO.LANGUAGES.CPP") (:export "C11-SCANNER" "UPGRADE-C11-TOKEN")) (defpackage "COM.INFORMATIMAGO.LANGUAGES.YACC.PARSER" (:use "COMMON-LISP" "YACC" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER" "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP" "COM.INFORMATIMAGO.LANGUAGES.CPP" "COM.INFORMATIMAGO.TOOLS.READER-MACRO" "COM.INFORMATIMAGO.LANGUAGES.C11.TOKENS" "COM.INFORMATIMAGO.LANGUAGES.C11.CONTEXT") (:export "C11-SCANNER" "READ-YACC") (:documentation " This package exports a function to read yacc grammars, returning a yacc:defgrammar form. ")) (defpackage "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER" (:use ;; "CL-STEPPER" "COMMON-LISP" "COM.INFORMATIMAGO.RDP" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM" "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.PARSER" "COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER" "COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP" "COM.INFORMATIMAGO.LANGUAGES.CPP" "COM.INFORMATIMAGO.TOOLS.READER-MACRO" "COM.INFORMATIMAGO.LANGUAGES.C11.TOKENS" "COM.INFORMATIMAGO.LANGUAGES.C11.CONTEXT" "COM.INFORMATIMAGO.LANGUAGES.C11.SCANNER") (:export "C11-PARSER")) (defpackage "COM.INFORMATIMAGO.LANGUAGES.C11.C" (:use) (:documentation "Default package where the C identifiers are interned.")) ;;;; THE END ;;;;
5,538
Common Lisp
.lisp
121
39.578512
87
0.607658
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
3c134e720774af363a2c8547cad77d641c54187f7b0b796270deedb0ce1281b7
5,207
[ -1 ]
5,208
c11-parser.lisp
informatimago_lisp/languages/c11/c11-parser.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: c11-parser.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; C11 parser. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2015-07-02 <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 "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER") (declaim (declaration stepper)) (defclass pre-scanned-scanner (buffered-scanner) ((tokens :initform '() :initarg :tokens :accessor pre-scanned-tokens) (actual-current :accessor pre-scanner-actual-current-token)) (:default-initargs :source "")) (defmethod (setf scanner-source) (new-source (scanner pre-scanned-scanner)) new-source) (defmethod scanner-file ((scanner pre-scanned-scanner)) (token-file (pre-scanner-actual-current-token scanner))) (defmethod scanner-source ((scanner pre-scanned-scanner)) (ignore-errors (pathname (scanner-file scanner)))) (defmethod scanner-line ((scanner pre-scanned-scanner)) (token-line (pre-scanner-actual-current-token scanner))) (defmethod scanner-column ((scanner pre-scanned-scanner)) (token-column (pre-scanner-actual-current-token scanner))) (defmethod scan-next-token ((scanner pre-scanned-scanner) &optional parser-data) (declare (stepper disable)) (declare (ignore parser-data)) (let ((token (pop (pre-scanned-tokens scanner)))) (when token (upgrade-c11-token token) #| TODO: handle [*] -> [ STAR ] |# ;; (format *trace-output* "~&scan-next-token -> ~A~%" token) (setf (pre-scanner-actual-current-token scanner) token (scanner-current-text scanner) (token-text token) ;; result: (scanner-current-token scanner) (token-kind token))))) (defmethod scanner-end-of-source-p ((scanner pre-scanned-scanner)) (declare (stepper disable)) (null (pre-scanned-tokens scanner))) (defmethod scanner-end-of-line-p ((scanner pre-scanned-scanner)) (scanner-end-of-source-p scanner)) (defmethod advance-line ((scanner pre-scanned-scanner)) "RETURN: The new current token = old next token" (if (scanner-end-of-source-p scanner) #|End of File -- don't move.|# nil (scan-next-token scanner))) (defmethod accept ((scanner pre-scanned-scanner) token) (if (word-equal token (scanner-current-token scanner)) (prog1 (list (scanner-current-token scanner) (scanner-current-text scanner) (pre-scanner-actual-current-token scanner)) (scan-next-token scanner)) (error 'unexpected-token-error :file (scanner-file scanner) :line (scanner-line scanner) :column (scanner-column scanner) :scanner scanner :expected-token token :format-control "Expected ~S, not ~A (~S)" :format-arguments (list token (scanner-current-token scanner) (scanner-current-text scanner))))) ;;;--------------------------------------------------------------------- (declaim (declaration stepper)) (progn (defmethod print-object ((self (eql '\()) stream) (declare (stepper disable)) (princ "\\(" stream) self) (defmethod print-object ((self (eql '\))) stream) (declare (stepper disable)) (princ "\\)" stream) self) (defmethod print-object ((self (eql '\,)) stream) (declare (stepper disable)) (princ "\\," stream) self) (defmethod print-object ((self (eql '\:)) stream) (declare (stepper disable)) (princ "\\:" stream) self) (defmethod print-object ((self (eql '\;)) stream) (declare (stepper disable)) (princ "\\;" stream) self) (defmethod print-object ((self (eql '|.|)) stream) (declare (stepper disable)) (princ "\\." stream) self) (defmethod print-object ((self (eql '\[)) stream) (declare (stepper disable)) (princ "\\[" stream) self) (defmethod print-object ((self (eql '\])) stream) (declare (stepper disable)) (princ "\\]" stream) self) (defmethod print-object ((self (eql '\{)) stream) (declare (stepper disable)) (princ "\\{" stream) self) (defmethod print-object ((self (eql '\})) stream) (declare (stepper disable)) (princ "\\}" stream) self) (defmethod print-object ((self (eql '\|)) stream) (declare (stepper disable)) (princ "\\|" stream) self)) (defstruct (compound-literal :named (:type list) (:constructor make-compound-literal (type-name initializer-list))) type-name initializer-list) (progn #1=(defgrammar c11 ;; rdp :scanner nil ; we use the pre-scanned-scanner defined above. :trace nil ;; Note: since we don't generate a scanner, the following terminals are not used, ;; but they are what is expected from the cpp scanner. :terminals ((identifier "identifier") (typedef-name "typedef_name") (func-name "func_name") (string-literal "string_literal") (i-constant "i_constant") (f-constant "f_constant") (enum-name "enum_name") (alignas "_Alignas") (alignof "_Alignof") (atomic "_Atomic") (complex "_Complex") (imaginary "_Imaginary") (generic "_Generic") (noreturn "_Noreturn") (static-assert "_Static_assert") (thread-local "_Thread_local") (auto "auto") (bool "bool") (break "break") (case "case") (char "char") (const "const") (continue "continue") (default "default") (do "do") (double "double") (else "else") (enum "enum") (extern "extern") (float "float") (for "for") (goto "goto") (if "if") (inline "inline") (int "int") (long "long") (register "register") (restrict "restrict") (return "return") (short "short") (signed "signed") (sizeof "sizeof") (static "static") (struct "struct") (switch "switch") (typedef "typedef") (union "union") (unsigned "unsigned") (void "void") (volatile "volatile") (while "while") (ellipsis "...") (^= "^=") (\|= "|=") (-= "-=") (<<= "<<=") (>>= ">>=") (&= "&=") (&& "&&") (|\|\|| "||") (*= "*=") (/= "/=") (%= "%=") (+= "+=") (-> "->") (++ "++") (-- "--") (<< "<<") (>> ">>") (<= "<=") (>= ">=") (== "==") (!= "!=") (\( "(") (\) ")") (\, ",") (\: ":") (\; ";") (\. ".") (\[ "[") (\] "]") (\{ "{") (\} "}") (\& "&") (\* "*") (\/ "/") (\+ "+") (\- "-") (\~ "~") (\! "!") (\% "%") (\< "<") (\> ">") (\= "=") (\^ "^") (\| "|") (\? "?") (STAR "*") ;; (seq [ (opt type_qualifier_list) * ]) ) :start translation-unit :rules ( (--> OR-ASSIGN \|= :action $1) (--> XOR-ASSIGN ^= :action $1) (--> SUB-ASSIGN -= :action $1) (--> LEFT-ASSIGN <<= :action $1) (--> RIGHT-ASSIGN >>= :action $1) (--> AND-ASSIGN &= :action $1) (--> AND-OP && :action $1) (--> OR-OP \|\| :action $1) (--> MUL-ASSIGN *= :action $1) (--> DIV-ASSIGN /= :action $1) (--> MOD-ASSIGN %= :action $1) (--> ADD-ASSIGN += :action $1) (--> PTR-OP -> :action $1) (--> INC-OP ++ :action $1) (--> DEC-OP -- :action $1) (--> LEFT-OP << :action $1) (--> RIGHT-OP >> :action $1) (--> LE-OP <= :action $1) (--> GE-OP >= :action $1) (--> EQ-OP == :action $1) (--> NE-OP != :action $1) (--> constant (alt (seq I-CONSTANT :action (token-value (third i-constant))) (seq F-CONSTANT :action (read-from-string (second f-constant)))) :action $1) (--> string (alt (seq STRING-LITERAL :action (token-value (third string-literal))) FUNC-NAME) :action $1) (--> ident identifier :action ;; (intern (second identifier) (load-time-value (find-package "COM.INFORMATIMAGO.LANGUAGES.C11.C")) ) (third identifier)) (--> simple-primary-expression (alt ident constant string generic-selection) :action $1) (--> primary-expression (alt simple-primary-expression (seq \( expression \) :action expression)) :action $1) (--> generic-selection (seq GENERIC \( assignment-expression \, generic-assoc-list \) :action (list 'generic assignment-expression generic-assoc-list)) :action $1) (--> generic-assoc-list (seq generic-association (rep \, generic-association :action $2) :action (cons $1 $2)) :action $1) (--> generic-association (alt (seq type-name \: assignment-expression :action (list type-name assignment-expression)) (seq DEFAULT \: assignment-expression :action (list 'default assignment-expression))) :action $1) ;; postfix is left-to-right: (--> postfix-expression (seq postfix-expression-head (rep postfix-expression-item :action $1) :action (wrap-left-to-right $1 $2)) :action $1) (--> postfix-expression-head (alt simple-primary-expression (seq \( (alt (seq expression \) ; = primary-expression :action expression) (seq type-name \) { initializer-list (opt \,)} :action `(compound-literal ,type-name ,initializer-list)) (seq \) :action nil #|TODO: WHAT IS THIS?|#)) :action $2)) :action $1) (--> postfix-expression-item (alt (seq [ expression ] :action `(aref ,expression)) (seq \( (opt argument-expression-list) \) :action `(call ,(first $2))) (seq |.| ident :action `(dot ,ident)) (seq PTR-OP ident :action `(ptr-op ,ident)) (seq INC-OP :action '(post-increment)) (seq DEC-OP :action '(post-decrement))) :action $1) (--> argument-expression-list (seq assignment-expression (rep \, assignment-expression :action $2) :action (cons $1 $2)) :action $1) ;; unary is right-to-left: (--> simple-unary-expression (alt (seq INC-OP unary-expression :action `(pre-increment ,unary-expression)) (seq DEC-OP unary-expression :action `(pre-decrement ,unary-expression)) (seq unary-operator cast-expression :action `(,unary-operator ,cast-expression)) (seq SIZEOF sizeof-argument :action `(size-of ,sizeof-argument)) (seq ALIGNOF \( type-name \) :action `(align-of ,type-name))) :action $1) (--> unary-operator (alt & * + - ~ !) :action (first $1)) (--> sizeof-argument (alt simple-unary-expression (seq (alt simple-primary-expression (seq \( (alt (seq expression \) :action expression) (seq type-name \) (opt { initializer-list (opt \,) } :action initializer-list) :action `(compound-literal ,type-name ,(first $3))) (seq \) :action nil #|TODO: WHAT IS THIS?|#)) :action $2)) (rep postfix-expression-item) :action (wrap-left-to-right $1 $2)))) (--> unary-expression (alt postfix-expression simple-unary-expression) :action `(unary ,$1)) (--> cast-expression (alt (seq simple-unary-expression :action `(unary ,$1)) (seq simple-primary-expression (rep postfix-expression-item :action $1) :action `(unary ,(wrap-left-to-right `(unary ,$1) $2))) (seq \( (alt (seq expression \) (rep postfix-expression-item :action $1) :action `(unary ,(wrap-left-to-right expression $3))) (seq type-name \) (alt (seq { initializer-list (opt \,) } (rep postfix-expression-item :action $1) :action `(compound-literal ,initializer-list ,$5)) (seq cast-expression :action `(cast ,cast-expression))) :action (if (and (eq 'compound-literal (first $3)) (third $3)) (wrap-left-to-right `(,(first $3) ,type-name ,(second $3)) (third $3)) `(,(first $3) ,type-name ,@(rest $3)))) ;; (seq \) :action '|()| #|WHAT IS THIS?|#) ) :action $2)) :action $1) ;; left-to-right: (--> multiplicative-expression (seq cast-expression (rep (alt * / %) cast-expression :action (list (first $1) $2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> additive-expression (seq multiplicative-expression (rep (alt + -) multiplicative-expression :action (list (first $1) $2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> shift-expression (seq additive-expression (rep (alt LEFT-OP RIGHT-OP) additive-expression :action (list (first $1) $2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> relational-expression (seq shift-expression (rep (alt < > LE-OP GE-OP) shift-expression :action (list (first $1) $2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> equality-expression (seq relational-expression (rep (alt EQ-OP NE-OP) relational-expression :action (list (first $1) $2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> and-expression (seq equality-expression (rep & equality-expression :action `(& ,$2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> exclusive-or-expression (seq and-expression (rep ^ and-expression :action `(^ ,$2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> inclusive-or-expression (seq exclusive-or-expression (rep \| exclusive-or-expression :action `(\| ,$2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> logical-and-expression (seq inclusive-or-expression (rep AND-OP inclusive-or-expression :action `(&& ,$2)) :action (wrap-left-to-right $1 $2)) :action $1) (--> logical-or-expression (seq logical-and-expression (rep OR-OP logical-and-expression :action `(\|\| ,$2)) :action (wrap-left-to-right $1 $2)) :action $1) ;; ternary if is right-to-left: (--> conditional-expression (seq logical-or-expression (opt ? expression \: conditional-expression :action (list expression conditional-expression)) :action (if $2 `(if ,$1 ,@$2) $1)) :action $1) ;; right-to-left: #-(and) (--> assignment-expression (alt conditional-expression (seq unary-expression assignment-operator assignment-expression))) (--> assignment-expression conditional-expression (opt assignment-operator assignment-expression :action (list $1 $2)) :action (if $2 (progn (check-unary $1) `(,(first (first $2)) ,(second $1) ,@(rest (first $2)))) $1)) (--> assignment-operator (alt (seq = :action '(setf)) MUL-ASSIGN DIV-ASSIGN MOD-ASSIGN ADD-ASSIGN SUB-ASSIGN LEFT-ASSIGN RIGHT-ASSIGN AND-ASSIGN XOR-ASSIGN OR-ASSIGN) :action (first $1)) ;; comma is left-to-right: (--> expression (seq assignment-expression (rep \, assignment-expression :action $2) :action (if $2 `(progn ,assignment-expression ,@$2) assignment-expression)) :action $1) (--> constant-expression conditional-expression :action (progn (check-constant-expression conditional-expression) conditional-expression)) ;; --- (--> alignment-specifier ALIGNAS \( (alt (seq type-name :action `(type ,type-name)) (seq constant-expression :action `(size ,constant-expression))) \) :action `(alignment-specifier ,$3)) (--> function-specifier (alt (seq INLINE :action 'inline) (seq NORETURN :action 'noreturn)) :action `(function-specifier ,$1)) (--> storage-class-specifier (alt (seq TYPEDEF :action 'typedef) (seq EXTERN :action 'extern) (seq STATIC :action 'static) (seq THREAD-LOCAL :action 'thread-load) (seq AUTO :action 'auto) (seq REGISTER :action 'register)) :action `(storage-class-specifier ,$1)) (--> type-qualifier (alt simple-type-qualifier (seq ATOMIC :action '(type-qualifier atomic))) :action $1) (--> simple-type-qualifier (alt (seq CONST :action 'const) (seq RESTRICT :action 'restrict) (seq VOLATILE :action 'volatile)) :action `(type-qualifier ,$1)) (--> type-specifier (alt simple-type-specifier atomic-type-specifier) :action $1) (--> atomic-type-specifier ATOMIC \( type-name \) :action `(type-specifier (type-qualifier atomic) ,$3)) (--> simple-type-specifier (alt (seq VOID :action 'void) (seq CHAR :action 'char) (seq SHORT :action 'short) (seq INT :action 'int) (seq LONG :action 'long) (seq FLOAT :action 'float) (seq DOUBLE :action 'double) (seq SIGNED :action 'signed) (seq UNSIGNED :action 'unsigned) (seq BOOL :action 'bool) (seq COMPLEX :action 'complex) (seq IMAGINARY :action 'imaginary) struct-or-union-specifier enum-specifier TYPEDEF-NAME) :action `(type-specifier ,$1)) (--> specifier-qualifier (alt (seq ATOMIC (opt \( type-name \) :action type-name) :action (if $2 `(type-specifier (type-qualifier atomic) ,@$2) `(type-qualifier atomic))) simple-type-qualifier simple-type-specifier) :action $1) (--> declaration-specifier (alt alignment-specifier function-specifier storage-class-specifier specifier-qualifier) :action $1) (--> declaration-specifiers (seq declaration-specifier (rep declaration-specifier :action $1) :action (cons $1 $2)) :action (classify-declaration-specifiers $1)) ;; --- (--> init-declarator-list init-declarator (rep \, init-declarator :action init-declarator) :action (cons init-declarator $2)) (--> init-declarator declarator (opt = initializer :action initializer) :action `(declarator ,declarator ,@$2)) ;; --- (--> struct-or-union-specifier struct-or-union (alt (seq { struct-declaration-list } :action (cons nil struct-declaration-list)) (seq ident (opt { struct-declaration-list } :action struct-declaration-list) :action (cons ident (first $2)))) :action (cons (first struct-or-union) $2)) (--> struct-or-union (alt STRUCT UNION) :action $1) (--> struct-declaration-list (seq struct-declaration (rep struct-declaration :action $1) :action (cons $1 $2)) :action $1) (--> struct-declaration (alt (seq specifier-qualifier-list (opt struct-declarator-list :action struct-declarator-list) \; :action `(struct-declaration ,specifier-qualifier-list ,@$2)) static-assert-declaration) :action $1) (--> specifier-qualifier-list specifier-qualifier (rep specifier-qualifier :action $1) :action (cons $1 $2)) (--> struct-declarator-list struct-declarator (rep \, struct-declarator :action $2) :action (cons $1 $2)) (--> struct-declarator (alt (seq \: constant-expression :action (list 'struct-declarator nil constant-expression)) (seq declarator (opt \: constant-expression :action constant-expression) :action `(struct-declarator ,declarator ,@$2))) :action $1) (--> enum-specifier ENUM (alt (seq { enumerator-list (opt \,) } :action `(enum nil ,@enumerator-list) ) (seq ident (opt { enumerator-list (opt \,) } :action enumerator-list) :action `(enum ,ident ,@$2))) :action $2) (--> enumerator-list enumerator (rep \, enumerator :action enumerator) :action (cons $1 $2)) (--> enumeration-constant ident :action ident) (--> enumerator enumeration-constant (opt = constant-expression :action constant-expression) :action (if $2 `(,enumeration-constant ,@$2) enumeration-constant)) ;; --- (--> declarator (alt (seq pointer direct-declarator :action (wrap-pointers direct-declarator pointer)) (seq direct-declarator :action $1)) :action $1) (--> direct-declarator (seq simple-direct-declarator (rep direct-declarator-item :action $1) :action (wrap-declarator simple-direct-declarator $2)) :action $1) (--> simple-direct-declarator (alt (seq ident :action (register-declarator ident)) (seq \( declarator \) :action declarator)) :action $1) (--> direct-declarator-item (alt (seq \( (opt direct-declarator-in-parentheses :action direct-declarator-in-parentheses) \) :action `(parameters ,@$2)) (seq \[ (alt (seq (opt STAR) :action `(array nil ,(if $1 '* nil))) (seq direct-declarator-in-brackets :action direct-declarator-in-brackets)) \] :action $2)) :action $1) (--> direct-declarator-in-parentheses (alt (seq identifier-list :action identifier-list) (seq parameter-type-list :action parameter-type-list)) :action $1) (--> direct-declarator-in-brackets (alt (seq assignment-expression :action `(array nil ,assignment-expression)) (seq STATIC (opt type-qualifier-list :action type-qualifier-list) assignment-expression :action `(array ,(cons 'static $2) ,assignment-expression)) (seq type-qualifier-list (opt (alt ;; * ;; TODO (seq (opt STATIC :action 'static) assignment-expression :action (list $1 $2))) :action $1) :action `(array ,(append type-qualifier-list (first $2)) ,(second $2)))) :action $1) ;; --- (--> parameter-type-list parameter-list (opt \, ELLIPSIS) :action (if $2 (append parameter-list '(ellipsis)) parameter-list)) (--> parameter-list parameter-declaration (rep \, parameter-declaration :action parameter-declaration) :action (cons parameter-declaration $2)) (--> parameter-declaration (seq declaration-specifiers :action (push-declaration-specifiers declaration-specifiers)) (opt declarator--or--abstract-declarator :action declarator--or--abstract-declarator) :action (prog1 (if $2 `(parameter ,$1 ,@$2) `(parameter ,$1)) (pop-declaration-specifiers))) (--> identifier-list ident (rep \, ident :action ident) :action (cons ident $2)) (--> type-qualifier-list type-qualifier (rep type-qualifier :action type-qualifier) :action `(type-qualifier ,@(cons type-qualifier $2))) (--> declarator--or--abstract-declarator (alt direct-declarator--or--direct-abstract-declarator (seq pointer (opt direct-declarator--or--direct-abstract-declarator :action direct-declarator--or--direct-abstract-declarator) :action (wrap-pointers (first $2) pointer))) :action $1) (--> direct-declarator--or--direct-abstract-declarator simple-direct-declarator--or--simple-direct-abstract-declarator (rep direct-declarator-item--or--direct-abstract-declarator-item :action $1) :action (cons $1 $2)) (--> simple-direct-declarator--or--simple-direct-abstract-declarator (alt (seq ident :action (register-declarator ident)) (seq \( (opt (alt (seq declarator--or--abstract-declarator (rep \, ident) :action (progn #|check declarator is ident if we have rep ident.|#)) (seq parameter-type-list)) :action $1) \)) bracket-direct-abstract-declarator) :action $1) (--> direct-declarator-item--or--direct-abstract-declarator-item (alt (seq \( (opt direct-declarator-in-parentheses :action direct-declarator-in-parentheses) \) :action `(parameters ,@$2)) bracket-direct-abstract-declarator) :action $1) (--> bracket-direct-abstract-declarator \[ (opt (alt (seq STAR) (seq direct-declarator-in-brackets :action (progn #| check no [*] |#))) :action `(aref ,$1)) \] :action $2) (--> pointer * (opt type-qualifier-list :action type-qualifier-list) (rep * (opt type-qualifier-list :action $1) :action (first $2)) :action (cons $2 $3)) (--> type-name specifier-qualifier-list (opt abstract-declarator) :action `(type-name ,specifier-qualifier-list ,@$2)) (--> abstract-declarator (alt (seq pointer (opt direct-abstract-declarator) :action (wrap-pointers $2 pointer)) (seq direct-abstract-declarator :action $1)) :action $1) (--> direct-abstract-declarator simple-direct-abstract-declarator (rep direct-abstract-declarator-item) :action (cons $1 $2)) (--> simple-direct-abstract-declarator (alt (seq \( (opt direct-abstract-declarator-in-parentheses) \)) bracket-direct-abstract-declarator) :action $1) (--> direct-abstract-declarator-in-parentheses (alt (seq abstract-declarator) (seq parameter-type-list)) :action $1) (--> direct-abstract-declarator-item (alt (seq \( (opt parameter-type-list) \)) bracket-direct-abstract-declarator) :action $1) (--> initializer (alt (seq { initializer-list (opt \,) } :action `(compound-literal nil ,initializer-list)) assignment-expression) :action $1) (--> initializer-list initializer-item (rep \, initializer-item :action initializer-item) :action (cons initializer-item $2)) (--> initializer-item (alt (seq designation initializer :action `(designation ,designation ,initializer)) (seq initializer :action initializer)) :action $1) (--> designation designator-list = :action designator-list) (--> designator-list designator (rep designator :action designator) :action (cons designator $2)) (--> designator (alt (seq \[ constant-expression \] :action `(aref ,constant-expression)) (seq |.| ident :action `(dref ,ident))) :action $1) (--> static-assert-declaration STATIC-ASSERT \( constant-expression \, STRING-LITERAL \) \; :action `(static-assert ,constant-expression ,string-literal)) ;; --- (--> statement (alt simple-labeled-statement expression-statement-or-label compound-statement selection-statement iteration-statement jump-statement) :action $1) (--> expression-statement-or-label (alt \; (seq expression (alt (seq \; :action 'expression-statement) ; expression-statement (seq \: statement :action statement)) ; label :action (if (eq $2 'expression-statement) expression `(label ,expression ,$2)))) :action $1) (--> expression-statement (alt (seq \; :action '(progn)) (seq expression \; :action expression)) :action $1) (--> simple-labeled-statement (alt (seq CASE constant-expression \: statement :action `(label ,constant-expression ,statement)) (seq DEFAULT \: statement :action `(label :default ,statement))) :action $1) (--> compound-statement (seq { (opt block-item-list :action block-item-list) } :action `(tagbody ,@$2)) :action $1) (--> block-item-list (seq block-item (rep block-item :action block-item) :action (cons block-item $2)) :action $1) (--> block-item (alt declaration statement) :action $1) (--> selection-statement (alt (seq IF \( expression \) statement (opt ELSE statement :action statement) :action `(if ,expression ,statement ,@$6)) (seq SWITCH \( expression \) statement :action `(switch ,expression ,statement))) :action $1) (--> iteration-statement (alt (seq WHILE \( expression \) statement :action `(while ,expression ,statement)) (seq DO statement WHILE \( expression \) \; :action `(do-while ,statement ,expression)) (seq FOR \( (alt (seq expression-statement expression-statement (opt expression) \) statement :action `(for ,expression-statement.1 ,expression-statement.2 ,@$3 ,statement)) (seq declaration expression-statement (opt expression) \) statement :action `(for ,declaration ,expression-statement ,@$3 ,statement))) :action $3)) :action $1) (--> jump-statement (alt (seq GOTO ident \; :action `(go ,ident)) (seq CONTINUE \; :action `(continue)) (seq BREAK \; :action `(break)) (seq RETURN (opt expression) \; :action `(return ,@$2))) :action $1) ;; --- (--> translation-unit external-declaration (rep external-declaration :action external-declaration) :action `(translation-unit ,$1 ,@$2)) (--> external-declaration (alt (seq static-assert-declaration :action `(external-declaration ,$1)) (seq (seq declaration-specifiers :action (push-declaration-specifiers declaration-specifiers)) (alt (seq \; :action '()) (seq declarator (alt (seq (opt = initializer :action $2) (rep \, init-declarator :action $2) \; :action `(:initializer ,(first $1) ,$2)) (seq (rep declaration) compound-statement ;; declaration-list are K&R parameters. :action `(:function-declarator ,$1 ,$2))) :action (ecase (first $2) (:initializer (cons `(declarator ,declarator ,@(second $2)) (third $2))) (:function-declarator `((function-declarator ,declarator ,(second $2) ,(third $2))))))) :action (let ((declaration-specifiers (pop-declaration-specifiers)) (declarators $2)) `(external-declaration ,declaration-specifiers ,@declarators)))) :action $1) (--> declaration (alt (seq static-assert-declaration :action `(external-declaration ,$1)) (seq (seq declaration-specifiers :action (push-declaration-specifiers declaration-specifiers)) (opt init-declarator-list) \; :action (let ((declaration-specifiers (pop-declaration-specifiers)) (init-declarator-list (first $2))) `(declaration ,declaration-specifiers ,@init-declarator-list)))) :action $1))) (defparameter *c* '#1#)) (defun classify-declaration-specifiers (specifiers) (let (alignment-specifiers function-specifiers storage-class-specifiers type-qualifiers type-specifiers) (loop :for specifier :in specifiers :do (ecase (first specifier) (alignment-specifier (push (second specifier) alignment-specifiers)) (function-specifier (push (second specifier) function-specifiers)) (storage-class-specifier (push (second specifier) storage-class-specifiers)) (type-qualifier (push (second specifier) type-qualifiers)) (type-specifier (push (second specifier) type-specifiers)))) (append (when storage-class-specifiers `((storage-class-specifier ,@storage-class-specifiers))) (when function-specifiers `((function-specifier ,@function-specifiers))) (when alignment-specifiers `((alignment-specifier ,@alignment-specifiers))) (when type-qualifiers `((type-qualifier ,@type-qualifiers))) (when type-specifiers `((type-specifier ,@type-specifiers))) '()))) (defun push-declaration-specifiers (specifiers) " DO: Push the specifiers onto the (context-declaration-specifiers *context*) stack. RETURN: specifiers NOTE: if the specifiers is a typedef, then pushes above it :typedef. " (push specifiers (context-declaration-specifiers *context*)) (when (member 'typedef (find 'storage-class-specifier specifiers :key (function first))) (push :typedef (context-declaration-specifiers *context*))) ;; (print `(specifiers --> ,specifiers)) (terpri) specifiers) (defun pop-declaration-specifiers () " DO: Pops (context-declaration-specifiers *context*) stack. RETURN: The old top of stack specifier. NOTE: if the top-of-stack is :typedef then pop it as well as the specifiers. " (let ((top (pop (context-declaration-specifiers *context*)))) (if (eq :typedef top) (pop (context-declaration-specifiers *context*)) top))) (defun unwrap-declarator (type declarator) ;; (print `(unwrap-declarator ,type ,declarator)) (loop :while (listp declarator) :do (case (first declarator) (pointer (setf type `(pointer ,(second declarator) ,type) declarator (third declarator))) (array (setf type `(array ,(second declarator) ,(third declarator) ,type) declarator (fourth declarator))) (function (setf type `(function ,(second declarator) ,type) declarator (third declarator))) (otherwise (loop-finish))) :finally (return (values declarator type)))) (defun declarator-name (declarator) ;; unwrap identifier: (unwrap-declarator nil declarator)) (defun register-declarator (declarator) (let ((name (declarator-name declarator)) (kind (first (context-declaration-specifiers *context*))) (declaration (second (context-declaration-specifiers *context*)))) (case kind (:typedef (enter-typedef *context* name declaration)) (:enum (enter-enumeration-constant *context* name declaration)) (:function (enter-function *context* name declaration)))) declarator) (defun check-constant-expression (expression) (declare (ignore expression)) #|TODO|# (values)) (defun check-unary (expression) (unless (and (listp expression) (eq 'unary (first expression))) (error "Expected an unary expression as left-hand-side of an assignment, instead of ~S" expression))) (defun wrap-left-to-right (expression partial-expressions) (loop :for (op . arguments) :in partial-expressions :do (setf expression `(,op ,expression ,@arguments)) :finally (return expression))) (defun wrap-pointers (declarator type-attributes) (loop :for type-attribute :in (reverse type-attributes) :do (setf declarator `(pointer ,type-attribute ,declarator)) :finally (return declarator))) (defun wrap-declarator (declarator items) ;; (print `(wrap-declarator ,declarator ,items)) (loop :for item :in items :do (setf declarator (ecase (first item) (parameters `(function ,declarator ,item)) (array `(array ,declarator ,@(rest item))))) :finally (return declarator))) ;; (wrap-pointers 'a '(() (const) (volatile const))) ;; (pointer nil (pointer (const) (pointer (volatile const) a))) (defun ^cons (a b) (cons a (reduce (function append) b))) (defun flatten-repeat (list) (reduce (function append) list)) (defun remove-unary (tree) (cond ((atom tree) tree) ((eql 'unary (first tree)) (remove-unary (second tree))) (t (mapcar (function remove-unary) tree)))) ;; NOT. Instead we return a parse tree close enough to the C syntax, ;; and will let post-processing deal with this: ;; ;; const int *ptc; (const int) ((pointer) ptc) -> (declarator ((pointer) (const int)) ptc) ;; int* const cp; (int) ((pointer const) cp) -> (declarator ((pointer const) (int)) cp) ;; typedef int *ip; (int) ((pointer) ip) -> (typedef ((pointer) (int)) ip) ;; const ip cp; (const ip) cp -> (declarator (const ip) cp) ;; ;; int *a [2] [3] (int) (pointer (array 3 (array 2 a))) --> (declarator (array 2 (array 3 (pointer int))) a) ;; a = array [2] of array [3] of pointer to int ;;;; THE END ;;;;
50,570
Common Lisp
.lisp
931
34.591837
137
0.441307
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
777b0434547c34db96f0bf62fef4ca10f689114f0adf29d9fa8b350e49c3736f
5,208
[ -1 ]
5,209
test.lisp
informatimago_lisp/languages/c11/test.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) ;; (in-package "COM.INFORMATIMAGO.LANGUAGES.C11.PARSER") (defpackage "TEST" (:use "COMMON-LISP" "COM.INFORMATIMAGO.RDP")) (in-package "TEST") (defgrammar simple-ex :scanner t :terminals ((identifier "[A-Za-z][A-Za-z0-9]*") (integer "[0-9]+")) :start expression :rules ((--> expression (alt (seq "+" integer) (seq "-" integer) (seq "*" integer) (seq "/" integer))))) (defgrammar ex :terminals ((identifier "[A-Za-z][A-Za-z0-9]*") (integer "[0-9]+")) :start expression :rules ((--> expression (alt impl-seq-no-action impl-seq-with-action seq-no-action seq-no-action-with-action seq-with-action seq-with-action-with-action rep-no-action rep-with-action opt-no-action opt-with-action alt-no-action alt-with-action)) (--> impl-seq-no-action "impl-seq-no-action" identifier integer) (--> impl-seq-with-action "impl-seq-with-action" identifier integer :action `(impl-seq-with-action ,identifier ,integer)) (--> seq-no-action (seq "seq-no-action" identifier integer)) (--> seq-no-action-with-action (seq "seq-no-action-with-action" identifier integer :action `(seq-no-action-with-action ,identifier ,integer))) (--> seq-with-action (seq "seq-with-action" identifier integer) :action $1) (--> seq-with-action-with-action (seq "seq-with-action-with-action" identifier integer :action `(seq-with-action-with-action ,identifier ,integer)) :action $1) (--> rep-no-action "rep-no-action" (rep identifier integer)) (--> rep-with-action "rep-with-action" (rep identifier integer) ; :action `(,identifier ,integer) :action `(rep-with-action ,@(reduce 'append $2))) (--> opt-no-action "opt-no-action" (opt identifier integer)) (--> opt-with-action "opt-with-action" (opt identifier integer) ; :action `(,identifier ,integer) :action `(opt-with-action ,@$2)) (--> alt-no-action "alt-no-action" (alt "with" "without") identifier) (--> alt-with-action "alt-with-action" (alt (seq "with" :action 'with) (seq "without" :action 'without)) identifier))) #-(and) (progn (parse-ex "impl-seq-no-action hello 42") (expression (impl-seq-no-action (|impl-seq-no-action| "impl-seq-no-action" 19) (identifier "hello" 25) (integer "42" 28))) (parse-ex "impl-seq-with-action hello 42") (expression (impl-seq-with-action (identifier "hello" 27) (integer "42" 30))) (parse-ex "seq-no-action hello 42") (expression (seq-no-action ((|seq-no-action| "seq-no-action" 14) (identifier "hello" 20) (integer "42" 23)))) (parse-ex "seq-with-action hello 42") (expression ((|seq-with-action| "seq-with-action" 16) (identifier "hello" 22) (integer "42" 25))) (parse-ex "seq-no-action-with-action hello 42") (expression (seq-no-action-with-action (seq-no-action-with-action (identifier "hello" 32) (integer "42" 35)))) (parse-ex "seq-with-action-with-action hello 42") (expression (seq-with-action-with-action (identifier "hello" 34) (integer "42" 37))) (list (parse-ex "rep-no-action") (parse-ex "rep-no-action hello 42") (parse-ex "rep-no-action hello 42 world 33")) ((expression (rep-no-action (|rep-no-action| "rep-no-action" 14) nil)) (expression (rep-no-action (|rep-no-action| "rep-no-action" 14) (((identifier "hello" 20) (integer "42" 23))))) (expression (rep-no-action (|rep-no-action| "rep-no-action" 14) (((identifier "hello" 20) (integer "42" 23)) ((identifier "world" 29) (integer "33" 32)))))) (list (parse-ex "rep-with-action") (parse-ex "rep-with-action hello 42") (parse-ex "rep-with-action hello 42 world 33")) ((expression (rep-with-action)) (expression (rep-with-action (identifier "hello" 22) (integer "42" 25))) (expression (rep-with-action (identifier "hello" 22) (integer "42" 25) (identifier "world" 31) (integer "33" 34)))) (parse-ex "opt-no-action") (expression (opt-no-action (|opt-no-action| "opt-no-action" 14) nil)) (parse-ex "opt-no-action whatisit 42") (expression (opt-no-action (|opt-no-action| "opt-no-action" 14) (((identifier "whatisit" 23) (integer "42" 26))))) (parse-ex "opt-with-action") (expression (opt-with-action (|opt-with-action| "opt-with-action" 16) nil)) (parse-ex "opt-with-action whatisit 42") (expression (opt-with-action ((identifier "whatisit" 25) (integer "42" 28)))) (list (parse-ex "alt-no-action with panache") (parse-ex "alt-no-action without panache")) ((expression (alt-no-action (|alt-no-action| "alt-no-action" 14) (|with| "with" 19) (identifier "panache" 32))) (expression (alt-no-action (|alt-no-action| "alt-no-action" 14) (|without| "without" 22) (identifier "panache" 32)))) (list (parse-ex "alt-with-action with panache") (parse-ex "alt-with-action without panache")) ((expression (alt-with-action (|alt-with-action| "alt-with-action" 16) with (identifier "panache" 34))) (expression (alt-with-action (|alt-with-action| "alt-with-action" 16) without (identifier "panache" 34)))) )
6,102
Common Lisp
.lisp
108
43.657407
167
0.560873
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
105f0563172339ebb85ff8a503a77e877f5e3547171739407b994c773d809e51
5,209
[ -1 ]
5,210
parser.lisp
informatimago_lisp/languages/latex/parser.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: parser.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A simple latex parser. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2020-05-16 <PJB> Corrected a few syntax (thanks phoe) and macro errors. ;;;; 2013-02-09 <PJB> Created. ;;;;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.COMMON-LISP.LATEX" (:use "COMMON-LISP") (:shadow "SET")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.LATEX") (defun latex-env-name (text) (let* ((left (position #\{ text)) (right (position #\} text :start left))) (subseq text (1+ left) right))) (defun test/latex-env-name () (assert (string= (latex-env-name "{Hello} {world}!") "Hello")) (assert (string= (latex-env-name "Hello {world}!") "world")) (assert (string= (latex-env-name "{world}") "world")) (assert (string= (latex-env-name "{world") "world")) (assert (null (ignore-errors (latex-env-name "world"))))) (defun escape-quotes (text) (with-output-to-string (*standard-output*) (loop :for ch :across text :do (when (char= #\" ch) (princ "\\")) (princ ch)))) (defun test/escape-quotes () (assert (string= (escape-quotes "Hello\"World\"!") "Hello\\\"World\\\"!")) (assert (string= (escape-quotes "Hello '\"' World!") "Hello '\\\"' World!")) (assert (string= (escape-quotes "Hello 'world'!") "Hello 'world'!")) (assert (string= (escape-quotes "Hello world!") "Hello world!"))) (defun get-macro-name (text) "Return the suffix of TEXT starting after the last backslash." (subseq text (1+ (or (position #\\ text :from-end t) -1)))) (defun test/get-macro-name () (assert (string= (get-macro-name "\\Hello") "Hello")) (assert (string= (get-macro-name "\\Hello\\World") "World")) (assert (string= (get-macro-name "Hello") "Hello"))) (defparameter *max-include-depth* 10) (defun set (chars) `(set ,chars)) (defun set-not (chars) `(set-not ,chars)) (defun alt (&rest options) `(alt ,@options)) (defun opt (&rest options) `(opt ,@options)) (defun rep+ (re) `(rep+ ,re)) (defun rep* (re) `(rep* ,re)) (defun seq (&rest res) `(seq ,@res)) (defun any () `(any)) (defun reject () (error "Failure reading the file.")) (defmacro scan-rules ((token-variable stream-variable) &body rules) (let ((vstate (gensym "state")) (vscan-buffer (gensym "buffer"))) `(let ((,vstate nil) (,token-variable nil) (,vscan-buffer (make-array 8 :element-type 'character :adjustable t :fill-pointer 0))) (flet ((goto (state) (setf ,vstate state)) (scan-current-stream () ,stream-variable) ((setf scan-current-stream) (new-stream) (setf ,stream-variable new-stream)) (scan-current-buffer () ,vscan-buffer) ((setf scan-current-buffer) (new-buffer) (assert (and (stringp new-buffer) (adjustable-array-p new-buffer) (array-has-fill-pointer-p new-buffer))) (setf ,vscan-buffer new-buffer)) (scan-reset-current-buffer () (setf ,vscan-buffer (make-array 8 :element-type 'character :adjustable t :fill-pointer 0)))) (macrolet ((when-state (state &body body) `(when (eq ,',vstate ,state) ,@body)) (rule (regexp &body body) `(when (setf ,',token-variable (scan-match-regexp ,',stream-variable ,regexp)) ,@body))) ,@rules))))) (defun scan-match-regexp (stream regex) (declare (ignore stream regex)) (cerror "Return NIL." "Not implemented yet")) (defun scan (stream &key (read-tex-dir #P".") (external-format :default) (if-include-fails :continue) ; or :error or some value to return from SCAN. ) (let* ((token-text "") (include-stack '()) (chapter-flag nil) (section-flag nil) (subsection-flag nil) (subsubsection-flag nil) (aparagraph-flag nil) (inline-quote-flag nil) (inline-math-flag nil) (display-math-flag nil) (table-count 0) (array-count 0) (saved-math-state nil) (brace-count nil) (list-environment-count 0) (list-stack nil) (current-list nil) (states '(:math :macro :picture)) (A-Z "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") (CONTROL-M #\return) (CONTROL-L #\page) (ALPHABET (set A-Z)) (ACCENT-ACUTE "\\'") (ACCENT-GRAV "\\`") (ACCENT-UMLAUT "\\\"" ) (ACCENT-CIRCUMFLEX "\\^") (ACCENT (alt ACCENT-CIRCUMFLEX ACCENT-GRAV ACCENT-ACUTE ACCENT-UMLAUT)) (FILENAME-CHAR (set A-Z)) (LETTER (alt (set A-Z) #\- ACCENT)) (DIGIT (set "0123456789")) (NUMBER (rep+ DIGIT)) (MATH-NUMBER (seq (rep* DIGIT) (opt ".") NUMBER)) (TEXT-NUMBER (seq NUMBER (rep* (seq (opt ",") MATH-NUMBER)))) (TIME-NUMBER (seq (rep+ DIGIT) (opt ":") (rep+ digit))) (ALPHABET-STRING (rep* LETTER)) (WHITESPACE (alt #\space #\tab #\newline)) (H-SPACE (alt #\space #\tab)) (NEWLINE #\newline) (BLANK-LINE (seq (rep* H-SPACE) NEWLINE) ) (PARAGRAPH-SEPARATOR (seq NEWLINE (rep+ BLANK-LINE))) (PUNCT (set "-=_^/.,:;!?\"()@[]|<>*+'`")) (BACKSLASH #\\) (LATEX-SPECIAL-CHAR (set "#$%&~_^{}\\")) (MATH-OP (set "+*/'<>=-")) (POS-TAB-ARG (seq "[" (rep+ (set "hbtp")) "]")) (OPT-TAB-ARG (seq "{" (rep* (set "lrc|")) "}")) (BEGIN-ENV-OPEN (seq BACKSLASH "begin" (rep* H-SPACE) "{")) (BEGIN-ENV-CLOSE (seq "}"(rep* WHITESPACE))) (BEGIN-DISPLAY-MATH "$$") (END-DISPLAY-MATH "$$") ) (scan-rules (token-text stream) (labels ((terminate () (cerror "Return NIL." "Not implemented yet")) (get-tex-filename-without-braces (text) "Return the tex file path designated by the token-text \"filename\". Use variable READ-TEX-DIR." (let ((dirname read-tex-dir) (filename text)) (concatenate 'string (or dirname "") filename (if (find #\. filename) "" ".tex")))) (get-tex-filename (text) "Return the tex file path designated by the token-text \"{filename}\". Use variable READ-TEX-DIR." (get-tex-filename-without-braces (latex-env-name text))) (open-list (&rest prefix) (push current-list list-stack) (setf current-list (reverse prefix))) (close-list () (let ((new-list (nreverse current-list))) (setf current-list (pop list-stack)) (push new-list current-list) new-list)) (add-as-string (text) (push text current-list)) (add-sexp (sexp) (push sexp current-list)) (clean-up-quotes () (when inline-quote-flag (setf inline-quote-flag nil) (close-list))) (list-env-p (text) (member text '("list" "exercises" "Exercises" "closeitemize" "alphlist" "Alphlist" "chapterex") :test (function string=))) (push-include (filename) (if (<= (length include-stack) *max-include-depth* ) (error "Includes nested too deeply.") (let ((infile (open filename :external-format external-format :if-does-not-exist (if (eq if-include-fails :error) :error nil)))) (if infile (case if-include-fails (:continue (goto nil)) (:error (error "Could not open include file ~S" filename)) (otherwise (return-from scan if-include-fails))) (progn (push (cons (scan-current-stream) (scan-current-buffer)) include-stack) (setf (scan-current-stream) infile) (scan-reset-current-buffer) (format *trace-output* "Reading input from include file ~S~%" filename) (goto :initial)))))) (pop-include () (when include-stack (close (scan-current-stream)) (setf (scan-current-stream) (car (car include-stack)) (scan-current-buffer) (cdr (car include-stack))) (pop include-stack) t)) (terminate-includes () (loop :while include-stack :do (pop-include))) (aparagraph-closer (closer) (lambda () (when aparagraph-flag (funcall closer) (close-list) (setf aparagraph-flag nil)))) (subsubsection-closer (closer) (lambda () (when subsubsection-flag (funcall closer) (close-list) (setf subsubsection-flag nil)))) (subsection-closer (closer) (lambda () (when subsection-flag (funcall closer) (close-list) (setf subsection-flag nil)))) (section-closer (closer) (lambda () (when section-flag (funcall closer) (clean-up-quotes) (close-list) (setf section-flag nil)))) (open-group (flag tag close-subgroup) (if flag (progn (funcall close-subgroup) (close-list) (open-list tag) nil) (progn (clean-up-quotes) (open-list tag) t)))) (unwind-protect (progn (rule (seq "\\end " (rep* H-SPACE)) (error "space after \\end can cause problems")) (rule "\\input" (goto :include)) (rule "\\include" (goto :include)) (when-state :include (rule (rep* H-SPACE) #|eat the whitespace|#) (rule (seq "{" (rep+ (set-not (alt "}" WHITESPACE))) "}") (let ((filename (get-tex-filename token-text))) (push-include filename))) (rule (rep+ filename-char) (let ((filename (get-tex-filename-without-braces token-text))) (push-include filename)))) (when-state :<<EOF>> (unless (pop-include) (terminate))) ;; Dectalk abbreviations: (rule (alt "Jan." "Feb." "Mar." "Apr." "Aug." "Sep." "Oct." "Nov." "Dec.") (add-as-string token-text)) (rule "i.e." (add-sexp '(cs "ie"))) (rule "e.g." (add-sexp '(cs "eg"))) ;; Misc abbreviations: (rule (alt "Corp." "etc.") (add-as-string token-text)) ;; Initials: (rule (seq ALPHABET ".") ;; A letter followed by a period is probably an initial. (add-as-string token-text)) ;; Salutations: (rule (alt "Prof." "Mr." "Mrs." "St." "PhD." "Phd." "Dr." ) (add-as-string token-text)) ;; Days of the week: (rule (alt "Sun." "Mon." "Tue." "Wed." "Thu." "Fri." "Sat.") (add-as-string token-text)) ;; tex commands that are stripped (rule (alt "\\hspace*" "\\bigskip" "\\noalign" "\\bigl" "\\bigr" "\\biggl" "\\biggr" "\\bigggl" "\\bigggr" (seq "\\thispagestyle{" (rep* (set-not #\})) "}" ) "\\medskip" "\\advance" "\\leftskip" "\\rightskip" (seq "by" (rep+ digit) "pc") (seq "by" (rep+ digit) "pt") (seq "by" (rep+ digit) "in") "\\protect" "\\smallskip" "\\displaystyle" "\\left" "\\right" "\\boldmath" "\\unboldmath" "\\raggedright" "\\vfil" "\\vfill" "\\hfil" "\\hfill" "\\scriptstyle" (seq "\\vskip" (rep* H-space) (opt (seq (rep+ digit) "pt"))) (seq "\\hspace*" (rep* H-space) (opt (seq (rep+ digit) "in"))) (seq "\\vspace*" (rep* H-space) (opt (seq (rep+ digit) "pt"))) (seq "\\vspace*" (rep* H-space) (opt (seq (rep+ digit) "in"))) (seq "\\kern*" (rep* H-space) (opt (seq (rep+ digit) "pt"))) "\\eject" "\\maketitle" "\\noindent" "\\goodbreak" "\\," "\\!" "\\:" "\\" "\\hline" "\\ " "\\/" "\\mathstrut" "\\pagebreak" "\\linebreak" ) #|nothing|#) (rule "\\@" (add-sexp '(cs "@"))) (rule "\\ul" (add-sexp '(cs "em"))) ;; Some special verb commands (rule "\\verb|[|" (add-as-string "[")) (rule "\\verb|{|" (add-as-string "{")) ;; special tex and latex characters */ (rule (alt "--" "---") (add-as-string token-text)) (rule "~" (add-as-string " ")) ; or ignore? (rule (alt "\\cr" "\\headrow" "\\newrow" (seq BACKSLASH BACKSLASH)) (if (or (plusp table-count) (plusp array-count)) (progn (close-list) ; End current array element. (close-list) ; End current row. (open-list) ; Now start next row (open-list))) ; and start its first element (add-sexp '(newline))) (rule (seq backslash latex-special-char) ;; print it after stripping off the backslash (add-as-string (escape-quotes (subseq token-text 1)))) (rule "&" (if (or (plusp table-count) (plusp array-count)) (progn (close-list) (open-list)) ;; output field separator so that we can handle tex matrix command (add-sexp '(field-separator)))) (when-state :math (rule "^" (add-as-string "^")) (rule "_" (add-as-string "_"))) ;; Skip pictures (rule (seq BEGIN-ENV-OPEN "picture" BEGIN-ENV-CLOSE) (goto :picture)) (rule (seq (rep* whitespace) backslash "end{picture}" (rep* h-space)) (goto nil)) (when-state :picture (rule (rep* (any)) #|ignore|#)) ;; kluges for handling macro definitions (rule (seq backslash "def" (rep* whitespace) backslash (rep* letter)) ;; handle macro definitions (add-sexp `(cs "def" ,(get-macro-name token-text))) ;; start arg list (open-list 'arglist) (goto :macro)) (rule (seq "#" digit) ;; Convert #1 to arg1 etc. (add-as-string (format nil "arg~C" (aref token-text 1)))) (when-state :macro (rule "{" ;; ending of arg list seen so mark it and remember (close-list) (open-list 'block) (goto nil))) ;; braces start groups (when-state :math (rule "{" (incf brace-count) (open-list 'subformula))) (rule "{" (incf brace-count) (open-list 'block)) (rule "}" (decf brace-count) (close-list) (when (zerop brace-count) ;; reset state to math if necessary (case saved-math-state ((nil)) ((:inline-math) (setf inline-math-flag t saved-math-state nil) (goto :math)) ((:display-math) (setf display-math-flag t saved-math-state nil) (goto :math)) (otherwise (error "Unknown saved-math-state ~S" saved-math-state))))) ;; hbox and mbox change state (rule (alt (seq backslash "fbox" (rep* h-space) "{") (seq backslash "hbox" (rep* h-space) "{") (seq backslash "mbox" (rep* h-space) "{")) (setf brace-count 1) ; reset brace count ;; When brace_count reaches 0 we have seen the ;; matching close brace and can close the hbox. ;; Both hbox and mbox marked as mbox and will be ;; processed as if they were user defined macros ;; ie: using define-text-object (clean-up-quotes) ;; first set up state (cond (display-math-flag (setf display-math-flag nil inline-math-flag nil ; kludge saved-math-state :display-math) (goto nil)) (inline-math-flag (setf display-math-flag nil ; kludge inline-math-flag nil saved-math-state :inline-math) (goto nil))) (add-sexp `(cs "mbox")) (open-list 'block)) ;; Brackets in latex (when-state :math (rule "[" (add-as-string "[")) (rule "]" (add-as-string "]"))) (rule "[" ; optional args in a block (open-list 'block)) (rule "]" (close-list)) ;; paragraph breaks (rule (alt (seq backslash "par") (seq backslash "paragraph") PARAGRAPH-SEPARATOR) ;; Don't put parbreaks inside math. (unless (or inline-math-flag display-math-flag) (clean-up-quotes) ;; Paragraph delimiter is a newline followed by ;; an arbitrary number blank lines, where a ;; blank is defined as a line with an arbitrary ;; amount of optional h-space followed by a ;; newline. Close apar if one opened. (when aparagraph-flag (close-list) (setf aparagraph-flag nil)) (add-sexp 'parbreak))) ;; Beginning and ending math mode (rule "\\[" (clean-up-quotes) (setf display-math-flag t) (open-list 'display-math) (goto :math)) (rule "\\]" (setf display-math-flag nil) (close-list) (goto nil)) (rule "$$" (when inline-math-flag (error "Display math started inside inline math? Probably an inline math was closed and immediately opened. Check the latex file.")) (if display-math-flag (progn (setf display-math-flag nil) (close-list) (goto nil)) (progn (clean-up-quotes) (setf display-math-flag t) (open-list 'display-math) (goto :math)))) (rule "\\(" (setf inline-math-flag t) (open-list 'inline-math) (goto :math)) (rule "\\)" (setf inline-math-flag nil) (close-list) (goto :math)) (rule "$" (if inline-math-flag (progn (setf inline-math-flag nil) (close-list) (goto nil)) (progn (setf inline-math-flag t) (open-list 'inline-math) (goto :math)))) ;; Math operators (when-state :math (rule "'" ; catch single quote in math mode (add-as-string "prime")) (rule (seq "''" (rep* h-space)) ; catch double prime in math mode (add-as-string "double-prime")) (rule MATH-OP (add-as-string token-text))) ;; tex comment (rule (seq "%" (rep* (any))) ; Latex comments run to the end of the line. ;; Not doing anything with comments, so throw them away. ;; (open-list 'comment) ;; (add-as-string (escape-quotes token-text)) ;; (close-list) ) ;; begin various environments (rule (seq begin-env-open (alt "document" "abstract" "center") begin-env-close) (open-list (intern (latex-env-name token-text)))) (rule (seq begin-env-open (alt "quote" "quotation" "verbatim") begin-env-close) (clean-up-quotes) (open-list (intern (latex-env-name token-text)))) (rule (seq begin-env-open (alt "description" "deflist" "enumerate" "itemize") begin-env-close) (clean-up-quotes) (incf list-environment-count) (open-list (intern (latex-env-name token-text))) ;; Generate dummy item ;; this is to allow \item to be handled cleanly (open-list 'item)) (rule (seq (rep* whitespace) backslash "item") (clean-up-quotes) ;; begin a new item after ending previous item (close-list) (when (zerop list-environment-count) (error "An item was found outside known list environment.")) ;; Note this is a quick fix, ;; and will leave a null list as the first item of each enumerated list (open-list 'item)) ;; begin equation (rule (seq begin-env-open "equation" begin-env-close) (clean-up-quotes) (open-list 'equation) (setf display-math-flag t) (goto :math)) ;; begin eqnarray (rule (seq begin-env-open (alt "eqnarray*" "eqnarray" "eqalign" "eqalign*") begin-env-close) ;; starting an eqnarray or an eqalign (incf array-count) (setf display-math-flag t) (goto :math) (open-list (intern (string-trim "*" (latex-env-name token-text)))) (open-list) ; start the first eqnarray row (open-list)) ; start the first eqnarray element (rule (seq begin-env-open (opt "tabular" "array") "}" (opt POS-TAB-ARG) (opt OPT-TAB-ARG) (rep* WHITESPACE)) (clean-up-quotes) (let ((op (intern (string-trim "*" (latex-env-name token-text))))) (if (eq op 'tabular) (incf table-count) (incf array-count)) (open-list op)) (open-list) ; start the first table row (open-list)) ; start the first table element ;; begin cases ;; Cases handled like table environment. Allow for text ;; inside math mode by saving state. If this works, use ;; similar approach for mbox hbox etc. (rule (seq begin-env-open "cases" "}" (opt POS-TAB-ARG) (rep* WHITESPACE)) (clean-up-quotes) (cond (display-math-flag (setf display-math-flag nil saved-math-state :display-math) (goto nil)) (inline-math-flag (setf inline-math-flag nil saved-math-state :inline-math) (goto nil))) (incf table-count) (open-list 'cases) (open-list) ; start the first table row (open-list)) ; start the first table element (rule (alt (seq (rep* blank-line) begin-env-open "slide}{}") (seq begin-env-open "slide" begin-env-close)) (clean-up-quotes) ;; starting a latex slide (open-list 'slide)) (rule (seq begin-env-open "displaymath" begin-env-close) (clean-up-quotes) (setf display-math-flag t) (open-list 'display-math) (goto :math)) ;; unrecognized environment (rule (alt (seq begin-env-open alphabet-string "}" (opt pos-tab-arg) (opt pos-tab-arg)) (seq begin-env-open (rep* (set-not "}")) "}")) ; environment names can have more that alphabets (clean-up-quotes) ;; Some new environments maybe declared as ;; enumerable by adding their name to ;; list_env_names. Handle this by checking if the ;; env name present in the table. (let ((name (latex-env-name token-text))) (if (list-env-p name) (progn (open-list 'new-environment name) ;; expect items in this env (incf list-environment-count) ;; generate dummy item ;; this is to allow \item to be handled cleanly (open-list 'item)) (open-list 'new-environment name)))) (rule (seq (rep* whitespace) backslash (alt "grieschapter" "chapter*" "chapterx" "chapter")) (setf chapter-flag (open-group chapter-flag 'chapter (section-closer (subsection-closer (subsubsection-closer (lambda ()))))))) (rule (seq (rep* whitespace) backslash (alt "griessection" "section*" "section")) (setf section-flag (open-group section-flag 'section (subsection-closer (subsubsection-closer (lambda ())))))) (rule (seq (rep* whitespace) backslash (alt "subsection*" "subsection")) (setf subsection-flag (open-group subsection-flag 'subsection (subsubsection-closer (lambda ()))))) (rule (seq (rep* whitespace) backslash (alt "subsubsection*" "subsubsection")) (setf subsubsection-flag (open-group subsubsection-flag 'subsubsection (lambda ())))) ;; absolute sectioning constructs (rule (seq (rep* whitespace) backslash "achapter") (setf chapter-flag (open-group chapter-flag 'achapter (section-closer (subsection-closer (subsubsection-closer (aparagraph-closer (lambda ())))))))) (rule (seq (rep* whitespace) backslash "asection") (setf section-flag (open-group section-flag 'asection (subsection-closer (subsubsection-closer (aparagraph-closer (lambda ()))))))) (rule (seq (rep* whitespace) backslash "asubsection") (setf subsection-flag (open-group subsection-flag 'asubsection (subsubsection-closer (aparagraph-closer (lambda ())))))) (rule (seq (rep* whitespace) backslash "asubsubsection") (setf subsubsection-flag (open-group subsubsection-flag 'asubsubsection (aparagraph-closer (lambda ()))))) (rule (seq (rep* whitespace) backslash "apar") (setf aparagraph-flag (open-group aparagraph-flag 'apar (lambda ())))) ;; end various environments (rule (seq (rep* whitespace) backslash "end{abstract}" (rep* h-space)) (clean-up-quotes) (when aparagraph-flag (close-list) (setf aparagraph-flag nil)) (close-list)) (rule (seq (rep* whitespace) backslash "end{" (alt "center" "quote" "quotation") "}" (rep* h-space)) (clean-up-quotes) (close-list)) (rule (seq (rep* whitespace) backslash "end{equation}" (rep* h-space)) (clean-up-quotes) (close-list) (setf display-math-flag nil) (goto nil)) (rule (seq (rep* whitespace) backslash "end{" (alt "eqnarray*" "eqnarray" "eqalign*" "eqalign") "}" (rep* h-space)) (decf array-count) (close-list) (close-list) (close-list) (setf display-math-flag nil) (goto nil)) (rule (seq (rep* whitespace) backslash "end{array}" (rep* h-space)) (decf array-count) (close-list) (close-list) (close-list)) (rule (seq (rep* whitespace) backslash "end{tabular}" (rep* h-space)) (decf table-count) (close-list) (close-list) (close-list)) ;; Cases handled like tabular (rule (seq (rep* whitespace) backslash "end{tabular}" (rep* h-space)) (decf table-count) (close-list) (close-list) (close-list) (case saved-math-state ((nil)) ((:inline-math) (setf inline-math-flag t saved-math-state nil) (goto :math)) ((:display-math) (setf display-math-flag t saved-math-state nil) (goto :math)) (otherwise (error "Unknown saved-math-state ~S" saved-math-state)))) (rule (seq (rep* whitespace) backslash "end{" (alt "enumerate" "description" "itemize") "}" (rep* h-space)) (clean-up-quotes) (decf list-environment-count) (close-list) (close-list)) (rule (seq (rep* whitespace) backslash "end{document}") (clean-up-quotes) (when aparagraph-flag (setf aparagraph-flag nil) (close-list)) (when subsubsection-flag (setf subsubsection-flag nil) (close-list)) (when subsection-flag (setf subsection-flag nil) (close-list)) (when section-flag (setf section-flag nil) (close-list)) (when chapter-flag (setf chapter-flag nil) (close-list)) (close-list)) (rule (seq (rep* whitespace) backslash "end{slide}") (clean-up-quotes) (close-list)) (rule (seq (rep* whitespace) backslash "end{displaymath}") (close-list) (setf display-math-flag nil) (goto nil)) (rule (seq backslash "end{" (alt (seq alphabet-string) (seq (rep* (set-not "}")))) (opt "*") "}") (clean-up-quotes) (let ((name (latex-env-name token-text))) (if (list-env-p name) (progn (decf list-environment-count) (close-list) (close-list)) (close-list)))) ;; tex control sequences eg macro names (rule (seq backslash (set-not alphabet)) ;; handle single characters with a backslash in front eg \. etc. (add-as-string (escape-quotes (subseq token-text 1)))) (when-state :math (rule (seq backslash (rep* alphabet)) (open-list 'math-cs (subseq token-text 1)) (close-list))) (rule (seq backslash (rep* alphabet)) (open-list 'cs (subseq token-text 1)) (close-list)) ;; be smart about numbers (when-state :math (rule (seq backslash math-number) (open-list 'math-number token-text) (close-list))) (rule time-number ;; Dectalk speaks time numbers correctly (add-as-string token-text)) (rule text-number (open-list 'text-number token-text) (close-list)) ;; words handled according to mode (when-state :math (rule (seq "''" (rep* h-space)) (add-as-string "double-prime"))) (rule (alt alphabet (seq alphabet (rep* letter) (opt "'") (rep+ alphabet))) (if (or inline-math-flag display-math-flag) ;; In math mode, the string should be broken up ;; into strings of one character ie "a+b" is "a" ;; "+" "b" since TeX allows for only plain ;; single letter variables (loop :for ch :across token-text :do (add-as-string (string ch))) ;; Convert text to strings. Not escape quotes ;; since umlaut now handled as a letter if this ;; causes trouble, reintroduce escape_quote as ;; in. (add-as-string token-text))) (rule (seq (rep* h-space) "\"") (if inline-quote-flag (reject) (progn (setf inline-quote-flag t) (open-list 'inline-quote)))) (rule (seq (rep* h-space) "``") (unless inline-quote-flag (setf inline-quote-flag t) (open-list 'inline-quote))) (rule (seq (alt "\"" "''") (rep* h-space)) ;; matching " here is a concession (if inline-quote-flag (progn ; Marking matched inline-quote (add-as-string "''") (close-list) (setf inline-quote-flag nil)) (progn ; This does not match a quotation, so just put it in the text: (add-as-string (escape-quotes token-text))))) (rule PUNCT (add-as-string (escape-quotes token-text))) (rule (rep* h-space) (add-as-string token-text)) ;; Trap things that are not caught and echo to stderr (rule (alt control-m control-l) #|ignore|#) (rule "#" (add-as-string "#")) (rule (any) (error "This escaped ~S" token-text))) (terminate-includes)))))) (defun read-token (stream) (let ((ch (read-char stream))) (case ch ;; ((#\\)) ((#\%)) (otherwise (loop :with text = (make-array 4 :element-type 'character :adjustable t :fill-pointer 0) :while (and (char/= #\\ ch) (char/= #\% ch)) :do (vector-push-extend ch text (length text)) :finally (unread-char ch stream) (return text)))))) #+testing (with-open-file (latex #-(and) #P"~/library/informatique/standards-and-protocol/cplusplus-draft/source/grammar.tex" #P"/Volumes/USER/srv/books/informatics/standards/cplusplus-draft/source/grammar.tex") (loop :for token = (read-token latex) :while token :do (print token))) #+testing (defun getenv (var) #+clisp (ext:getenv var) #+ccl (ccl:getenv var) #-(or clisp ccl) (error "Please implement getenv in ~A" (lisp-implementation-type))) #+testing (with-open-file (latex #-(and) #P"~/library/informatique/standards-and-protocol/cplusplus-draft/source/grammar.tex" #P"/Volumes/USER/srv/books/informatics/standards/cplusplus-draft/source/grammar.tex") (scan latex :read-tex-dir (getenv "READ_TEX_DIR")))
44,271
Common Lisp
.lisp
872
30.332569
155
0.416826
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0234d9d27662c33d2efb61706bcf88fb3c0446c4c432a70d08f2f6db60087c59
5,210
[ -1 ]
5,211
reader.lisp
informatimago_lisp/languages/ruby/reader.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: reader.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Reader macros to read ruby sexps as lisp sexps. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-02-16 <PJB> Created. ;;;;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))) (eval-when (:compile-toplevel :load-toplevel :execute) (ignore-errors (delete-package "COM.INFORMATIMAGO.RUBY.READER")) (ignore-errors (delete-package "COM.INFORMATIMAGO.RUBY.RUBY")) (ignore-errors (delete-package "COM.INFORMATIMAGO.RUBY.IDENTIFIERS"))) (defpackage "COM.INFORMATIMAGO.RUBY.IDENTIFIERS" (:use) (:nicknames "RIDS")) (defpackage "COM.INFORMATIMAGO.RUBY.RUBY" (:use) (:nicknames "RUBY") (:export "DEF" "VAR-REF" "VAR-FIELD" "IDENT" "CONST" "FLOAT" "INT" "CHAR" "RETURN" "COMMAND" "COMMAND-CALL" "CALL" "VCALL" "FCALL")) (defpackage "COM.INFORMATIMAGO.RUBY.READER" (:use "COMMON-LISP") (:export "ENABLE-RUBY-READTABLE" "DISABLE-RUBY-READTABLE")) (in-package "COM.INFORMATIMAGO.RUBY.READER") (defun read-bracket-list (stream character) (declare (ignore character)) (values (read-delimited-list #\] stream))) (defun read-symbol (stream character) (declare (ignore character)) (let ((*package* (load-time-value (find-package "KEYWORD")))) (let ((symbol (read stream))) (values (if (stringp symbol) (intern symbol) symbol))))) (defun make-ruby-readtable () (let ((*readtable* (copy-readtable nil))) (set-syntax-from-char #\, #\space) (set-syntax-from-char #\] #\)) (set-syntax-from-char #\| #\a) (set-macro-character #\[ 'read-bracket-list nil) (set-macro-character #\: 'read-symbol nil) *readtable*)) (defparameter *ruby-readtable* (make-ruby-readtable)) (defmacro enable-ruby-readtable () `(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* *ruby-readtable*))) (defmacro disable-ruby-readtable () `(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil)))) (defun collect-keywords (object) (let ((kw (make-hash-table))) (labels ((collect (object) (typecase object (cons (collect (car object)) (collect (cdr object))) (keyword (setf (gethash object kw) kw))))) (collect object)) (let ((r '())) (maphash (lambda (k v) (declare (ignore v)) (push k r)) kw) (sort r (function string<))))) ;; (defparameter *ruby-asts* ;; (with-open-file (inp #P"~/src/public/lisp/ruby/ruby-1.9-1-library.ast") ;; (let ((*readtable* *ruby-readtable*)) ;; (loop ;; :for sexp = (read inp nil inp) ;; :until (eq sexp inp) ;; :collect sexp)))) ;; ;; (collect-keywords (mapcar (function third) *ruby-asts*)) ;; ;; (:! :!= :!~ :% :& :&& :* :** :+ :+@ :- :-@ :|.| :/ :|::| :< :<< :<= ;; :<=> :== :=== :=~ :> :>= :>> :@backref :@char :@const :@cvar :@float ;; :@gvar :@ident :@int :@ivar :@kw :@label :@op :@period :@regexp_end ;; :@tstring_content :alias :and :aref :aref_field :args_add ;; :args_add_block :args_add_star :args_new :arg_paren :array :assign ;; :assoclist_from_args :assoc_new :bare_assoc_hash :begin :binary ;; :blockarg :block_var :bodystmt :brace_block :break :call :case :class ;; :command :command_call :const_path_field :const_path_ref :const_ref ;; :def :defined :defs :dot2 :dot3 :do_block :dyna_symbol :else :elsif ;; :end :ensure :fcall :field :for :hash :if :ifop :if_mod :lambda ;; :massign :method_add_arg :method_add_block :mlhs_add :mlhs_add_star ;; :mlhs_new :mlhs_paren :module :mrhs_add :mrhs_add_star :mrhs_new ;; :mrhs_new_from_args :next :not :opassign :or :params :paren :program ;; :qwords_add :qwords_new :redo :regexp_add :regexp_literal :regexp_new ;; :rescue :rescue_mod :rest_param :retry :return :return0 :sclass ;; :stmts_add :stmts_new :string_add :string_concat :string_content ;; :string_dvar :string_embexpr :string_literal :super :symbol ;; :symbol_literal :top_const_ref :unary :undef :unless :unless_mod ;; :until :until_mod :var_alias :var_field :var_ref :vcall :void_stmt ;; :when :while :while_mod :xstring_add :xstring_literal :xstring_new ;; :yield :yield0 :zsuper :^ :\| :|\|\|| :~) (defun ruby-ast (ruby-text) (let ((tempfile (format nil "/tmp/ruby-ast-~8,'0X.rb" ())))) (with-output-to-file ())) (defun ripper (ruby-text) (let ((buffer (make-array 4096 :element-type 'character)) (status nil) out err) (flet ((copy (in out) (let ((read-size (read-sequence buffer in))) (write-sequence buffer out :end read-size)))) (setf out (with-output-to-string (out) (setf err (with-output-to-string (err) (let* ((p (ccl:run-program "ruby" (list "-e" "require 'ripper'" "-e" (format nil "print Ripper.sexp_raw(~S)" ruby-text)) :input nil :output :stream :error :stream :element-type 'character :external-format :utf-8)) (pout (ccl:external-process-output-stream p)) (perr (ccl:external-process-error-stream p))) (loop :do (when (listen pout) (copy pout out)) (when (listen perr) (copy perr err)) :until (setf status (ccl:external-process-status p)))))))) (when (string/= out "") out)))) (defun ripper-sexp (ruby-text) (let ((rexp-text (ripper ruby-text))) (when rexp-text (let ((*readtable* *ruby-readtable*)) (read-from-string rexp-text))))) (defun simplify-lisp-form (sexp) (if (atom sexp) sexp (case (first sexp) ((progn) (loop :with body = '() :for item :in (rest sexp) :for sitem = (simplify-lisp-form item) :do (if (and (listp sitem) (eq 'progn (first sitem))) (setf body (nconc body (rest sitem))) (setf body (nconc body (list sitem)))) :finally (return (if (null (cdr body)) (first body) `(progn ,@body))))) (otherwise `(,(first sexp) ,@(mapcar (function simplify-lisp-form) (rest sexp))))))) (defun lispify-ruby-sexp (rexp) (labels ((lispify (rexp) (if (atom rexp) (case rexp ((:!) 'not) ((:!=) '/=) ((:!~) 'regexp-match-not) ((:%) 'mod) ((:&) 'bit-and) ((:&&) 'and) ((:*) '*) ((:**) 'expt) ((:+) '+) ((:+@) '+) ; unary ((:-) '-) ((:-@) '-) ; unary ((:|.|) 'dot) ((:/) '/) ((:|::|) 'scope) ((:<) '<) ((:<<) 'shift-left) ((:<=) '<=) ((:<=>)) ((:==) '=) ((:===) 'typep) ((:=~) 'regexp-match) ((:>) '>) ((:>=) '>=) ((:>>) 'shift-right) ((:^) 'bit-xor) ((:\|) 'bit-ior) ((:|\|\||) 'or) ((:~) 'bit-not) (otherwise rexp)) (ecase (first rexp) ((:symbol_literal) (lispify (second rexp))) ((:symbol) (intern (string (second (lispify (second rexp)))) (load-time-value (find-package "KEYWORD")))) ((:@ident) `(ruby:ident ,(intern (second rexp) (load-time-value (find-package "COM.INFORMATIMAGO.RUBY.IDENTIFIERS"))))) ((:@const) `(ruby:const ,(intern (second rexp) (load-time-value (find-package "COM.INFORMATIMAGO.RUBY.IDENTIFIERS"))))) ((:@char) `(ruby:char ,(second rexp))) ((:@int) `(ruby:int ,(parse-integer (second rexp)))) ((:@float) `(ruby:int ,(let ((*read-default-float-format* 'double-float)) (read-from-string (second rexp))))) ((:unary) (assert (null (cdddr rexp))) `(,(lispify (second rexp)) ,(lispify (third rexp)))) ((:binary) (assert (null (cddddr rexp))) `(,(lispify (third rexp)) ,(lispify (second rexp)) ,(lispify (fourth rexp)))) ((:void_stmt) `(progn)) ((:stmts_new) `(progn)) ((:stmts_add) (append (lispify (second rexp)) (list (lispify (third rexp))))) ((:array) `(vector ,@(lispify (second rexp)))) ((:args_add_block) (destructuring-bind (op arguments block) rexp (if (eq block 'false) (lispify arguments) (append (lispify arguments) `(lambda () ,(lispify block)))))) ((:args_new) '()) ((:args_add) (append (lispify (second rexp)) (list (lispify (third rexp))))) ((:def) `(ruby:def ,@(mapcar (function lispify) (rest rexp)))) ((:params) (destructuring-bind (op mandatory optional rest pars2 block) rexp (append (mapcar (function lispify) mandatory) (when optional `(&optional ,@(mapcar (function lispify) optional))) (when rest `(&rest ,(lispify rest))) (when pars2 `(&pars2 ,@(mapcar (function lispify) pars2))) (when block `(&block ,(lispify block)))))) ((:var_ref) `(ruby:var-ref ,@(mapcar (function lispify) (rest rexp)))) ((:var_field) `(ruby:var-field ,@(mapcar (function lispify) (rest rexp)))) ((:paren :arg_paren) (if (null (cddr rexp)) (lispify (second rexp)) `(list ,@(mapcar (function lispify) (rest rexp))))) ((:return0) `(ruby:return)) ((:return) (destructuring-bind (op arguments) rexp `(ruby:return ,@(lispify arguments)))) ((:command) (destructuring-bind (op function arguments) rexp `(ruby:command ,(lispify function) ,@(lispify arguments)))) ((:command_call) (destructuring-bind (op function arguments) rexp `(ruby:command-call ,(lispify function) ,@(lispify arguments)))) ((:vcall) (destructuring-bind (op function) rexp `(ruby:vcall ,(lispify function)))) ((:call) (destructuring-bind (op function) rexp `(ruby:call ,(lispify function)))) ((:fcall) (destructuring-bind (op function) rexp `(ruby:fcall ,(lispify function)))) ((:method_add_arg) (destructuring-bind (op call arguments) rexp (append (lispify call) (lispify arguments)))) ((:method_add_block) (destructuring-bind (op call arguments) rexp (append (lispify call) (lispify arguments)))) ((:program) `(progn ,@(mapcar (function lispify) (rest rexp)))) ((:bodystmt) (destructuring-bind (op body rescue else ensure) rexp (flet ((generate (body rescue else) (if (or rescue else) `(handler-case ,(lispify body) ,@(lispify rescue) ,@(when else `((t ,(lispify else))))) (lispify body)))) (if ensure `(unwind-protect ,(generate body rescue else) ,(lispify ensure)) (generate body rescue else))))) ((:rescue) (destructuring-bind (op conditions variable expression rest) rexp (let ((conditions (mapcar (function lispify) conditions))) `((,(if (null (cdr conditions)) (first conditions) `(or ,@conditions)) (,(lispify variable)) ,(lispify expression)) ,@(lispify rest))))) ((:else) `(progn ,@(mapcar (function lispify) (rest rexp)))) ((:ensure) `(progn ,@(mapcar (function lispify) (rest rexp)))) (otherwise (mapcar (function lispify) rexp)) ((:@backref :@cvar :@gvar :@ivar :@kw :@label :@op :@period :@regexp_end :@tstring_content :alias :and :aref :aref_field :args_add_star :assign :assoclist_from_args :assoc_new :bare_assoc_hash :begin :binary :blockarg :block_var :brace_block :break :case :class :const_path_field :const_path_ref :const_ref :defined :defs :dot2 :dot3 :do_block :dyna_symbol :elsif :end :field :for :hash :if :ifop :if_mod :lambda :massign :mlhs_add :mlhs_add_star :mlhs_new :mlhs_paren :module :mrhs_add :mrhs_add_star :mrhs_new :mrhs_new_from_args :next :not :opassign :or :qwords_add :qwords_new :redo :regexp_add :regexp_literal :regexp_new :rescue_mod :rest_param :retry :sclass :string_add :string_concat :string_content :string_dvar :string_embexpr :string_literal :super :top_const_ref :unary :undef :unless :unless_mod :until :until_mod :var_alias :when :while :while_mod :xstring_add :xstring_literal :xstring_new :yield :yield0 :zsuper) rexp))))) (simplify-lisp-form (lispify rexp)))) (pprint (ripper-sexp (com.informatimago.common-lisp.cesarum.file:text-file-contents "test3.rb"))) (pprint (lispify-ruby-sexp (ripper-sexp (com.informatimago.common-lisp.cesarum.file:text-file-contents "ast.txt")))) (defparameter *ast* (let ((*readtable* *ruby-readtable*)) (with-open-file (in "ast.txt") (loop :for sexp = (read in nil in) :until (eq sexp in) :collect sexp)))) (loop :for (file path program) :in *ast* :do (terpri) (pprint (lispify-ruby-sexp program)))
17,779
Common Lisp
.lisp
326
37.726994
140
0.460085
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0bc2d91df80941baca0c13f78d6acf3ec877d82a27c4eb488210a0e3bbfe9f33
5,211
[ -1 ]
5,212
c-runtime.lisp
informatimago_lisp/languages/linc/c-runtime.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC.C-RUNTIME") (defun initialize () (values))
238
Common Lisp
.lisp
6
37.833333
57
0.761905
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9155fead4eefbca4af71de931ef2e42d0550359b46c5f2b8654b58f0e8230e9a
5,212
[ -1 ]
5,213
c-sexp-test.lisp
informatimago_lisp/languages/linc/c-sexp-test.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (assert (string= (with-output-to-string (*c-out*) (generate (parse-pointer-type '(|pointer| |restrict| (|pointer| |const| |int|))))) "int * const * restrict"))
328
Common Lisp
.lisp
6
49.833333
94
0.663551
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1a612970ff22d920b891e92383d73ee2347d0eaa98fd2b02953ce1e8831a9c08
5,213
[ -1 ]
5,214
c-sexp-loader.lisp
informatimago_lisp/languages/linc/c-sexp-loader.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (defun linc-eval (form) 0) (defun load-linc-file (input-file &key output-file (verbose *compile-verbose*) (print *compile-print*) (external-format :default) (if-does-not-exist :error)) (let ((*package* (com.informatimago.common-lisp.interactive.interactive:mkupack :name "com.informatimago.languages.linc.c-" :use '("COM.INFORMATIMAGO.LANGUAGES.LINC.C"))) (*readtable* (copy-readtable com.informatimago.languages.linc::*c-readtable*)) (*compile-verbose* verbose) (*compile-print* print) (warnings-p nil) (failure-p nil)) (with-open-file (input input-file :external-format external-format :if-does-not-exist (when if-does-not-exist :error)) (handler-bind ((warning (lambda (condition) (declare (ignore condition)) (incf warnings-p) nil)) (style-warning (lambda (condition) (declare (ignore condition)) nil)) (error (lambda (condition) (format *error-output* "~&;; ~A~%" condition) (invoke-restart (find-restart 'continue-translation condition))))) (loop :for form := (read input nil input) :until (eql form input) :do (when print (format t "~&~S~%" form)) (let ((result (linc-eval form))) (when verbose (format t "~&-> ~S~%" result))) :finally (return t)))))) ;;;; THE END ;;;;
2,136
Common Lisp
.lisp
41
32.341463
106
0.451721
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b6fa93f182119e5bcfc37da38a4759c5b4bbcf727af6fc359ebeb123e04f09de
5,214
[ -1 ]
5,215
c-operators.lisp
informatimago_lisp/languages/linc/c-operators.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: c-operators.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; XXX ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-07-02 <PJB> ;;;;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 "COM.INFORMATIMAGO.LANGUAGES.LINC") (make-declare variable "A variable.") (make-declare class "A class.") (make-declare struct "A struct.") (make-declare union "A union.") (make-declare type "A type.") (make-declare enum "An enum.") (make-declare function "A function.") (make-declare macro "A preprocessor macro.") (gen-operators) ;;;; THE END ;;;;
1,795
Common Lisp
.lisp
46
37.913043
83
0.601947
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
acbee7ec3411a1c69158dde66ae0c3aabcccfba5034cb518ef12ce6dd20991d9
5,215
[ -1 ]
5,216
c++.lisp
informatimago_lisp/languages/linc/c++.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: c++.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; C++ grammar. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2012-07-02 <PJB> Added this header. ;;;;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 "COM.INFORMATIMAGO.LANGUAGES.LINC") ;; hex-quad: ;; hexadecimal-digit hexadecimal-digit hexadecimal-digit hexadecimal-digit ;; ;; universal-character-name: ;; \u hex-quad ;; \U hex-quad hex-quad ;; ;; preprocessing-token: ;; header-name ;; identifier ;; pp-number ;; character-literal ;; string-literal ;; preprocessing-op-or-punc ;; each non-white-space character that cannot be one of the above ;; ;; token: ;; identifier ;; keyword ;; literal ;; operator ;; punctuator ;; ;; header-name: ;; <h-char-sequence> ;; "q-char-sequence" ;; ;; h-char-sequence: ;; h-char ;; h-char-sequence h-char ;; ;; h-char: ;; any member of the source character set except ;; new-line and > ;; ;; q-char-sequence: ;; q-char ;; q-char-sequence q-char ;; ;; q-char: ;; any member of the source character set except ;; new-line and " ;; ;; pp-number: ;; digit ;; . digit ;; pp-number digit ;; pp-number nondigit ;; pp-number e sign ;; pp-number E sign ;; pp-number . ;; ;; identifier: ;; nondigit ;; identifier nondigit ;; identifier digit ;; ;; nondigit: one of ;; universal-character-name ;; _ 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 ;; ;; digit: one of ;; 0 1 2 3 4 5 6 7 8 9 ;; ;; preprocessing-op-or-punc: one of ;; { } [ ] # ## ( ) ;; <: :> <% %> %: %:%: ; : ... ;; new delete ? :: . .* ;; + - * / % ^ & | ~ ;; ! = < > += -= *= /= %= ;; ^= &= |= << >> >>= <<= == != ;; <= >= && || ++ -- , ->* -> ;; and and_eq bitand bitor compl not not_eq ;; or or_eq xor xor_eq ;; ;; literal: ;; integer-literal ;; character-literal ;; floating-literal ;; string-literal ;; boolean-literal ;; ;; integer-literal: ;; decimal-literal integer-suffixopt ;; octal-literal integer-suffixopt ;; hexadecimal-literal integer-suffixopt ;; ;; decimal-literal: ;; nonzero-digit ;; decimal-literal digit ;; ;; octal-literal: ;; 0 ;; octal-literal octal-digit ;; ;; hexadecimal-literal: ;; 0x hexadecimal-digit ;; 0X hexadecimal-digit ;; hexadecimal-literal hexadecimal-digit ;; ;; nonzero-digit: one of ;; 1 2 3 4 5 6 7 8 9 ;; ;; octal-digit: one of ;; 0 1 2 3 4 5 6 7 ;; ;; hexadecimal-digit: one of ;; 0 1 2 3 4 5 6 7 8 9 ;; a b c d e f ;; A B C D E F ;; ;; integer-suffix: ;; unsigned-suffix long-suffixopt ;; long-suffix unsigned-suffixopt ;; ;; unsigned-suffix: one of ;; u U ;; ;; long-suffix: one of ;; l L ;; ;; character-literal: ;; 'c-char-sequence' ;; L'c-char-sequence' ;; ;; c-char-sequence: ;; c-char ;; c-char-sequence c-char ;; ;; c-char: ;; any member of the source character set except ;; the single-quote ', backslash \, or new-line character ;; escape-sequence ;; universal-character-name ;; ;; escape-sequence: ;; simple-escape-sequence ;; octal-escape-sequence ;; hexadecimal-escape-sequence ;; ;; simple-escape-sequence: one of ;; \' \" \? \\ ;; \a \b \f \n \r \t \v ;; ;; octal-escape-sequence: ;; \ octal-digit ;; \ octal-digit octal-digit ;; \ octal-digit octal-digit octal-digit ;; ;; hexadecimal-escape-sequence: ;; \x hexadecimal-digit ;; hexadecimal-escape-sequence hexadecimal-digit ;; ;; floating-literal: ;; fractional-constant exponent-partopt floating-suffixopt ;; digit-sequence exponent-part floating-suffixopt ;; ;; fractional-constant: ;; digit-sequenceopt . digit-sequence ;; digit-sequence . ;; ;; exponent-part: ;; e signopt digit-sequence ;; E signopt digit-sequence ;; ;; sign: one of ;; + - ;; ;; digit-sequence: ;; digit ;; digit-sequence digit ;; ;; floating-suffix: one of ;; f l F L ;; ;; string-literal: ;; "s-char-sequenceopt" ;; L"s-char-sequenceopt" ;; ;; s-char-sequence: ;; s-char ;; s-char-sequence s-char ;; ;; s-char: ;; any member of the source character set except ;; the double-quote ", backslash \, or new-line character ;; escape-sequence ;; universal-character-name ;; ;; boolean-literal: ;; false ;; true (translation-unit ::= ( declaration-seq[opt] )) (primary-expression ::= ( literal ) ( "this" ) ( "(" expression ")" ) ( id-expression )) (id-expression ::= ( unqualified-id ) ( qualified-id )) (unqualified-id ::= ( identifier ) ( operator-function-id ) ( conversion-function-id ) ( "~" class-name ) ( template-id )) ;; (qualify name name name (template name arg...) name ~ name) ;; (absolute-qualify name name name (template name arg...) name ~ name) (qualified-id ::= ( "::"[opt] nested-name-specifier "template"[opt] unqualified-id ) ( "::" identifier ) ( "::" operator-function-id ) ( "::" template-id )) (nested-name-specifier ::= ( class-or-namespace-name "::" nested-name-specifier[opt] ) ( class-or-namespace-name "::" "template" nested-name-specifier )) (class-or-namespace-name ::= ( class-name ) ( namespace-name )) (postfix-expression ::= ( primary-expression ) ( Postfix-expression "[" expression "]" ) ( postfix-expression "(" expression-list[opt] ")" ) ( simple-type-specifier "(" expression-list[opt] ")" ) ( "typename" "::"[opt] nested-name-specifier identifier "(" expression-list[opt] ")" ) ( "typename" "::"[opt] nested-name-specifier "template"[opt] template-id "(" expression-list[opt] ")" ) ( postfix-expression "." "template"[opt] id-expression ) ( postfix-expression "->" "template"[opt] id-expression ) ( postfix-expression "." pseudo-destructor-name ) ( postfix-expression "->" pseudo-destructor-name ) ( postfix-expression "++" ) ( postfix-expression "--" ) ( "dynamic_cast" "<" type-id ">" "(" expression ")" ) ( "static_cast" "<" type-id ">" "(" expression ")" ) ( "reinterpret_cast" "<" type-id ">" "(" expression ")" ) ( "const_cast" "<" type-id ">" "(" expression ")" ) ( "typeid" "(" expression ")" ) ( "typeid" "(" type-id ")" )) (expression-list ::= ( assignment-expression ) ( expression-list "," assignment-expression )) (pseudo-destructor-name ::= ( "::"[opt] nested-name-specifier[opt] type-name "::" "~" type-name ) ( "::"[opt] nested-name-specifier "template" template-id "::" "~" type-name ) ( "::"[opt] nested-name-specifier[opt] "~" type-name )) (unary-expression ::= ( postfix-expression ) ( "++" cast-expression ) ( "--" cast-expression ) ( unary-operator cast-expression ) ( "sizeof" unary-expression ) ( "sizeof" "(" type-id ")" ) ( new-expression ) ( delete-expression )) (unary-operator ::= "*" "&" "+" "-" "!" "~") (new-expression ::= ( "::"[opt] "new" new-placement[opt] new-type-id new-initializer[opt] ) ( "::"[opt] "new" new-placement[opt] "(" type-id ")" new-initializer[opt] )) (new-placement ::= ( "(" expression-list ")" )) (new-type-id ::= ( type-specifier-seq new-declarator[opt] )) (new-declarator ::= ( ptr-operator new-declarator[opt] ) ( direct-new-declarator )) (direct-new-declarator ::= ( "[" expression "]" ) ( direct-new-declarator "[" constant-expression "]" )) (new-initializer ::= ( "(" expression-list[opt] ")" )) (delete-expression ::= ( "::"[opt] "delete" cast-expression ) ( "::"[opt] "delete" "[" "]" cast-expression )) (cast-expression ::= ( unary-expression ) ( "(" type-id ")" cast-expression )) (pm-expression ::= ( cast-expression ) ( pm-expression ".*" cast-expression ) ( pm-expression "->*" cast-expression )) (multiplicative-expression ::= ( pm-expression ) ( multiplicative-expression "*" pm-expression ) ( multiplicative-expression "/" pm-expression ) ( multiplicative-expression "%" pm-expression )) (additive-expression ::= ( multiplicative-expression ) ( additive-expression "+" multiplicative-expression ) ( additive-expression "-" multiplicative-expression )) (shift-expression ::= ( additive-expression ) ( shift-expression "<<" additive-expression ) ( shift-expression ">>" additive-expression )) (relational-expression ::= ( shift-expression ) ( relational-expression "<" shift-expression ) ( relational-expression ">" shift-expression ) ( relational-expression "<=" shift-expression ) ( relational-expression ">=" shift-expression )) (equality-expression ::= ( relational-expression ) ( equality-expression "==" relational-expression ) ( equality-expression "!=" relational-expression )) (and-expression ::= ( equality-expression ) ( and-expression "&" equality-expression )) (exclusive-or-expression ::= ( and-expression ) ( exclusive-or-expression "^" and-expression )) (inclusive-or-expression ::= ( exclusive-or-expression ) ( inclusive-or-expression "|" exclusive-or-expression )) (logical-and-expression ::= ( inclusive-or-expression ) ( logical-and-expression "&&" inclusive-or-expression )) (logical-or-expression ::= ( logical-and-expression ) ( logical-or-expression "||" logical-and-expression )) (conditional-expression ::= ( logical-or-expression ) ( logical-or-expression "?" expression ":" assignment-expression )) (assignment-expression ::= ( conditional-expression ) ( logical-or-expression assignment-operator assignment-expression ) ( throw-expression )) (assignment-operator ::= "=" "*=" "/=" "%=" "+=" "-=" ">>=" "<<=" "&=" "^=" "|=" ) (expression ::= ( assignment-expression ) ( expression "," assignment-expression )) (constant-expression ::= ( conditional-expression )) (statement ::= ( labeled-statement ) ( expression-statement ) ( compound-statement ) ( selection-statement ) ( iteration-statement ) ( jump-statement ) ( declaration-statement ) ( try-block )) (labeled-statement ::= ( identifier ":" statement ) ( "case" constant-expression ":" statement ) ( "default" ":" statement )) (expression-statement ::= ( expression[opt] ";" )) (compound-statement ::= ( "{" statement-seq[opt] "}" )) (statement-seq ::= ( statement ) ( statement-seq statement )) (selection-statement ::= ( "if" "(" condition ")" statement ) ( "if" "(" condition ")" statement "else" statement ) ( "switch" "(" condition ")" statement )) (condition ::= ( expression ) ( type-specifier-seq declarator "=" assignment-expression )) (iteration-statement ::= ( "while" "(" condition ")" statement ) ( "do" statement "while" "(" expression ")" ";" ) ( "for" "(" for-init-statement condition[opt] ";" expression[opt] ")" statement )) (for-init-statement ::= ( expression-statement ) ( simple-declaration )) (jump-statement ::= ( "break" ";" ) ( "continue" ";" ) ( "return" expression[opt] ";" ) ( "goto" identifier ";" )) (declaration-statement ::= ( block-declaration )) (declaration-seq ::= ( declaration ) ( declaration-seq declaration )) (declaration ::= ( block-declaration ) ( function-definition ) ( template-declaration ) ( explicit-instantiation ) ( explicit-specialization ) ( linkage-specification ) ( namespace-definition )) (block-declaration ::= ( simple-declaration ) ( asm-definition ) ( namespace-alias-definition ) ( using-declaration ) ( using-directive )) (simple-declaration ::= ( decl-specifier-seq[opt] init-declarator-list[opt] ";" )) (decl-specifier ::= ( storage-class-specifier ) ( type-specifier ) ( function-specifier ) ( "friend" ) ( "typedef" )) (decl-specifier-seq ::= ( decl-specifier-seq[opt] decl-specifier )) (storage-class-specifier ::= ( "auto" ) ( "register" ) ( "static" ) ( "extern" ) ( "mutable" )) (function-specifier ::= ( "inline" ) ( "virtual" ) ( "explicit" )) (typedef-name ::= ( identifier )) (type-specifier ::= ( simple-type-specifier ) ( class-specifier ) ( enum-specifier ) ( elaborated-type-specifier ) ( cv-qualifier )) (simple-type-specifier ::= ( "::"[opt] nested-name-specifier[opt] type-name ) ( "::"[opt] nested-name-specifier "template" template-id ) ( "char" ) ( "wchar"_"t" ) ( "bool" ) ( "short" ) ( "int" ) ( "long" ) ( "signed" ) ( "unsigned" ) ( "float" ) ( "double" ) ( "void" )) (type-name ::= ( class-name ) ( enum-name ) ( typedef-name )) (elaborated-type-specifier ::= ( class-key "::"[opt] nested-name-specifier[opt] identifier ) ( "enum" "::"[opt] nested-name-specifier[opt] identifier ) ( "typename" "::"[opt] nested-name-specifier identifier ) ( "typename" "::"[opt] nested-name-specifier "template"[opt] template-id )) (enum-name ::= ( identifier )) (enum-specifier ::= ( "enum" identifier[opt] "{" enumerator-list[opt] "}" )) (enumerator-list ::= ( enumerator-definition ) ( enumerator-list "," enumerator-definition )) (enumerator-definition ::= ( enumerator ) ( enumerator "=" constant-expression )) (enumerator ::= ( identifier )) (namespace-name ::= ( original-namespace-name ) ( namespace-alias )) (original-namespace-name ::= ( identifier )) (namespace-definition ::= ( named-namespace-definition ) ( unnamed-namespace-definition )) (named-namespace-definition ::= ( original-namespace-definition ) ( extension-namespace-definition )) (original-namespace-definition ::= ( "namespace" identifier "{" namespace-body "}" )) (extension-namespace-definition ::= ( "namespace" original-namespace-name "{" namespace-body "}" )) (unnamed-namespace-definition ::= ( "namespace" "{" namespace-body "}" )) (namespace-body ::= ( declaration-seq[opt] )) (namespace-alias ::= ( identifier )) (namespace-alias-definition ::= ( "namespace" identifier "=" qualified-namespace-specifier ";" )) (qualified-namespace-specifier ::= ( "::"[opt] nested-name-specifier[opt] namespace-name )) (using-declaration ::= ( "using" "typename"[opt] "::"[opt] nested-name-specifier unqualified-id ";" ) ( "using" "::" unqualified-id ";" )) (using-directive ::= ( "using" "namespace" "::"[opt] nested-name-specifier[opt] namespace-name ";" )) (asm-definition ::= ( "asm" "(" string-literal ")" ";" )) (linkage-specification ::= ( "extern" string-literal "{" declaration-seq[opt] "}" ) ( "extern" string-literal declaration )) (init-declarator-list ::= ( init-declarator ) ( init-declarator-list "," init-declarator )) (init-declarator ::= ( declarator initializer[opt] )) (declarator ::= ( direct-declarator ) ( ptr-operator declarator )) (direct-declarator ::= ( declarator-id ) ( direct-declarator "(" parameter-declaration-clause ")" cv-qualifier-seq[opt] exception-specification[opt] ) ( direct-declarator "[" constant-expression[opt] "]" ) ( "(" declarator ")" )) (ptr-operator ::= ( "*" cv-qualifier-seq[opt] ) ( "&" ::[opt] nested-name-specifier "*" cv-qualifier-seq[opt] )) (cv-qualifier-seq ::= ( cv-qualifier cv-qualifier-seq[opt] )) (cv-qualifier ::= ( "const" ) ( "volatile" )) (declarator-id ::= ( id-expression ) ( "::"[opt] nested-name-specifier[opt] type-name )) (type-id ::= ( type-specifier-seq abstract-declarator[opt] )) (type-specifier-seq ::= ( type-specifier type-specifier-seq[opt] )) (abstract-declarator ::= ( ptr-operator abstract-declarator[opt] ) ( direct-abstract-declarator )) (direct-abstract-declarator ::= ( direct-abstract-declarator[opt] ) ( "(" parameter-declaration-clause ")" cv-qualifier-seq[opt] exception-specification[opt] ) ( direct-abstract-declarator[opt] "[" constant-expression[opt] "]" ) ( "(" abstract-declarator ")" )) (parameter-declaration-clause ::= ( parameter-declaration-list[opt] "..." [opt] ) ( parameter-declaration-list "," "..." )) (parameter-declaration-list ::= ( parameter-declaration ) ( parameter-declaration-list "," parameter-declaration )) (parameter-declaration ::= ( decl-specifier-seq declarator ) ( decl-specifier-seq declarator "=" assignment-expression ) ( decl-specifier-seq abstract-declarator[opt] ) ( decl-specifier-seq abstract-declarator[opt] "=" assignment-expression )) (function-definition ::= ( decl-specifier-seq[opt] declarator ctor-initializer[opt] function-body ) ( decl-specifier-seq[opt] declarator function-try-block )) (function-body ::= ( compound-statement )) (initializer ::= ( "=" initializer-clause ) ( "(" expression-list ")" )) (initializer-clause ::= ( assignment-expression ) ( "{" initializer-list ","[opt] "}" ) ( "{" "}" )) (initializer-list ::= ( initializer-clause ) ( initializer-list "," initializer-clause )) (class-name ::= ( identifier ) ( template-id )) (class-specifier ::= ( class-head "{" member-specification[opt] "}" )) (class-head ::= ( class-key identifier[opt] base-clause[opt] ) ( class-key nested-name-specifier identifier base-clause[opt] ) ( class-key nested-name-specifier[opt] template-id base-clause[opt] )) (class-key ::= ( "class" ) ( "struct" ) ( "union" )) (member-specification ::= ( member-declaration member-specification[opt] ) ( access-specifier ":" member-specification[opt] )) (member-declaration ::= ( decl-specifier-seq[opt] member-declarator-list[opt] ";" ) ( function-definition ";"[opt] ) ( "::"[opt] nested-name-specifier "template"[opt] unqualified-id ";" ) ( using-declaration ) ( template-declaration )) (member-declarator-list ::= ( member-declarator ) ( member-declarator-list "," member-declarator )) (member-declarator ::= ( declarator pure-specifier[opt] ) ( declarator constant-initializer[opt] ) ( identifier[opt] ":" constant-expression )) (pure-specifier ::= ( "=" "0" )) (constant-initializer ::= ( "=" constant-expression )) (base-clause ::= ( ":" base-specifier-list )) (base-specifier-list ::= ( base-specifier ) ( base-specifier-list "," base-specifier )) (base-specifier ::= ( "::"[opt] nested-name-specifier[opt] class-name ) ( "virtual" access-specifier[opt] "::"[opt] nested-name-specifier[opt] class-name ) ( access-specifier "virtual"[opt] "::"[opt] nested-name-specifier[opt] class-name )) (access-specifier ::= ( "private" ) ( "protected" ) ( "public" )) (conversion-function-id ::= ( operator conversion-type-id )) (conversion-type-id ::= ( type-specifier-seq conversion-declarator[opt] )) (conversion-declarator ::= ( ptr-operator conversion-declarator[opt] )) (ctor-initializer ::= ( ":" mem-initializer-list )) (mem-initializer-list ::= ( mem-initializer ) ( mem-initializer "," mem-initializer-list )) (mem-initializer ::= ( mem-initializer-id "(" expression-list[opt] ")" )) (mem-initializer-id ::= ( "::"[opt] nested-name-specifier[opt] class-name ) ( identifier )) (operator-function-id ::= ( operator operator )) (operator ::= "new" "delete" "new[]" "delete[]" "+" "-" "*" "/" "%" "^" "&" "|" "~" "!" "=" "<" ">" "+=" "-=" "*=" "/=" "%=" "^=" "&=" "|=" "<<" ">>" ">>=" "<<=" "==" "!=" "<=" ">=" "&&" "||" "++" "--" "","" "->*" "->" "()" "[]" ) (template-declaration ::= ( "export"[opt] "template" "<" template-parameter-list ">" declaration )) (template-parameter-list ::= ( template-parameter ) ( template-parameter-list "," template-parameter )) (template-parameter ::= ( type-parameter ) ( parameter-declaration )) (type-parameter ::= ( "class" identifier[opt] ) ( "class" identifier[opt] "=" type-id ) ( "typename" identifier[opt] ) ( "typename" identifier[opt] "=" type-id ) ( "template" "<" template-parameter-list ">" "class" identifier[opt] ) ( "template" "<" template-parameter-list ">" "class" identifier[opt] "=" id-expression )) (template-id ::= ( template-name "<" template-argument-list[opt] ">" )) (template-name ::= ( identifier )) (template-argument-list ::= ( template-argument ) ( template-argument-list "," template-argument )) (template-argument ::= ( assignment-expression ) ( type-id ) ( id-expression )) (explicit-instantiation ::= ( "template" declaration )) (explicit-specialization ::= ( "template" "<" ">" declaration )) (try-block ::= ( "try" compound-statement handler-seq )) (function-try-block ::= ( "try" ctor-initializer[opt] function-body handler-seq )) (handler-seq ::= ( handler handler-seq[opt] )) (handler ::= ( "catch" "(" exception-declaration ")" compound-statement )) (exception-declaration ::= ( type-specifier-seq declarator ) ( type-specifier-seq abstract-declarator ) ( type-specifier-seq ) ( "..." )) (throw-expression ::= ( "throw" assignment-expression[opt] )) (exception-specification ::= ( "throw" "(" type-id-list[opt] ")" )) (type-id-list ::= ( type-id ) ( type-id-list "," type-id )) (preprocessing-file ::= ( group[opt] )) (group ::= ( group-part ) ( group group-part )) (group-part ::= ( pp-tokens[opt] new-line ) ( if-section ) ( control-line )) (if-section ::= ( if-group elif-groups[opt] else-group[opt] endif-line )) (if-group ::= ( "#" "if" constant-expression new-line group[opt] ) ( "#" "ifdef" identifier new-line group[opt] ) ( "#" "ifndef" identifier new-line group[opt] )) (elif-groups ::= ( elif-group ) ( elif-groups elif-group )) (elif-group ::= ( "#" "elif" constant-expression new-line group[opt] )) (else-group ::= ( "#" "else" new-line group[opt] )) (endif-line ::= ( "#" "endif" new-line )) (control-line ::= ( "#" "include" pp-tokens new-line ) ( "#" "define" identifier replacement-list new-line ) ( "#" "define" identifier lparen identifier-list[opt] ")" replacement-list new-line ) ( "#" "undef" identifier new-line ) ( "#" "line" pp-tokens new-line ) ( "#" "error" pp-tokens[opt] new-line ) ( "#" "pragma" pp-tokens[opt] new-line ) ( "#" new-line )) (lparen ::= ( "(" #|the left-parenthesis character without preceding white-space |# )) (replacement-list ::= ( pp-tokens[opt] )) (pp-tokens ::= ( preprocessing-token ) ( pp-tokens preprocessing-token )) (new-line ::= ( #\newline #|the new-line character|# ))
24,460
Common Lisp
.lisp
909
24.30033
112
0.609567
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c58c1e8592799bcde34cf93c20a93e90f8fab8cf974dce84e96408561d4983f3
5,216
[ -1 ]
5,217
utilities.lisp
informatimago_lisp/languages/linc/utilities.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (defun find-in-tree (item tree) (cond ((null tree) nil) ((atom tree) (eql item tree)) (t (or (find-in-tree item (car tree)) (find-in-tree item (cdr tree))))))
331
Common Lisp
.lisp
9
32.666667
54
0.657321
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5bfca31089a835cb83b071df5123c82c9f700c41edc0af4bd2198f32bff2a963
5,217
[ -1 ]
5,218
readtable-test.lisp
informatimago_lisp/languages/linc/readtable-test.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (defun test/reader-c-sexp-list () (assert (equal (with-input-from-string (input " (sscanf b \"%d\" (address bv)) (sprintf res \"%d\" (+ a b)) (return res) })") (read-c-sexp-list input)) '((com.informatimago.languages.linc.c::|sscanf| com.informatimago.languages.linc.c::\b "%d" (com.informatimago.languages.linc.c::|address| com.informatimago.languages.linc.c::|bv|)) (com.informatimago.languages.linc.c::|sprintf| com.informatimago.languages.linc.c::|res| "%d" (com.informatimago.languages.linc.c::+ com.informatimago.languages.linc.c::\a com.informatimago.languages.linc.c::\b)) (com.informatimago.languages.linc.c::|return| com.informatimago.languages.linc.c::|res|)))) :success) (defun test/read-ellipsis () (map nil (lambda (result expected) (if (find expected #(simple-stream-error)) (assert (cl:typep result expected)) (assert (cl:equal result expected)))) (mapcar (lambda (string) (with-input-from-string (input string) (read-char input) (handler-case (read-ellipsis input) (error (err) err)))) '(". a b c" ".;hello d e" ".#foo d e" ".abc d e" ".. a b c" "..;hello d e" "..#foo d e" "..abc d e" "... a b c" "...;hello d e" "...#foo d e" "...abc d e")) '(|.| |.| |.#FOO| .abc simple-stream-error simple-stream-error ..\#FOO ..abc |...| |...| ...\#FOO ...abc)) :success) (enable-c-sexp-reader-macros) #-(and) (defparameter *c-source* '#{ (define-function string_add ((a (char *)) (b (char *))) (char *) (let ((av int) (bv int) (res (char *) (malloc (+ 2 (max (strlen a) (strlen b)))))) (sscanf a "%d" (address av)) (sscanf b "%d" (address bv)) (sprintf res "%d" (+ a b)) (return res))) }) ;; (print-c-sexp-form *c-source*) (defun test/all () (test/reader-c-sexp-list) (test/read-ellipsis)) (test/all)
2,635
Common Lisp
.lisp
58
30.913793
113
0.471713
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d75cada9e7e7c08078bf9206e96b0c0419227eafedfab05589117adb38e5f511
5,218
[ -1 ]
5,219
c-sexp-translator.lisp
informatimago_lisp/languages/linc/c-sexp-translator.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (defvar *translate-linc-verbose* nil) (defvar *translate-linc-print* nil) (defvar *translate-linc-pathname* nil) (defvar *translate-linc-truename* nil) (defvar *source-form* nil) (defparameter *allow-print-backtrace* t) (defun print-backtrace (&optional (output *error-output*)) #+ccl (when *allow-print-backtrace* (let ((*allow-print-backtrace* nil)) (format output "~&~80,,,'-<~>~&~{~A~%~}~80,,,'-<~>~&" (ccl::backtrace-as-list))))) (define-condition linc-error (simple-error) ()) (define-condition linc-program-error (linc-error) ((source-form :initarg :source-form :reader linc-program-error-source-form) (source-file :initarg :source-file :reader linc-program-error-source-file)) (:report (lambda (condition stream) (let ((*print-readably* nil) (*print-escape* nil) (*print-case* :downcase)) (format stream "~?~%in form: ~A~%in file: ~S~%" (simple-condition-format-control condition) (simple-condition-format-arguments condition) (linc-program-error-source-form condition) (linc-program-error-source-file condition)))))) (define-condition linc-internal-error (linc-program-error) ()) (define-condition linc-stray-atom-error (linc-program-error) ()) (define-condition linc-invalid-operator-error (linc-program-error) ()) (define-condition linc-not-implemented-yet-error (linc-program-error) ((operator :initarg :operator :reader linc-not-implemented-yet-error-operator))) (defun not-implemented-yet (operator form) (error 'linc-not-implemented-yet-error :operator operator :source-form form :source-file *translate-linc-truename* :format-control "Not implemented yet: ~S" :format-arguments (list operator))) ;;;--------------------------------------------------------------------- (defparameter *c-keywords* '(|*| |auto| |break| |case| |char| |const| |continue| |default| |do| |double| |else| |enum| |extern| |float| |for| |goto| |if| |inline| |int| |long| |register| |restrict| |return| |short| |signed| |sizeof| |static| |struct| |switch| |typedef| |union| |unsigned| |void| |volatile| |while| ;; ---- |_Alignas| |_Alignof| |_Atomic| |_Bool| |_Complex| |_Generic| |_Imaginary| |_Noreturn| |_Static_assert| |_Thread_local| ;; ---- aliases: |align-as| |align-of| |atomic| |bool| |complex| |generic| |imaginary| |noreturn| |static-assert| |thread-local|)) (defun c-keyword-p (name) (find name *c-keywords*)) (defun c-identifier-p (name) (and (symbolp name) (not (c-keyword-p name)))) (defun check-identifier (name) (unless (c-identifier-p name) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid identifier: ~S" :format-arguments (list name)))) ;;;--------------------------------------------------------------------- ;;; Pre-processor (defun parse-include (form) ;; (include <foo.h>|"foo.h" …) (let ((files (rest form))) (when (null files) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing file in include form.")) (make-instance 'c-sequence :elements (mapcar (lambda (file) (typecase file (symbol (let ((name (string file))) (if (and (< 2 (length name)) (char= #\< (aref name 0)) (char= #\> (aref name (- (length name) 1))) (not (find-if (lambda (ch) (find ch "<>")) (subseq name 1 (- (length name) 1))))) (include :system (subseq name 1 (- (length name) 1))) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid file name in include form: ~A" :format-arguments (list (symbol-name file)))))) (string (if (and (< 1 (length file)) (not (find #\" file))) (include :local file) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid file file in include form: ~S" :format-arguments (list file)))) (otherwise (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid file name in include form: ~S" :format-arguments (list file))))) files)))) ;;;--------------------------------------------------------------------- (defclass preprocessor-conditional (c-item) ((operator :initarg :operator :reader preprocessor-conditional-operator :type (member |#if| |#ifdef| |#ifndef| |#elif| |#else| |#endif|)) (expression :initarg :expression :initform nil :reader preprocessor-conditional-expression))) (defun preprocessor-conditional (operator &optional expression) (make-instance 'preprocessor-conditional :operator operator :expression expression)) (defmethod generate ((item preprocessor-conditional)) (let ((*indent* 0)) (emit :fresh-line (format nil "~(~A~)" (preprocessor-conditional-operator item))) (when (preprocessor-conditional-expression item) (emit " ") (generate (preprocessor-conditional-expression item))) (emit :newline))) #| (#ifdef test expression … #elif test expression … #else expression … #endif) (#ifdef test) expression … (#elif test) expression … (#else) expression … (#endif) |# (defun split-preprocessor (forms) (nsplit-list-on-indicator (copy-list forms) (lambda (previous current) (declare (ignore previous)) (member current '(|#ifdef| |#ifndef| |#if| |#elif| |#else| |#endif|))))) (defun parse-preprocessor (forms) (labels ((expect-argument (section) (when (null (rest section)) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing argument after ~A" :format-arguments (list (first section))))) (expect-symbol-argument (section) (expect-argument section) (unless (symbolp (second section)) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Expected a symbol argument after ~A, not the expression ~S" :format-arguments (list (first section) (second section))))) (expect-nothing (section) (when (rest section) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Expected nothing after ~A, instead got: ~A" :format-arguments (list (first section) (rest section)))))) (make-instance 'c-sequence :elements (mapcan (lambda (section) (let ((*source-form* section)) (ecase (first section) ((|#ifdef| |#ifndef|) (expect-symbol-argument section) (cons (preprocessor-conditional (first section) (second section)) (mapcar (function parse-linc-form) (rest (rest section))))) ((|#if| |#elif|) (expect-argument section) (cons (preprocessor-conditional (first section) (parse-expression (second section))) (mapcar (function parse-linc-form) (rest (rest section))))) ((|#else|) (cons (preprocessor-conditional (first section) nil) (mapcar (function parse-linc-form) (rest section)))) ((|#endif|) (expect-nothing section) (list (preprocessor-conditional (first section) nil)))))) (split-preprocessor forms))))) ;;;--------------------------------------------------------------------- ;;; Types (defparameter *storage-classes* '(|typedef| |extern| |static| |thread-local| |auto| |register|)) (defparameter *storage-classes-map* '((|thread-local| . |_Thread_local|))) (defparameter *type-qualifiers* '(|const| |restrict| |volatile| |atomic|)) (defparameter *type-qualifiers-map* '((|atomic| . |_Atomic|))) (defparameter *type-specifiers* '(|void| |char| |short| |int| |long| |float| |double| |signed| |unsigned| |bool| |complex|)) (defparameter *type-specifiers-map* '((|bool| . |_Bool|) (|complex| . |_Complex|))) (defparameter *type-constructors* '(|struct| |enum| |union| |atomic|)) (defparameter *type-declarators* '(|pointer| |array| |function|)) (defparameter *compound-types* (concatenate 'list *type-constructors* *type-declarators*)) (defun compound-type-form-p (form) (and (listp form) (find (first form) *compound-types*))) (defun function-specifier-p (item) (find item '(|inline| |noreturn| |static|))) (defparameter *scalar-types* '(((|void|)) ((|char|)) ((|signed| |char|)) ((|unsigned| |char|)) ((|short|) (|signed| |short|) (|short| |int|) (|signed| |short| |int|)) ((|unsigned| |short|) (|unsigned| |short| |int|)) ((|int|) (|signed|) (|signed| |int|)) ((|unsigned|) (|unsigned| |int|)) ((|long|) (|signed| |long|) (|long| |int|) (|signed| |long| |int|)) ((|unsigned| |long|) (|unsigned| |long| |int|)) ((|long| |long|) (|signed| |long| |long|) (|long| |long| |int|) (|signed| |long| |long| |int|)) ((|unsigned| |long| |long|) (|unsigned| |long| |long| |int|)) ((|float|)) ((|double|)) ((|long| |double|)) ((|bool|)) ((|float| |complex|)) ((|double| |complex|)) ((|long| |double| |complex|)))) (defun ensure-type-list (type) (if (or (atom type) (compound-type-form-p type)) (list type) type)) (defun split-storage-classes-and-type-qualifiers (list) (loop :for (item . rest) :on list :while (or (member item *storage-classes*) (member item *type-qualifiers*)) :if (member item *storage-classes*) :collect item :into storage-classes :else :collect item :into type-qualifiers :finally (return (values storage-classes type-qualifiers (cons item rest))))) (defun split-type (tokens) (loop :for token :in tokens :if rest :collect token :into rest :else :if (member token *storage-classes*) :collect token :into storage-classes :else :if (member token *type-qualifiers*) :collect token :into type-qualifiers :else :if (member token *type-specifiers*) :collect token :into type-specifiers :else :if (compound-type-form-p token) :collect token :into compound-types :else :if (and (null identifiers) (c-identifier-p token)) :collect token :into identifiers :else :collect token :into rest :finally (return (values storage-classes type-qualifiers type-specifiers identifiers compound-types rest)))) (defun validate-split-type (storage-classes type-qualifiers type-specifiers identifiers compound-types) (declare (ignore type-qualifiers)) ; TODO (let* ((thread-local (find '|thread-local| storage-classes)) (classes (remove thread-local storage-classes))) (when (cdr classes) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Only one storage class can be specified at once: ~A" :format-arguments (list storage-classes))) (when (and thread-local (set-difference classes '(|extern| |static|))) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "thread-local can only be specified with extern or static: ~A" :format-arguments (list storage-classes)))) (when type-specifiers (unless (validate-type type-specifiers) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid type specifier: ~A" :format-arguments (list type-specifiers)))) (unless (or type-specifiers identifiers compound-types) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "No types specifier given" :format-arguments '())) (when (or (and type-specifiers identifiers) (and type-specifiers compound-types) (and identifiers compound-types)) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Multiple types specified: ~@{~@[~{~A~^ ~}~^, ~]~}" :format-arguments (list type-specifiers identifiers compound-types))) (when (cdr identifiers) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Multiple types specified: ~{~A~^, ~}" :format-arguments (list identifiers))) (when (cdr compound-types) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Multiple compound types specified: ~{~A~^, ~}" :format-arguments (list identifiers)))) (defun map-token (token map) (or (cdr (assoc token map)) token)) (defun count-elements (list) (let ((counts '())) (dolist (element list (sort counts (function string<) :key (function car))) (let ((entry (assoc element counts))) (if (null entry) (push (cons element 1) counts) (incf (cdr entry))))))) (defun simple-type-equal-p (a b) (equal (count-elements a) (count-elements b))) (defun validate-type (type) (find-if (lambda (alternatives) (find type alternatives :test (function simple-type-equal-p))) *scalar-types*)) ;;---------------------------------------- (defclass c-type (c-item) ()) (defclass c-named-type (c-type) ((name :initarg :name :initform nil :reader c-type-name) (storage-classes :initarg :storage-classes :initform '() :reader c-type-storage-classes) (qualifiers :initarg :qualifiers :initform '() :reader c-type-qualifiers))) (defmethod generate ((item c-named-type)) (let ((storage-classes (c-type-storage-classes item)) (qualifiers (c-type-qualifiers item)) (sep "")) (dolist (storage-class storage-classes) (emit sep (map-token storage-class *storage-classes-map*)) (setf sep " ")) (dolist (qualifier qualifiers) (emit sep (map-token qualifier *type-qualifiers-map*)) (setf sep " ")) (emit sep))) ;;---------------------------------------- (defclass c-simple-type (c-named-type) ()) (defun c-simple-type (name storage-classes qualifiers) (make-instance 'c-simple-type :name name :storage-classes storage-classes :qualifiers qualifiers)) (defmethod generate ((item c-simple-type)) (let ((name (c-type-name item))) (when (null name) (error 'linc-internal-error :source-file *translate-linc-truename* :format-control "A ~S such as ~S must not have a null name" :format-arguments (list 'c-simple-type item))) (call-next-method) (if (atom name) (generate name) (let ((sep "")) (dolist (item (c-type-name item)) (emit sep (map-token item *type-specifiers-map*)) (setf sep " ")))))) ;;---------------------------------------- (defclass c-struct-union (c-named-type) ((operator :initarg :operator :reader c-struct-union-operator) (slots :initarg :slots :reader c-struct-union-slots))) (defun c-struct-union (name storage-classes qualifiers operator slots) (make-instance 'c-struct-union :name name :storage-classes storage-classes :qualifiers qualifiers :operator operator :slots slots)) (defmethod generate ((item c-struct-union)) (emit (c-struct-union-operator item)) (when (c-type-name item) (emit " ") (generate (c-type-name item))) (when (and (slot-boundp item 'slots) (not (eq :none (slot-value item 'slots)))) (emit " ") (with-parens "{}" (dolist (slot (c-struct-union-slots item)) (generate slot))))) ;;---------------------------------------- (defclass c-slot (c-item) ((name :initarg :name :reader c-slot-name) (type :initarg :type :reader c-slot-type) (bits :initarg :bits :initform nil :reader c-slot-bits))) (defun c-slot (name type bits) (make-instance 'c-slot :name name :type type :bits bits)) (defmethod generate ((item c-slot)) (emit :fresh-line) (generate (wrap-declarator (c-slot-name item) (c-slot-type item))) (let ((bits (c-slot-bits item))) (when bits (emit ":") (generate bits))) (emit ";" :newline)) (defun parse-slot (slot) (let* ((current slot) (name (pop current)) (bits (member-if (lambda (item) (and (listp item) (eql '|bit| (first item)))) current)) (type (ldiff current bits)) (bit-field-size nil)) (when bits (when (cdr bits) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid bit field size specifier ~S in slot ~S" :format-arguments (list (first bits) slot))) (setf bit-field-size (parse-expression (second (first bits))))) (c-slot name (parse-type (ensure-type-list type)) bit-field-size))) ;; types := void char short int long float double signed unsigned bool complex ;; | (struct …) | (enum …) | (union …) | (atomic …) | (pointer …) | (array …) | (function …) ;; | identifier #| (type (qualifiers…) (types…)) (type (qualifiers…) identifier) (struct (qualifiers…) name slots…) (union (qualifiers…) name slots…) (enum name values…) (type (qualifiers…) (struct identifier)) (type (qualifiers…) (struct [identifier] slots…)) (type (qualifiers…) (struct [identifier] slots…)) ;; foo (pointer const atomic unsigned int) -> (type const atomic unsigned int) ; (pointer foo) qualifier ::= const restrict volatile atomic (align-as type) (align-as size) type ::= identfier (atomic type) (struct name) -> struct name; (struct name ()) -> struct name { }; /* no slots */ (struct name slots…) -> struct name { slots… }; (struct slots…) -> struct { slots… }; (union name) (union name ()) (union name slots…) (union slots…) (enum name) (enum name values…) (enum values…) (pointer qualifiers… type) (array qualifiers|static… type [static] [expression|*]) (function ((identifer type) (type) ...) type (declare-function fname ((identifer type) (type) ...) type inline|noreturn… (block …)) slot ::= (name qualifiers… type [(bit size)]) (qualifiers… type [(bit size)]) |# (defun parse-struct-or-union-type (type) ;; (struct|union [name] [NIL]|(slot)…) (let ((operator (pop type)) (name (when (and (symbolp (first type)) (not (null (first type)))) (pop type))) (slotsp type) (slots (if type (if (null (first type)) '() type)))) (when name (check-identifier name)) (c-struct-union name nil nil operator (if slotsp (mapcar (function parse-slot) slots) :none)))) ;;---------------------------------------- (defclass c-enum (c-named-type) ((values :initarg :values :initform '() :reader c-enum-values))) (defun c-enum (name storage-classes qualifiers values) (make-instance 'c-enum :name name :storage-classes storage-classes :qualifiers qualifiers :values values)) (defmethod generate ((item c-enum)) (emit "enum") (when (c-type-name item) (emit " ") (generate (c-type-name item))) (when (c-enum-values item) (emit " ") (with-parens "{}" (dolist (value (c-enum-values item)) (generate value))))) (defclass c-enum-value (c-item) ((name :initarg :name :reader c-enum-value-name) (value :initarg :value :initform nil :reader c-enum-value-value))) (defun c-enum-value (name value) (make-instance 'c-enum-value :name name :value value)) (defmethod generate ((item c-enum-value)) (emit :fresh-line) (generate (c-enum-value-name item)) (when (c-enum-value-value item) (emit "=") (generate (c-enum-value-value item))) (emit ",") (emit :newline)) (defun parse-enum-type (form) ;; (enum [name] [storage-classes|type-qualifiers]… constant-variable (constant-variable value-expression)) (let ((current form)) (pop current) (let ((name (when (let ((item (first current))) (and (atom item) (not (or (member item *storage-classes*) (member item *type-qualifiers*))))) (pop current)))) (when name (check-identifier name)) (multiple-value-bind (storage-classes type-qualifiers values) (split-storage-classes-and-type-qualifiers current) (c-enum name storage-classes type-qualifiers (mapcar (lambda (value-form) (if (atom value-form) (progn (check-identifier value-form) (c-enum-value value-form nil)) (let* ((current value-form) (name (pop current)) (constexpr (pop current))) (when current (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Too many items in the enum value: ~S" :format-arguments (list value-form))) (check-identifier name) (c-enum-value name (parse-expression constexpr))))) values)))))) ;;;------------------------------------------------------------------------------- (defclass c-atomic (c-type) ((type :initarg :type :reader c-atomic-type))) (defun c-atomic (type) (make-instance 'c-atomic :type type)) (defmethod generate ((item c-atomic)) (emit "_Atomic") (with-parens "()" (generate (c-atomic-type item)))) (defun parse-atomic-type (form) (let ((current form)) (pop current) (c-atomic (parse-type current)))) ;;;------------------------------------------------------------------------------- (defclass c-pointer (c-type) ((type :initarg :type :reader c-pointer-type) (qualifiers :initarg :qualifiers :initform '() :reader c-type-qualifiers))) (defun c-pointer (type qualifiers) (make-instance 'c-pointer :type type :qualifiers qualifiers)) (defmethod generate ((item c-pointer)) (generate (c-pointer-type item)) (emit "*") (dolist (qualifier (c-type-qualifiers item)) (emit " " (map-token qualifier *type-qualifiers-map*)))) (defun parse-pointer-type (form) ;; (pointer qualifiers… type) (let ((current form)) (pop current) (multiple-value-bind (storage-classes type-qualifiers type-specifiers identifiers compound-types rest) (split-type current) (validate-split-type storage-classes type-qualifiers type-specifiers identifiers compound-types) (when rest (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Superfluous tokens after type: ~S" :format-arguments (list rest))) (unless (null storage-classes) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid storage class in pointer type: ~S" :format-arguments (list form))) (c-pointer (cond (type-specifiers (c-simple-type type-specifiers nil nil)) (identifiers (c-simple-type (first identifiers) nil nil)) (compound-types (parse-compound-type (first compound-types) nil nil))) type-qualifiers)))) ;;;------------------------------------------------------------------------------- (defclass c-array (c-type) ((qualifiers :initarg :qualifiers :initform '() :reader c-type-qualifiers) (storage-classes :initarg :storage-classes :initform '() :reader c-type-storage-classes) (element-type :initarg :element-type :reader c-array-element-type) (element-count :initarg :element-count :initform nil :reader c-array-element-count))) (defun c-array (type-qualifiers storage-classes element-type element-count) (make-instance 'c-array :qualifiers type-qualifiers :storage-classes storage-classes :element-type element-type :element-count element-count)) (defmethod generate ((item c-array)) (generate (c-array-element-type item)) (with-parens "[]" (let ((sep "")) (dolist (storage-class (c-type-storage-classes item)) (emit sep (map-token storage-class *storage-classes-map*)) (setf sep " ")) (dolist (qualifier (c-type-qualifiers item)) (emit sep (map-token qualifier *type-qualifiers-map*)) (setf sep " ")) (when (c-array-element-count item) (emit sep) (generate (c-array-element-count item)))))) (defun parse-array-type (form) ;; (array (type) qualifiers|static… [expression|*]) (let ((current form)) (pop current) (let* ((type (pop current)) (element-type (if (and type (or (symbolp type) (listp type))) (parse-type (ensure-type-list type)) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid element-type array type: ~S" :format-arguments (list type))))) (multiple-value-bind (storage-classes type-qualifiers current) (split-storage-classes-and-type-qualifiers current) (unless (or (null storage-classes) (equal storage-classes '(|static|))) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid storage class in array type: ~S" :format-arguments (list storage-classes))) (let ((element-count (cond ((null current) nil) ((eql '* (first current)) (pop current)) (t (parse-expression (pop current)))))) (when current (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid tokens in array type: ~S" :format-arguments (list current))) (c-array type-qualifiers storage-classes element-type element-count)))))) ;;;------------------------------------------------------------------------------- (defclass c-parameter (c-item) ((name :initarg :name :initform nil :reader c-parameter-name) (type :initarg :type :reader c-parameter-type))) (defun c-parameter (name type) (make-instance 'c-parameter :name name :type type)) (defmethod generate ((item c-parameter)) (generate (c-parameter-type item)) (when (c-parameter-name item) (emit " ") (generate (c-parameter-name item)))) (defun parse-function-parameter (form) ;; ([identifer] type) (let ((name (first form))) (if (and (not (null name)) (symbolp name) (not (member name *storage-classes*)) (not (member name *type-qualifiers*)) (not (member name *type-specifiers*)) (not (null (second form)))) (c-parameter name (parse-type (rest form))) (c-parameter nil (parse-type form))))) ;;;------------------------------------------------------------------------------- (defclass c-ftype (c-type) ((parameters :initarg :parameters :reader c-ftype-parameters) (result-type :initarg :result-type :reader c-ftype-result-type))) (defun c-ftype (parameters result-type) (make-instance 'c-ftype :parameters parameters :result-type result-type)) (defmethod generate ((item c-ftype)) (generate (c-ftype-result-type item)) (emit " ") (with-parens "()" (emit "*")) (with-parens "()" (let ((sep "")) (dolist (parameter (c-ftype-parameters item)) (emit sep) (generate parameter) (setf sep ", "))))) (defun parse-function-signature (form) ;; ((([identifer] type) |...|) type [inline|noreturn|static]… body…) (check-type form list) (let ((current form)) (unless (listp (first current)) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid parameter list in function signature: ~S" :format-arguments (list (first current)))) (let ((parameters (mapcar (lambda (parameter) (if (eql parameter '|...|) parameter (parse-function-parameter (if (atom parameter) (list parameter) parameter)))) (pop current)))) (let ((ellipsis (member '|...| parameters))) (when (rest ellipsis) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid parameter list in function signature; ellipsis must be last: ~S" :format-arguments (list ellipsis)))) (unless current (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing return-type in signature signature: ~S" :format-arguments (list form))) (let* ((type (pop current)) (return-type (parse-type (ensure-type-list type))) (specifiers (loop :while (function-specifier-p (first current)) :collect (pop current) :into specifiers :finally (return (delete-duplicates specifiers)))) (body (ensure-block current))) (values parameters return-type specifiers body))))) (defun parse-function-type (form) ;; (function (([identifer] type) |...|) type) (let ((current form)) (pop current) (multiple-value-bind (parameters return-type specifiers body) (parse-function-signature current) (when specifiers (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Unexpected function specifiers in function type declaration ~S" :format-arguments (list specifiers))) (when body (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Unexpected function body in function type declaration ~S" :format-arguments (list body))) (c-ftype parameters return-type)))) ;;;------------------------------------------------------------------------------- (defun parse-compound-type (form storage-class type-qualifiers) ;; (struct …) | (enum …) | (union …) | (atomic …) | (pointer …) | (array …) | (function …) (when (atom form) (error 'linc-internal-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid compound type: ~A" :format-arguments (list form))) (when (or storage-class type-qualifiers) (error 'linc-internal-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Compound type cannot take storage classes or type qualifiers for now: ~S ~S" :format-arguments (list storage-class type-qualifiers))) (case (first form) ((|struct| |union|) (parse-struct-or-union-type form)) ((|enum|) (parse-enum-type form)) ((|atomic|) (parse-atomic-type form)) ((|pointer|) (parse-pointer-type form)) ((|array|) (parse-array-type form)) ((|function|) (parse-function-type form)) (otherwise (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid compound type: ~A" :format-arguments (list form))))) (defun parse-type (type) (multiple-value-bind (storage-classes type-qualifiers type-specifiers identifiers compound-types rest) (split-type type) (validate-split-type storage-classes type-qualifiers type-specifiers identifiers compound-types) (when rest (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Superfluous tokens after type: ~S" :format-arguments (list rest))) (cond (type-specifiers (c-simple-type type-specifiers storage-classes type-qualifiers)) (identifiers (c-simple-type (first identifiers) storage-classes type-qualifiers)) (compound-types (parse-compound-type (first compound-types) storage-classes type-qualifiers))))) ;;;--------------------------------------------------------------------- (defclass c-declaration (c-item) ((declared :initarg :declared :reader c-declaration-declared))) (defun c-declaration (declared) (make-instance 'c-declaration :declared declared)) (defmethod generate ((item c-declaration)) (emit :fresh-line) (generate (c-declaration-declared item)) (emit ";" :newline)) (defmethod ensure-statement ((item c-declaration)) item) ;;;--------------------------------------------------------------------- (defclass c-definition (c-item) ((defined :initarg :defined :reader c-definition-defined) (needs-semicolon :initarg :needs-semicolon :initform t :reader c-definition-needs-semicolon-p))) (defun c-definition (defined &key (needs-semicolon t)) (make-instance 'c-definition :defined defined :needs-semicolon needs-semicolon)) (defmethod generate ((item c-definition)) (emit :fresh-line) (generate (c-definition-defined item)) (when (c-definition-needs-semicolon-p item) (emit ";")) (emit :newline)) (defmethod ensure-statement ((item c-definition)) item) ;;;--------------------------------------------------------------------- (defclass c-typedef (c-item) ((name :initarg :name :reader c-typedef-name) (type :initarg :type :reader c-typedef-type))) (defun c-typedef (name type) (check-type name symbol) (check-type type c-type) (make-instance 'c-typedef :name name :type type)) (defmethod generate ((item c-typedef)) (emit "typedef" " ") (generate (wrap-declarator (c-typedef-name item) (c-typedef-type item)))) (defun parse-declare-struct-or-union (operator form) ;; (declare-structure name slots) ;; (declare-union name alternatives) (let ((name-and-slots form)) (pop name-and-slots) (let ((name (first name-and-slots))) (check-identifier name)) (c-declaration (parse-struct-or-union-type `(,operator ,@name-and-slots))))) (defun parse-declare-structure (form) ;; (declare-structure name slots) (parse-declare-struct-or-union '|struct| form)) (defun parse-declare-union (form) ;; (declare-union name alternatives) (parse-declare-struct-or-union '|union| form)) (defun parse-declare-enumeration (form) ;; (declare-enumeration name values) (let ((name-and-values form)) (pop name-and-values) (let ((name (first name-and-values))) (check-identifier name)) (c-declaration (parse-enum-type `(|enum| ,@name-and-values))))) (defun parse-declare-type (form) ;; (declare-type name type) (let ((type form)) (pop type) (let ((name (pop type))) (check-identifier name) (when (null type) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing type in declare-type form: ~S" :format-arguments (list form))) (c-declaration (c-typedef name (parse-type type)))))) ;;;--------------------------------------------------------------------- (defclass c-constant (c-item) ((name :initarg :name :reader c-constant-name) (type :initarg :type :reader c-constant-type) (value :initarg :value :initform nil :reader c-constant-value))) (defun c-constant (name type value) (check-type name symbol) (check-type type c-type) (check-type value (or null c-expression)) (make-instance 'c-constant :name name :type type :value value)) (defmethod generate ((item c-constant)) (emit "const" " ") (generate (c-constant-type item)) (emit " ") (generate (c-constant-name item)) (when (c-constant-value item) (emit " " "=" " ") (generate (c-constant-value item)))) (defun parse-declare-constant (form) ;; (declare-constant name type) (let ((current form)) (pop current) (let ((name (pop current))) (check-identifier name) (when (null current) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing type in declare-constant form: ~S" :format-arguments (list form))) (let ((type (pop current))) (when current (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Superfluous tokens define-constant form: ~S" :format-arguments (list form))) (c-declaration (c-constant name (parse-type (if (listp type) type (list type))) nil)))))) (defun parse-define-constant (form) ;; (define-constant name type value) (let ((current form)) (pop current) (let ((name (pop current))) (check-identifier name) (when (null current) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing type in define-constant form: ~S" :format-arguments (list form))) (let ((type (pop current))) (when (null current) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing value in define-constant form: ~S" :format-arguments (list form))) (let ((valuep current) (value (pop current))) (c-definition (c-constant name (parse-type type) (if (and valuep (null value)) (c-literal value) (parse-expression value))))))))) ;;;--------------------------------------------------------------------- (defclass c-variable (c-expression) ((name :initarg :name :reader c-variable-name) (type :initarg :type :reader c-variable-type) (value :initarg :value :initform nil :reader c-variable-value))) (defun c-variable (name type value) (check-type name symbol) (check-type type c-type) (check-type value (or null c-expression)) (make-instance 'c-variable :name name :type type :value value)) (defmethod generate ((item c-variable)) (generate (wrap-declarator (c-variable-name item) (c-variable-type item))) (when (c-variable-value item) (emit " " "=" " ") (generate (c-variable-value item)))) (defun parse-declare-variable (form) ;; (declare-variable name type) (let ((type form)) (pop type) (let ((name (pop type))) (check-identifier name) (when (null type) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing type in declare-variable form: ~S" :format-arguments (list form))) (c-declaration (c-variable name (parse-type type) nil))))) (defun parse-define-variable (form) ;; (define-variable name type value) (let ((current form)) (pop current) (let ((name (pop current))) (check-identifier name) (when (null current) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing type in define-variable form: ~S" :format-arguments (list form))) (let ((type (pop current))) (when (null current) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing value in define-variable form: ~S" :format-arguments (list form))) (let ((valuep current) (value (pop current))) (c-definition (c-variable name (parse-type (ensure-type-list type)) (if (and valuep (null value)) (c-literal value) (parse-expression value))))))))) ;;;--------------------------------------------------------------------- (defclass c-function (c-item) ((name :initarg :name :reader c-function-name) (parameters :initarg :parameters :reader c-function-parameters) (result-type :initarg :result-type :reader c-function-result-type) (specifiers :initarg :specifiers :reader c-function-specifiers :initform nil) (body :initarg :body :reader c-function-body :initform nil))) (defun c-function (name parameters result-type specifiers body) (check-type name symbol) (check-type parameters list) (assert (every (lambda (item) (cl:typep item 'c-parameter)) parameters) (parameters)) (check-type result-type c-type) (check-type specifiers list) (check-type body (or null c-statement)) (make-instance 'c-function :name name :parameters parameters :result-type result-type :specifiers specifiers :body body)) (defmethod generate ((item c-function)) (emit :fresh-line) (let ((sep "")) (dolist (specifier (c-function-specifiers item)) (emit sep) (generate specifier) (setf sep " ")) (emit sep) (generate (c-function-result-type item))) (emit " ") (generate (c-function-name item)) (with-parens "()" (let ((sep "")) (dolist (parameter (c-function-parameters item)) (emit sep) (generate (wrap-declarator (c-parameter-name parameter) (c-parameter-type parameter))) (setf sep ", ")))) (when (c-function-body item) (emit :newline) (generate (c-function-body item)) (emit :newline))) (defun parse-declare-function (form) ;; (declare-function name lambda-list type [inline] [noreturn]) (let ((current form)) (pop current) (let ((name (pop current))) (check-identifier name) (multiple-value-bind (parameters return-type specifiers body) (parse-function-signature current) (when body (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Unexpected function body in function declaration ~S" :format-arguments (list body))) (c-declaration (c-function name parameters return-type specifiers nil)))))) (defun parse-define-function (form) ;; (define-function name lambda-list type [inline] [noreturn] [static] &body body) (let ((current form)) (pop current) (let ((name (pop current))) (check-identifier name) (multiple-value-bind (parameters return-type specifiers body) (parse-function-signature current) (unless body (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Missing function body in function definition ~S" :format-arguments (list form))) (c-definition (c-function name parameters return-type specifiers body) :needs-semicolon nil))))) ;;;--------------------------------------------------------------------- (defclass c-declarator (c-item) ((type :initarg :type :accessor c-declarator-type) (declarator :initarg :declarator :accessor c-declarator-declarator))) (defmethod generate ((item c-declarator)) (when (slot-boundp item 'type) (generate (c-declarator-type item)) (emit " ")) (generate (c-declarator-declarator item))) (defclass c-pointer-declarator (c-declarator) ((qualifiers :initarg :qualifiers :accessor c-pointer-declarator-qualifiers))) (defmethod generate ((item c-pointer-declarator)) (when (slot-boundp item 'type) (generate (c-declarator-type item)) (emit " ")) (with-parens "()" (emit "*") (dolist (qualifier (c-pointer-declarator-qualifiers item)) (emit " ") (generate qualifier)) (emit " ") (generate (c-declarator-declarator item))) ;; (typecase (c-declarator-declarator item) ;; ((or c-identifier ;; c-pointer-declarator ;; c-function-declarator ;; symbol) ;; (generate (c-declarator-declarator item))) ;; (t ;; (with-parens "()" ;; ))) ) (defclass c-array-declarator (c-declarator) ((qualifiers :initarg :qualifiers :accessor c-array-declarator-qualifiers) (size-expression :initarg :size-expression :accessor c-array-declarator-size-expression))) (defmethod generate ((item c-array-declarator)) (when (slot-boundp item 'type) (generate (c-declarator-type item)) (emit " ")) (generate (c-declarator-declarator item)) (with-parens "[]" (let ((sep "")) (dolist (qualifier (c-array-declarator-qualifiers item)) (emit sep) (setf sep " ") (generate qualifier)) (emit sep) (generate (c-array-declarator-size-expression item))))) (defclass c-function-declarator (c-declarator) ((parameters :initarg :parameters :accessor c-function-declarator-parameters))) (defmethod generate ((item c-function-declarator)) (when (slot-boundp item 'type) (generate (c-declarator-type item))) (with-parens "()" (emit "*") (generate (c-declarator-declarator item))) (with-parens "()" (let ((sep "")) (dolist (parameter (c-function-declarator-parameters item)) (emit sep) (setf sep ",") (generate (wrap-declarator (c-parameter-name parameter) (c-parameter-type parameter))))))) ;;;------------------------------------------------------------------------------- (defgeneric wrap-declarator (declarator type) (:method (declarator (type c-named-type)) (make-instance 'c-declarator :declarator declarator :type type)) (:method (declarator (type c-atomic)) (make-instance 'c-declarator :declarator declarator :type type)) (:method (declarator (type c-pointer)) (make-instance 'c-pointer-declarator :declarator declarator :type (c-pointer-type type) :qualifiers (c-type-qualifiers type))) (:method (declarator (type c-array)) (make-instance 'c-array-declarator :declarator declarator :type (c-array-element-type type) :size-expression (c-array-element-count type) :qualifiers (c-type-qualifiers type))) (:method (declarator (type c-ftype)) (make-instance 'c-function-declarator :declarator declarator :type (c-ftype-result-type type) :parameters (c-ftype-parameters type)))) (defgeneric wrap-declarator (declarator type) (:method (declarator (type c-named-type)) (make-instance 'c-declarator :declarator declarator :type type)) (:method (declarator (type c-atomic)) (make-instance 'c-declarator :declarator declarator :type type)) (:method (declarator (type c-pointer)) (wrap-declarator (make-instance 'c-pointer-declarator :declarator declarator :qualifiers (c-type-qualifiers type)) (c-pointer-type type))) (:method (declarator (type c-array)) ;; int [3] [42] foo ;; int [3] foo [42] ;; int foo [42] [3] (wrap-declarator (make-instance 'c-array-declarator :declarator declarator :size-expression (c-array-element-count type) :qualifiers (c-type-qualifiers type)) (c-array-element-type type))) (:method (declarator (type c-ftype)) (wrap-declarator (make-instance 'c-function-declarator :declarator declarator :parameters (c-ftype-parameters type)) (c-ftype-result-type type)))) ;;;--------------------------------------------------------------------- (defclass c-macro (c-item) ((name :initarg :name :reader c-macro-name) (parameters :initarg :parameters :reader c-macro-parameters :initform nil) (expansion :initarg :expansion :reader c-macro-expansion))) (defun c-macro (name parameters expansion) (check-type name symbol) (check-type parameters list) (check-type expansion string) (make-instance 'c-macro :name name :parameters parameters :expansion expansion)) (defmethod generate ((item c-macro)) (emit :fresh-line "#define" " ") (generate (c-macro-name item)) (when (c-macro-parameters item) (with-parens "()" (let ((sep "")) (dolist (parameter (c-macro-parameters item)) (emit sep) (generate parameter) (setf sep ", "))))) (emit " ") (emit (c-macro-expansion item)) (emit :newline)) (defun parse-define-macro (form) ;; (define-macro name [lambda-list] expansion-string) (let ((current form)) (pop current) (let ((name (pop current))) (check-identifier name) (flet ((check-eof (current) (when current (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Superfluous tokens after macro expansion: ~S" :format-arguments (list current)))) (check-expansion (expansion) (unless (stringp expansion) (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "A C macro expansion must be a string, not ~S" :format-arguments (list expansion))))) (if (listp (first current)) (let ((parameters (pop current)) (expansion (pop current))) (check-eof current) (check-expansion expansion) (dolist (parameter parameters) (check-identifier parameter)) (c-definition (c-macro name parameters expansion) :needs-semicolon nil)) (let ((expansion (pop current))) (check-eof current) (check-expansion expansion) (c-definition (c-macro name nil expansion) :needs-semicolon nil))))))) ;;;--------------------------------------------------------------------- (defun parse-expression (expression) (if (atom expression) (if (symbolp expression) (c-varref expression) (c-literal expression)) (let* ((operator (first expression)) (arguments (if (member operator '(com.informatimago.languages.linc.c:|cast|)) (rest expression) (mapcar (function parse-expression) (rest expression))))) (flet ((op-or-call () (cond ((c-operator-p operator) (apply operator arguments)) ((symbolp operator) (apply (function expr-call) operator arguments)) (t (error 'linc-program-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid operator ~S in expression ~S" :format-arguments (list operator expression)))))) (case operator ((com.informatimago.languages.linc.c:+) (if (= 1 (length arguments)) (expr-pos (first arguments)) (op-or-call))) ((com.informatimago.languages.linc.c:-) (if (= 1 (length arguments)) (expr-neg (first arguments)) (op-or-call))) ((com.informatimago.languages.linc.c:*) (if (= 1 (length arguments)) (expr-deref (first arguments)) (op-or-call))) ((com.informatimago.languages.linc.c:&) (if (= 1 (length arguments)) (expr-address (first arguments)) (op-or-call))) ((com.informatimago.languages.linc.c:|::|) (apply (if (= 1 (length arguments)) (function absolute-scope) (function expr-scope)) arguments)) ((com.informatimago.languages.linc.c:|cast|) (expr-cast (parse-expression (first arguments)) (parse-type (rest arguments)))) ((com.informatimago.languages.linc.c:|post--|) (expr-postdecr (first arguments))) ((com.informatimago.languages.linc.c:|post++|) (expr-postincr (first arguments))) (otherwise (op-or-call))))))) ;; (enable-c-sexp-reader-macros) ;; (parse-expression (first '{ (= a (? (== a (cast 0 int)) 1 (+ a (* b (- c d))))) })) ;; (parse-expression (first '{ (cast (+ 1 41) unsigned int) })) (defun ensure-block (forms) ;; ((print 'hi)) ;; ((print 'hi) (print 'lo)) ;; ((|block| (print 'hi) (print 'lo))) (cond ((null forms) nil) ((and (= 1 (length forms)) (listp (first forms)) (member (first (first forms)) '(|block| |let| |let*|))) (parse-statement (first forms))) (t (parse-statement `(|block| ,@forms))))) (defvar *linc-macros* (make-hash-table)) (defun linc-macro-p (name) (gethash name *linc-macros*)) (defun linc-macroexpand (form) (funcall (or (gethash (first form) *linc-macros*) (error "Not a linc macro ~S" (first form))) form)) (defmacro define-linc-macro (name (&rest lambda-list) &body body) (let ((whole (gensym))) `(progn (setf (gethash ',name *linc-macros*) (lambda (,whole) (destructuring-bind (,@lambda-list) (rest ,whole) (block ,name ,@body)))) ',name))) (define-linc-macro |let| ((&rest bindings) &body body) (let ((temps (mapcar (lambda (binding) (gentemp (format nil "temp-~(~A~)" (first binding)) *c-package-name*)) bindings))) `(|block| ,@(mapcar (lambda (temp binding) `(|define-variable| ,temp ,@(rest binding))) temps bindings) ,@(mapcar (lambda (temp binding) `(|define-variable| ,@(subseq binding 0 2) ,temp)) temps bindings) ,@body))) (define-linc-macro |let*| ((&rest bindings) &body body) `(|block| ,@(mapcar (lambda (binding) `(|define-variable| ,@binding)) bindings) ,@body)) ;; (pprint (linc-macroexpand (first '{(let* ((a int 42) (b int (+ a 2))) (print a b))}))) ;; --> (|block| ;; (|define-variable| COM\.INFORMATIMAGO\.LANGUAGES\.LINC\.C::\a |int| 42) ;; (|define-variable| COM\.INFORMATIMAGO\.LANGUAGES\.LINC\.C::\b |int| (COM\.INFORMATIMAGO\.LANGUAGES\.LINC\.C:+ COM\.INFORMATIMAGO\.LANGUAGES\.LINC\.C::\a 2)) ;; (COM\.INFORMATIMAGO\.LANGUAGES\.LINC\.C::|print| COM\.INFORMATIMAGO\.LANGUAGES\.LINC\.C::\a COM\.INFORMATIMAGO\.LANGUAGES\.LINC\.C::\b)) (define-linc-macro |cond| (&rest clauses) (case (length clauses) (0 `(block)) (1 `(if ,(first (first clauses)) (block ,@(rest (first clauses))))) (otherwise ))) (defun parse-statement (form) (if (atom form) (stmt-expr (parse-expression form)) (case (first form) ;; 0-ary ((|break|) (stmt-break)) ((|continue|) (stmt-continue)) ;; 1-ary ((|label|) (stmt-label (c-identifier (second form)))) ((|goto|) (stmt-goto (c-identifier (second form)))) ;; ((asm) (stmt-asm (second form))) ;; 0/1-ary ((|return|) (if (rest form) (stmt-return (parse-expression (second form))) (stmt-return))) ;; any-ary ((|block|) (stmt-block (mapcar (function parse-statement) (rest form)))) ((|while|) (stmt-while (ensure-block (rest (rest form))) (parse-expression (second form)))) ((|do|) (let ((while (last form 2)) (body (butlast (rest form) 2))) (unless (eql '|while| (first while)) (error "syntax error in (do … while test)")) (stmt-do (ensure-block body) (parse-expression (second while))))) ((|case|) (stmt-case (parse-expression (second form)) (ensure-block (rest (rest form))))) ((|default|) (stmt-default (ensure-block (rest form)))) ;; syntax ((|if|) (destructuring-bind (if test then &optional else) form (declare (ignore if)) (stmt-if (parse-statement then) (when else (parse-statement else)) (parse-expression test)))) ((|for|) (destructuring-bind (for (init test step) &body body) form (declare (ignore for)) (stmt-for (parse-expression init) ; TODO declarator!!! (parse-expression test) (parse-expression step) (ensure-block body)))) ((|switch|) (destructuring-bind (switch expression &body body) form (declare (ignore switch)) (stmt-switch (ensure-block body) (parse-expression expression)))) ;; local declarations or definitions (all but function definitions): ((|declare-structure|) (parse-declare-structure form)) ((|declare-union|) (parse-declare-union form)) ((|declare-type|) (parse-declare-type form)) ((|declare-enumeration|) (parse-declare-enumeration form)) ((|declare-constant|) (parse-declare-constant form)) ((|declare-variable|) (parse-declare-variable form)) ((|declare-function|) (parse-declare-function form)) ((|define-constant|) (parse-define-constant form)) ((|define-variable|) (parse-define-variable form)) ((|define-macro|) (parse-define-macro form)) ;; macros or function calls: (otherwise (if (linc-macro-p (first form)) (parse-statement (linc-macroexpand form)) (stmt-expr (parse-expression form))))))) ;;;--------------------------------------------------------------------- (defun parse-linc-form (form) (cond ((stringp form) (c-comment form)) ((atom form) (error 'linc-stray-atom-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Stray atom in C-sexp source: ~S; ignored." :format-arguments (list form))) (t (let ((op (first form))) (case op ((|include|) (parse-include form)) ((|#ifdef| |#ifndef| |#if| |#elif| |#else| |#endif|) (parse-preprocessor form)) ((|declare-structure|) (parse-declare-structure form)) ((|declare-union|) (parse-declare-union form)) ((|declare-type|) (parse-declare-type form)) ((|declare-enumeration|) (parse-declare-enumeration form)) ((|declare-constant|) (parse-declare-constant form)) ((|declare-variable|) (parse-declare-variable form)) ((|declare-function|) (parse-declare-function form)) ((|define-constant|) (parse-define-constant form)) ((|define-variable|) (parse-define-variable form)) ((|define-function|) (parse-define-function form)) ((|define-macro|) (parse-define-macro form)) (otherwise (error 'linc-invalid-operator-error :source-form *source-form* :source-file *translate-linc-truename* :format-control "Invalid operator: ~S" :format-arguments (list op)))))))) (defun translate-linc-form (*source-form*) (let ((item (parse-linc-form *source-form*))) (with-output-to-string (*c-out*) (generate item)))) (defun translate-linc-file (input-file &key output-file (verbose *translate-linc-verbose*) (print *translate-linc-print*) (external-format :default)) (with-open-file (input input-file :external-format external-format) (with-open-file (output (or output-file (make-pathname :type "c" :case :local :defaults input-file)) :direction :output :external-format external-format :if-does-not-exist :create :if-exists :supersede) (write-line "/* ------------------------- DO NOT EDIT! --------------------------------- */" output) (write-line "/* WARNING: This file is generated automatically by LINC from the source */" output) (let ((name (namestring input-file))) (format output "/* file ~VA */~%" (- 78 3 5 3) name)) (write-line "/* ------------------------- DO NOT EDIT! --------------------------------- */" output) (terpri output) (let ((temp-package (let ((*package* *package*)) (com.informatimago.common-lisp.interactive.interactive:mkupack :name (format nil "com.informatimago.languages.linc.c.~(~A~)." (file-namestring input)) :use '("COM.INFORMATIMAGO.LANGUAGES.LINC.C"))))) (unwind-protect (let ((*package* temp-package) (*readtable* (copy-readtable com.informatimago.languages.linc::*c-readtable*)) (*translate-linc-verbose* verbose) (*translate-linc-print* print) (*translate-linc-pathname* (pathname input)) (*translate-linc-truename* (truename input)) (warnings-p nil) (failures-p nil)) (handler-bind ((warning (lambda (condition) (declare (ignore condition)) (if warnings-p (incf warnings-p) (setf warnings-p 1)) nil)) (style-warning (lambda (condition) (declare (ignore condition)) nil)) (linc-error (lambda (condition) (if failures-p (incf failures-p) (setf failures-p 1)) (format *error-output* "~&ERROR: ~{~A~%~^ ~}" (split-sequence #\newline (princ-to-string condition))) (finish-output *error-output*) (invoke-restart (find-restart 'continue-translation condition))))) (loop :for form := (read input nil input) :until (eql form input) :do (when print (let ((*print-pretty* t) (*print-right-margin* 120)) (format t "~&~S~%" form))) (with-simple-restart (continue-translation "Continue Translation") (let ((code (translate-linc-form form))) (when verbose (format t "~&~{;; ~A~%~}" (split-sequence #\newline code))) (write-string code output))) :finally (return (values (truename output) warnings-p failures-p))))) (delete-package temp-package)))))) ;;;; THE END ;;;;
71,545
Common Lisp
.lisp
1,418
37.61354
164
0.531236
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c96ddaa1e6dafbd20fa3db7b23bb5662766268348255ea0acf2dbcaad75e882a
5,219
[ -1 ]
5,220
c-syntax-test.lisp
informatimago_lisp/languages/linc/c-syntax-test.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (assert (equal (camel-case (symbol-name 'com.informatimago.languages.linc.c::my-var) :capitalize-initial nil) "myVar")) (defmacro check-emited (form expected) `(let ((result (with-output-to-string (*c-out*) ,form))) (assert (equal result ,expected) () "Evaluating ~S~% returned ~S~% instead of ~S" ',form result ,expected))) (defmacro check-item-and-emited (form expected) `(progn ;; TODO: implement an equal method on c-item (assert (equal (read-from-string (prin1-to-string ,form)) (read-from-string (prin1-to-string (eval ',form))))) (check-emited (generate ,form) ,expected))) (check-emited (emit (camel-case (symbol-name 'com.informatimago.languages.linc.c::printf) :capitalize-initial nil)) "printf") (check-emited (generate 'com.informatimago.languages.linc.c::my-var) "myVar") (assert (equal (c-sexp 'com.informatimago.languages.linc.c::my-var) ''com.informatimago.languages.linc.c::my-var)) (check-emited (generate "hello world\\r") "\"hello world\\r\"") (check-emited (dolist (x (list 0 -1 1 -128 127 128 -32768 32767 32768 (- (expt 2 31)) (1- (expt 2 31)) (expt 2 31) (- (expt 2 32)) (1- (expt 2 32)) (expt 2 32) (- (expt 2 63)) (1- (expt 2 63)) (expt 2 63) (- (expt 2 64)) (1- (expt 2 64)) (expt 2 64) (- (expt 2 127)) (1- (expt 2 127)) (expt 2 127) (- (expt 2 128)) (1- (expt 2 128)) (expt 2 128))) (block go-on (handler-bind ((error (lambda (err) (declare (ignore err)) ;; (princ err) (terpri) (return-from go-on)))) (generate x))) (emit ", ")) "0, -1, 1, -128, 127, 128, -32768, 32767, 32768, -2147483648, 2147483647, 2147483648L, -4294967296L, 4294967295L, 4294967296L, -9223372036854775808L, 9223372036854775807L, 9223372036854775808L, -18446744073709551616L, 18446744073709551615L, 18446744073709551616L, -170141183460469231731687303715884105728LL, 170141183460469231731687303715884105727LL, 170141183460469231731687303715884105728LL, -340282366920938463463374607431768211456LL, 340282366920938463463374607431768211455LL, , ") (check-emited (generate pi) "3.141592653589793E+0") (check-emited (generate (coerce pi 'short-float)) "3.1415927E+0F") (check-emited (generate (coerce (expt pi 130) 'long-float)) "4.260724468298572E+64") (check-emited (generate 123.456l89) "1.23456E+91") (check-emited (generate #\a) "'a'") (check-emited (generate #\newline) "'\\12'") (check-item-and-emited (expr-seq (assign 'a 1) (assign 'b 2) (assign 'c 3)) "a=1,b=2,c=3") (check-item-and-emited (expr-callargs (assign 'a 1) (assign 'b 2) (assign 'c 3)) "a=1,b=2,c=3") (check-item-and-emited (expr-callargs (expr-seq (assign 'a 1) (assign 'b 2) (assign 'c 3))) "a=1,b=2,c=3") ;; TODO: expr-args above expr-seq to force parens in: fun(arg,(f(a),g(b)),arg); (check-item-and-emited (expr-callargs (assign 'a 1) (expr-seq (assign 'b 2) (assign 'c 3))) "a=1,b=2,c=3") (check-item-and-emited (expr-if (expr-eq 'a 1) 2 3) "a==1?2:3") (check-item-and-emited (assign 'var 42) "var=42") (check-item-and-emited (assign-times 'var 42) "var*=42") (check-item-and-emited (assign-divided 'var 42) "var/=42") (check-item-and-emited (assign-modulo 'var 42) "var%=42") (check-item-and-emited (assign-plus 'var 42) "var+=42") (check-item-and-emited (assign-minus 'var 42) "var-=42") (check-item-and-emited (assign-right-shift 'var 42) "var>>=42") (check-item-and-emited (assign-left-shift 'var 42) "var<<=42") (check-item-and-emited (assign-bitand 'var 42) "var&=42") (check-item-and-emited (assign-bitor 'var 42) "var|=42") (check-item-and-emited (assign-bitxor 'var 42) "var^=42") (check-item-and-emited (expr-logor (expr-eq 'p 0) (expr-ne 'q 0)) "p==0||q!=0") (check-item-and-emited (expr-logand (expr-eq 'p 0) (expr-ne 'q 0)) "p==0&&q!=0") (check-item-and-emited (expr-bitor (expr-eq 'p 0) (expr-ne 'q 0)) "p==0|q!=0") (check-item-and-emited (expr-bitxor (expr-eq 'p 0) (expr-ne 'q 0)) "p==0^q!=0") (check-item-and-emited (expr-bitand (expr-eq 'p 0) (expr-ne 'q 0)) "p==0&q!=0") (check-item-and-emited (expr-eq 'p 0) "p==0") (check-item-and-emited (expr-ne 'p 0) "p!=0") (check-item-and-emited (expr-lt 'p 'q) "p<q") (check-item-and-emited (expr-le 'p 'q) "p<=q") (check-item-and-emited (expr-gt 'p 'q) "p>q") (check-item-and-emited (expr-ge 'p 'q) "p>=q") (check-item-and-emited (expr-left-shift 'var 42) "var<<42") (check-item-and-emited (expr-right-shift 'var 42) "var>>42") (check-item-and-emited (expr-plus 'a 'b) "a+b") (check-item-and-emited (expr-minus 'a 'b) "a-b") (check-item-and-emited (expr-times 'a 'b) "a*b") (check-item-and-emited (expr-divided 'a 'b) "a/b") (check-item-and-emited (expr-modulo 'a 'b) "a%b") (check-item-and-emited (expr-memptr-deref 'p 'mem) "p.*mem") (check-item-and-emited (expr-ptrmemptr-deref 'p 'mem) "p->*mem") (check-item-and-emited (expr-preincr 'a) "++a") (check-item-and-emited (expr-predecr 'a) "--a") (check-item-and-emited (expr-postincr 'a) "a++") (check-item-and-emited (expr-postdecr 'a) "a--") (check-item-and-emited (expr-lognot 'p) "!p") (check-item-and-emited (expr-bitnot 'q) "~q") (check-item-and-emited (expr-deref 'p) "(*(p))") (check-item-and-emited (expr-address 'a) "(&(a))") (check-item-and-emited (expr-deref (expr-address 'a)) "(*((&(a))))") (check-item-and-emited (expr-pos 'a) "(+(a))") (check-item-and-emited (expr-neg 'a) "(-(a))") (check-item-and-emited (expr-sizeof 'a) "sizeof(a)") (check-item-and-emited (expr-new 'a) "new a") (check-item-and-emited (expr-new[] 'a) "new[] a") (check-item-and-emited (expr-delete 'a) "delete a") (check-item-and-emited (expr-delete[] 'a) "delete[] a") (check-item-and-emited (cpp-stringify 'foo) "#foo") (check-item-and-emited (expr-field 'p 'a) "p.a") (check-item-and-emited (expr-field 'p 'a 'b 'c) "p.a.b.c") (check-item-and-emited (expr-ptrfield 'p 'a) "p->a") (check-item-and-emited (expr-ptrfield 'p 'q 'r 'a) "p->q->r->a") (check-item-and-emited (expr-aref 'a 1 2 3) "a[1][2][3]") (check-item-and-emited (expr-call 'f 1 2 3) "f(1,2,3)") (check-item-and-emited (expr-call 'f (expr-seq 1 2) 3) "f(1,2,3)") (check-item-and-emited (absolute-scope 'a) "::a") (check-item-and-emited (expr-scope 'b 'c) "b::c") (check-item-and-emited (expr-scope 'a) "a") (check-item-and-emited (cpp-join 'foo 'bar) "foo##bar") (check-item-and-emited (stmt-expr (assign 'a 1)) " a=1; ") (check-item-and-emited (ensure-statement (assign 'a 1)) "a=1; ") (check-item-and-emited (stmt-label 'foo (ensure-statement (assign 'a 1))) "foo: a=1; ") (check-item-and-emited (stmt-case 'bar (ensure-statement (assign 'a 1))) "case bar: a=1; ") (check-item-and-emited (stmt-default (ensure-statement (assign 'a 1))) "default: a=1; ") (check-item-and-emited (stmt-block (list (ensure-statement (assign 'a 1)) (ensure-statement (assign 'b 2)) (ensure-statement (assign 'c 3)))) "{ a=1; b=2; c=3; }") (check-item-and-emited (stmt-let (list (ensure-statement (assign 'a 'x)) (ensure-statement (assign 'b 'y)) (ensure-statement (assign 'c 'z))) (list)) " { a=x; b=y; c=z; }") (check-item-and-emited (stmt-if (expr-call 'print 'a) (expr-call 'print 'b) (expr-eq 'a 'b)) " if(a==b) CommonLisp_print(a); else CommonLisp_print(b); ") (check-item-and-emited (stmt-if (expr-call 'print 'a) nil (expr-eq 'a 'b)) "if(a==b) CommonLisp_print(a); ") (check-item-and-emited (stmt-switch (stmt-block (list (stmt-case 'foo (ensure-statement (assign 'a 1))) (stmt-break) (stmt-case 'bar (ensure-statement (assign 'a 2))) (stmt-break) (stmt-default (ensure-statement (assign 'a 3))))) (expr-seq 'x)) "switch(x){ case foo: a=1; break; case bar: a=2; break; default: a=3; }") (check-item-and-emited (stmt-while (ensure-statement (assign-plus 'a 'b)) (expr-eq 'a 'b)) " while(a==b) a+=b; ") (check-item-and-emited (stmt-do (stmt-block (list (assign-plus 'a 'b))) (expr-eq 'a 'b)) "do{ a+=b; }while(a==b)") (check-item-and-emited (stmt-for (assign 'a '0) (expr-lt 'a '100) (expr-postincr 'a) (stmt-block (list (assign-plus 'a 'b)))) " for(a=0;a<100;a++){ a+=b; }") (check-item-and-emited (stmt-break) " break; ") (check-item-and-emited (stmt-continue) "continue; ") (check-item-and-emited (stmt-return nil) "return; ") (check-item-and-emited (stmt-return 42) "return 42; ") (check-item-and-emited (stmt-goto 'foo) "goto foo; ") (check-item-and-emited (asm "move.l d0,d1") "asm(\"move.l d0,d1\"); ") (check-item-and-emited (extern1 "C" (asm "move.l d0,d1")) "extern \"C\" asm(\"move.l d0,d1\"); ") (check-item-and-emited (extern "C" (list (asm "move.l d0,d1") (asm "move.l d2,d0"))) "extern \"C\"{ asm(\"move.l d0,d1\"); asm(\"move.l d2,d0\"); } ") (check-item-and-emited (with-extern "C" (asm "move.l d0,d1") (asm "move.l d2,d0")) "extern \"C\"{ asm(\"move.l d0,d1\"); asm(\"move.l d2,d0\"); } ") (check-item-and-emited (pointer 'foo :const t :volatile t) "* const volatile foo") (check-item-and-emited (reference 'foo) "&foo") (check-item-and-emited (member-pointer 'bar 'foo :const t :volatile t) "bar* const volatile foo") (check-item-and-emited (c-function 'foo (list 'int) :const t :volatile t :throw '(error warning)) "foo(int) const volatile throw (CommonLisp_error,CommonLisp_warning)") (check-item-and-emited (c-vector 'com.informatimago.languages.linc.c::|char| 42) "char[42]") ;;;; THE END ;;;;
10,486
Common Lisp
.lisp
245
36.493878
486
0.598046
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cdb0bdd5d3a689f7ad6879079f3ae3580ea28fd831d29b623fae77fc531ad2a0
5,220
[ -1 ]
5,221
annex-a.lisp
informatimago_lisp/languages/linc/annex-a.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (defparameter *ansi-c-grammar* '(("(6.4)" token --> keyword identifier constant string-literal punctuator) ("(6.4)" preprocessing-token --> header-name identifier pp-number character-constant string-literal punctuator |each non-white-space character that cannot be one of the above|) ("(6.4.1)" keyword --> |*| |auto| |break| |case| |char| |const| |continue| |default| |do| |double| |else| |enum| |extern| |float| |for| |goto| |if| |inline| |int| |long| |register| |restrict| |return| |short| |signed| |sizeof| |static| |struct| |switch| |typedef| |union| |unsigned| |void| |volatile| |while| |_Alignas| |_Alignof| |_Atomic| |_Bool| |_Complex| |_Generic| |_Imaginary| |_Noreturn| |_Static_assert| |_Thread_local|) ("(6.4.2.1)" identifier --> identifier-nondigit (identifier identifier-nondigit) (identifier digit)) ("(6.4.2.1)" identifier-nondigit --> nondigit universal-character-name |other implementation-defined characters|) ("(6.4.2.1)" nondigit --> \_ \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) ("(6.4.2.1)" digit --> \0 \1 \2 \3 \4 \5 \6 \7 \8 \9) ("(6.4.3)" universal-character-name --> (|\\u| hex-quad) (|\\U| hex-quad hex-quad)) ("(6.4.3)" hex-quad --> (hexadecimal-digit hexadecimal-digit) (hexadecimal-digit hexadecimal-digit)) ("(6.4.4)" constant --> integer-constant floating-constant enumeration-constant character-constant) ("(6.4.4.1)" integer-constant --> (decimal-constant (opt integer-suffix)) (octal-constant (opt integer-suffix)) (hexadecimal-constant (opt integer-suffix))) ("(6.4.4.1)" decimal-constant --> nonzero-digit (decimal-constant digit)) ("(6.4.4.1)" octal-constant --> \0 (octal-constant octal-digit)) ("(6.4.4.1)" hexadecimal-constant --> (hexadecimal-prefix hexadecimal-digit) (hexadecimal-constant hexadecimal-digit)) ("(6.4.4.1)" hexadecimal-prefix --> |0x| |0X|) ("(6.4.4.1)" nonzero-digit --> \1 \2 \3 \4 \5 \6 \7 \8 \9) ("(6.4.4.1)" octal-digit --> \0 \1 \2 \3 \4 \5 \6 \7) ("(6.4.4.1)" hexadecimal-digit --> \0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f \A \B \C \D \E \F) ("(6.4.4.1)" integer-suffix --> (unsigned-suffix (opt long-suffix)) ; u ul (unsigned-suffix long-long-suffix) ; ull (long-suffix (opt unsigned-suffix)) ; lu (long-long-suffix (opt unsigned-suffix))) ; llu ("(6.4.4.1)" unsigned-suffix --> \u \U) ("(6.4.4.1)" long-suffix --> \l \L) ("(6.4.4.1)" long-long-suffix --> |ll| |LL|) ("(6.4.4.2)" floating-constant --> decimal-floating-constant hexadecimal-floating-constant) ("(6.4.4.2)" decimal-floating-constant --> (fractional-constant (opt exponent-part) (opt floating-suffix)) (digit-sequence exponent-part (opt floating-suffix))) ("(6.4.4.2)" hexadecimal-floating-constant --> (hexadecimal-prefix hexadecimal-fractional-constant binary-exponent-part (opt floating-suffix)) (hexadecimal-prefix hexadecimal-digit-sequence binary-exponent-part (opt floating-suffix))) ("(6.4.4.2)" fractional-constant --> ((opt digit-sequence) \. digit-sequence) (digit-sequence \.)) ("(6.4.4.2)" exponent-part --> (|e| (opt sign) digit-sequence) (|E| (opt sign) digit-sequence)) ("(6.4.4.2)" sign --> \+ \-) ("(6.4.4.2)" digit-sequence --> digit (digit-sequence digit)) ("(6.4.4.2)" hexadecimal-fractional-constant --> ((opt hexadecimal-digit-sequence) \. hexadecimal-digit-sequence) (hexadecimal-digit-sequence \.)) ("(6.4.4.2)" binary-exponent-part --> (|p| (opt sign) digit-sequence) (|P| (opt sign) digit-sequence)) ("(6.4.4.2)" hexadecimal-digit-sequence --> hexadecimal-digit (hexadecimal-digit-sequence hexadecimal-digit)) ("(6.4.4.2)" floating-suffix --> \f \l \F \L) ("(6.4.4.3)" enumeration-constant --> identifier) ("(6.4.4.4)" character-constant --> (\' c-char-sequence \') (\L\' c-char-sequence \') (\u\' c-char-sequence \') (\U\' c-char-sequence \')) ("(6.4.4.4)" c-char-sequence --> c-char (c-char-sequence c-char)) ("(6.4.4.4)" c-char --> |any member of the source character set except the single-quote ', backslash \, or new-line character| escape-sequence) ("(6.4.4.4)" escape-sequence --> simple-escape-sequence octal-escape-sequence hexadecimal-escape-sequence universal-character-name) ("(6.4.4.4)" simple-escape-sequence --> \\\' \\\" \\\? \\\\ \\\a \\\b \\\f \\\n \\\r \\\t \\\v) ("(6.4.4.4)" octal-escape-sequence --> (\\ octal-digit) (\\ octal-digit octal-digit) (\\ octal-digit octal-digit octal-digit)) ("(6.4.4.4)" hexadecimal-escape-sequence --> (|\\x| hexadecimal-digit) (hexadecimal-escape-sequence hexadecimal-digit)) ("(6.4.5)" string-literal --> ((opt encoding-prefix) \" (opt s-char-sequence) \")) ("(6.4.5)" encoding-prefix --> |u8| |u| |U| |L|) ("(6.4.5)" s-char-sequence --> s-char (s-char-sequence s-char)) ("(6.4.5)" s-char --> |any member of the source character set except the double-quote ", backslash \, or new-line character escape-sequence|) ("(6.4.6)" punctuator --> \[ \] \( \) \{ \} \. \-\> \+\+ \-\- \& \* \+ \- \~ \! \/ \% \<\< \>\> \< \> \<\= \>\= \=\= \!\= \^ \| \&\& \|\| \? \: \; \.\.\. \= \*\= \/\= \%\= \+\= \-\= \<\<\= \>\>\= \&\= \^\= \|\= \, \# \#\# \<\: \:\> \<\% \%\> \%\: \%\:\%\:) ("(6.4.7)" header-name --> (\< h-char-sequence \>) (\" q-char-sequence \")) ("(6.4.7)" h-char-sequence --> h-char (h-char-sequence h-char)) ("(6.4.7)" h-char --> |any member of the source character set except the new-line character and >|) ("(6.4.7)" q-char-sequence --> q-char (q-char-sequence q-char)) ("(6.4.7)" q-char --> |any member of the source character set except the new-line character and "|) ("(6.4.8)" pp-number --> digit (\. digit) (pp-number digit) (pp-number identifier-nondigit) (pp-number \e sign) (pp-number \E sign) (pp-number \p sign) (pp-number \P sign) (pp-number \.)) ("(6.5.1)" primary-expression --> identifier constant string-literal (\( expression \)) generic-selection) ("(6.5.1.1)" generic-selection --> (|_Generic| \( assignment-expression \, generic-assoc-list \))) ("(6.5.1.1)" generic-assoc-list --> generic-association (generic-assoc-list \, generic-association)) ("(6.5.1.1)" generic-association --> (type-name \: assignment-expression) (|default| \: assignment-expression)) ("(6.5.2)" postfix-expression --> primary-expression (postfix-expression \[ expression \]) (postfix-expression \( (opt argument-expression-list) \)) (postfix-expression \. identifier) (postfix-expression |->| identifier) (postfix-expression |++|) (postfix-expression |--|) (\( type-name \) \{ initializer-list \}) (\( type-name \) \{ initializer-list \, \})) ("(6.5.2)" argument-expression-list --> assignment-expression (argument-expression-list \, assignment-expression)) ("(6.5.3)" unary-expression --> postfix-expression (|++| unary-expression) (|--| unary-expression) (unary-operator cast-expression) (|sizeof| unary-expression) (|sizeof| \( type-name \)) (|_Alignof| \( type-name \))) ("(6.5.3)" unary-operator --> \& \* \+ \- \~ \!) ("(6.5.4)" cast-expression --> unary-expression (\( type-name \) cast-expression)) ("(6.5.5)" multiplicative-expression --> cast-expression (multiplicative-expression \* cast-expression) (multiplicative-expression \/ cast-expression) (multiplicative-expression \% cast-expression)) ("(6.5.6)" additive-expression --> multiplicative-expression (additive-expression \+ multiplicative-expression) (additive-expression \- multiplicative-expression)) ("(6.5.7)" shift-expression --> additive-expression (shift-expression |<<| additive-expression) (shift-expression |>>| additive-expression)) ("(6.5.8)" relational-expression --> shift-expression (relational-expression |<| shift-expression) (relational-expression |>| shift-expression) (relational-expression |<=| shift-expression) (relational-expression |>=| shift-expression)) ("(6.5.9)" equality-expression --> relational-expression (equality-expression |==| relational-expression) (equality-expression |!=| relational-expression)) ("(6.5.10)" AND-expression --> equality-expression (AND-expression |&| equality-expression)) ("(6.5.11)" exclusive-OR-expression --> AND-expression (exclusive-OR-expression |^| AND-expression)) ("(6.5.12)" inclusive-OR-expression --> exclusive-OR-expression (inclusive-OR-expression \| exclusive-OR-expression)) ("(6.5.13)" logical-AND-expression --> inclusive-OR-expression (logical-AND-expression |&&| inclusive-OR-expression)) ("(6.5.14)" logical-OR-expression --> logical-AND-expression (logical-OR-expression \|\| logical-AND-expression)) ("(6.5.15)" conditional-expression --> logical-OR-expression (logical-OR-expression |?| expression |:| conditional-expression)) ("(6.5.16)" assignment-expression --> conditional-expression (unary-expression assignment-operator assignment-expression)) ("(6.5.16)" assignment-operator --> \= \*\= \/\= \%\= \+\= \-\= \<\<\= \>\>\= \&\= \^\= \|\=) ("(6.5.17)" expression --> assignment-expression (expression \, assignment-expression)) ("(6.6)" constant-expression --> conditional-expression) ("(6.7)" declaration --> (declaration-specifiers (opt init-declarator-list) \;) static_assert-declaration) ("(6.7)" declaration-specifiers --> (storage-class-specifier (opt declaration-specifiers)) (type-specifier (opt declaration-specifiers)) (type-qualifier (opt declaration-specifiers)) (function-specifier (opt declaration-specifiers)) (alignment-specifier (opt declaration-specifiers))) ("(6.7)" init-declarator-list --> init-declarator (init-declarator-list \, init-declarator)) ("(6.7)" init-declarator --> declarator (declarator \= initializer)) ("(6.7.1)" storage-class-specifier --> |typedef| |extern| |static| |_Thread_local| |auto| |register|) ("(6.7.2)" type-specifier --> |void| |char| |short| |int| |long| |float| |double| |signed| |unsigned| |_Bool| |_Complex| atomic-type-specifier struct-or-union-specifier enum-specifier typedef-name) ("(6.7.2.1)" struct-or-union-specifier --> (struct-or-union (opt identifier) \{ struct-declaration-list \}) struct-or-union identifier) ("(6.7.2.1)" struct-or-union --> |struct| |union|) ("(6.7.2.1)" struct-declaration-list --> struct-declaration (struct-declaration-list struct-declaration)) ("(6.7.2.1)" struct-declaration --> (specifier-qualifier-list (opt struct-declarator-list) \;) static_assert-declaration) ("(6.7.2.1)" specifier-qualifier-list --> (type-specifier (opt specifier-qualifier-list)) (type-qualifier (opt specifier-qualifier-list))) ("(6.7.2.1)" struct-declarator-list --> struct-declarator (struct-declarator-list \, struct-declarator)) ("(6.7.2.1)" struct-declarator --> declarator ((opt declarator) \: constant-expression)) ("(6.7.2.2)" enum-specifier --> (|enum| (opt identifier) \{ enumerator-list \}) (|enum| (opt identifier) \{ enumerator-list \, \}) (|enum| identifier)) ("(6.7.2.2)" enumerator-list --> enumerator (enumerator-list \, enumerator)) ("(6.7.2.2)" enumerator --> enumeration-constant (enumeration-constant \= constant-expression)) ("(6.7.2.4)" atomic-type-specifier --> (|_Atomic| \( type-name \))) ("(6.7.3)" type-qualifier --> |const| |restrict| |volatile| |_Atomic|) ("(6.7.4)" function-specifier --> |inline| |_Noreturn|) ("(6.7.5)" alignment-specifier --> (|_Alignas| \( type-name \)) (|_Alignas| \( constant-expression \))) ("(6.7.6)" declarator --> ((opt pointer) direct-declarator)) ("(6.7.6)" direct-declarator --> identifier (\( declarator \)) (direct-declarator \[ (opt type-qualifier-list) (opt assignment-expression) \]) (direct-declarator \[ static (opt type-qualifier-list) assignment-expression \]) (direct-declarator \[ type-qualifier-list static assignment-expression \]) (direct-declarator \[ (opt type-qualifier-list) \* \]) (direct-declarator \( parameter-type-list \)) (direct-declarator \( (opt identifier-list) \))) ("(6.7.6)" pointer --> (\* (opt type-qualifier-list)) (\* (opt type-qualifier-list) pointer)) ("(6.7.6)" type-qualifier-list --> type-qualifier (type-qualifier-list type-qualifier)) ("(6.7.6)" parameter-type-list --> parameter-list (parameter-list \, |...|)) ("(6.7.6)" parameter-list --> parameter-declaration (parameter-list \, parameter-declaration)) ("(6.7.6)" parameter-declaration --> (declaration-specifiers declarator) (declaration-specifiers (opt abstract-declarator))) ("(6.7.6)" identifier-list --> identifier (identifier-list \, identifier)) ("(6.7.7)" type-name --> (specifier-qualifier-list (opt abstract-declarator))) ("(6.7.7)" abstract-declarator --> pointer ((opt pointer) direct-abstract-declarator)) ("(6.7.7)" direct-abstract-declarator --> (\( abstract-declarator \)) ((opt direct-abstract-declarator) \[ (opt type-qualifier-list) (opt assignment-expression) \]) ((opt direct-abstract-declarator) \[ |static| (opt type-qualifier-list) assignment-expression \]) ((opt direct-abstract-declarator) \[ type-qualifier-list |static| assignment-expression \]) ((opt direct-abstract-declarator) \[ \* \]) ((opt direct-abstract-declarator) \( (opt parameter-type-list) \))) ("(6.7.8)" typedef-name --> identifier) ("(6.7.9)" initializer --> assignment-expression (\{ initializer-list \}) (\{ initializer-list \, \})) ("(6.7.9)" initializer-list --> ((opt designation) initializer) (initializer-list \, (opt designation) initializer)) ("(6.7.9)" designation --> (designator-list \=)) ("(6.7.9)" designator-list --> designator (designator-list designator)) ("(6.7.9)" designator --> (\[ constant-expression \]) (\. identifier)) ("(6.7.10)" static_assert-declaration --> (|_Static_assert| \( constant-expression \, string-literal \) \;)) ("(6.8)" statement --> labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement) ("(6.8.1)" labeled-statement --> (identifier \: statement) (|case| constant-expression \: statement) (|default| \: statement)) ("(6.8.2)" compound-statement --> (\{ (opt block-item-list) \})) ("(6.8.2)" block-item-list --> block-item (block-item-list block-item)) ("(6.8.2)" block-item --> declaration statement) ("(6.8.3)" expression-statement --> ((opt expression) \;)) ("(6.8.4)" selection-statement --> (|if| \( expression \) statement) (|if| \( expression \) statement |else| statement) (|switch| \( expression \) statement)) ("(6.8.5)" iteration-statement --> (|while| \( expression \) statement) (|do| statement |while| \( expression \) \;) (|for| \( (opt expression) \; (opt expression) \; (opt expression) \) statement) (|for| \( declaration (opt expression) \; (opt expression) \) statement)) ("(6.8.6)" jump-statement --> (|goto| identifier \;) (|continue| \;) (|break| \;) (|return| (opt expression) \;)) ("(6.9)" translation-unit --> external-declaration (translation-unit external-declaration)) ("(6.9)" external-declaration --> function-definition declaration) ("(6.9.1)" function-definition --> (declaration-specifiers declarator (opt declaration-list) compound-statement)) ("(6.9.1)" declaration-list --> declaration (declaration-list declaration)) ("(6.10)" preprocessing-file --> (opt group)) ("(6.10)" group --> group-part (group group-part)) ("(6.10)" group-part --> if-section (control-line text-line) (\# non-directive)) ("(6.10)" if-section --> (if-group (opt elif-groups) (opt else-group) endif-line)) ("(6.10)" if-group --> (\# |if| constant-expression new-line (opt group)) (\# |ifdef| identifier new-line (opt group)) (\# |ifndef| identifier new-line (opt group))) ("(6.10)" elif-groups --> elif-group (elif-groups elif-group)) ("(6.10)" elif-group --> (\# |elif| constant-expression new-line (opt group))) ("(6.10)" else-group --> (\# |else| new-line (opt group))) ("(6.10)" endif-line --> (\# |endif|)) ("(6.10)" control-line --> (\# |include| pp-tokens new-line) (\# |define| identifier replacement-list new-line) (\# |define| identifier lparen (opt identifier-list) \) replacement-list new-line) (\# |define| identifier lparen |...| \) replacement-list new-line) (\# |define| identifier lparen identifier-list \, |...| \) replacement-list new-line) (\# |undef| identifier new-line) (\# |line| pp-tokens new-line) (\# |error| (opt pp-tokens) new-line) (\# |pragma| (opt pp-tokens) new-line) (\# new-line)) ("(6.10)" text-line --> ((opt pp-tokens) new-line)) ("(6.10)" non-directive --> (pp-tokens new-line)) ("(6.10)" lparen --> |a ( character not immediately preceded by white-space|) ("(6.10)" replacement-list --> (opt pp-tokens)) ("(6.10)" pp-tokens --> preprocessing-token (pp-tokens preprocessing-token)) ("(6.10)" new-line --> |the new-line character|)))
19,330
Common Lisp
.lisp
557
28.734291
124
0.582541
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
eb66a276e524c6cde87a1f82e5da31cd817e2730d2c6259a947de4120a5a1ff2
5,221
[ -1 ]
5,222
c-string-reader.lisp
informatimago_lisp/languages/linc/c-string-reader.lisp
;;;; -*- mode:lisp;coding:utf-8 -*- ;;;;************************************************************************** ;;;;FILE: c-string-reader.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; A C string reader, implementing C string back-slash escapes. ;;;; Also includes a writer to print strings with C back-slash escapes. ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal J. Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2013-05-22 <PJB> Added character-code-reader-macro, factorized ;;;; out c-escaped-character-map. ;;;; Published as http://paste.lisp.org/display/137262 ;;;; 2011-05-21 <PJB> Updated from http://paste.lisp.org/display/69905 (lost). ;;;;BUGS ;;;;LEGAL ;;;; AGPL3 ;;;; ;;;; Copyright Pascal J. Bourguignon 2013 - 2013 ;;;; ;;;; 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.LANGUAGES.LINC") (defun c-escaped-character-map (escaped-character) (case escaped-character ((#\' #\" #\? #\\) escaped-character) ((#\newline) -1) ((#\a) 7) ((#\b) 8) ((#\t) 9) ((#\n) 10) ((#\v) 11) ((#\f) 12) ((#\r) 13) ((#\x) :hexa) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7) :octal) (otherwise :default))) (defun char-unicode (character) (let ((bytes (babel:string-to-octets (string character) :encoding :utf-32be :use-bom nil))) (+ (* 256 (+ (* 256 (+ (* 256 (aref bytes 0)) (aref bytes 1))) (aref bytes 2))) (aref bytes 3)))) (defun character-code-reader-macro (stream quotation-mark) (declare (ignore quotation-mark)) (flet ((encode (ch) (char-unicode ch))) (let ((ch (read-char stream))) (if (char/= #\\ ch) (encode ch) (let* ((ch (read-char stream)) (code (c-escaped-character-map ch))) (flet ((read-code (*read-base* base-name) (let ((code (read stream))) (if (and (integerp code) (<= 0 code (1- char-code-limit))) code (error "Invalid ~A character code: ~A" base-name code))))) (case code (:hexa (read-code 16 "hexadecimal")) (:octal (unread-char ch stream) (read-code 8 "octal")) (:default ;; In emacs ?\x = ?x (encode ch)) (otherwise (if (characterp code) (encode code) code))))))))) (defun read-c-string (stream char) "Read a C string from the STREAM The initial double-quote must have been read already." (declare (ignore char)) (let ((buffer (make-array 80 :element-type 'character :adjustable t :fill-pointer 0)) (state :in-string) (start 0)) (flet ((process-token (ch) (ecase state ((:in-string) (setf state (case ch ((#\") :out) ((#\\) :escape) (otherwise (vector-push-extend ch buffer) :in-string))) nil) ((:escape) (setf state :in-string) (let ((code (c-escaped-character-map ch))) (case code (:hexa (setf state :in-hexa start (fill-pointer buffer))) (:octal (setf state :in-octal start (fill-pointer buffer)) (vector-push-extend ch buffer)) (:default (error "Invalid escape character \\~C at position ~D" ch (fill-pointer buffer))) (otherwise (cond ((characterp code) (vector-push-extend code buffer)) ((eql -1 code) #|remove it|#) (t (vector-push-extend (aref #(- - - - - - - #\bell #\backspace #\tab #\linefeed #\vt #\page #\return) code) buffer)))))) nil) ((:in-octal) (flet ((insert-octal () (setf (aref buffer start) (code-char (parse-integer buffer :start start :radix 8)) (fill-pointer buffer) (1+ start) state :in-string))) (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7) (vector-push-extend ch buffer) (when (<= 3 (- (fill-pointer buffer) start)) (insert-octal)) nil) (otherwise (insert-octal) :again)))) ((:in-hexa) (case ch ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\a #\b #\c #\d #\e #\f #\A #\B #\C #\D #\E #\F) (vector-push-extend ch buffer) nil) (otherwise (if (< start (fill-pointer buffer)) (setf (aref buffer start) (code-char (parse-integer buffer :start start :radix 16)) (fill-pointer buffer) (1+ start)) (error "Invalid hexadecimal digit at position ~A" (fill-pointer buffer))) (setf state :in-string) :again)))))) (loop :for ch = (read-char stream) :do (loop :while (process-token ch)) :until (eq state :out) :finally (return buffer))))) (defun write-c-string (string &optional (stream *standard-output*)) "Prints the string as a C string, with C escape sequences." (loop :for ch :across string :initially (princ "\"" stream) :do (princ (case ch ((#\bell) "\\a") ((#\backspace) "\\b") ((#\page) "\\f") ((#\newline #-#.(cl:if (cl:char= #\newline #\linefeed) '(:and) '(:or)) #\linefeed) "\\n") ((#\return) "\\r") ((#\tab) "\\t") ((#\vt) "\\v") ((#\") "\\\"") ((#\\) "\\\\") (otherwise (if (< (char-code ch) 32) (format nil "\\~3,'0o" (char-code ch)) ch))) stream) :finally (princ "\"" stream))) (defun test/read-c-string () (let ((*readtable* (let ((rt (copy-readtable nil))) (set-macro-character #\" (function read-c-string) nil rt) rt))) (read-from-string "\"Hello, bell=\\a, backspace=\\b, page=\\f, newline=\\n, return=\\r, tab=\\t, vt=\\v, \\ \\\"double-quotes\\\", \\'single-quotes\\', question\\?, backslash=\\\\, \\ hexa=\\x3BB, octal=\\101, \\7\\77\\107\\3071\""))) ;;;; THE END ;;;;
8,439
Common Lisp
.lisp
191
30.554974
111
0.433131
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b65bbd69d99c1f4fa2bd75fde4562d79b4713ad3e1c117149b3fb9a54fa493ee
5,222
[ -1 ]
5,223
run.lisp
informatimago_lisp/languages/linc/run.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COMMON-LISP-USER") (defparameter *compile-linc-c-files* t) (load (make-pathname :name "generate" :type "lisp" :version nil :defaults (or *load-truename* (error "This file must be loaded as source.")))) ;; (cc (translate-linc-file "test-expressions.sexpc" :print t :verbose t) ;; :output "test-expressions.o" :to :object :options '("-Werror" "-Wall"))
526
Common Lisp
.lisp
9
50.555556
84
0.631068
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
dd7bea8587a0dfada59f69509f92b701cc155336692431475a770465bf3a6810
5,223
[ -1 ]
5,224
c-sexp-compiler.lisp
informatimago_lisp/languages/linc/c-sexp-compiler.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (defun compile-linc-file () )
181
Common Lisp
.lisp
5
33.8
54
0.745665
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bdf7899c17e0aa6abb700e55b5d76a9c5d616978af9680f571296c63aa9c2edf
5,224
[ -1 ]
5,225
readtable.lisp
informatimago_lisp/languages/linc/readtable.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (in-package "COM.INFORMATIMAGO.LANGUAGES.LINC") (define-condition simple-stream-error (stream-error simple-condition) () (:report (lambda (condition stream) (format stream "~?" (simple-condition-format-control condition) (simple-condition-format-arguments condition))))) (defparameter *c-readtable-without-reader-macros* (let ((rt (copy-readtable nil))) (set-syntax-from-char #\# #\a rt) (setf (readtable-case rt) :preserve) rt)) (defvar *c-readtable*) (defun read-c-sexp-list (stream) (let ((*package* (load-time-value (find-package *c-package-name*))) (*readtable* *c-readtable*)) (loop :with c-sexps := '() :for ch := (peek-char t stream) :do (case ch ((#\}) (read-char stream) (return (nreverse c-sexps))) ((#\;) (read-line stream) (return (read-c-sexp-list stream))) ((#\#) (read-char stream) (if (char= #\| (peek-char nil stream)) (let ((object-after-comment (read stream))) (if (eql *c-closing-brace* object-after-comment) (return (nreverse c-sexps)) (push object-after-comment c-sexps))) (progn (unread-char #\# stream) (push (read stream) c-sexps)))) (otherwise (push (read stream) c-sexps)))))) (defun reader-macro-c-sexp-list (stream ch) (declare (ignore ch)) (read-c-sexp-list stream)) (defun reader-dispatching-macro-c-sexp-list (stream ch sub) (declare (ignore ch sub)) (cons *c-progn* (read-c-sexp-list stream))) (defun reader-dispatching-macro-c-preprocessor-token (stream ch sub) (declare (ignore ch)) (let ((*readtable* *c-readtable-without-reader-macros*)) (with-input-from-string (prefix (format nil "#~C" sub)) (read (make-concatenated-stream prefix stream))))) (defparameter *c-spaces* #(#\space #\tab #\newline #\page)) (defun read-dot-and-ellipsis (stream) (let ((buffer (make-array 80 :element-type 'character :fill-pointer 0 :adjustable t))) (vector-push #\. buffer) (loop :for ch := (peek-char nil stream) :while (char= #\. ch) :do (vector-push-extend (read-char stream) buffer) :finally (return (multiple-value-bind (fun non-terminating-p) (get-macro-character ch) (if (if fun non-terminating-p (not (find ch *c-spaces*))) (with-input-from-string (buffer-stream buffer) (let ((input (make-concatenated-stream buffer-stream stream)) (*readtable* *c-readtable-without-reader-macros*)) (read input))) (case (length buffer) ((1 3) (intern buffer)) (otherwise (error 'simple-stream-error :stream stream :format-control "Invalid token ~S" :format-arguments (list buffer)))))))))) (defun reader-macro-dot-and-ellipsis (stream ch) (declare (ignore ch)) (read-dot-and-ellipsis stream)) (defun set-c-sexp-reader-macros (readtable) (set-macro-character #\" (function read-c-string) nil readtable) (set-macro-character #\. (function reader-macro-dot-and-ellipsis) t readtable) (set-macro-character *c-opening-brace* (function reader-macro-c-sexp-list) nil readtable) ;; (set-dispatch-macro-character #\# #\i (function reader-dispatching-macro-c-preprocessor-token) readtable) ;; (set-dispatch-macro-character #\# #\e (function reader-dispatching-macro-c-preprocessor-token) readtable) ;; (set-dispatch-macro-character #\# *c-opening-brace* (function reader-dispatching-macro-c-sexp-list) readtable) readtable) (defmacro enable-c-sexp-reader-macros (&optional (readtable '*readtable*)) `(eval-when (:compile-toplevel :load-toplevel :execute) (set-c-sexp-reader-macros ,readtable))) (defparameter *c-readtable* (let ((rt (copy-readtable *c-readtable-without-reader-macros*))) (enable-c-sexp-reader-macros rt) rt) "Readtable to read S-expified C code.") (defun print-c-sexp-form (form &optional (*standard-output* *standard-output*)) (let ((*package* (load-time-value (find-package *c-package-name*))) (*readtable* *c-readtable*) (*print-right-margin* 72)) (write-string "{") (pprint form) (terpri) (write-line "}") (values))) ;;;; THE END ;;;;
4,954
Common Lisp
.lisp
103
38.019417
124
0.570513
informatimago/lisp
20
6
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4eba13e15c478a37b1bd43984ae3bdb29a49c9d86cf65728a6ba9c79e00f1f91
5,225
[ -1 ]