id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | tests.lisp | jscl-project_jscl/tests.lisp | (defparameter *total-tests* 0)
(defparameter *passed-tests* 0)
(defparameter *failed-tests* 0)
(defvar *use-html-output-p* nil)
(defvar *timestamp* nil)
(defun test-fn (fn form expect-success)
(let (result success normal-exit)
;; Execute the test and put T/NIL if SUCCESS if the test
;; completed successfully.
(handler-case
(catch 'recover
(unwind-protect
(progn
(setq result (funcall fn))
(if result
(setq success t)
(setq success nil))
(setq normal-exit t))
(unless normal-exit
(setq success nil)
(throw 'recover t))))
(error ()
nil))
(incf *total-tests*)
(cond
((eq success expect-success)
;; the resut is expected
;; do nothing
(incf *passed-tests*))
(t
(incf *failed-tests*)
(cond
(expect-success
(if *use-html-output-p*
(format t "<font color='red'>Test `~S' failed.</font>~%" form)
(format t "Test `~S' failed.~%" form)))
(t
(if *use-html-output-p*
(format t "<font color='orange'>Test `~S' was expected to fail.</font>~%" form)
(format t "Test `~S' was expected to fail!~%" form))))))))
(defmacro test (condition)
`(test-fn (lambda () ,condition)
',condition
t))
(defmacro expected-failure (condition)
`(test-fn (lambda () ,condition)
',condition
nil))
(defmacro test-equal (form value)
`(test (equal ,form ,value)))
(defun *gensym* ()
(intern (symbol-name (gensym))))
(defun not* (f) (not (not f)))
(defun eqlt (f s) (equal f s))
(defmacro mv-eql (form &rest result)
`(equal
(multiple-value-list
(handler-case
(progn
,form)
(error (msg)
(format t " ERROR: ~a"
(format nil
(simple-condition-format-control msg)
(simple-condition-format-arguments msg)))
(values nil))))
',result))
(setq *timestamp* (get-internal-real-time))
(terpri)
| 2,183 | Common Lisp | .lisp | 69 | 22.797101 | 93 | 0.537399 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 31cdc341076ce330a1682b94539ebc9ad2a95380d006fd0fff7bbfd963e17fd5 | 0 | [
-1
] |
1 | tests-report.lisp | jscl-project_jscl/tests-report.lisp | (format t "~%Finished. The execution took ~a seconds.~%"
(/ (- (get-internal-real-time) *timestamp*) internal-time-units-per-second 1.0))
(if (= *passed-tests* *total-tests*)
(format t "All the tests (~a) passed successfully.~%" *total-tests*)
(format t "~a/~a test(s) passed successfully.~%" *passed-tests* *total-tests*))
(terpri)
#+jscl
(progn
(when #j:phantom
(#j:phantom:exit *failed-tests*))
(when #j:process
(#j:process:exit *failed-tests*)))
| 481 | Common Lisp | .lisp | 12 | 36.5 | 88 | 0.650215 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 98c91b36505e6c117540b310d47a0adc7da143b4e2e6774173a70e867b2c9069 | 1 | [
-1
] |
2 | jscl.lisp | jscl-project_jscl/jscl.lisp | ;;; jscl.lisp ---
;; Copyright (C) 2012, 2013 David Vazquez
;; Copyright (C) 2012 Raimon Grau
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(defpackage :jscl
(:use :cl)
(:export #:bootstrap #:compile-application #:run-tests-in-host))
(in-package :jscl)
(require :uiop)
(defvar *base-directory*
(if #.*load-pathname*
(make-pathname :name nil :type nil :defaults #.*load-pathname*)
*default-pathname-defaults*))
(defvar *version*
(or (uiop:getenv "JSCL_VERSION")
;; Read the version from the package.json file. We could have used a
;; json library to parse this, but that would introduce a dependency
;; and we are not using ASDF yet.
(with-open-file (in (merge-pathnames "package.json" *base-directory*))
(loop
for line = (read-line in nil)
while line
when (search "\"version\":" line)
do (let ((colon (position #\: line))
(comma (position #\, line)))
(return (string-trim '(#\newline #\" #\tab #\space)
(subseq line (1+ colon) comma))))))))
;;; List of all the source files that need to be compiled, and whether they
;;; are to be compiled just by the host, by the target JSCL, or by both.
;;; All files have a `.lisp' extension, and
;;; are relative to src/
;;; Subdirectories are indicated by the presence of a list rather than a
;;; keyword in the second element of the list. For example, this list:
;;; (("foo" :target)
;;; ("bar"
;;; ("baz" :host)
;;; ("quux" :both)))
;;; Means that src/foo.lisp and src/bar/quux.lisp need to be compiled in the
;;; target, and that src/bar/baz.lisp and src/bar/quux.lisp need to be
;;; compiled in the host
(defvar *source*
'(("boot" :target)
("compat" :host)
("setf" :target)
("utils" :both)
("defstruct" :both)
("lambda-list" :both)
("ffi" :target)
("numbers" :target)
("char" :target)
("list" :target)
("array" :target)
("string" :target)
("sequence" :target)
("symbol" :target)
("package" :target)
("hash-table" :target)
("types-prelude" :both)
("types" :target)
("clos"
("kludges" :target)
("std-object" :target)
("mop-utils" :target)
("std-generic" :target)
("std-method" :target)
("bootstrap" :target)
("macros" :target)
("methods" :target))
("conditions" :target)
("ansiloop"
("ansi-loop" :both))
("structures" :both)
("stream" :target)
("print" :target)
("misc" :target)
("format" :target)
("read" :both)
("backquote" :both)
("compiler"
("codegen" :both)
("compiler" :both))
("documentation" :target)
("worker" :target)
("clos"
("tools" :target)
("exports" :target)
("describe" :target))
("load" :target)))
(defun source-pathname (filename &key (directory '(:relative "src")) (type nil) (defaults filename))
(merge-pathnames
(if type
(make-pathname :type type :directory directory :defaults defaults)
(make-pathname :directory directory :defaults defaults))
*base-directory*))
(defun get-files (file-list type dir)
"Traverse FILE-LIST and retrieve a list of the files within which match
either TYPE or :BOTH, processing subdirectories."
(let ((file (car file-list)))
(cond
((null file-list)
())
((listp (cadr file))
(append
(get-files (cdr file) type (append dir (list (car file))))
(get-files (cdr file-list) type dir)))
((member (cadr file) (list type :both))
(cons (source-pathname (car file) :directory dir :type "lisp")
(get-files (cdr file-list) type dir)))
(t
(get-files (cdr file-list) type dir)))))
(defmacro do-source (name type &body body)
"Iterate over all the source files that need to be compiled in the host or
the target, depending on the TYPE argument."
(unless (member type '(:host :target))
(error "TYPE must be one of :HOST or :TARGET, not ~S" type))
`(dolist (,name (get-files *source* ,type '(:relative "src")))
,@body))
;;; Compile and load jscl into the host
(with-compilation-unit ()
(do-source input :host
(multiple-value-bind (fasl warn fail) (compile-file input)
(declare (ignore warn))
#-ccl (when fail
(error "Compilation of ~A failed." input))
(load fasl))))
(defun read-whole-file (filename)
(with-open-file (in filename)
(let* ((seq (make-array (file-length in) :element-type 'character))
(char-count (read-sequence seq in)))
(subseq seq 0 char-count))))
(defun !compile-file (filename out &key print)
(let ((*compiling-file* t)
(*compile-print-toplevels* print)
(*package* *package*))
(let* ((source (read-whole-file filename))
(in (make-string-input-stream source)))
(format t "Compiling ~a...~%" (enough-namestring filename))
(loop
with eof-mark = (gensym)
for x = (ls-read in nil eof-mark)
until (eq x eof-mark)
do (let ((compilation (compile-toplevel x)))
(when (plusp (length compilation))
(write-string compilation out)))))))
(defun dump-global-environment (stream)
(flet ((late-compile (form)
(let ((*standard-output* stream))
(write-string (compile-toplevel form)))))
;; We assume that environments have a friendly list representation
;; for the compiler and it can be dumped.
(dolist (b (lexenv-function *environment*))
(when (eq (binding-type b) 'macro)
(setf (binding-value b) `(,*magic-unquote-marker* ,(binding-value b)))))
(late-compile `(setq *environment* ',*environment*))
;; Set some counter variable properly, so user compiled code will
;; not collide with the compiler itself.
(late-compile
`(progn
(setq *variable-counter* ,*variable-counter*)
(setq *gensym-counter* ,*gensym-counter*)))
(late-compile `(setq *literal-counter* ,*literal-counter*))))
(defun compile-application (files output &key shebang)
(with-compilation-environment
(with-open-file (out output :direction :output :if-exists :supersede)
(when shebang
(format out "#!/usr/bin/env node~%"))
(format out "(function(jscl){~%")
(format out "'use strict';~%")
(format out "(function(values, internals){~%")
(dolist (input files)
(!compile-file input out))
(format out "})(jscl.internals.pv, jscl.internals);~%")
(format out "})( typeof require !== 'undefined'? require('./jscl'): window.jscl )~%"))))
(defun bootstrap (&optional verbose)
(let ((*features* (list* :jscl :jscl-xc *features*))
(*package* (find-package "JSCL"))
(*default-pathname-defaults* *base-directory*))
(setq *environment* (make-lexenv))
(with-compilation-environment
(with-open-file (out (merge-pathnames "jscl.js" *base-directory*)
:direction :output
:if-exists :supersede)
(format out "(function(){~%")
(format out "'use strict';~%")
(write-string (read-whole-file (source-pathname "prelude.js")) out)
(do-source input :target
(!compile-file input out :print verbose))
(dump-global-environment out)
;; NOTE: This file must be compiled after the global
;; environment. Because some web worker code may do some
;; blocking, like starting a REPL, we need to ensure that
;; *environment* and other critical special variables are
;; initialized before we do this.
(!compile-file "src/toplevel.lisp" out :print verbose)
(format out "})();~%")))
(report-undefined-functions)
;; Tests
(compile-application
`(,(source-pathname "tests.lisp" :directory nil)
,@(directory (source-pathname "*" :directory '(:relative "tests") :type "lisp"))
;; Loop tests
,(source-pathname "validate.lisp" :directory '(:relative "tests" "loop") :type "lisp")
,(source-pathname "base-tests.lisp" :directory '(:relative "tests" "loop") :type "lisp")
,(source-pathname "tests-report.lisp" :directory nil))
(merge-pathnames "tests.js" *base-directory*))
;; Web REPL
(compile-application (list (source-pathname "repl.lisp" :directory '(:relative "web")))
(merge-pathnames "jscl-web.js" *base-directory*))
;; Node REPL
(compile-application (list (source-pathname "node.lisp" :directory '(:relative "node")))
(merge-pathnames "jscl-node.js" *base-directory*)
:shebang t)
;; Deno REPL
(compile-application (list (source-pathname "deno.lisp" :directory '(:relative "deno")))
(merge-pathnames "jscl-deno.js" *base-directory*)
:shebang nil)))
;;; Run the tests in the host Lisp implementation. It is a quick way
;;; to improve the level of trust of the tests.
(defun run-tests-in-host ()
(let ((*package* (find-package "JSCL"))
(*default-pathname-defaults* *base-directory*))
(load (source-pathname "tests.lisp" :directory nil))
(let ((*use-html-output-p* nil))
(declare (special *use-html-output-p*))
(dolist (input (directory "tests/*.lisp"))
(load input)))
(load "tests-report.lisp")))
| 10,284 | Common Lisp | .lisp | 238 | 36.57563 | 100 | 0.606382 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 73921fe1278045b5fa1a3c2bae13acd939c833e215a8500c685653bd9f1cf1a3 | 2 | [
-1
] |
3 | deno.lisp | jscl-project_jscl/deno/deno.lisp | ;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading repl-deno/repl.lisp!")
(defun start-repl ()
(welcome-message)
(let ((prompt (format nil "~a>" (package-name *package*))))
(loop
do
(let ((line (#j:prompt prompt)))
(%js-try
(progn
(handler-case
(let ((results (multiple-value-list
(eval-interactive (read-from-string line)))))
(dolist (result results)
(print result)))
(error (err)
(format t "ERROR: ")
(apply #'format t (!condition-args err))
(terpri))))
(catch (err)
(let ((message (or (oget err "message") err)))
(format t "ERROR[!]: ~a~%" message))))
(setf prompt (format nil "~a>" (package-name *package*)))))))
(defun deno-init ()
(let ((text-encoder (make-new #j:TextEncoder)))
(setq *standard-output*
(make-stream
:write-fn (lambda (string)
;; TODO switch to std/io/utils because Deno.writeAllSync is deprecated
(#j:Deno:writeAllSync #j:Deno:stdout ((oget text-encoder "encode") string))))))
(start-repl))
(deno-init)
| 1,813 | Common Lisp | .lisp | 43 | 34.209302 | 99 | 0.603624 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 893578feb401a6c15473a636caa42a7f2ab69b3bba549638fab27461eb1967f9 | 3 | [
-1
] |
4 | documentation.lisp | jscl-project_jscl/src/documentation.lisp | ;;; documentation.lisp --- Accessing DOCUMENTATION
(/debug "loading documentation.lisp!")
;;; Documentation.
(defun documentation (x type)
"Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
(ecase type
(function
(let ((func (fdefinition x)))
(oget func "docstring")))
(variable
(unless (symbolp x)
(error "The type of documentation `~S' is not a symbol." type))
(oget x "vardoc"))))
;;; APROPOS and friends
(defun map-apropos-symbols (function string package external-only)
(flet ((handle-symbol (symbol)
(when (search string (symbol-name symbol) :test #'char-equal)
(funcall function symbol))))
(if package
(if external-only
(do-external-symbols (symbol package) (handle-symbol symbol))
(do-symbols (symbol package) (handle-symbol symbol)))
(if external-only
(do-all-external-symbols (symbol) (handle-symbol symbol))
(do-all-symbols (symbol) (handle-symbol symbol))))))
(defun apropos/regexp-test (pattern str)
((oget pattern "test") str))
(defun apropos-list (string &optional package externals-only)
(let* ((result '())
(pattern (#j:RegExp string))
(comparator (lambda (x)
(let ((name (symbol-name x)))
(when (apropos/regexp-test pattern name)
(pushnew x result :test 'eq)))))
(single-package (lambda (pkg)
(map-for-in comparator (if externals-only
(%package-external-symbols pkg)
(%package-symbols pkg))))))
(if package
(funcall single-package package)
(map-for-in single-package *package-table*))
result))
(defun apropos (string &optional package externals-only)
(princ
(with-output-to-string (buf)
(dolist (it (apropos-list string package externals-only))
(prin1 it buf)
(when (boundp it)
(princ ", Value: " buf)
(prin1 (symbol-value it) buf))
(when (fboundp it)
(princ ", Def: " buf)
(if (find-generic-function it nil)
(princ "Standard generic function" buf)
(princ "Function" buf)))
(format buf "~%"))))
(terpri)
(values))
| 2,377 | Common Lisp | .lisp | 58 | 31.137931 | 85 | 0.580087 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 38997a0c367ec04636e1507d40511a10c84ad0b6bc85e50c6d5c590de3cce11d | 4 | [
-1
] |
5 | backquote.lisp | jscl-project_jscl/src/backquote.lisp | ;;; backquote.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading backquote.lisp!")
;;; Backquote implementation.
;;;
;;; Author: Guy L. Steele Jr. Date: 27 December 1985
;;; Tested under Symbolics Common Lisp and Lucid Common Lisp.
;;; This software is in the public domain.
;;; The following are unique tokens used during processing.
;;; They need not be symbols; they need not even be atoms.
(defvar *comma* 'unquote)
(defvar *comma-atsign* 'unquote-splicing)
(defvar *bq-list* (make-symbol "BQ-LIST"))
(defvar *bq-append* (make-symbol "BQ-APPEND"))
(defvar *bq-list** (make-symbol "BQ-LIST*"))
(defvar *bq-nconc* (make-symbol "BQ-NCONC"))
(defvar *bq-clobberable* (make-symbol "BQ-CLOBBERABLE"))
(defvar *bq-quote* (make-symbol "BQ-QUOTE"))
(defvar *bq-quote-nil* (list *bq-quote* nil))
;;; BACKQUOTE is an ordinary macro (not a read-macro) that processes
;;; the expression foo, looking for occurrences of #:COMMA,
;;; #:COMMA-ATSIGN, and #:COMMA-DOT. It constructs code in strict
;;; accordance with the rules on pages 349-350 of the first edition
;;; (pages 528-529 of this second edition). It then optionally
;;; applies a code simplifier.
;;; If the value of *BQ-SIMPLIFY* is non-NIL, then BACKQUOTE
;;; processing applies the code simplifier. If the value is NIL,
;;; then the code resulting from BACKQUOTE is exactly that
;;; specified by the official rules.
(defparameter *bq-simplify* t)
(defmacro backquote (x)
(bq-completely-process x))
;;; The BACKQUOTE macro should remove all occurences of UNQUOTE and
;;; UNQUOTE-SPLICING from the source before we reach them. If we ever reach
;;; one, it must have occurred outside a BACKQUOTE form, so we signal the
;;; appropriate error.
(defmacro unquote (x) (error "Comma not inside a backquote: ,~S" x))
(defmacro unquote-splicing (x) (error "Comma-atsign not inside a backquote: ,@~S" x))
;;; Backquote processing proceeds in three stages:
;;;
;;; (1) BQ-PROCESS applies the rules to remove occurrences of
;;; #:COMMA, #:COMMA-ATSIGN, and #:COMMA-DOT corresponding to
;;; this level of BACKQUOTE. (It also causes embedded calls to
;;; BACKQUOTE to be expanded so that nesting is properly handled.)
;;; Code is produced that is expressed in terms of functions
;;; #:BQ-LIST, #:BQ-APPEND, and #:BQ-CLOBBERABLE. This is done
;;; so that the simplifier will simplify only list construction
;;; functions actually generated by BACKQUOTE and will not involve
;;; any user code in the simplification. #:BQ-LIST means LIST,
;;; #:BQ-APPEND means APPEND, and #:BQ-CLOBBERABLE means IDENTITY
;;; but indicates places where "%." was used and where NCONC may
;;; therefore be introduced by the simplifier for efficiency.
;;;
;;; (2) BQ-SIMPLIFY, if used, rewrites the code produced by
;;; BQ-PROCESS to produce equivalent but faster code. The
;;; additional functions #:BQ-LIST* and #:BQ-NCONC may be
;;; introduced into the code.
;;;
;;; (3) BQ-REMOVE-TOKENS goes through the code and replaces
;;; #:BQ-LIST with LIST, #:BQ-APPEND with APPEND, and so on.
;;; #:BQ-CLOBBERABLE is simply eliminated (a call to it being
;;; replaced by its argument). #:BQ-LIST* is replaced by either
;;; LIST* or CONS (the latter is used in the two-argument case,
;;; purely to make the resulting code a tad more readable).
(defun bq-completely-process (x)
(let ((raw-result (bq-process x)))
(bq-remove-tokens (if *bq-simplify*
(bq-simplify raw-result)
raw-result))))
(defun bq-process (x)
(cond ((atom x)
(list *bq-quote* x))
((eq (car x) 'backquote)
(bq-process (bq-completely-process (cadr x))))
((eq (car x) *comma*) (cadr x))
((eq (car x) *comma-atsign*)
(error ",@~S after `" (cadr x)))
;; ((eq (car x) *comma-dot*)
;; ;; (error ",.~S after `" (cadr x))
;; (error "ill-formed"))
(t (do ((p x (cdr p))
(q '() (cons (bracket (car p)) q)))
((atom p)
(cons *bq-append*
(nreconc q (list (list *bq-quote* p)))))
(when (eq (car p) *comma*)
(unless (null (cddr p))
(error "Malformed ,~S" p))
(return (cons *bq-append*
(nreconc q (list (cadr p))))))
(when (eq (car p) *comma-atsign*)
(error "Dotted ,@~S" p))
;; (when (eq (car p) *comma-dot*)
;; ;; (error "Dotted ,.~S" p)
;; (error "Dotted"))
))))
;;; This implements the bracket operator of the formal rules.
(defun bracket (x)
(cond ((atom x)
(list *bq-list* (bq-process x)))
((eq (car x) *comma*)
(list *bq-list* (cadr x)))
((eq (car x) *comma-atsign*)
(cadr x))
;; ((eq (car x) *comma-dot*)
;; (list *bq-clobberable* (cadr x)))
(t (list *bq-list* (bq-process x)))))
;;; This auxiliary function is like MAPCAR but has two extra
;;; purposes: (1) it handles dotted lists; (2) it tries to make
;;; the result share with the argument x as much as possible.
(defun maptree (fn x)
(if (atom x)
(funcall fn x)
(let ((a (funcall fn (car x)))
(d (maptree fn (cdr x))))
(if (and (eql a (car x)) (eql d (cdr x)))
x
(cons a d)))))
;;; This predicate is true of a form that when read looked
;;; like %@foo or %.foo.
(defun bq-splicing-frob (x)
(and (consp x)
(or (eq (car x) *comma-atsign*)
;; (eq (car x) *comma-dot*)
)))
;;; This predicate is true of a form that when read
;;; looked like %@foo or %.foo or just plain %foo.
(defun bq-frob (x)
(and (consp x)
(or (eq (car x) *comma*)
(eq (car x) *comma-atsign*)
;; (eq (car x) *comma-dot*)
)))
;;; The simplifier essentially looks for calls to #:BQ-APPEND and
;;; tries to simplify them. The arguments to #:BQ-APPEND are
;;; processed from right to left, building up a replacement form.
;;; At each step a number of special cases are handled that,
;;; loosely speaking, look like this:
;;;
;;; (APPEND (LIST a b c) foo) => (LIST* a b c foo)
;;; provided a, b, c are not splicing frobs
;;; (APPEND (LIST* a b c) foo) => (LIST* a b (APPEND c foo))
;;; provided a, b, c are not splicing frobs
;;; (APPEND (QUOTE (x)) foo) => (LIST* (QUOTE x) foo)
;;; (APPEND (CLOBBERABLE x) foo) => (NCONC x foo)
(defun bq-simplify (x)
(if (atom x)
x
(let ((x (if (eq (car x) *bq-quote*)
x
(maptree #'bq-simplify x))))
(if (not (eq (car x) *bq-append*))
x
(bq-simplify-args x)))))
(defun bq-simplify-args (x)
(do ((args (reverse (cdr x)) (cdr args))
(result
nil
(cond ((atom (car args))
(bq-attach-append *bq-append* (car args) result))
((and (eq (caar args) *bq-list*)
(notany #'bq-splicing-frob (cdar args)))
(bq-attach-conses (cdar args) result))
((and (eq (caar args) *bq-list**)
(notany #'bq-splicing-frob (cdar args)))
(bq-attach-conses
(reverse (cdr (reverse (cdar args))))
(bq-attach-append *bq-append*
(car (last (car args)))
result)))
((and (eq (caar args) *bq-quote*)
(consp (cadar args))
(not (bq-frob (cadar args)))
(null (cddar args)))
(bq-attach-conses (list (list *bq-quote*
(caadar args)))
result))
((eq (caar args) *bq-clobberable*)
(bq-attach-append *bq-nconc* (cadar args) result))
(t (bq-attach-append *bq-append*
(car args)
result)))))
((null args) result)))
(defun null-or-quoted (x)
(or (null x) (and (consp x) (eq (car x) *bq-quote*))))
;;; When BQ-ATTACH-APPEND is called, the OP should be #:BQ-APPEND
;;; or #:BQ-NCONC. This produces a form (op item result) but
;;; some simplifications are done on the fly:
;;;
;;; (op '(a b c) '(d e f g)) => '(a b c d e f g)
;;; (op item 'nil) => item, provided item is not a splicable frob
;;; (op item 'nil) => (op item), if item is a splicable frob
;;; (op item (op a b c)) => (op item a b c)
(defun bq-attach-append (op item result)
(cond ((and (null-or-quoted item) (null-or-quoted result))
(list *bq-quote* (append (cadr item) (cadr result))))
((or (null result) (equal result *bq-quote-nil*))
(if (bq-splicing-frob item) (list op item) item))
((and (consp result) (eq (car result) op))
(list* (car result) item (cdr result)))
(t (list op item result))))
;;; The effect of BQ-ATTACH-CONSES is to produce a form as if by
;;; `(LIST* ,@items ,result) but some simplifications are done
;;; on the fly.
;;;
;;; (LIST* 'a 'b 'c 'd) => '(a b c . d)
;;; (LIST* a b c 'nil) => (LIST a b c)
;;; (LIST* a b c (LIST* d e f g)) => (LIST* a b c d e f g)
;;; (LIST* a b c (LIST d e f g)) => (LIST a b c d e f g)
(defun bq-attach-conses (items result)
(cond ((and (every #'null-or-quoted items)
(null-or-quoted result))
(list *bq-quote*
(append (mapcar #'cadr items) (cadr result))))
((or (null result) (equal result *bq-quote-nil*))
(cons *bq-list* items))
((and (consp result)
(or (eq (car result) *bq-list*)
(eq (car result) *bq-list**)))
(cons (car result) (append items (cdr result))))
(t (cons *bq-list** (append items (list result))))))
;;; Removes funny tokens and changes (#:BQ-LIST* a b) into
;;; (CONS a b) instead of (LIST* a b), purely for readability.
(defun bq-remove-tokens (x)
(cond ((eq x *bq-list*) 'list)
((eq x *bq-append*) 'append)
((eq x *bq-nconc*) 'nconc)
((eq x *bq-list**) 'list*)
((eq x *bq-quote*) 'quote)
((atom x) x)
((eq (car x) *bq-clobberable*)
(bq-remove-tokens (cadr x)))
((and (eq (car x) *bq-list**)
(consp (cddr x))
(null (cdddr x)))
(cons 'cons (maptree #'bq-remove-tokens (cdr x))))
(t (maptree #'bq-remove-tokens x))))
| 11,094 | Common Lisp | .lisp | 248 | 37.592742 | 85 | 0.581116 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | a8a69b0fea5392bafd9eb079dff50bc1312e7a9c530d31e5a2f81f99f79537bd | 5 | [
-1
] |
6 | package.lisp | jscl-project_jscl/src/package.lisp | ;;; package.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading package.lisp!")
(defvar *package-table*
(%js-vref "packages"))
(defun list-all-packages ()
(let ((packages nil))
(map-for-in (lambda (name) (pushnew name packages))
*package-table*)
packages))
(defun find-package (package-designator)
(if (packagep package-designator)
package-designator
(oget *package-table* (string package-designator))))
(defun delete-package (package-designator)
;; TODO: Signal a correctlable error in case the package-designator does not
;; name a package.
;; TODO: Implement unuse-package and remove the deleted package from packages
;; that use it.
(delete-property (package-name (find-package-or-fail package-designator))
*package-table*))
(defun %make-package (name use)
(when (find-package name)
(error "A package namded `~a' already exists." name))
(let ((package (new)))
(setf (oget package "packageName") name)
(setf (oget package "symbols") (new))
(setf (oget package "exports") (new))
(setf (oget package "use") use)
(setf (oget *package-table* name) package)
package))
(defun resolve-package-list (packages)
(let (result)
(dolist (package (mapcar #'find-package-or-fail packages))
(pushnew package result :test #'eq))
(reverse result)))
(defun make-package (name &key use)
(%make-package
(string name)
(resolve-package-list use)))
(defun packagep (x)
(and (objectp x) (not (js-null-p x)) (in "symbols" x)))
(defun package-name (package-designator)
(let ((package (find-package-or-fail package-designator)))
(oget package "packageName")))
(defun %package-symbols (package-designator)
(let ((package (find-package-or-fail package-designator)))
(oget package "symbols")))
(defun package-use-list (package-designator)
(let ((package (find-package-or-fail package-designator)))
(oget package "use")))
(defun %package-external-symbols (package-designator)
(let ((package (find-package-or-fail package-designator)))
(oget package "exports")))
(defvar *user-package*
(make-package "CL-USER" :use (list (find-package "CL"))))
(defvar *keyword-package*
(find-package "KEYWORD"))
(defun keywordp (x)
(and (symbolp x) (eq (symbol-package x) *keyword-package*)))
(defvar *package* (find-package "CL"))
(defmacro in-package (string-designator)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setq *package* (find-package-or-fail ',string-designator))))
(defmacro defpackage (name &rest options)
(let (exports use)
(dolist (option options)
(ecase (car option)
(:export
(setf exports (append exports (cdr option))))
(:use
(setf use (append use (cdr option))))))
`(progn
(eval-when (:load-toplevel :execute)
(let ((package (%defpackage ',(string name) ',use)))
(export
(mapcar (lambda (symbol) (intern (symbol-name symbol) package)) ',exports)
package)
package))
(eval-when (:compile-toplevel)
(let ((package
(or (find-package ,name)
(make-package ',(string name) :use ',use))))
(export
(mapcar (lambda (symbol) (intern (symbol-name symbol) package)) ',exports)
package)
package))
(find-package ,name))))
(defun %redefine-package (package use)
(setf (oget package "use") use)
package)
(defun %defpackage (name use)
(let ((package (find-package name))
(use (resolve-package-list use)))
(if package
(%redefine-package package use)
(make-package name :use use))))
(defun find-symbol (name &optional (package *package*))
(let* ((package (find-package-or-fail package))
(externals (%package-external-symbols package))
(symbols (%package-symbols package)))
(cond
((in name externals)
(values (oget externals name) :external))
((in name symbols)
(values (oget symbols name) :internal))
(t
(dolist (used (package-use-list package) (values nil nil))
(let ((exports (%package-external-symbols used)))
(when (in name exports)
(return (values (oget exports name) :inherited)))))))))
;;; It is a function to call when a symbol is interned. The function
;;; is invoked with the already interned symbol as argument.
(defvar *intern-hook* nil)
(defun intern (name &optional (package *package*))
(let ((package (find-package-or-fail package)))
(multiple-value-bind (symbol foundp)
(find-symbol name package)
(if foundp
(values symbol foundp)
(let ((symbols (%package-symbols package)))
(oget symbols name)
(let ((symbol (make-symbol name)))
(setf (oget symbol "package") package)
(when (eq package *keyword-package*)
(setf (oget symbol "value") symbol)
(export (list symbol) package))
(when *intern-hook*
(funcall *intern-hook* symbol))
(setf (oget symbols name) symbol)
(values symbol nil)))))))
(defun symbol-package (symbol)
(unless (symbolp symbol)
(error "`~S' is not a symbol." symbol))
(oget symbol "package"))
(defun export (symbols &optional (package *package*))
(let ((exports (%package-external-symbols package)))
(dolist (symb (ensure-list symbols) t)
(setf (oget exports (symbol-name symb)) symb))))
(defun %map-external-symbols (function package)
(map-for-in function (%package-external-symbols package)))
(defun %map-symbols (function package)
(map-for-in function (%package-symbols package))
(dolist (used (package-use-list package))
(%map-external-symbols function used)))
(defun %map-all-symbols (function)
(map-for-in (lambda (package)
(map-for-in function (%package-symbols package)))
*package-table*))
(defun %map-all-external-symbols (function)
(map-for-in (lambda (package)
(map-for-in function (%package-external-symbols package)))
*package-table*))
(defmacro do-symbols ((var &optional (package '*package*) result-form)
&body body)
`(block nil
(%map-symbols
(lambda (,var) ,@body)
(find-package ,package))
,result-form))
(defmacro do-external-symbols ((var &optional (package '*package*)
result-form)
&body body)
`(block nil
(%map-external-symbols
(lambda (,var) ,@body)
(find-package ,package))
,result-form))
(defmacro do-all-symbols ((var &optional result-form) &body body)
`(block nil (%map-all-symbols (lambda (,var) ,@body)) ,result-form))
(defmacro do-all-external-symbols ((var &optional result-form) &body body)
`(block nil (%map-all-external-symbols (lambda (,var) ,@body)) ,result-form))
(defun find-all-symbols (string &optional external-only)
(let (symbols)
(map-for-in (lambda (package)
(multiple-value-bind (symbol status) (find-symbol string package)
(when (if external-only (eq status :external) status)
(pushnew symbol symbols :test #'eq))))
*package-table*)
symbols))
| 7,948 | Common Lisp | .lisp | 191 | 35.020942 | 86 | 0.644292 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 4840a15498d1ed5c76bbf526566ef1a0c371f2d569897c8152fa4d9be7f7b8d3 | 6 | [
-1
] |
7 | hash-table.lisp | jscl-project_jscl/src/hash-table.lisp | ;;; hash-table.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; Plain Javascript objects are the natural way to implement Common
;;; Lisp hash tables. However, there is a big differences between
;;; them which we need to work around. Javascript objects require the
;;; keys to be strings. To solve that, we map Lisp objects to strings
;;; such that "equivalent" values map to the same string, regarding
;;; the equality predicate used (one of `eq', `eql', `equal' and
;;; `equalp').
;;;
;;; Additionally, we want to iterate across the hash table
;;; key-values. So we use a cons (key . value)
;;; as value in the Javascript object. It implicitly gives the
;;; inverse mapping of strings to our objects.
;;; If a hash table has `eq' as test, we need to generate unique
;;; strings for each Lisp object. To do this, we tag the objects with
;;; a `$$jscl_id' property. As a special case, numbers do not need to
;;; be tagged, as they can be used to index Javascript objects.
(/debug "loading hash-table.lisp!")
(defvar *eq-hash-counter* 0)
(defun eq-hash (x)
(cond ((numberp x) x)
(t (unless (in "$$jscl_id" x)
(oset (concat "$" *eq-hash-counter*) x "$$jscl_id")
(incf *eq-hash-counter*))
(oget x "$$jscl_id"))))
;;; We do not have bignums, so eql is equivalent to eq.
(defun eql-hash (x)
(eq-hash x))
;;; In the case of equal-based hash tables, we do not store the hash
;;; in the objects, but compute a hash from the elements it contains.
(defun equal-hash (x)
(cond ((consp x)
(concat "(" (equal-hash (car x)) (equal-hash (cdr x)) ")"))
((stringp x)
;; at this place x always string, so used (oget length)
(concat "s" (storage-vector-size x) ":" (lisp-to-js x)))
(t (eql-hash x))))
(defun equalp-hash (x)
;; equalp is not implemented as predicate. So I am skipping this one
;; by now.
)
(defun hash-table-p (obj)
(if (js-undefined-p obj)
nil
(eql (object-type-code obj) :hash-table)))
(defun %select-hash-fn (fn)
(cond
((eql fn #'eq) 'eq-hash )
((eql fn #'eql) 'eql-hash )
((eql fn #'equal) 'equal-hash )
(t (error "Incorrect hash function: ~s." test))))
(defun make-hash-table (&key (test #'eql) size)
(let ((cell (cons (%select-hash-fn test) (new))))
(set-object-type-code cell :hash-table)
cell))
(defun gethash (key hash-table &optional default)
(let ((table (cdr hash-table))
(hash (funcall (car hash-table) key)))
(if (in hash table)
(values (cdr (oget table hash)) t)
(values default nil))))
(defun sethash (new-value key hash-table)
(let ((table (cdr hash-table))
(hash (funcall (car hash-table) key)))
(oset (cons key new-value) table hash)
new-value))
(define-setf-expander gethash (key hash-table &optional defaults)
(let ((g!key (gensym))
(g!hash-table (gensym))
(g!defaults (gensym))
(g!new-value (gensym)))
(values (list g!key g!hash-table g!defaults) ; temporary variables
(list key hash-table defaults) ; value forms
(list g!new-value) ; store variables
`(progn
(sethash ,g!new-value ,g!key ,g!hash-table) ; storing form
,g!new-value)
`(gethash ,g!key ,g!hash-table) ; accessing form
)))
(defun remhash (key table)
(unless (hash-table-p table)
(error "The value ~s is not of type HASH-TABLE." table))
(let ((obj (cdr table))
(hash (funcall (car table) key)))
(prog1
(in hash obj)
(delete-property hash obj))))
(defun clrhash (obj)
(if (hash-table-p obj)
(progn
(rplacd obj (new))
obj)
(error "The value ~s is not of type HASH-TABLE." obj)))
(defun hash-table-count (obj)
(if (and (consp obj) (eql (object-type-code obj) :hash-table))
(oget (#j:Object:entries (cdr obj)) "length")
0))
(defun maphash (function table)
(unless (hash-table-p table)
(error "The value ~s is not of type HASH-TABLE." table))
(map-for-in
(lambda (x) (funcall function (car x) (cdr x)))
(cdr table))
nil)
;;; the test value returned is always a symbol
(defun hash-table-test (obj)
(unless (hash-table-p obj)
(error "The value ~s is not of type HASH-TABLE." obj))
(let ((test (car obj)))
(cond ((eq test 'eq-hash) 'eq)
((eq test 'eql-hash) 'eql)
(t 'equal))))
;;; copy-hash-table - not in standard
(defun copy-hash-table (origin)
(unless (hash-table-p origin)
(error "The value ~s is not of type HASH-TABLE." origin))
(let ((cell (cons (car origin)
;; todo: Object.assign as builtin method-call?
(#j:Object:assign (new) (cdr origin)))))
(oset :hash-table cell "td_Name")
cell))
;;; all keys containing
(defun hash-table-keys (table)
(let ((keys nil))
(maphash (lambda (k v)
(declare (ignore v))
(push k keys))
table)
keys))
;;; all values containing
(defun hash-table-values (table)
(let ((values nil))
(maphash (lambda (k v)
(declare (ignore k))
(push v values))
table)
values))
;;; EOF
| 5,870 | Common Lisp | .lisp | 150 | 33.893333 | 81 | 0.623003 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | a4011baae3453bc244ab80b272a8b0f5d4c5b092d00992bfa01dde1153e04e7f | 7 | [
-1
] |
8 | symbol.lisp | jscl-project_jscl/src/symbol.lisp | ;;; symbols ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading symbol.lisp!")
(defun symbolp (x) (symbolp x))
(defun symbol-plist (x)
(cond
((not (symbolp x))
(error "`~a' is not a symbol." x))
((in "plist" x)
(oget* x "plist"))))
(defun set-symbol-plist (new-value x)
(unless (symbolp x )
(error "`~a' is not a symbol." x))
(unless (listp new-value)
(error "`~a' is not a list." new-value))
(oset* new-value x "plist"))
(define-setf-expander symbol-plist (x)
(let ((g!x (gensym))
(g!value (gensym)))
(values (list g!x)
(list x)
(list g!value)
`(set-symbol-plist ,g!value ,g!x)
`(symbol-plist ,g!x))))
(defun get (symbol indicator &optional default)
(getf (symbol-plist symbol) indicator default))
(define-setf-expander get (symbol indicator &optional default)
(get-setf-expansion `(getf (symbol-plist ,symbol) ,indicator ,default)))
(defun symbol-function (symbol)
(symbol-function symbol))
(defsetf symbol-function fset)
| 1,628 | Common Lisp | .lisp | 42 | 35.071429 | 74 | 0.678934 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | edad3694a33b9eef2ec099122bbb94ff46dbfc5567bba871d67cfe9a8bf173e0 | 8 | [
-1
] |
9 | toplevel.lisp | jscl-project_jscl/src/toplevel.lisp | ;;; toplevel.lisp ---
;; Copyright (C) 2012, 2013, 2014 David Vazquez
;; Copyright (C) 2012 Raimon Grau
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading toplevel.lisp!")
(defun eval (x)
(let ((jscode
(with-compilation-environment
(compile-toplevel x t t))))
(js-eval jscode)))
(defvar * nil)
(defvar ** nil)
(defvar *** nil)
(defvar / nil)
(defvar // nil)
(defvar /// nil)
(defvar + nil)
(defvar ++ nil)
(defvar +++ nil)
(defvar - nil)
(defun eval-interactive (x)
(setf - x)
(let ((results (multiple-value-list (eval x))))
(setf /// //
// /
/ results
*** **
** *
* (car results)))
(unless (boundp '*)
;; FIXME: Handle error
(setf * nil))
(setf +++ ++
++ +
+ -)
(values-list /))
(export
'(&allow-other-keys &aux &body &environment &key &optional &rest &whole
* ** *** *break-on-signals* *compile-file-pathname*
*compile-file-truename* *compile-print* *compile-verbose* *debug-io*
*debugger-hook* *default-pathname-defaults* *error-output* *features*
*gensym-counter* *load-pathname* *load-print* *load-truename*
*load-verbose* *macroexpand-hook* *modules* *package* *print-array*
*print-base* *print-case* *print-circle* *print-escape* *print-gensym*
*print-length* *print-level* *print-lines* *print-miser-width*
*print-pprint-dispatch* *print-pretty* *print-radix* *print-readably*
*print-right-margin* *query-io* *random-state* *read-base*
*read-default-float-format* *read-eval* *read-suppress* *readtable*
*standard-input* *standard-output* *terminal-io* *trace-output* + ++
+++ - / // /// /= 1+ 1- < <= = > >= abort abs acons acos acosh
add-method adjoin adjust-array adjustable-array-p allocate-instance
alpha-char-p alphanumericp and append apply apropos apropos-list aref
arithmetic-error arithmetic-error-operands arithmetic-error-operation
array array-dimension array-dimension-limit array-dimensions
array-displacement array-element-type array-has-fill-pointer-p
array-in-bounds-p array-rank array-rank-limit array-row-major-index
array-total-size array-total-size-limit arrayp ash asin asinh assert
assoc assoc-if assoc-if-not atan atanh atom base-char base-string
bignum bit bit-and bit-andc1 bit-andc2 bit-eqv bit-ior bit-nand
bit-nor bit-not bit-orc1 bit-orc2 bit-vector bit-vector-p bit-xor
block boole boole-1 boole-2 boole-and boole-andc1 boole-andc2 boole-c1
boole-c2 boole-clr boole-eqv boole-ior boole-nand boole-nor boole-orc1
boole-orc2 boole-set boole-xor boolean both-case-p boundp break
broadcast-stream broadcast-stream-streams built-in-class butlast byte
byte-position byte-size caaaar caaadr caaar caadar caaddr caadr caar
cadaar cadadr cadar caddar cadddr caddr cadr call-arguments-limit
call-method call-next-method car case catch ccase cdaaar cdaadr cdaar
cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr
cdr ceiling cell-error cell-error-name cerror change-class char
char-code char-code-limit char-downcase char-equal char-greaterp
char-int char-lessp char-name char-not-equal char-not-greaterp
char-not-lessp char-upcase char/= char< char<= char= char> char>=
character characterp check-type cis class class-name class-of
clear-input clear-output close clrhash code-char coerce
compilation-speed compile compile-file compile-file-pathname
compiled-function compiled-function-p compiler-macro
compiler-macro-function complement complex complexp
compute-applicable-methods compute-restarts concatenate
concatenated-stream concatenated-stream-streams cond condition
conjugate cons consp constantly constantp continue control-error
copy-alist copy-list copy-pprint-dispatch copy-readtable copy-seq
copy-structure copy-symbol copy-tree cos cosh count count-if
count-if-not ctypecase debug decf declaim declaration declare
decode-float decode-universal-time defclass defconstant defgeneric
define-compiler-macro define-condition define-method-combination
define-modify-macro define-setf-expander define-symbol-macro defmacro
defmethod defpackage defparameter defsetf defstruct deftype defun
defvar delete delete-duplicates delete-file delete-if delete-if-not
delete-package denominator deposit-field describe describe-object
destructuring-bind digit-char digit-char-p directory
directory-namestring disassemble division-by-zero do do*
do-all-symbols do-external-symbols do-symbols documentation dolist
dotimes double-float double-float-epsilon
double-float-negative-epsilon dpb dribble dynamic-extent ecase
echo-stream echo-stream-input-stream echo-stream-output-stream ed
eighth elt encode-universal-time end-of-file endp enough-namestring
ensure-directories-exist ensure-generic-function eq eql equal equalp
error etypecase eval eval-when evenp every exp export expt
extended-char fboundp fceiling fdefinition ffloor fifth file-author
file-error file-error-pathname file-length file-namestring
file-position file-stream file-string-length file-write-date fill
fill-pointer find find-all-symbols find-class find-if find-if-not
find-method find-package find-restart find-symbol finish-output first
fixnum flet float float-digits float-precision float-radix float-sign
floating-point-inexact floating-point-invalid-operation
floating-point-overflow floating-point-underflow floatp floor
fmakunbound force-output format formatter fourth fresh-line fround
ftruncate ftype funcall function function-keywords
function-lambda-expression functionp gcd generic-function gensym
gentemp get get-decoded-time get-dispatch-macro-character
get-internal-real-time get-internal-run-time get-macro-character
get-output-stream-string get-properties get-setf-expansion
get-universal-time getf gethash go graphic-char-p handler-bind
handler-case hash-table hash-table-count hash-table-p
hash-table-rehash-size hash-table-rehash-threshold hash-table-size
hash-table-test host-namestring identity if ignorable ignore
ignore-errors imagpart import in-package incf initialize-instance
inline input-stream-p inspect integer integer-decode-float
integer-length integerp interactive-stream-p intern
internal-time-units-per-second intersection invalid-method-error
invoke-debugger invoke-restart invoke-restart-interactively isqrt
keyword keywordp labels lambda lambda-list-keywords
lambda-parameters-limit last lcm ldb ldb-test ldiff
least-negative-double-float least-negative-long-float
least-negative-normalized-double-float
least-negative-normalized-long-float
least-negative-normalized-short-float
least-negative-normalized-single-float least-negative-short-float
least-negative-single-float least-positive-double-float
least-positive-long-float least-positive-normalized-double-float
least-positive-normalized-long-float
least-positive-normalized-short-float
least-positive-normalized-single-float least-positive-short-float
least-positive-single-float length let let* lisp-implementation-type
lisp-implementation-version list list* list-all-packages list-length
listen listp load load-logical-pathname-translations load-time-value
locally log logand logandc1 logandc2 logbitp logcount logeqv
logical-pathname logical-pathname-translations logior lognand lognor
lognot logorc1 logorc2 logtest logxor long-float long-float-epsilon
long-float-negative-epsilon long-site-name loop loop-finish
lower-case-p machine-instance machine-type machine-version
macro-function macroexpand macroexpand-1 macrolet make-array
make-broadcast-stream make-concatenated-stream make-condition
make-dispatch-macro-character make-echo-stream make-hash-table
make-instance make-instances-obsolete make-list make-load-form
make-load-form-saving-slots make-method make-package make-pathname
make-random-state make-sequence make-string make-string-input-stream
make-string-output-stream make-symbol make-synonym-stream
make-two-way-stream makunbound map map-into mapc mapcan mapcar mapcon
maphash mapl maplist mask-field max member member-if member-if-not
merge merge-pathnames method method-combination
method-combination-error method-qualifiers min minusp mismatch mod
mop-object mop-object-p
most-negative-double-float most-negative-fixnum
most-negative-long-float most-negative-short-float
most-negative-single-float most-positive-double-float
most-positive-fixnum most-positive-long-float
most-positive-short-float most-positive-single-float muffle-warning
multiple-value-bind multiple-value-call multiple-value-list
multiple-value-prog1 multiple-value-setq multiple-values-limit
name-char namestring nbutlast nconc next-method-p nil nintersection
ninth no-applicable-method no-next-method not notany notevery
notinline nreconc nreverse nset-difference nset-exclusive-or
nstring-capitalize nstring-downcase nstring-upcase nsublis nsubst
nsubst-if nsubst-if-not nsubstitute nsubstitute-if nsubstitute-if-not
nth nth-value nthcdr null number numberp numerator nunion oddp open
open-stream-p optimize or otherwise output-stream-p package
package-error package-error-package package-name package-nicknames
package-shadowing-symbols package-use-list package-used-by-list
packagep pairlis parse-error parse-integer parse-namestring pathname
pathname-device pathname-directory pathname-host pathname-match-p
pathname-name pathname-type pathname-version pathnamep peek-char phase
pi plusp pop position position-if position-if-not pprint
pprint-dispatch pprint-exit-if-list-exhausted pprint-fill
pprint-indent pprint-linear pprint-logical-block pprint-newline
pprint-pop pprint-tab pprint-tabular prin1 prin1-to-string princ
princ-to-string print print-not-readable print-not-readable-object
print-object print-unreadable-object probe-file proclaim prog prog*
prog1 prog2 progn program-error progv provide psetf psetq push pushnew
quote random random-state random-state-p rassoc rassoc-if
rassoc-if-not ratio rational rationalize rationalp read read-byte
read-char read-char-no-hang read-delimited-list read-from-string
read-line read-preserving-whitespace read-sequence reader-error
readtable readtable-case readtablep real realp realpart reduce
reinitialize-instance rem remf remhash remove remove-duplicates
remove-if remove-if-not remove-method remprop rename-file
rename-package replace require rest restart restart-bind restart-case
restart-name return return-from revappend reverse room rotatef round
row-major-aref rplaca rplacd safety satisfies sbit scale-float schar
search second sequence serious-condition set set-difference
set-dispatch-macro-character set-exclusive-or set-macro-character
set-pprint-dispatch set-syntax-from-char setf setq seventh shadow
shadowing-import shared-initialize shiftf short-float
short-float-epsilon short-float-negative-epsilon short-site-name
signal signed-byte signum simple-array simple-base-string
simple-bit-vector simple-bit-vector-p simple-condition
simple-condition-format-arguments simple-condition-format-control
simple-error simple-string simple-string-p simple-type-error
simple-vector simple-vector-p simple-warning sin single-float
single-float-epsilon single-float-negative-epsilon sinh sixth sleep
slot-boundp slot-exists-p slot-makunbound slot-missing slot-unbound
slot-value software-type software-version some sort space special
special-operator-p speed sqrt stable-sort standard standard-char
standard-char-p standard-class standard-generic-function
standard-method standard-object step storage-condition store-value
stream stream-element-type stream-error stream-error-stream
stream-external-format streamp string string-capitalize
string-downcase string-equal string-greaterp string-left-trim
string-lessp string-not-equal string-not-greaterp string-not-lessp
string-right-trim string-stream string-trim string-upcase string/=
string< string<= string= string> string>= stringp structure
structure-class structure-object style-warning sublis subseq subsetp
subst subst-if subst-if-not substitute substitute-if substitute-if-not
subtypep svref sxhash symbol symbol-function symbol-macrolet
symbol-name symbol-package symbol-plist symbol-value symbolp
synonym-stream synonym-stream-symbol t tagbody tailp tan tanh tenth
terpri the third throw time trace translate-logical-pathname
translate-pathname tree-equal truename truncate two-way-stream
two-way-stream-input-stream two-way-stream-output-stream type
type-error type-error-datum type-error-expected-type type-of typecase
typep unbound-slot unbound-slot-instance unbound-variable
undefined-function unexport unintern union unless unread-char
unsigned-byte untrace unuse-package unwind-protect
update-instance-for-different-class
update-instance-for-redefined-class upgraded-array-element-type
upgraded-complex-part-type upper-case-p use-package use-value
user-homedir-pathname values values-list variable vector vector-pop
vector-push vector-push-extend vectorp warn warning when
wild-pathname-p with-accessors with-compilation-unit
with-condition-restarts with-hash-table-iterator
with-input-from-string with-open-file with-open-stream
with-output-to-string with-package-iterator with-simple-restart
with-slots with-standard-io-syntax write write-byte write-char
write-line write-sequence write-string write-to-string y-or-n-p
yes-or-no-p zerop))
(setq *package* *user-package*)
(defun compilation-notice ()
#.(let ((build-time
;; The variable SOURCE_DATE_EPOCH specifies the point in
;; time of the project. It is usually set to the unix
;; timestamp of the GIT commit being built, to make the
;; build artifact reproducible. Variable is specified at
;;
;; https://reproducible-builds.org/specs/source-date-epoch/
;;
(or (get-source-data-epoch)
(get-universal-time)) ))
(multiple-value-bind (second minute hour date month year)
(decode-universal-time build-time)
(declare (ignore second minute hour))
(format nil "built on ~d ~a ~d"
date
(elt #("" "January" "February" "March" "April" "May" "June"
"July" "August" "September" "October" "November"
"December")
month)
year))))
(when (and (string/= (%js-typeof |module|) "undefined")
(string= (%js-typeof |phantom|) "undefined")
(string/= (%js-typeof |process|) "undefined"))
(push :node *features*))
(when (string/= (%js-typeof |Deno|) "undefined")
(push :deno *features*))
(defun welcome-message (&key (html nil))
(format t "Welcome to ~a (version ~a ~a)~%~%"
(lisp-implementation-type)
(lisp-implementation-version)
(compilation-notice))
(format t "JSCL is a Common Lisp implementation on Javascript.~%")
(if html
(%write-string
(format nil "For more information, visit the project page at <a href=\"https://github.com/jscl-project/jscl\">GitHub</a>.~%~%")
nil)
(format t "For more information, visit the project page at https://github.com/jscl-project/jscl.~%~%")))
;;; Basic *standard-output* stream. This will usually be overriden by
;;; web or node REPL.
;;;
;;; TODO: Cache character operation so they result in a single call to
;;; console.log.
;;;
(setq *standard-output*
(make-stream
:write-fn (lambda (string)
(#j:console:log string))))
(cond
((find :node *features*)
(setq *root* (%js-vref "global"))
(setf #j:Fs (funcall (%js-vref "require") "fs"))
(setf #j:FsPath (funcall (%js-vref "require") "path")))
((string/= (%js-typeof |window|) "undefined")
(setq *root* (%js-vref "window")))
(t
(setq *root* (%js-vref "self"))))
(defun require (name)
(if (find :node *features*)
(funcall (%js-vref "require") name)))
(when (jscl::web-worker-p)
(jscl::initialize-web-worker))
| 16,872 | Common Lisp | .lisp | 309 | 49.935275 | 134 | 0.763223 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 4a2d9cabdf0983eeaef8834170bbee3ed2402f1a5301a9f04203cdb4abec2d8e | 9 | [
-1
] |
10 | types.lisp | jscl-project_jscl/src/types.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; Tiny type system for JSCL @vkm
;;;
;;; JSCL is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; JSCL is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading types.lisp!")
;;; for internal used only
(defun true () t)
(defun false () nil)
(defun void () (values))
;;; For to accurately definition LIST and CONS forms.
;;; Now inferno gate is opened. Welcome to DOOM
;;;
;;; (typep form
;;; (cons
;;; (cond ((true-cons-p form) .... code sensetive for cons)
;;; (t ...))))
;;; (true-list-p '(1 2 3 . t)) => nil
;;; (true-consp-p '(1 2 3 . t)) => t
;;;
;;; todo: rename true-cons-p -> dotted-pair-p
;;; move to list.lisp
(defun true-cons-p (form)
(%js-try
(progn
(list-length form)
nil)
(catch (err)
t)))
;;; pure list predicate: (true-list-p (cons 1 2)) => nil
;;; (listp (cons 1 2)) => t
;;; todo: rename true-list-p -> proper-list-p
;;; move to list.lisp
(defun true-list-p (obj) (and (consp obj) (not (true-cons-p obj))))
(defun get-expander-for (type)
(let ((exists (%deftype-info (if (symbolp type) type (car type)) nil)))
(if exists (type-info-expand exists))))
(defun get-compound-for (type)
(let ((exists (%deftype-info (if (symbolp type) type (car type)) nil)))
(if exists (type-info-compound exists))))
(defun get-predicate-for (type)
(let ((exists (%deftype-info (if (symbolp type) type (car type)) nil)))
(if exists (type-info-predicate exists))))
(defparameter *types-basic-types*
;; name predicate class super-class rest
'((hash-table hash-table-p t t )
(package packagep t t )
;;(stream streamp t t )
(atom atom t t )
;;(structure structure-p t t )
(js-object js-object-p t t )
(js-null js-null-p t t )
(clos-object mop-object-p nil t)
(character characterp t t )
;; symbol relations
(symbol symbolp t t )
(keyword keywordp t symbol t)
;; callable relations
(function functionp t t )
;; numeric relations
(number numberp nil t)
(real realp nil number t)
(rational rationalp nil rational real number t)
;;(float floatp t real number t)
;;(integer integerp t rational real number t)
(float floatp t number t)
(integer integerp t number t)
;; sequnce relations
(sequence sequencep nil t)
(list listp t sequence t)
(cons consp t list sequence t)
(array arrayp t sequence t)
(vector vectorp t array sequence t)
(string stringp t vector array sequence t)
(null null t list sequence t)
(nil null nil list sequence t)
(t true nil t)))
(%i-struct (basic-type (:form &key)) name predicate class-of supertype tpl)
(defvar *builtin-types* (make-hash-table :test #'eql) "hand off")
(let ((tip))
(/debug " compile basic types")
(dolist (it *types-basic-types*)
(destructuring-bind (name predicate class-of &rest tpl) it
(setq tip (%make-basic-type
:name name
:predicate predicate
:supertype (car tpl)
:class-of class-of
:tpl tpl))
(setf (gethash name *builtin-types*) tip)
(%deftype name :predicate predicate))))
(defun builtin-type-p (name &optional (content-p nil))
(let (type-info)
(setq type-info
(gethash (if (consp name) (car name) name) *builtin-types*))
(if (null type-info)
(values nil nil)
(if content-p
(values type-info t)
(values (if type-info t nil) t)))))
;;; => class-cpl-list::= (name ... name)
;;; name::= symbol
(defun %class-cpl(class-name)
(%lmapcar #'class-name (class-precedence-list (find-class class-name nil))))
;;; c1-cpl::= symbol | cpl
;;; c2-name::= symbol | (find-class c2)
(defun %subclass (c1-cpl c2-name)
(if (memq (if (symbolp c2-name) c2-name (class-name c2-name))
(if (symbolp c1-cpl) (%class-cpl c1-cpl) c1-cpl))
t
nil))
;;; from CLOS std-object.lisp
(defun built-in-class-of (x)
(typecase x
(null (!find-class 'null))
(hash-table (!find-class 'hash-table))
(structure (!find-class 'structure))
(stream (!find-class 'stream))
(symbol (!find-class 'symbol))
(keyword (!find-class 'keyword))
;;(number (!find-class 'number))
;;(real (!find-class 'real))
;;(rational (!find-class 'rational))
(integer (!find-class 'integer))
(float (!find-class 'float))
(cons (!find-class 'cons))
(character (!find-class 'character))
(package (!find-class 'package))
(string (!find-class 'string))
(vector (!find-class 'vector))
(array (!find-class 'array))
;;(sequence (!find-class 'sequence))
(function (!find-class 'function))
(js-object (!find-class 'js-object))
;;; and Root of the Evil
(t (!find-class 't))))
;;; type expander
(defun %type-expand-1 (type)
(unless (symbolp type)
(unless (consp type)
(return-from %type-expand-1 (values type nil))))
(let ((expander (get-expander-for type)))
(cond (expander
(if (symbolp type)
(setq type (list type)))
(values (funcall expander type) t))
((and (consp type)
(cadr type))
(multiple-value-bind (expansion expanded-p)
(%type-expand (cadr type))
(if expanded-p
(values (list* (car type) expansion (cddr type)) t)
(values type nil))))
(t (values type nil)))))
(defun %type-expand (form)
(let ((expanded-p nil))
(while t
(multiple-value-bind (expander continue)
(%type-expand-1 form)
(unless continue
(return-from %type-expand
(values expander expanded-p)))
(setq expanded-p t
form expander)))))
;;; very simple logic
;;; complicate logic - increase execution time
(defun %unwanted-types (thing)
(if (or (arrayp thing)
(numberp thing)
(functionp thing)
(packagep thing))
(error "Bad thing to be a type specifier ~a." thing)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun !typep (object type-specifier)
;; (%unwanted-types type-specifier)
(if (or (eql type-specifier 't)
(eql type-specifier 'nil))
(return-from !typep type-specifier))
;; may be any clos form
(if (mop-object-p type-specifier)
(return-from !typep (!typep object (class-name type-specifier))))
;; may be predicate or class name
(if (symbolp type-specifier)
(let ((test (get-predicate-for type-specifier)))
(if test (return-from !typep (funcall test object)))
;; try class name
(if (gethash type-specifier *class-table*)
(let ((class-object
(cond ((std-instance-p object) (class-name (class-of object)))
;; fixme:
((std-instance-class object) (class-name object))
(t nil))))
(if class-object
(return-from !typep
(%subclass (%class-cpl class-object) type-specifier)))))))
;; may be compound type specifier
(let ((test (get-compound-for type-specifier)))
(if test
(return-from !typep (funcall test object type-specifier))))
;; may be predicate cons form without arguments
(if (and (consp type-specifier) (null (rest type-specifier)))
(let ((test (get-predicate-for (car type-specifier))))
(if test (return-from !typep (funcall test object)))))
;; can be a form with any typep specific syntax
(multiple-value-bind (expansion expanded-p)
(%type-expand type-specifier)
(if expanded-p
(!typep object expansion)
(error "Unknown type-specifier ~a." type-specifier)))))
(defun type-of (object)
(cond ((js-null-p object) 'js-null)
((integerp object)
(case object
((0 1) 'bit)
(t 'integer)))
((characterp object) 'character)
((floatp object) 'float)
((mop-object-p object) (class-name (class-of object)))
((hash-table-p object) 'hash-table)
((consp object) 'cons)
((stringp object)`(string ,(oget object "length")))
((arrayp object)
(cond ((null (cdr (array-dimensions object)))
`(vector ,(oget object "length")))
(t `(array ,(array-dimensions object)))))
((symbolp object)
(cond ((eq object 'nil) 'null)
((eq object 't) 'boolean)
((keywordp object) 'keyword)
(t 'symbol)))
((functionp object) 'function)
((js-object-p object) 'js-object)
((packagep object) 'package)
(t 'unreadable-object)))
;;; numeric [lower-limit [upper-limit]]
(defun check-numeric-limit (limit his-type)
(when (consp limit)
(if (rest limit)(error "Bad numeric limit ~a." limit))
(setq limit (1- (car limit))))
(unless (or (eql limit '*) (!typep limit his-type))
(error "Bad numeric limit ~a." limit))
limit)
(defun canonicalize-numeric-limits (type-specifier limit-type)
(if (consp type-specifier)
(let* ((req (validate-reqvars (cdr type-specifier) 0))
(low (if (null req) '* (car req)))
(high (if (null (cdr req)) '* (cadr req))))
(values (check-numeric-limit low limit-type)
(check-numeric-limit high limit-type) ))
(values '* '*)))
(defmacro deftype-compound (&whole whole name args &body body)
(destructuring-bind (name lambda-list &body body) whole
(multiple-value-bind (body decls docstring)
(parse-body body :declarations t :docstring t)
(let* ((compound
`(function
(lambda ,lambda-list
,@body))))
`(eval-when (:load-toplevel :execute)
(%deftype ',name :compound ,compound))))))
(macrolet ((dc (type-name predicate-name limit-type)
`(deftype-compound ,type-name (object type)
(if (,predicate-name object)
(multiple-value-bind (min max)
(canonicalize-numeric-limits type ',limit-type)
(and (or (eql min '*)
(>= object min))
(or (eql max '*)
(<= object max))))))))
(dc integer integerp integer)
;;(dc rational integerp integer)
(dc number numberp number)
;;(dc real numberp real)
(dc float floatp float))
;;; type compound: (array type dimensions)
(defun %compare-array-type (object type-spec)
(destructuring-bind (type-base &optional (type-element '* te-p) (type-dimensions '*))
type-spec
(let ((object-type (array-element-type object))
(object-dimensions (array-dimensions object)))
(when (and (eq object-type 'character) (not (eq type-element 'character)))
(if te-p (return-from %compare-array-type nil)))
(when (null object-dimensions)
(setq object-dimensions (list (oget object "length"))))
(cond ((numberp type-dimensions)
(setq type-dimensions (make-list type-dimensions :initial-element '*)))
(t (if (eql '* type-dimensions)
(setq type-dimensions
(make-list (list-length object-dimensions) :initial-element '*)))))
(cond ((not (eql (list-length type-dimensions)
(list-length object-dimensions)))
nil)
((equal (make-list (list-length type-dimensions) :initial-element 't)
(mapcar
(lambda (axis-object axis-type)
(cond ((eql axis-type '*) t)
((eql axis-object '*) nil)
(t (= axis-object axis-type))))
object-dimensions
type-dimensions)))))))
(defun %canonical-array-dimensions (dims)
(cond ((consp dims)
(dolist (it dims t)
(cond ((eq it '*))
((non-negative-fixnump it))
(t (error "Bad dimension in array type ~a." it)))))
((non-negative-fixnump dims) t)
((eq dims '*) t)
((null dims) t)
(t (error "Bad dimensions form in array type ~a." dims))))
(deftype-compound array (object type-spec)
(and (arrayp object)
(%canonical-array-dimensions (caddr type-spec))
(%compare-array-type object type-spec)))
;;; (cons * *) (cons thing aught)
(deftype-compound cons (object type)
(if (consp object)
(destructuring-bind (&optional (t1 '*) (t2 '*)) (cdr type)
(if (eq t1 '*) (setq t1 't))
(if (eq t2 '*) (setq t2 't))
(and (or (eql t1 't)
(!typep (car object) t1))
(or (eql t2 't)
(!typep (cdr object) t2))))))
;;; (list-length *) | (list-length 0) | (list-length n)
;;; (typep (list) '(list-length 0))
;;; (typesace x ((list-length 1) :ok) ((list-length 0) :bad))
(deftype-compound list-length (object type)
(when (listp object)
(if (not (true-cons-p object))
(destructuring-bind (&optional (size '*))
(cdr type)
(cond ((eq size '*) t)
((non-negative-fixnump size)
(eq size (list-length object)))
(t (error "Bad type list size specificator ~a." type)))))))
;;; (satisfies predicate)
(deftype-compound satisfies (object type)
(let ((fn (cadr type)))
(unless (or (symbolp fn) (functionp fn))
(error "Not satisfies function ~a." fn))
(funcall fn object)))
;;; (or expr .... expr*)
(deftype-compound or (object type)
(dolist (it (cdr type))
(if (!typep object it) (return t))))
;;; (and expr ... expr*)
(deftype-compound and (object type)
(dolist (it (cdr type) t)
(if (not (!typep object it)) (return nil))))
;;; (not type-specifier)
(deftype-compound not (object type)
(not (!typep object (cadr type))))
;;; (member object ... object*)
(deftype-compound member (object type)
(dolist (o (cdr type))
(if (eql object o) (return t))))
;;; (eql value)
(deftype-compound eql (object type)
(eql object (cadr type)))
;;; todo: canonical deftype lambda-list
(defmacro deftype (&whole whole name lambda-list &body body)
(destructuring-bind (name (&rest args) &body body) whole
(if (null args)
(setq args '(&optional ignore)))
(multiple-value-bind (body decls docstring)
(parse-body body :declarations t :docstring t)
(let* ((expr (gensym (symbol-name name)))
(expander
`(function
(lambda (,expr)
(destructuring-bind ,args (cdr ,expr)
,@body)))))
`(progn
(%deftype ',name :expander ,expander)
',name)))))
;;; predefenition types
;;; (mod n) -> (1- n)
(deftype mod (n)
(unless (and (integerp n) (plusp n)) (error "Type (mod ~a)." n))
`(integer 0 (,n)))
;;; (typep 1|0 '(bit)) -> t
(deftype bit () `(integer 0 1))
(deftype fixnum ()
`(integer ,most-negative-fixnum ,most-positive-fixnum))
(deftype bignum ()
;; and integer not fixnum
`(and integer (not (integer ,most-negative-fixnum ,most-positive-fixnum))))
;;; (signed-byte) |(signed-byte *)!(signed-byte n)
(deftype signed-byte (&optional (s '*))
(cond ((eq s '*) 'integer)
((and (integerp s) (> s 0))
(let ((bound (ash 1 (1- s)))) `(integer ,(- bound) ,(1- bound))))
(t (error "Bad size specified for SIGNED-BYTE type specifier: ~a." s))))
;;; (typep x 'jscl::signed-byte-8)
(deftype signed-byte-8 ()
`(and (satisfies fixnump) (integer -128 #x100)))
;;; (typep x 'jscl::signed-byte-16)
(deftype signed-byte-16 ()
`(and (satisfies fixnump) (integer -32768 32767)))
;;; (typep x 'jscl::signed-byte-16)
(deftype signed-byte-32 ()
`(and (satisfies bignump) (integer -2147483648 2147483647)))
;;; (typep x '(usigned-byte 8!16|32|4|number|*))
;;; | '(usigned-byte)
(deftype unsigned-byte (&optional (s '*))
(cond ((eq s '*) '(integer 0 *))
((and (integerp s) (> s 0)) `(integer 0 ,(1- (ash 1 s))))
(t (error "Bad size specified for UNSIGNED-BYTE type specifier: ~a." s))))
;;; jscl::unsigned-byte-8
(deftype unsigned-byte-8 ()
`(and (satisfies fixnump) (integer 0 #x100)))
;;; jscl::unsigned-byte-16
(deftype unsigned-byte-16 ()
`(and (satisfies fixnump) (integer 0 (#x10000))))
;;; jscl::unsigned-byte-32
(deftype unsigned-byte-32 ()
`(and (satisfies fixnump) (integer 0 #xffffffff)))
(deftype string (&optional (size '*))
`(array character (,size)))
(deftype vector (&optional (type 't) (size '*))
`(array ,type (,size)))
#+jscl (fset 'typep (fdefinition '!typep))
(push :types *features*)
;;; EOF
| 18,393 | Common Lisp | .lisp | 435 | 35.216092 | 92 | 0.556282 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 41abe6f4c445a77edbb5953e2c290ff700265bf07423254a0dcb4f1cc8b6bac1 | 10 | [
-1
] |
11 | utils.lisp | jscl-project_jscl/src/utils.lisp | ;;; utils.lisp ---
;; Copyright (C) 2012, 2013 David Vazquez
;; Copyright (C) 2012 Raimon Grau
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading utils.lisp!")
(defmacro with-collect (&body body)
"Makes available to BODY a function named collect. The function accumulates
values passed to it. The return value of with-collect is the list of values
accumulated, in the order."
(let ((head (gensym))
(tail (gensym)))
`(let* ((,head (cons 'sentinel nil))
(,tail ,head))
(flet ((collect (x)
(rplacd ,tail (cons x nil))
(setq ,tail (cdr ,tail))
x))
,@body)
(cdr ,head))))
(defmacro with-collector ((name &optional (collector (intern (format nil "COLLECT-~a" (symbol-name name))))) &body body)
"Similar to `with-collect' with the following differences:
1) However the list where the values are being accumulated is available to the body by the name NAME.
2) The name COLLECTOR function can be passed as a parameter
3) The return value the last form of BODY"
(let ((head (gensym))
(tail (gensym)))
`(let* ((,head (cons 'sentinel nil))
(,tail ,head))
(symbol-macrolet ((,name (cdr ,head)))
(flet ((,collector (x)
(rplacd ,tail (cons x nil))
(setq ,tail (cdr ,tail))
x))
,@body)))))
(defmacro concatf (variable &body form)
`(setq ,variable (concat ,variable (progn ,@form))))
;;; This couple of helper functions will be defined in both Common
;;; Lisp and in JSCL
(defun ensure-list (x)
(if (listp x)
x
(list x)))
(defun !reduce (func list initial-value)
(let ((result initial-value))
(dolist (element list result)
(setq result (funcall func result element)))))
;;; Concatenate a list of strings, with a separator
(defun join (list &optional (separator ""))
(if (null list)
""
(!reduce (lambda (s o) (concat s separator o))
(cdr list)
(car list))))
(defun join-trailing (list &optional (separator ""))
(if (null list)
""
(concat (car list) separator (join-trailing (cdr list) separator))))
(defun mapconcat (func list)
(join (mapcar func list)))
(defun vector-to-list (vector)
(let ((size (length vector)))
(with-collect
(dotimes (i size)
(collect (aref vector i))))))
(defun list-to-vector (list)
(let ((v (make-array (length list)))
(i 0))
(dolist (x list v)
(aset v i x)
(incf i))))
(defmacro awhen (condition &body body)
`(let ((it ,condition))
(when it ,@body)))
(defun integer-to-string (x)
(cond
((zerop x)
"0")
((minusp x)
(concat "-" (integer-to-string (- 0 x))))
(t
(let ((digits nil))
(while (not (zerop x))
(push (rem x 10) digits)
(setq x (truncate x 10)))
(mapconcat (lambda (x) (string (digit-char x)))
digits)))))
(defun float-to-string (x)
#+jscl (float-to-string x)
#-jscl (format nil "~f" x))
(defun satisfies-test-p (x y &key key (test #'eql) testp (test-not #'eql) test-not-p)
(when (and testp test-not-p)
(error "Both test and test-not are set"))
(let ((key-val (if key (funcall key y) y))
(fn (if test-not-p (complement test-not) test)))
(funcall fn x key-val)))
(defun interleave (list element &optional after-last-p)
(unless (null list)
(with-collect
(collect (car list))
(dolist (x (cdr list))
(collect element)
(collect x))
(when after-last-p
(collect element)))))
(defun find-package-or-fail (package-designator)
(or (find-package package-designator)
(error "The name `~S' does not designate any package." package-designator)))
| 4,367 | Common Lisp | .lisp | 118 | 31.5 | 120 | 0.628666 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | a42bd1c9239007768c87932f66e92bee2396a2037856a0dcdf23fe5740fe0013 | 11 | [
-1
] |
12 | lambda-list.lisp | jscl-project_jscl/src/lambda-list.lisp | ;;; lambda-list.lisp --- Lambda list parsing and destructuring
;;; Copyright (C) 2013 David Vazquez
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading lambda-list.lisp!")
(defvar !lambda-list-keywords
'(&optional &rest &key &aux &allow-other-keys &body &optional))
;;;; Lambda list parsing
(def!struct optvar
variable initform supplied-p-parameter)
(def!struct keyvar
variable keyword-name initform supplied-p-parameter)
(def!struct auxvar
variable initform)
(def!struct lambda-list
wholevar
reqvars
optvars
restvar
allow-other-keys
keyvars
auxvars)
(defun var-or-pattern (x)
(etypecase x
(symbol x)
(cons (parse-destructuring-lambda-list x))))
(defun parse-optvar (desc)
(etypecase desc
(symbol
(make-optvar :variable desc))
(cons
(let ((variable (first desc))
(initform (second desc))
(supplied-p-parameter (third desc)))
(unless (null (cdddr desc))
(error "Bad optional parameter specification `~S'" desc))
(unless (symbolp supplied-p-parameter)
(error "`~S' is not a valid supplied optional parameter." supplied-p-parameter))
(make-optvar :variable (var-or-pattern variable)
:initform initform
:supplied-p-parameter supplied-p-parameter)))))
(defun parse-keyvar (desc)
(etypecase desc
(symbol
(make-keyvar :variable desc :keyword-name (intern (string desc) "KEYWORD")))
(cons
(let (variable
keyword-name
(initform (second desc))
(supplied-p-parameter (third desc)))
(unless (null (cdddr desc))
(error "Bad keyword parameter specification `~S'" desc))
(unless (symbolp supplied-p-parameter)
(error "`~S' is not a valid supplied optional parameter." supplied-p-parameter))
(let ((name (first desc)))
(etypecase name
(symbol
(setq keyword-name (intern (string name) "KEYWORD"))
(setq variable name))
(cons
(unless (null (cddr name))
(error "Bad keyword argument name description `~S'" name))
(setq keyword-name (first name))
(setq variable (second name)))))
(unless (symbolp keyword-name)
(error "~S is not a valid keyword-name." keyword-name))
(make-keyvar :variable (var-or-pattern variable)
:keyword-name keyword-name
:initform initform
:supplied-p-parameter supplied-p-parameter)))))
(defun parse-auxvar (desc)
(etypecase desc
(symbol
(make-auxvar :variable desc))
(cons
(let ((variable (first desc))
(initform (second desc)))
(unless (null (cdddr desc))
(error "Bad aux variable specification `~S'" desc))
(make-auxvar :variable (var-or-pattern variable)
:initform initform)))))
(defun parse-destructuring-lambda-list (lambda-list)
(let (;; Destructure lambda list structure where we accumulate the
;; results of the parsing.
(ll (make-lambda-list))
;; List of lambda list keywords which we have already seen.
(lambda-keywords nil))
(flet (;; Check if we are in the beginning of the section NAME in
;; the lambda list. It also checks if the section is in the
;; proper place and it is new.
(lambda-section (name)
(let ((section (and (consp lambda-list) (first lambda-list))))
(when (find section lambda-keywords)
(error "Bad placed ~a in the lambda-list ~S." section lambda-list))
(when (eq name section)
(push name lambda-keywords)
(pop lambda-list)
t)))
;; Check if we are in the middle of a lambda list section,
;; looking for a lambda list keyword in the current
;; position of the lambda list.
(in-section-p ()
(and (consp lambda-list)
(not (find (first lambda-list) !lambda-list-keywords)))))
;; &whole var
(when (lambda-section '&whole)
(let ((wholevar (pop lambda-list)))
(setf (lambda-list-wholevar ll) (var-or-pattern wholevar))))
;; required vars
(while (in-section-p)
(let ((var (pop lambda-list)))
(push (var-or-pattern var) (lambda-list-reqvars ll))))
(setf (lambda-list-reqvars ll)
(reverse (lambda-list-reqvars ll)))
;; optional vars
(when (lambda-section '&optional)
(while (in-section-p)
(push (parse-optvar (pop lambda-list))
(lambda-list-optvars ll)))
(setf (lambda-list-optvars ll)
(reverse (lambda-list-optvars ll))))
;; Dotted lambda-list and &rest/&body vars. If the lambda-list
;; is dotted. Convert it the tail to a &rest and finish.
(when (and lambda-list (atom lambda-list))
(push lambda-list (lambda-list-restvar ll))
(setq lambda-list nil))
(when (find (car lambda-list) '(&body &rest))
(pop lambda-list)
(setf (lambda-list-restvar ll)
(var-or-pattern (pop lambda-list))))
;; Keyword arguments
(when (lambda-section '&key)
(while (in-section-p)
(push (parse-keyvar (pop lambda-list))
(lambda-list-keyvars ll)))
(setf (lambda-list-keyvars ll)
(reverse (lambda-list-keyvars ll))))
(when (lambda-section '&allow-other-keys)
(setf (lambda-list-allow-other-keys ll) t))
;; Aux variables
(when (lambda-section '&aux)
(while (in-section-p)
(push (parse-auxvar (pop lambda-list))
(lambda-list-auxvars ll)))
(setf (lambda-list-auxvars ll)
(reverse (lambda-list-auxvars ll))))
ll)))
;;;; Destructuring
(defmacro do-keywords (var value list &body body)
(let ((g!list (gensym)))
`(let ((,g!list ,list))
(while ,g!list
(let ((,var (car ,g!list))
(,value (cadr ,g!list)))
,@body)
(setq ,g!list (cddr ,g!list))))))
;;; Return T if KEYWORD is supplied in the list of arguments LIST.
(defun keyword-supplied-p (keyword list)
(do-keywords key value list
(declare (ignore value))
(when (eq key keyword) (return t))
(setq list (cddr list))))
;;; Return the value of KEYWORD in the list of arguments LIST or NIL
;;; if it is not supplied.
(defun keyword-lookup (keyword list)
(do-keywords key value list
(when (eq key keyword) (return value))
(setq list (cddr list))))
(defun validate-reqvars (list n)
(unless (listp list)
(error "`~S' is not a list." list))
(if (zerop n)
list
;; Note that we don't mind if the list is an improper list.
(let ((tail (nthcdr (1- n) list)))
(unless (consp tail)
(error "Too few list elements in `~S'. Expected at least ~a elements." list n))
list)))
(defun validate-max-args (list)
(unless (null list)
(error "Too many elements `~S' in the lambda-list" list))
list)
;;; Validate a list of keyword arguments.
(defun validate-keyvars (list keyword-list &optional allow-other-keys)
(let (;; If it is non-NIL, we have to check for unknown keyword
;; arguments in the list to signal an error in that case.
(allow-other-keys
(or allow-other-keys (keyword-lookup :allow-other-keys list))))
(unless allow-other-keys
(do-keywords key value list
(declare (ignore value))
(unless (find key keyword-list)
(error "Unknown keyword argument `~S'." key))))
(do* ((tail list (cddr tail))
(key (car tail) (car tail)))
((null tail) list)
(unless (symbolp key)
(error "Keyword argument `~S' is not a symbol." key))
(unless (consp (cdr tail))
(error "Odd number of keyword arguments.")))))
(defun !expand-destructuring-bind (lambda-list expression &rest body)
(multiple-value-bind (ll)
(parse-destructuring-lambda-list lambda-list)
(let ((bindings '()))
(labels ( ;; Return a chain of the form (CAR (CDR (CDR ... (CDR X))),
;; such that there are N calls to CDR.
(nth-chain (x n &optional tail)
(if tail
(if (zerop n) x `(cdr ,(nth-chain x (1- n) t)))
`(car ,(nth-chain x n t))))
;; Compute the bindings for a pattern against FORM. If
;; PATTERN is a lambda-list the pattern is bound to an
;; auxiliary variable, otherwise PATTERN must be a
;; symbol it will be bound to the form. The variable
;; where the form is bound is returned.
(compute-pbindings (pattern form)
(cond
((null pattern))
((symbolp pattern)
(push `(,pattern ,form) bindings)
pattern)
((lambda-list-p pattern)
(compute-bindings pattern form))))
;; Compute the bindings for the full LAMBDA-LIST ll
;; against FORM.
(compute-bindings (ll form)
(let ((reqvar-count (length (lambda-list-reqvars ll)))
(optvar-count (length (lambda-list-optvars ll)))
(whole (or (lambda-list-wholevar ll) (gensym))))
;; Create a binding for the whole expression
;; FORM. It will match to LL, so we validate the
;; number of elements on the result of FORM.
(compute-pbindings whole `(validate-reqvars ,form ,reqvar-count))
(let ((count 0))
;; Required vars
(dolist (reqvar (lambda-list-reqvars ll))
(compute-pbindings reqvar (nth-chain whole count))
(incf count))
;; Optional vars
(dolist (optvar (lambda-list-optvars ll))
(when (optvar-supplied-p-parameter optvar)
(compute-pbindings (optvar-supplied-p-parameter optvar)
`(not (null ,(nth-chain whole count t)))))
(compute-pbindings (optvar-variable optvar)
`(if (null ,(nth-chain whole count t))
,(optvar-initform optvar)
,(nth-chain whole count)))
(incf count))
;; Rest-variable and keywords
;; If there is a rest or keyword variable, we
;; will add a binding for the rest or an
;; auxiliary variable. The computations in of the
;; keyword start in this variable, so we avoid
;; the long tail of nested CAR/CDR operations
;; each time. We also include validation of
;; keywords if there is any.
(let* ((chain (nth-chain whole (+ reqvar-count optvar-count) t))
(restvar (lambda-list-restvar ll))
(pattern (or restvar (gensym)))
(keywords (mapcar #'keyvar-keyword-name (lambda-list-keyvars ll)))
(rest
;; Create a binding for the rest of the
;; arguments. If there is keywords, then
;; validate this list. If there is no
;; keywords and no &rest variable, then
;; validate that the rest is empty, it is
;; to say, there is no more arguments
;; that we expect.
(cond
(keywords (compute-pbindings pattern `(validate-keyvars ,chain ',keywords ,(lambda-list-allow-other-keys ll))))
(restvar (compute-pbindings pattern chain))
(t (compute-pbindings pattern `(validate-max-args ,chain))))))
(when (lambda-list-keyvars ll)
;; Keywords
(dolist (keyvar (lambda-list-keyvars ll))
(let ((variable (keyvar-variable keyvar))
(keyword (keyvar-keyword-name keyvar))
(supplied (or (keyvar-supplied-p-parameter keyvar)
(gensym))))
(when supplied
(compute-pbindings supplied `(keyword-supplied-p ,keyword ,rest)))
(compute-pbindings variable `(if ,supplied
(keyword-lookup ,keyword ,rest)
,(keyvar-initform keyvar)))))))
;; Aux variables
(dolist (auxvar (lambda-list-auxvars ll))
(compute-pbindings (auxvar-variable auxvar) (auxvar-initform auxvar))))
whole)))
;; Macroexpansion. Compute bindings and generate code for them
;; and some necessary checking.
(compute-bindings ll expression)
`(let* ,(reverse bindings)
,@body)))))
;;; Because DEFMACRO uses destructuring-bind to parse the arguments of
;;; the macro-function, we can't define DESTRUCTURING-BIND with
;;; defmacro to avoid a circularity. So just define the macro function
;;; explicitly.
#-jscl
(defmacro !destructuring-bind (lambda-list expression &body body)
(apply #'!expand-destructuring-bind lambda-list expression body))
#+jscl
(eval-when (:compile-toplevel)
(let ((macroexpander
'#'(lambda (form &optional environment)
(declare (ignore environment))
(apply #'!expand-destructuring-bind form))))
(%compile-defmacro '!destructuring-bind macroexpander)
(%compile-defmacro 'destructuring-bind macroexpander)))
| 14,979 | Common Lisp | .lisp | 318 | 34.459119 | 142 | 0.562978 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 08192c40af717382b2746d40221bf70c10f33459601308937eea5dc1d04eef78 | 12 | [
-1
] |
13 | sequence.lisp | jscl-project_jscl/src/sequence.lisp | ;;; sequence.lisp
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading sequence.lisp!")
(defun sequencep (thing)
(or (listp thing) (vectorp thing)))
(defun not-seq-error (thing)
(error "`~S' is not of type SEQUENCE" thing))
(defun length (seq)
(cond
((arrayp seq)
(if (array-has-fill-pointer-p seq)
(fill-pointer seq)
(oget seq "length")))
((listp seq)
(list-length seq))
(t
(not-seq-error seq))))
(defun vector-reverse (vector)
(let* ((length (length vector))
(new-vector (make-array length :element-type (array-element-type vector))))
(dotimes (index length new-vector)
(setf (aref new-vector index) (aref vector (- length (1+ index)))))))
(defun reverse (sequence)
"Return a new sequence containing the same elements but in reverse order."
(etypecase sequence
(list (revappend sequence '()))
(vector (vector-reverse sequence))))
(defun list-nreverse (list)
(do ((1st (cdr list) (if (endp 1st) 1st (cdr 1st)))
(2nd list 1st)
(3rd '() 2nd))
((atom 2nd) 3rd)
(rplacd 2nd 3rd)))
(defun nreverse (sequence)
(etypecase sequence
(list (list-nreverse sequence))
(vector
(let ((size (length sequence)))
(do ((i 0 (1+ i)))
((< i (/ size 2)) sequence)
(set (elt sequence i) (elt sequence (- size i 1))))))))
(defmacro do-sequence ((elt seq &optional (index (gensym "i") index-p)) &body body)
(let ((nseq (gensym "seq")))
(unless (symbolp elt)
(error "`~S' must be a symbol." elt))
`(let ((,nseq ,seq))
(if (listp ,nseq)
,(if index-p
`(let ((,index -1))
(dolist (,elt ,nseq)
(incf ,index)
,@body))
`(dolist (,elt ,nseq)
,@body))
(dotimes (,index (length ,nseq))
(let ((,elt (aref ,nseq ,index)))
,@body))))))
(defun count (item sequence &key from-end (start 0) end
key (test #'eql testp)
(test-not #'eql test-not-p))
;; TODO: Implement START and END efficiently for all the sequence
;; functions.
(let* ((l (length sequence))
(end (or end l))
(result 0))
(if from-end
(do-sequence (x (reverse sequence) index)
(when (and (<= start (- l index 1))
(< (- l index 1) end)
(satisfies-test-p item x
:key key :test test :testp testp
:test-not test-not :test-not-p test-not-p))
(incf result)))
(do-sequence (x sequence index)
(when (and (<= start index)
(< index end)
(satisfies-test-p item x
:key key :test test :testp testp
:test-not test-not :test-not-p test-not-p))
(incf result))))
result))
(defun count-if (predicate sequence &key from-end (start 0) end key)
;; TODO: Implement START and END efficiently for all the sequence
;; functions.
(let* ((l (length sequence))
(end (or end l))
(result 0))
(if from-end
(do-sequence (x (reverse sequence) index)
(when (and (<= start (- l index 1))
(< (- l index 1) end)
(funcall predicate (if key (funcall key x) x)))
(incf result)))
(do-sequence (x sequence index)
(when (and (<= start index)
(< index end)
(funcall predicate (if key (funcall key x) x)))
(incf result))))
result))
(defun count-if-not (predicate sequence &key from-end (start 0) end key)
(count-if (complement predicate) sequence :from-end from-end
:start start :end end :key key))
(defun find (item seq &key key (test #'eql testp) (test-not #'eql test-not-p))
(do-sequence (x seq)
(when (satisfies-test-p item x :key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
(return x))))
(defun find-if (predicate sequence &key key)
(if key
(do-sequence (x sequence)
(when (funcall predicate (funcall key x))
(return x)))
(do-sequence (x sequence)
(when (funcall predicate x)
(return x)))))
(defun position (elt sequence
&key from-end key (test #'eql testp)
(test-not #'eql test-not-p)
(start 0) end)
;; TODO: Implement START and END efficiently for all the sequence
;; functions.
(let ((end (or end (length sequence)))
(result nil))
(do-sequence (x sequence index)
(when (and (<= start index)
(< index end)
(satisfies-test-p elt x
:key key :test test :testp testp
:test-not test-not :test-not-p test-not-p))
(setf result index)
(unless from-end
(return))))
result))
(defun position-if (predicate sequence
&key from-end key (start 0) end)
;; TODO: Implement START and END efficiently for all the sequence
;; functions.
(let ((end (or end (length sequence)))
(result nil))
(do-sequence (x sequence index)
(when (and (<= start index)
(< index end)
(funcall predicate (if key (funcall key x) x)))
(setf result index)
(unless from-end
(return))))
result))
(defun position-if-not (predicate sequence
&key from-end key (start 0) end)
(position-if (complement predicate) sequence
:from-end from-end :key key :start start :end end))
(defun substitute (new old seq
&key (key #'identity) (test #'eql))
(and seq
(map (cond
((stringp seq) 'string)
((vectorp seq) 'vector)
((listp seq) 'list))
(lambda (elt)
(if (funcall test old (funcall key elt))
new
elt))
seq)))
(defun remove (x seq &key key (test #'eql testp) (test-not #'eql test-not-p))
(cond
((null seq)
nil)
((listp seq)
(let* ((head (cons nil nil))
(tail head))
(do-sequence (elt seq)
(unless (satisfies-test-p x elt :key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
(let ((new (list elt)))
(rplacd tail new)
(setq tail new))))
(cdr head)))
(t
(let (vector)
(do-sequence (elt seq index)
(if (satisfies-test-p x elt :key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
;; Copy the beginning of the vector only when we find an element
;; that does not match.
(unless vector
(setq vector (make-array 0 :fill-pointer 0))
(dotimes (i index)
(vector-push-extend (aref seq i) vector)))
(when vector
(vector-push-extend elt vector))))
(or vector seq)))))
(defun some (function seq)
(do-sequence (elt seq)
(when (funcall function elt)
(return-from some t))))
;;; more sequences version
(defun every (predicate first-seq &rest more-sequences)
(apply #'map nil (lambda (&rest seqs)
(when (not (apply predicate seqs))
(return-from every nil)))
first-seq more-sequences)
t)
(defun remove-if (func seq)
(cond
((listp seq) (list-remove-if func seq nil))
((arrayp seq) (vector-remove-if func seq nil))
(t (not-seq-error seq))))
(defun remove-if-not (func seq)
(cond
((listp seq) (list-remove-if func seq t))
((arrayp seq) (vector-remove-if func seq t))
(t (not-seq-error seq))))
(defun list-remove-if (func list negate)
(if (endp list)
()
(let ((test (funcall func (car list))))
(if (if negate (not test) test)
(list-remove-if func (cdr list) negate)
(cons (car list) (list-remove-if func (cdr list) negate))))))
(defun vector-remove-if (func vector negate)
(let ((out-vector (make-array 0 :fill-pointer 0)))
(do-sequence (element vector i)
(let ((test (funcall func element)))
(when (if negate test (not test))
(vector-push-extend element out-vector))))
out-vector))
(defun subseq (seq a &optional b)
(cond
((listp seq)
(if b
(let ((diff (- b a)))
(cond
((zerop diff) ())
((minusp diff)
(error "Start index must be smaller than end index"))
(t
(let* ((drop-a (copy-list (nthcdr a seq)))
(pointer drop-a))
(dotimes (_ (1- diff))
(setq pointer (cdr pointer))
(when (null pointer)
(error "Ending index larger than length of list")))
(rplacd pointer ())
drop-a))))
(copy-list (nthcdr a seq))))
((vectorp seq)
(let* ((b (or b (length seq)))
(size (- b a))
(new (make-array size :element-type (array-element-type seq))))
(do ((i 0 (1+ i))
(j a (1+ j)))
((= j b) new)
(aset new i (aref seq j)))))
(t (not-seq-error seq))))
(defun copy-seq (sequence)
(subseq sequence 0))
(defun elt (sequence index)
(when (< index 0)
(error "The index ~D is below zero." index))
(etypecase sequence
(list
(let ((i 0))
(dolist (elt sequence)
(when (eql index i)
(return-from elt elt))
(incf i))
(error "The index ~D is too large for ~A of length ~D." index 'list i)))
(array
(let ((length (length sequence)))
(when (>= index length)
(error "The index ~D is too large for ~A of length ~D." index 'vector length))
(aref sequence index)))))
(define-setf-expander elt (sequence index)
(let ((g!sequence (gensym))
(g!index (gensym))
(g!value (gensym)))
(values (list g!sequence g!index)
(list sequence index)
(list g!value)
`(jscl::aset ,g!sequence ,g!index ,g!value)
`(aref ,g!sequence ,g!index))))
(defun zero-args-reduce (function initial-value initial-value-p)
(if initial-value-p
(funcall function initial-value)
(funcall function)))
(defun one-args-reduce (function element from-end initial-value initial-value-p)
(if from-end
(if initial-value-p
(funcall function element initial-value)
element)
(if initial-value-p
(funcall function initial-value element)
element)))
(defun reduce (function sequence &key (key #'identity) from-end (start 0) end (initial-value nil initial-value-p))
(let* ((sequence (subseq sequence start (when end end)))
(sequence-length (length sequence)))
(case sequence-length
(0 (zero-args-reduce function initial-value initial-value-p))
(1 (one-args-reduce function (funcall key (elt sequence 0)) from-end initial-value initial-value-p))
(t (let* ((function (if from-end
#'(lambda (x y) (funcall function y x))
function))
(sequence (if from-end
(reverse sequence)
sequence))
(value (elt sequence 0)))
(when initial-value-p
(setf value (funcall function initial-value (funcall key value))))
(etypecase sequence
(list (dolist (elt (cdr sequence) value)
(setf value (funcall function value (funcall key elt)))))
(vector (dotimes (index (1- sequence-length) value)
(setf value (funcall function value (funcall key (elt sequence (1+ index)))))))))))))
(defun mismatch (sequence1 sequence2 &key key (test #'eql testp) (test-not nil test-not-p)
(start1 0) (end1 (length sequence1))
(start2 0) (end2 (length sequence2)))
(let ((index1 start1)
(index2 start2))
(while (and (<= index1 end1) (<= index2 end2))
(when (or (eql index1 end1) (eql index2 end2))
(return-from mismatch (if (eql end1 end2) NIL index1)))
(unless (satisfies-test-p (elt sequence1 index1) (elt sequence2 index2)
:key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
(return-from mismatch index1))
(incf index1)
(incf index2))))
(defun list-search (sequence1 list2 args)
(let ((length1 (length sequence1))
(position 0))
(while list2
(let ((mismatch (apply #'mismatch sequence1 list2 args)))
(when (or (not mismatch) (>= mismatch length1))
(return-from list-search position)))
(pop list2)
(incf position))))
(defun vector-search (sequence1 vector2 args)
(let ((length1 (length sequence1)))
(dotimes (position (length vector2))
(let ((mismatch (apply #'mismatch sequence1 (subseq vector2 position) args)))
(when (or (not mismatch) (>= mismatch length1))
(return-from vector-search position))))))
(defun search (sequence1 sequence2 &rest args &key key test test-not)
(unless (sequencep sequence1)
(not-seq-error sequence1))
(when (or (and (listp sequence1) (null sequence1))
(and (vectorp sequence1) (zerop (length sequence1))))
(return-from search 0))
(funcall
(typecase sequence2
(list #'list-search)
(array #'vector-search)
(t (not-seq-error sequence2)))
sequence1 sequence2 args))
(defparameter *iterator-done* (gensym))
(defun make-list-iterator (the-list)
(let ((tail the-list))
(lambda ()
(if (null tail)
*iterator-done*
(pop tail)))))
(defun make-vector-iterator (the-vector)
(let ((i 0)
(len (length the-vector)))
(lambda ()
(if (= i len)
*iterator-done*
(let ((item (aref the-vector i)))
(incf i)
item)))))
(defun make-iterator (sequence)
(funcall (cond ((listp sequence) #'make-list-iterator)
((vectorp sequence) #'make-vector-iterator)
(t (error "Not of type SEQUENCE")))
sequence))
(defun make-list-collector ()
(let* (the-list tail)
(lambda (&rest item)
(cond ((and item (null the-list))
(setf the-list item
tail item))
(item (setf (cdr tail) item
tail (cdr tail))))
the-list)))
(defun make-vector-collector (&key (element-type t))
(let* ((the-vector (make-array 0 :adjustable t :element-type element-type :fill-pointer 0)))
(lambda (&rest item)
(when item
(vector-push-extend (first item) the-vector))
the-vector)))
(defun make-collector (type)
(case type
(list (make-list-collector))
(string (make-vector-collector :element-type 'character))
(vector (make-vector-collector))
(t
(when (and (listp type)
(eql 'vector (first type)))
(make-vector-collector :element-type (or (second type) t))))))
(defun map (result-type function &rest sequences)
(let ((iterators (mapcar #'make-iterator sequences))
(result-collector (make-collector result-type)))
(do ((args (mapcar #'funcall iterators) (mapcar #'funcall iterators)))
((find *iterator-done* args)
(when result-type (funcall result-collector)))
(if result-type
(funcall result-collector (apply function args))
(apply function args)))))
(defun check-sequence-type-specifier (specifier)
(unless (member specifier '(vector string list))
(error "Not a valid sequence type specifier")))
(defun concatenate (result-type &rest sequences)
(check-sequence-type-specifier result-type)
(let ((iterators (mapcar #'make-iterator sequences))
(result-collector (make-collector result-type)))
(dolist (it iterators)
(do ((arg (funcall it) (funcall it)))
((eq *iterator-done* arg))
(funcall result-collector arg)))
(funcall result-collector)))
;;; remove duplicates
(defun %remove-duplicates (seq from-end test test-not key start end)
(let ((result)
(test-fn test)
(sequence (if from-end seq (reverse seq))))
(when test-not
(setq test-fn (complement test-not)))
(when (or (not (eql start 0))
end)
(setq sequence (subseq sequence start end)))
(dolist (it sequence)
(unless (find (funcall key it) result :key key :test test-fn)
(push it result)))
(if from-end
(reverse result)
result)))
(defun remove-duplicates (seq &key from-end (test 'eq) test-not (key 'identity) (start 0) end)
(cond ((listp seq)
(%remove-duplicates seq from-end test test-not key start end))
((stringp seq)
(apply #'concat (%remove-duplicates (vector-to-list seq) from-end test test-not key start end)))
((vectorp seq)
(list-to-vector (%remove-duplicates (vector-to-list seq) from-end test test-not key start end)))
(t (error "Its not sequence ~a" seq))))
;;; replace sequences - http://clhs.lisp.se/Body/f_replac.htm
;;; string <- string
;;; vector <- vector
;;; otherwise =>error
(defun %replace-seq-eql (x y)
(typecase x
(number (and (numberp y) (= x y)))
(character (and (characterp y) (char-equal x y)))
(string
(and (stringp y)
(equal x y) ))
(vector
(and (vectorp y)
(let ((lex (length x)))
(= lex (length y))
(dotimes (i lex t)
(when (not (%replace-seq-eql (aref x i) (aref y i)))
(return nil))))))
(t (equal x y))))
(defun %replace-seq (seq-1 seq-2 start1 end1 start2 end2)
(let* ((trimed-end (min (- end1 start1) (- end2 start2)))
(back nil))
(setq end1 (+ start1 trimed-end)
end2 (+ start2 trimed-end))
;; set copy backward flag
(when (and (%replace-seq-eql seq-1 seq-2)
(<= start2 start1)
(or (and (<= start1 start2) (< start2 end1))
(and (< start1 end2) (<= end2 end1))
(and (<= start2 start1) (< start1 end2))
(and (< start2 end1) (<= end1 end2))))
(when (eq start1 start2)
;; nothing to copy
(return-from %replace-seq seq-1))
(setq back t))
(cond (back
(dotimes (i trimed-end seq-1)
(setf (aref seq-1 (- (+ start1 trimed-end) i 1))
(aref seq-2 (- (+ start2 trimed-end) i 1)))))
(t
(dotimes (i trimed-end seq-1)
(setf (aref seq-1 (+ start1 i))
(aref seq-2 (+ start2 i))))))
))
(defun replace (sequence-1
sequence-2
&key (start1 0)
(end1 (length sequence-1))
(start2 0) (end2 (length sequence-2)))
(let ((compatible-types-replace (eql (array-element-type sequence-1)
(array-element-type sequence-2)))
(region-nondecreasing-order-seq-1 (<= 0 start1 end1 (length sequence-1)))
(region-nondecreasing-order-seq-2 (<= 0 start2 end2 (length sequence-2))))
(assert compatible-types-replace)
;; check region monotonically nondecreasing order
(assert region-nondecreasing-order-seq-1)
(assert region-nondecreasing-order-seq-2))
(%replace-seq sequence-1 sequence-2 start1 end1 start2 end2))
;;; EOF
| 20,167 | Common Lisp | .lisp | 514 | 30.498054 | 114 | 0.573427 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 933f7ca8483de6492db80f2b7fff84ba1ef863bac7857e6cf1e874040a98fc92 | 13 | [
-1
] |
14 | array.lisp | jscl-project_jscl/src/array.lisp | ;;; arrays.lisp
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading array.lisp!")
(defun upgraded-array-element-type (typespec &optional environment)
(declare (ignore environment))
(if (eq typespec 'character)
'character
t))
(defun make-array (dimensions &key element-type initial-element adjustable fill-pointer)
(let* ((dimensions (ensure-list dimensions))
(size (!reduce #'* dimensions 1))
(array (make-storage-vector size)))
(cond ((eq fill-pointer t) (setq fill-pointer size))
((eq fill-pointer nil) nil)
((integerp fill-pointer)
(if (or (< fill-pointer 0) (> fill-pointer size))
(error "make-array - invalid FILL-POINTER ~a." fill-pointer)))
(t (error "make-array - bad FILL-POINTER ~s type ~a." fill-pointer (type-of fill-pointer))))
;; Upgrade type
(if (eq element-type 'character)
(progn
(oset 1 array "stringp")
(setf element-type 'character
initial-element (or initial-element #\space)))
(setf element-type t))
(when (and (listp dimensions)
(not (null (cdr dimensions)))
fill-pointer)
(error "make-array - FILL-POINTER cannot be specified on multidimensional arrays."))
;; Initialize array
(storage-vector-fill array initial-element)
;; Record and return the object
(setf (oget array "type") element-type
(oget array "dimensions") dimensions
(oget array "fillpointer") fill-pointer)
array))
(defun arrayp (x)
(storage-vector-p x))
(defun adjustable-array-p (array)
(unless (arrayp array)
(error "~S is not an array." array))
t)
(defun array-element-type (array)
(unless (arrayp array)
(error "~S is not an array." array))
(if (eq (oget array "stringp") 1)
'character
(oget array "type")))
(defun array-dimensions (array)
(unless (arrayp array)
(error "~S is not an array." array))
(oget array "dimensions"))
(defun array-dimension (array axis)
(unless (arrayp array)
(error "~S is not an array." array))
(let* ((dimensions (oget array "dimensions"))
(la (length dimensions)))
(if (>= axis la)
(error "axis ~d is too big. Array ~s has ~d dimensions." axis array la))
(nth axis dimensions)))
(defun aref (array index)
(unless (arrayp array)
(error "~S is not an array." array))
(storage-vector-ref array index))
(defun aset (array index value)
(unless (arrayp array)
(error "~S is not an array." array))
(storage-vector-set array index value))
(define-setf-expander aref (array index)
(let ((g!array (gensym))
(g!index (gensym))
(g!value (gensym)))
(values (list g!array g!index)
(list array index)
(list g!value)
`(aset ,g!array ,g!index ,g!value)
`(aref ,g!array ,g!index))))
(defun array-has-fill-pointer-p (array)
(and (oget array "fillpointer") t))
(defun fill-pointer (array)
(unless (arrayp array)
(error "~S is not an array" array))
(unless (array-has-fill-pointer-p array)
(error "~S does not have a fill pointer" array))
(oget array "fillpointer"))
(defun set-fill-pointer (array new-value)
(unless (arrayp array)
(error "~S is not an array" array))
(unless (array-has-fill-pointer-p array)
(error "~S does not have a fill pointer" array))
(setf (oget array "fillpointer") new-value))
(defsetf fill-pointer set-fill-pointer)
;;; Vectors
(defun vectorp (x)
(and (arrayp x) (null (cdr (array-dimensions x)))))
(defun vector (&rest objects)
(list-to-vector objects))
(defun vector-pop (vector)
(unless (array-has-fill-pointer-p vector)
(error "~S does not have a fill pointer"))
(let ((element (aref vector (1- (length vector)))))
(decf (fill-pointer vector))
element))
(defun vector-push (element vector)
(cond ((>= (fill-pointer vector)
(array-dimension vector 0))
nil)
(t (let ((prev-idx (fill-pointer vector)))
;; store and increment take place
(storage-vector-set! vector prev-idx element)
(incf (fill-pointer vector))
prev-idx))))
(defun vector-push-extend (new-element vector)
(unless (vectorp vector)
(error "~S is not a vector." vector))
;; Note that JS will automatically grow the array as new elements
;; are assigned, so no need to do `adjust-array` here.
(storage-vector-set! vector (fill-pointer vector) new-element)
(incf (fill-pointer vector)))
;;; EOF
| 5,145 | Common Lisp | .lisp | 131 | 33.908397 | 102 | 0.656845 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c1d12e722f40fd993544c2553d27e38c731b60b6190e48bc1d97fad0b62735a4 | 14 | [
-1
] |
15 | read.lisp | jscl-project_jscl/src/read.lisp | ;;; read.lisp ---
;; Copyright (C) 2012, 2013 David Vazquez
;; Copyright (C) 2012 Raimon Grau
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading read.lisp!")
;;;; Reader
#+jscl(defvar *read-base* 10)
;;; Reader radix bases
(defvar *fixed-radix-bases* '((#\B . 2) (#\b . 2) (#\o . 8) (#\O . 8) (#\x . 16) (#\X . 16)))
;;; If it is not NIL, we do not want to read the expression but just
;;; ignore it. For example, it is used in conditional reads #+.
(defvar *read-skip-p* nil)
;;; The Lisp reader, parse strings and return Lisp objects. The main
;;; entry points are `ls-read' and `ls-read-from-string'.
;;; #= / ## implementation
;; For now associations label->object are kept in a plist
;; May be it makes sense to use a vector instead if speed
;; is considered a problem with many labelled objects
(defvar *labelled-objects* nil)
(defun new-labelled-objects-table ()
(setf *labelled-objects* nil))
(defun find-labelled-object (id)
(assoc id *labelled-objects*))
(defun add-labelled-object (id value)
(push (cons id value) *labelled-objects*))
;; A unique value used to mark in the labelled objects
;; table an object that is being constructed
;; (e.g. #1# while reading elements of "#1=(#1# #1# #1#)")
(defvar *future-value* (make-symbol "future"))
;; A unique value used to mark temporary values that will
;; be replaced when fixups are run.
(defvar *fixup-value* (make-symbol "fixup"))
;; Fixup locations keeps a list of conses where the CAR
;; is a callable to be called with the value of the object
;; associated to label stored in CDR once reading is completed
(defvar *fixup-locations* nil)
(defun fixup-backrefs ()
(while *fixup-locations*
(let* ((fixup (pop *fixup-locations*))
(callable (car fixup))
(cell (find-labelled-object (cdr fixup))))
(if cell
(funcall callable (cdr cell))
(error "Internal error in fixup-backrefs: object #~S# not found"
(cdr fixup))))))
;; A function that will need to return a fixup callback
;; for the object that is being read. The returned callback will
;; be called with the result of reading.
(defvar *make-fixup-function*
(lambda ()
(error "Internal error in fixup creation during read")))
(defun %peek-char (stream)
(peek-char nil stream nil))
(defun %read-char (stream)
(read-char stream nil))
(defun whitespacep (ch)
(or (char= ch #\space) (char= ch #\newline) (char= ch #\tab) (char= ch (char "" 0))))
(defun skip-whitespaces (stream)
(let (ch)
(setq ch (%peek-char stream))
(while (and ch (whitespacep ch))
(%read-char stream)
(setq ch (%peek-char stream)))))
(defun terminating-char-p (ch)
(or (char= #\" ch)
(char= #\) ch)
(char= #\( ch)
(char= #\` ch)
(char= #\, ch)
(char= #\' ch)
(char= #\; ch)))
(defun terminalp (ch)
(or (null ch) (whitespacep ch) (terminating-char-p ch)))
(defun read-until (stream func)
(let ((string "")
(ch))
(setq ch (%peek-char stream))
(while (and ch (not (funcall func ch)))
(setq string (concat string (string ch)))
(%read-char stream)
(setq ch (%peek-char stream)))
string))
(defun read-escaped-until (stream func)
(let ((string "")
(ch (%peek-char stream))
(multi-escape nil))
(while (and ch (or multi-escape (not (funcall func ch))))
(cond
((char= ch #\|)
(if multi-escape
(setf multi-escape nil)
(setf multi-escape t)))
((char= ch #\\)
(%read-char stream)
(setf ch (%peek-char stream))
(setf string (concat string "\\" (string ch))))
(t
(if multi-escape
(setf string (concat string "\\" (string ch)))
(setf string (concat string (string ch))))))
(%read-char stream)
(setf ch (%peek-char stream)))
string))
(defun skip-whitespaces-and-comments (stream)
(let (ch)
(skip-whitespaces stream)
(setq ch (%peek-char stream))
(while (and ch (char= ch #\;))
(read-until stream (lambda (x) (char= x #\newline)))
(skip-whitespaces stream)
(setq ch (%peek-char stream)))))
(defun discard-char (stream expected)
(let ((ch (%read-char stream)))
(when (null ch)
(error "End of file when character ~S was expected." expected))
(unless (char= ch expected)
(error "Character ~S was found but ~S was expected." ch expected))))
(defun %read-list (stream &optional (eof-error-p t) eof-value)
(skip-whitespaces-and-comments stream)
(let ((ch (%peek-char stream)))
(cond
((null ch)
(error "Unexpected EOF"))
((char= ch #\))
(discard-char stream #\))
nil)
(t
(let* ((cell (cons nil nil))
(*make-fixup-function* (lambda ()
(lambda (obj)
(rplaca cell obj))))
(eof (gensym))
(next (ls-read stream nil eof t)))
(rplaca cell next)
(skip-whitespaces-and-comments stream)
(cond
((eq next eof)
(discard-char stream #\))
nil)
(t
(if (char= (%peek-char stream) #\.)
(progn
(discard-char stream #\.)
(if (terminalp (%peek-char stream))
(let ((*make-fixup-function* (lambda ()
(lambda (obj)
(rplacd cell obj)))))
;; Dotted pair notation
(rplacd cell (ls-read stream eof-error-p eof-value t))
(skip-whitespaces-and-comments stream)
(let ((ch (%peek-char stream)))
(if (or (null ch) (char= #\) ch))
(discard-char stream #\))
(error "Multiple objects following . in a list"))))
(let ((token (concat "." (read-escaped-until stream #'terminalp))))
(rplacd cell (cons (interpret-token token)
(%read-list stream eof-error-p eof-value))))))
(rplacd cell (%read-list stream eof-error-p eof-value)))
cell)))))))
(defun read-string (stream)
(let ((string "")
(ch nil))
(setq ch (%read-char stream))
(while (not (eql ch #\"))
(when (null ch)
(error "Unexpected EOF"))
(when (eql ch #\\)
(setq ch (%read-char stream)))
(setq string (concat string (string ch)))
(setq ch (%read-char stream)))
string))
(defun eval-feature-expression (expression)
(etypecase expression
(keyword
(and (find (symbol-name expression) *features* :key #'symbol-name :test #'string=) t))
(list
;; Macrocharacters for conditional reading #+ and #- bind the
;; current package to KEYWORD so features are correctly
;; interned. For this reason, AND, OR and NOT symbols will be
;; also keyword in feature expressions.
(ecase (first expression)
(:and
(every #'eval-feature-expression (rest expression)))
(:or
(some #'eval-feature-expression (rest expression)))
(:not
(destructuring-bind (subexpr) (rest expression)
(not (eval-feature-expression subexpr))))))))
(defun read-sharp (stream &optional eof-error-p eof-value)
(%read-char stream)
(let ((ch (%read-char stream)))
(case ch
(#\'
(list 'function (ls-read stream eof-error-p eof-value t)))
(#\.
(eval (ls-read stream)))
(#\(
(do ((elements nil)
(result nil)
(index 0 (1+ index)))
((progn (skip-whitespaces-and-comments stream)
(or (null (%peek-char stream))
(char= (%peek-char stream) #\))))
(discard-char stream #\))
(setf result (make-array index))
(dotimes (i index)
(aset result (decf index) (pop elements)))
result)
(let* ((ix index) ; Can't just use index: the same var would be captured in all fixups
(*make-fixup-function* (lambda ()
(lambda (obj)
(aset result ix obj))))
(eof (gensym))
(value (ls-read stream nil eof t)))
(push value elements))))
(#\:
(make-symbol
(unescape-token
(string-upcase-noescaped
(read-escaped-until stream #'terminalp)))))
(#\\
(let ((cname
(concat (string (%read-char stream))
(read-until stream #'terminalp))))
(cond
((string-equal cname "space") #\space)
((string-equal cname "tab") #\tab)
((string-equal cname "newline") #\newline)
(t (char cname 0)))))
((#\+ #\-)
(let* ((expression
(let ((*package* (find-package :keyword)))
(ls-read stream eof-error-p eof-value t))))
(if (eql (char= ch #\+) (eval-feature-expression expression))
(ls-read stream eof-error-p eof-value t)
(prog2 (let ((*read-skip-p* t))
(ls-read stream))
(ls-read stream eof-error-p eof-value t)))))
((#\J #\j)
(unless (char= (%peek-char stream) #\:)
(error "FFI descriptor must start with a colon."))
(let ((descriptor (subseq (read-until stream #'terminalp) 1))
(subdescriptors nil))
(do* ((start 0 (1+ end))
(end (position #\: descriptor :start start)
(position #\: descriptor :start start)))
((null end)
(push (subseq descriptor start) subdescriptors)
`(oget *root* ,@(reverse subdescriptors)))
(push (subseq descriptor start end) subdescriptors))))
;; Sharp radix
((#\B #\b #\O #\o #\X #\x)
(sharp-radix-reader ch stream))
(#\|
(labels ((read-til-bar-sharpsign ()
(do ((ch (%read-char stream) (%read-char stream)))
((and (char= ch #\|) (char= (%peek-char stream) #\#))
(%read-char stream))
(when (and (char= ch #\#) (char= (%peek-char stream) #\|))
(%read-char stream)
(read-til-bar-sharpsign)))))
(read-til-bar-sharpsign)
(ls-read stream eof-error-p eof-value t)))
(otherwise
(cond
((and ch (digit-char-p ch))
(let ((id (digit-char-p ch)))
(while (and (%peek-char stream)
(digit-char-p (%peek-char stream)))
(setf id (+ (* id 10) (digit-char-p (%read-char stream)))))
(ecase (%peek-char stream)
(#\=
(%read-char stream)
(if (find-labelled-object id)
(error "Duplicated label #~S=" id)
(progn
(add-labelled-object id *future-value*)
(let ((obj (ls-read stream eof-error-p eof-value t)))
;; FIXME: somehow the more natural
;; (setf (cdr (find-labelled-object id)) obj)
;; doesn't work
(rplacd (find-labelled-object id) obj)
obj))))
(#\#
(%read-char stream)
(let ((cell (find-labelled-object id)))
(if cell
(if (eq (cdr cell) *future-value*)
(progn
(push (cons (funcall *make-fixup-function*)
id)
*fixup-locations*)
*fixup-value*)
(cdr cell))
(error "Invalid labelled object #~S#" id)))))))
(t
(error "Invalid dispatch character after #")))))))
(defun sharp-radix-reader (ch stream)
;; Sharp radix base #\B #\O #\X
(let* ((fixed-base (assoc ch jscl::*fixed-radix-bases*))
(base (cond (fixed-base (cdr fixed-base))
(t (error "No radix base in #~A" ch))))
(*read-base* base)
(number nil)
(string (read-until stream #'terminalp)))
(setq number (read-integer string))
(unless number
(error "#~c: bad base(~d) digit at ~s~%"
ch
base
string))
number))
(defun unescape-token (x)
(let ((result ""))
(dotimes (i (length x))
(unless (char= (char x i) #\\)
(setq result (concat result (string (char x i))))))
result))
(defun string-upcase-noescaped (s)
(let ((result "")
(last-escape nil))
(dotimes (i (length s))
(let ((ch (char s i)))
(if last-escape
(progn
(setf last-escape nil)
(setf result (concat result (string ch))))
(if (char= ch #\\)
(setf last-escape t)
(setf result (concat result (string-upcase (string ch))))))))
result))
;;; Parse a string of the form NAME, PACKAGE:NAME or
;;; PACKAGE::NAME and return the symbol. If the string is of the
;;; form 1) or 3), but the symbol does not exist, it will be created
;;; and interned in that package.
(defun read-symbol (string)
(let ((size (length string))
package name internalp index)
(setq index 0)
(while (and (< index size)
(not (char= (char string index) #\:)))
(when (char= (char string index) #\\)
(incf index))
(incf index))
(cond
;; No package prefix
((= index size)
(setq name string)
(setq package (package-name *package*))
(setq internalp t))
(t
;; Package prefix
(if (zerop index)
(setq package "KEYWORD")
(setq package (string-upcase-noescaped (subseq string 0 index))))
(incf index)
(when (char= (char string index) #\:)
(setq internalp t)
(incf index))
(setq name (subseq string index))))
;; Canonalize symbol name and package
(setq name (if (string= package "JS")
(setq name (unescape-token name))
(setq name (string-upcase-noescaped name))))
(setq package (find-package-or-fail package))
(if (or internalp
(eq package (find-package "KEYWORD"))
(eq package (find-package "JS")))
(intern name package)
(multiple-value-bind (symbol external)
(find-symbol name package)
(if (eq external :external)
symbol
(error "The symbol `~S' is not external in the package ~S." name package))))))
(defun read-integer (string)
(let ((base *read-base*)
(negative nil)
(number 0)
(start 0)
(end (length string)))
(when (eql #\. (char string (1- (length string))))
(setf base 10 end (1- end)))
(when (or (eql #\+ (char string 0))
(eql #\- (char string 0)))
(setq negative (eql #\- (char string 0))
start (1+ start)))
(when (not (= (- end start) 0))
(do ((idx start (1+ idx)))
((>= idx end)
(if negative
(- number)
number))
(let ((weight (digit-char-p (char string idx) base)))
(unless weight (return))
(setq number (+ (* number base) weight)))))))
(defun read-float (string)
(block nil
(let ((sign 1)
(integer-part nil)
(fractional-part nil)
(number 0)
(divisor 1)
(exponent-sign 1)
(exponent 0)
(size (length string))
(index 0))
(when (zerop size) (return))
;; Optional sign
(case (char string index)
(#\+ (incf index))
(#\- (setq sign -1)
(incf index)))
(unless (< index size) (return))
;; Optional integer part
(awhen (digit-char-p (char string index))
(setq integer-part t)
(while (and (< index size)
(setq it (digit-char-p (char string index))))
(setq number (+ (* number 10) it))
(incf index)))
(unless (< index size) (return))
;; Decimal point is mandatory if there's no integer part
(unless (or integer-part (char= #\. (char string index))) (return))
;; Optional fractional part
(when (char= #\. (char string index))
(incf index)
(unless (< index size) (return))
(awhen (digit-char-p (char string index))
(setq fractional-part t)
(while (and (< index size)
(setq it (digit-char-p (char string index))))
(setq number (+ (* number 10) it))
(setq divisor (* divisor 10))
(incf index))))
;; Either left or right part of the dot must be present
(unless (or integer-part fractional-part) (return))
;; Exponent is mandatory if there is no fractional part
(when (and (= index size) (not fractional-part)) (return))
;; Optional exponent part
(when (< index size)
;; Exponent-marker
(unless (find (char-upcase (char string index)) "ESFDL")
(return))
(incf index)
(unless (< index size) (return))
;; Optional exponent sign
(case (char string index)
(#\+ (incf index))
(#\- (setq exponent-sign -1)
(incf index)))
(unless (< index size) (return))
;; Exponent digits
(let ((value (digit-char-p (char string index))))
(unless value (return))
(while (and (< index size)
(setq value (digit-char-p (char string index))))
(setq exponent (+ (* exponent 10) value))
(incf index))))
(unless (= index size) (return))
;; Everything went ok, we have a float
;; XXX: Use FLOAT when implemented.
(/ (* sign (expt 10.0 (* exponent-sign exponent)) number) divisor 1.0))))
(defun !parse-integer (string start end radix junk-allow)
(block nil
(let ((value 0)
(index start)
(size (or end (length string)))
(sign 1))
;; Leading whitespace
(while (and (< index size)
(whitespacep (char string index)))
(incf index))
(unless (< index size) (return (values nil 0)))
;; Optional sign
(case (char string 0)
(#\+ (incf index))
(#\- (setq sign -1)
(incf index)))
;; First digit
(unless (and (< index size)
(setq value (digit-char-p (char string index) radix)))
(return (values nil index)))
(incf index)
;; Other digits
(while (< index size)
(let ((digit (digit-char-p (char string index) radix)))
(unless digit (return))
(setq value (+ (* value radix) digit))
(incf index)))
;; Trailing whitespace
(do ((i index (1+ i)))
((or (= i size) (not (whitespacep (char string i))))
(and (= i size) (setq index i))))
(if (or junk-allow
(= index size))
(values (* sign value) index)
(values nil index)))))
#+jscl
(defun parse-integer (string &key (start 0) end (radix 10) junk-allowed)
(multiple-value-bind (num index)
(jscl::!parse-integer string start end radix junk-allowed)
(if (or num junk-allowed)
(values num index)
(error "Junk detected."))))
(defun interpret-token (string)
(or (read-integer string)
(read-float string)
(read-symbol string)))
(defun ls-read (&optional (stream *standard-input*) (eof-error-p t) eof-value recursive-p)
(let ((save-labelled-objects *labelled-objects*)
(save-fixup-locations *fixup-locations*))
(unless recursive-p
(setf *fixup-locations* nil)
(setf *labelled-objects* (new-labelled-objects-table)))
(prog1
(progn
(skip-whitespaces-and-comments stream)
(let ((ch (%peek-char stream)))
(cond
((null ch)
(if eof-error-p
(error "End of file")
eof-value))
((char= ch #\))
(if eof-error-p
(error "unmatched close parenthesis")
eof-value))
((char= ch #\()
(%read-char stream)
(%read-list stream eof-error-p eof-value))
((char= ch #\')
(%read-char stream)
(list 'quote (ls-read stream eof-error-p eof-value t)))
((char= ch #\`)
(%read-char stream)
(list 'backquote (ls-read stream eof-error-p eof-value t)))
((char= ch #\")
(%read-char stream)
(read-string stream))
((char= ch #\,)
(%read-char stream)
(if (eql (%peek-char stream) #\@)
(progn (%read-char stream) (list 'unquote-splicing
(ls-read stream eof-error-p eof-value t)))
(list 'unquote (ls-read stream eof-error-p eof-value t))))
((char= ch #\#)
(read-sharp stream eof-error-p eof-value))
(t
(let ((string (read-escaped-until stream #'terminalp)))
(unless *read-skip-p*
(interpret-token string)))))))
(unless recursive-p
(fixup-backrefs)
(setf *labelled-objects* save-labelled-objects)
(setf *fixup-locations* save-fixup-locations)))))
#+jscl
(fset 'read #'ls-read)
(defun ls-read-from-string (string &optional (eof-error-p t) eof-value)
(ls-read (make-string-input-stream string) eof-error-p eof-value))
#+jscl
(fset 'read-from-string #'ls-read-from-string)
| 22,651 | Common Lisp | .lisp | 572 | 29.458042 | 95 | 0.535156 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | d49ac9643b78648a180d8337e815a7ab3b449703a917bfddd36d70273e34a74b | 15 | [
-1
] |
16 | print.lisp | jscl-project_jscl/src/print.lisp | ;;; print.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading print.lisp!")
;;; Printer
(defun lisp-escape-string (string)
(let ((output "")
(index 0)
(size (length string)))
(while (< index size)
(let ((ch (char string index)))
(when (or (char= ch #\") (char= ch #\\))
(setq output (concat output "\\")))
(when (or (char= ch #\newline))
(setq output (concat output "\\"))
(setq ch #\n))
(setq output (concat output (string ch))))
(incf index))
(concat "\"" output "\"")))
;;; Return T if the string S contains characters which need to be
;;; escaped to print the symbol name, NIL otherwise.
(defun escape-symbol-name-p (s)
(let ((dots-only t))
(dotimes (i (length s))
(let ((ch (char s i)))
(setf dots-only (and dots-only (char= ch #\.)))
(when (or (terminalp ch)
(char= ch #\:)
(char= ch #\\)
(not (char= ch (char-upcase ch)))
(char= ch #\|))
(return-from escape-symbol-name-p t))))
dots-only))
;;; Return T if the specified string can be read as a number
;;; In case such a string is the name of a symbol then escaping
;;; is required when printing to ensure correct reading.
(defun potential-number-p (string)
;; The four rules for being a potential number are described in
;; 2.3.1.1 Potential Numbers as Token
;;
;; First Rule
(dotimes (i (length string))
(let ((char (char string i)))
(cond
;; Digits TODO: DIGIT-CHAR-P should work with the current
;; radix here. If the radix is not decimal, then we have to
;; make sure there is not a decimal-point in the string.
((digit-char-p char))
;; Signs, ratios, decimal point and extension mark
((find char "+-/._^"))
;; Number marker
((alpha-char-p char)
(when (and (< i (1- (length string)))
(alpha-char-p (char string (1+ i))))
;; fail: adjacent letters are not number marker, or
;; there is a decimal point in the string.
(return-from potential-number-p)))
(t
;; fail: there is a non-allowed character
(return-from potential-number-p)))))
(and
;; Second Rule. In particular string is not empty.
(find-if #'digit-char-p string)
;; Third rule
(let ((first (char string 0)))
(and (not (char= first #\:))
(or (digit-char-p first)
(find first "+-._^"))))
;; Fourth rule
(not (find (char string (1- (length string))) "+-)"))))
#+nil
(mapcar #'potential-number-p
'("1b5000" "777777q" "1.7J" "-3/4+6.7J" "12/25/83" "27^19"
"3^4/5" "6//7" "3.1.2.6" "^-43^" "3.141_592_653_589_793_238_4"
"-3.7+2.6i-6.17j+19.6k"))
#+nil
(mapcar #'potential-number-p '("/" "/5" "+" "1+" "1-" "foo+" "ab.cd" "_" "^" "^/-"))
(defun escape-token-p (string)
(or (potential-number-p string)
(escape-symbol-name-p string)))
;;; Returns the token in a form that can be used for reading it back.
(defun escape-token (s)
(if (escape-token-p s)
(let ((result "|"))
(dotimes (i (length s))
(let ((ch (char s i)))
(when (or (char= ch #\|)
(char= ch #\\))
(setf result (concat result "\\")))
(setf result (concat result (string ch)))))
(concat result "|"))
s))
#+jscl (defvar *print-escape* t)
#+jscl (defvar *print-circle* nil)
;;; @vkm-path-printer 04-09-2022
;;; add variables
#+jscl (defvar *print-base* 10)
#+jscl (defvar *print-radix* nil)
;; To support *print-circle* some objects must be tracked for sharing:
;; conses, arrays and apparently-uninterned symbols. These objects
;; are placed in an array and a parallel array is used to mark if
;; they're found multiple times by assining them an id starting from
;; 1.
;;
;; After the tracking has been completed the printing phase can begin:
;; if an object has an id > 0 then #<n>= is prefixed and the id is
;; changed to negative. If an object has an id < 0 then #<-n># is
;; printed instead of the object.
;;
;; The processing is O(n^2) with n = number of tracked
;; objects. Hopefully it will become good enough when the new compiler
;; is available.
(defun scan-multiple-referenced-objects (form)
(let ((known-objects (make-array 0 :adjustable t :fill-pointer 0))
(object-ids (make-array 0 :adjustable t :fill-pointer 0)))
(vector-push-extend nil known-objects)
(vector-push-extend 0 object-ids)
(let ((count 0))
(labels ((mark (x)
(let ((i (position x known-objects)))
(cond
((null i)
(vector-push-extend x known-objects)
(vector-push-extend 0 object-ids)
t)
(t
(setf (aref object-ids i) (incf count))
nil))))
(visit (x)
(cond
;; prevent scan infinity mop pbjects
((mop-object-p x)
(mark x))
((and x (symbolp x) (null (symbol-package x)))
(mark x))
((consp x)
(when (mark x)
(visit (car x))
(visit (cdr x))))
((vectorp x)
(when (mark x)
(dotimes (i (length x))
(visit (aref x i))))))))
(visit form)))
(values known-objects object-ids)))
;;; Write an integer to stream.
;;; @vkm-path-printer 04-09-2022
#| write-integer test case
http://clhs.lisp.se/Body/v_pr_bas.htm
(dolist (pb '(2 3 8 10 16))
(write 10 :base pb :radix t)
(terpri))
=>
#B1010
#3.r101
#O12
10.
#Xa
(dotimes (i 35)
(let ((base (+ i 2)))
(write 40 :base base)
(if (zerop (mod i 10)) (terpri) (format t " "))))
=>
101000
1111 220 130 104 55 50 44 40 37 34
31 2C 2A 28 26 24 22 20 1J 1I
1H 1G 1F 1E 1D 1C 1B 1A 19 18
17 16 15 14
|#
(defun write-integer (argument stream)
(let* ((print-base *print-base*)
(print-radix *print-radix*)
(result))
(setq result
(cond ((eql print-base 10)(integer-to-string argument))
(t (check-type print-base (integer 2 36))
(funcall ((oget argument "toString" "bind") argument print-base)))))
(when print-radix
;; print base prefix
(case print-base
(2 (write-string "#B" stream))
(8 (write-string "#O" stream))
(16 (write-string "#X" stream))
(10)
(t ;; #Nr prefix
(write-char #\# stream)
(write print-base :stream stream :base 10)
(write-char #\r stream))))
;; print result
(write-string (string result) stream)
argument))
;;; @vkm-path-printer 04-09-2022
(defun gensym-p (s)
(if (symbol-package s)
nil
(not (eq s (find-symbol (symbol-name s))))))
#+jscl (defvar *print-gensym* t)
#+nil
(defun write-symbol (form &optiona (stream *standard-output*))
(let ((name (symbol-name form))
(package (symbol-package form)))
;; Check if the symbol is accesible from the current package. It
;; is true even if the symbol's home package is not the current
;; package, because it could be inherited.
(if (eq form (find-symbol (symbol-name form)))
(write-string (escape-token (symbol-name form)) stream)
;; Symbol is not accesible from *PACKAGE*, so let us prefix
;; the symbol with the optional package or uninterned mark.
(progn
(cond
((null package) (write-char #\# stream))
((eq package (find-package "KEYWORD")))
(t (write-string (escape-token (package-name package)) stream)))
(write-char #\: stream)
(when package
(multiple-value-bind (symbol type)
(find-symbol name package)
;;(declare (ignorable symbol))
(when (eq type :internal)
(write-char #\: stream))))
(write-string (escape-token name) stream)))))
;;; This version of format supports only ~A for strings and ~D for
;;; integers. It is used to avoid circularities. Indeed, it just
;;; ouputs to streams.
(defun simple-format (stream fmt &rest args)
(do ((i 0 (1+ i)))
((= i (length fmt)))
(let ((char (char fmt i)))
(if (char= char #\~)
(let ((next (if (< i (1- (length fmt)))
(char fmt (1+ i))
(error "`~~' appears in the last position of the format control string ~S." fmt))))
(ecase next
(#\~ (write-char #\~ stream))
(#\d (write-integer (pop args) stream))
(#\a (write-string (pop args) stream)))
(incf i))
(write-char char stream)))))
(defun write-char-aux (char stream)
(if (and (not (eql char #\Space))
(graphic-char-p char))
(write-char char stream)
(write-string (string-capitalize (char-name char)) stream)))
(defun write-aux (form stream known-objects object-ids)
(when *print-circle*
(let* ((ix (or (position form known-objects) 0))
(id (aref object-ids ix)))
(cond
((and id (> id 0))
(simple-format stream "#~d=" id)
(setf (aref object-ids id) (- id)))
((and id (< id 0))
(simple-format stream "#~d#" (- id))
(return-from write-aux)))))
(typecase form
;; NIL
(null
(write-string "NIL" stream))
;; Symbols
(symbol
(let ((name (symbol-name form))
(package (symbol-package form)))
;; Check if the symbol is accesible from the current package. It
;; is true even if the symbol's home package is not the current
;; package, because it could be inherited.
(if (eq form (find-symbol (symbol-name form)))
(write-string (escape-token (symbol-name form)) stream)
;; Symbol is not accesible from *PACKAGE*, so let us prefix
;; the symbol with the optional package or uninterned mark.
(progn
(cond
((null package) (write-char #\# stream))
((eq package (find-package "KEYWORD")))
(t (write-string (escape-token (package-name package)) stream)))
(write-char #\: stream)
(when package
(multiple-value-bind (symbol type)
(find-symbol name package)
(declare (ignorable symbol))
(when (eq type :internal)
(write-char #\: stream))))
(write-string (escape-token name) stream)))))
;; Integers
(integer
(write-integer form stream))
;; Floats
(float
(write-string (float-to-string form) stream))
;; Characters
(character
(write-string "#\\" stream)
(write-char-aux form stream))
;; Strings
(string
(if *print-escape*
(write-string (lisp-escape-string form) stream)
(write-string form stream)))
;; Functions
(function
(let ((name #+jscl (oget form "fname")
#-jscl nil))
(if name
(simple-format stream "#<FUNCTION ~a>" name)
(write-string "#<FUNCTION>" stream))))
;; mop object
(mop-object (mop-object-printer form stream))
;; structure object
(structure (structure-object-printer form stream))
;; hash-table object
(hash-table (hash-table-object-printer form stream))
;; Lists
(list
(write-char #\( stream)
(unless (null form)
(write-aux (car form) stream known-objects object-ids)
(do ((tail (cdr form) (cdr tail)))
;; Stop on symbol OR if the object is already known when we
;; accept circular printing.
((or (atom tail)
(and *print-circle*
(let* ((ix (or (position tail known-objects) 0))
(id (aref object-ids ix)))
(not (zerop id)))))
(unless (null tail)
(write-string " . " stream)
(write-aux tail stream known-objects object-ids)))
(write-char #\space stream)
(write-aux (car tail) stream known-objects object-ids)))
(write-char #\) stream))
;; Vectors
(vector
(write-string "#(" stream)
(when (plusp (length form))
(write-aux (aref form 0) stream known-objects object-ids)
(do ((i 1 (1+ i)))
((= i (length form)))
(write-char #\space stream)
(write-aux (aref form i) stream known-objects object-ids)))
(write-char #\) stream))
;; Packages
(package
(simple-format stream "#<PACKAGE ~a>" (package-name form)))
;; Others
(js-object
(simple-format stream "#<JS-OBJECT ~a>" (js-object-signature form)))
(otherwise
(simple-format stream "#<JS-OBJECT ~a>" (#j:String form)))))
#+jscl
(defun output-stream-designator (x)
(cond ((eq x nil) *standard-output*)
((eq x t) *standard-output*)
(t (if (output-stream-p x)
x
(error "Form ~s is not output stream type." (write-to-string x))))))
#+jscl
(defun invoke-object-printer (fn form &optional (stream *standard-output*))
(let ((stream (output-stream-designator stream)))
(funcall fn form stream)))
;;; structure object printer
(defun structure-object-printer (form stream)
(let ((res))
(setq res (concat "#<structure " (string-downcase (string (car form))) ">"))
(simple-format stream res)))
;;; hash-table printer
(defun %hash-fn-print-name (form)
(let ((name (oget (car form) "name")))
(string-downcase (subseq name 0 (position #\- name)))))
(defun hash-table-object-printer (form stream)
;; object printer called under typecase. so, check-type not do
(simple-format
stream
(concat "#<hash-table :test " (%hash-fn-print-name form)
" :count ~d>")
(hash-table-count form)))
#+jscl
(defun write (form &key (stream *standard-output*)
(escape *print-escape*)
(gensym *print-gensym*)
(base *print-base*)
(radix *print-radix*)
(circle *print-circle*))
(let* ((*print-escape* escape)
(*print-gensym* gensym)
(*print-base* base)
(*print-radix* radix)
(*print-circle* circle))
(cond ((mop-object-p form)
(invoke-object-printer #'mop-object-printer form stream))
((hash-table-p form)
(invoke-object-printer #'hash-table-object-printer form stream))
((structure-p form)
(invoke-object-printer #'structure-object-printer form stream))
(t (let ((stream (output-stream-designator stream)))
(multiple-value-bind (objs ids)
(scan-multiple-referenced-objects form)
(write-aux form stream objs ids)
form))))))
#+jscl
(defun write-to-string (form)
(with-output-to-string (output)
(write form :stream output)))
;;; @vkm-path-printer 04-09-2022
#+jscl
(defun fresh-line (&optional (stream *standard-output*))
(let ((s (output-stream-designator stream)))
(cond ((start-line-p s)
nil)
(t (write-char #\Newline s)
t))))
#+jscl
(progn
(defun prin1 (form &optional stream)
(write form :stream stream :escape t))
(defun prin1-to-string (form)
(with-output-to-string (output)
(prin1 form output)))
(defun princ (form &optional stream)
(write form :stream stream :escape nil))
(defun princ-to-string (form)
(with-output-to-string (output)
(princ form output)))
(defun terpri (&optional (stream *standard-output*))
(write-char #\newline stream)
(values))
;;(defun print (x)
;; (prog1 (prin1 x)
;; (terpri)))
(defun print (x &optional stream)
(let ((s (output-stream-designator stream)))
(terpri s)
(write x :stream s :escape t)
(write-char #\space s)
x))
)
;;; EOF
| 16,834 | Common Lisp | .lisp | 445 | 29.78427 | 109 | 0.571027 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 9e02ff2be3976cf096861d84c097074c9ae2fa05f06cbb52f07a4d17345e4dfc | 16 | [
-1
] |
17 | load.lisp | jscl-project_jscl/src/load.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;;
;;; LOAD - load & compile Common Lisp file.
;;; Simple implementation of the common Lisp function 'load'
;;; for JSCL environment.
;;;
;;; JSCL is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; JSCL is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;;
(defun _xhr_receiver_ (uri fn-ok &optional fn-err)
(let ((req (make-new #j:XMLHttpRequest)))
((oget req "open" ) "GET" uri t)
((oget req "setRequestHeader") "Cache-Control" "no-cache")
((oget req "setRequestHeader") "Cache-Control" "no-store")
(setf (oget req "onreadystatechange")
(lambda (evt)
(if (= (oget req "readyState") 4)
(if (= (oget req "status") 200)
(funcall fn-ok (oget req "responseText"))
(if fn-err
(funcall fn-err uri (oget req "status") )
(format t "xhr: ~a~% ~a~%" (oget req "statusText") uri )) ))))
((oget req "send"))))
(defun _ldr_eval_ (sexpr verbose)
(when verbose
(format t "~a ~a~%" (car sexpr) (cadr sexpr)))
(handler-case
(progn
(dolist (x (multiple-value-list (eval sexpr)))
(format t " ~a~%" x))
t)
(error (msg)
(typecase condition
(simple-error
(apply #'format t
(simple-condition-format-control condition)
(simple-condition-format-arguments condition)))
(t (let* ((*print-escape* nil))
(print-object condition))))
nil))
nil)
(defun _load_form_eval_ (input verbose)
(let ((stream)
(expr)
(eof (gensym "LOADER" )))
(setq stream (make-string-input-stream input))
(terpri)
(tagbody
rdr-feeder
(setq expr (ls-read stream nil eof))
(when (eql expr eof)
(go rdr-eof))
(_ldr_eval_ expr verbose)
(go rdr-feeder)
rdr-eof)
(values)))
;;; replace cntrl-r from input
(defun _ldr_ctrl-r_replace_ (src)
(let ((reg (#j:RegExp (code-char 13) "g")))
((oget (lisp-to-js src) "replace") reg " ")))
;;; (load name &key verbose sync output place hook)
;;;
;;; sync - use node.js 'fs' facilities for read/write ops
;;; automatically turned off for browser with warn
;;;
;;; output - optional mode
;;; only for node/electron platform
;;; 'output' it is the place of the local file system where will be saved the file
;;; with the javascript code after compilation for future loading
;;; by the function 'require'.
;;;
;;; place - optional mode
;;; only for node/electron platform
;;; required 'jscl.js' path, by default eq './'
;;; 'place' it is the file system location from where the module 'jscl.js'
;;; will be is load by function 'require'
;;;
;;; Example:
;;;
;;; By default your 'jscl.js' location is "./"
;;;
;;; (load "src/project/jso.lisp" :output "./lib/app/jso/jso" :place "../../../")
;;;
;;; 1. ./lib/app/jso must be exists
;;; 2. ./lib/app/jso must contains file 'package.json' with (as minimum):
;;; {
;;; "name": "jso",
;;; "main": "jso.js"
;;; }
;;; So, (require "./lib/app/jso/jso") will load file 'jso.js' from './lib/app/jso'
;;;
;;; See node.js documentation for 'require' function
;;;
;;; hook - #() store place for js-code
;;;
;;; IMPORTANT!! don't use literal #() (see Issue #345)
;;; (setq bin (make-array 0 :fillpointer 0))
;;; (load "file1.lisp" :hook bin)
;;; (load "file2.lisp" :hook bin)
;;; (load "file3.lisp" :hook bin :output "lib.js")
;;; => will be bundle js-code file1, file2, file3 from bin to "lib.js"
;;;
;;;
;;; you will be use (require "./lib") or use html tag:
;;; <script src="lib.js" type="text/javascript" charset="utf-8"></script>
;;; without compilation.
;;;
;;;
;;; have a fun
;;;
(defun node-environment-p ()
(if (find :node *features*) t))
(defun load (name &key verbose (sync (node-environment-p)) output place hook)
(terpri)
(cond
;; node.js/electron platform
((node-environment-p)
(if place
(setq place (concat place "./"))
(setq place "./"))
(if sync
(loader-sync-mode name verbose output place hook)
(loader-async-mode name verbose output place hook)))
;; browser platform
(t (when sync
(warn "sync mode only for node/electron platform~%will be used async mode"))
(when (or output hook)
(warn "output/hook options only for node/electron platform"))
(warn "In browser mode, the LOAD function is executed ONLY if `web-security` is DISABLED (CORS restriction)")
(loader-browser-mode name verbose)))
(values))
(defun loader-browser-mode (name verbose)
(_xhr_receiver_
name
(lambda (input)
(_load_form_eval_ (_ldr_ctrl-r_replace_ input) verbose))
(lambda (url status)
(format t "~%Load: Can't load ~a~% Status: ~a~%" url status))))
;;; alowe make bundle from source received from local fs (by FILE:)
;;; or from remote resourse (by HTTP:)
(defun loader-async-mode (name verbose bundle-name place hook)
(_xhr_receiver_
name
(lambda (input)
(_load_eval_bundle_ (_ldr_ctrl-r_replace_ input) verbose bundle-name place hook))
(lambda (url status)
(format t "~%Load: Can't load ~a~% Status: ~a~%" url status))))
;;; sync mode
(defun loader-sync-mode (name verbose bundle-name place hook)
;; check what input file exists
(unless (#j:Fs:existsSync name)
(error "No such file ~s" name))
(_load_eval_bundle_
(_ldr_ctrl-r_replace_ (#j:Fs:readFileSync name "utf-8"))
verbose
bundle-name
place
hook))
(defun _load_eval_bundle_ (input verbose bundle-name place hook)
(let (stream eof code expr rc code-stor fbundle)
(setq eof (gensym "LOADER"))
(if hook (setq code-stor hook))
(when bundle-name
(if hook
(setq code-stor hook)
;; see Issue #345, #350, #397
(setq code-stor (make-array 0 :fill-pointer 0)))
(setq fbundle t))
(setq stream (make-string-input-stream input))
(tagbody sync-loader-rdr
_feeder_
(handler-case
(progn
(setq expr (ls-read stream nil eof))
(when (eq expr eof) (go _rdr_done_))
(when verbose (format t "~a ~a~%" (car expr) (cadr expr)))
(with-compilation-environment
(setq code (compile-toplevel expr t t))
(setq rc (js-eval code))
(when verbose (format t " ~a~%" rc))
;; so, expr already verifyed
;; store expression after compilation/evaluated
(cond (fbundle ((oget code-stor "push") code))
(hook ((oget code-stor "push") code))
(t t)) ))
(error (msg)
(format t " Error: ")
(load_cond_err_handl_ msg)
;; break read-eval loop
;; no bundle
(setq fbundle nil)
(go _rdr_done_)))
(go _feeder_)
_rdr_done_
(setq stream nil expr nil code nil))
(when fbundle
(_loader_check_output_directory_ bundle-name)
(_loader_make_bundle code-stor bundle-name place)
(setq code-stor nil))
(values)))
;;; error message handle path
(defun _load_cond_err_handl_(condition)
(typecase condition
(simple-error
(apply #'format t
(simple-condition-format-control condition)
(simple-condition-format-arguments condition)))
(type-error
;; note:
;; there can be custom event handling here.
;; while it remains as it was done.
;; sometime later
(let* ((*print-escape* nil))
(print-object condition)))
(t (let* ((*print-escape* nil))
(print-object condition))))
(write-char #\newline))
;;; Check what output directory exists
(defun _loader_check_output_directory_ (path)
(let ((dir (oget (#j:FsPath:parse path) "dir")))
(if (> (length dir) 0)
(unless (#j:Fs:existsSync dir)
;; dont create new directory
(error "No such output directory ~s" dir))
;; path eq "file.lisp"
;; so, dir eq "" and eq "./" by default
t )))
;;; header for jscl application module
(defun _loader_bundle_stm_open_ (stream)
((oget stream "write")
(concat "(function(jscl){'use strict'; (function(values, internals){" #\newline)))
;;; tail for jscl application module
(defun _loader_bundle_stm_close_ (stream place)
((oget stream "write")
(concat #\newline
"})(jscl.internals.pv, jscl.internals); })(typeof require !== 'undefined'? require('"
place
"jscl'): window.jscl)"
#\newline)))
;;; wrapper for one module statement
(defun _loader_stm_wraper_ (code)
(concat
"(function(values, internals){"
code
";})(values,internals);" #\newline) )
;;; bundle maker
(defun _loader_make_bundle (code fname place)
(let ((stream (#j:Fs:createWriteStream fname))
(nums 0))
(_loader_bundle_stm_open_ stream)
;; for each statement in code
((oget code "forEach")
(lambda (stm &rest others)
(setq nums (1+ nums))
;; write to stream
((oget stream "write") (_loader_stm_wraper_ stm))))
(_loader_bundle_stm_close_ stream place)
((oget stream "end"))
(format t "The bundle up ~d expressions into ~s~%" nums fname) ))
;;; other loader functions
;;;
;;; Warning:
;;; The both functions only for rapidly development
;;; Not for production
;;;
;;; load-js - load javascript code from local file system (by FILE:),
;;; or remote resource (by HTTP:) with used html tag 'link/stylesheet'
(defun load-js (from &optional onload)
(let ((link (#j:window:document:createElement "script"))
(body #j:window:document:body ))
(setf (oget link "charset") "utf-8"
(oget link "type") "text/javascript"
(oget link "src") from
(oget link "onerror") (lambda (ignore)
(format t "~%Error loading ~s file.~%" from)
(funcall ((oget body "removeChild" "bind") body link ))
(values)))
(when onload
(setf (oget link "onload") (lambda (ignore)
(funcall ((oget body "removeChild" "bind") body link ))
(funcall onload)
(values))))
(funcall ((oget body "appendChild" "bind" ) body link))
(unless onload
(funcall ((oget body "removeChild" "bind") body link )))
(values) ))
;;;
;;; load-css - load cascade style from local file system (by FILE:),
;;; or remote resource (by HTTP:) with used html tag 'link/stylesheet'
(defun load-css (from &optional onload)
(let ((link (#j:window:document:createElement "link"))
(body #j:window:document:body ))
(setf (oget link "rel") "stylesheet"
(oget link "type") "text/css"
(oget link "href") from
(oget link "onerror") (lambda (ignore)
(format t "~%Error loading ~s file.~%" from)
(funcall ((oget body "removeChild" "bind") body link ))
(values)))
(when onload
(setf (oget link "onload")
(lambda (ignore) (funcall onload from))))
(funcall ((oget body "appendChild" "bind" ) body link))
(values) ))
;;; EOF
| 12,216 | Common Lisp | .lisp | 315 | 32.374603 | 116 | 0.580664 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | ed2a70e871f58e5ea069947431fe1c6ca5afd9b76056499c3f3da2e150d43f61 | 17 | [
-1
] |
18 | format.lisp | jscl-project_jscl/src/format.lisp | ;;; format.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading format.lisp!")
(defun modifier-char-p (c)
(or (char= c #\:) (char= c #\@)))
(defun format-special (chr arg parameters modifiers stream)
(case (char-upcase chr)
(#\S (prin1 arg stream))
(#\A (princ arg stream))
(#\D (princ arg stream))
(#\C (cond ((member #\: modifiers)
(write-char-aux arg stream))
(t
(write-char arg stream))))
(t
(warn "~S is not implemented yet, using ~~S instead" chr)
(prin1 arg stream))))
(defun get-format-parameter (fmt i args)
(let ((c (char fmt i)))
(values (cond ((char= c #\')
(prog1 (char fmt (incf i))
(incf i)))
((char= c #\v)
(prog1 (pop args)
(incf i)))
((char= c #\#)
(prog1 (length args)
(incf i)))
((digit-char-p c)
(let ((chars nil))
(while (char<= #\0 (char fmt i) #\9)
(push (char fmt i) chars)
(incf i))
(parse-integer (map 'string 'identity (nreverse chars))))))
i
args)))
(defun parse-format-directive (fmt i args)
(let ((parms nil)
(modifiers '())
parm)
(block nil
(loop
(multiple-value-setq (parm i args) (get-format-parameter fmt i args))
(if parm
(push parm parms)
(let ((c (char fmt i)))
(cond ((char= c #\,)
(incf i))
((modifier-char-p c)
(push c modifiers)
(when (modifier-char-p (char fmt (incf i)))
(push (char fmt i) modifiers)
(incf i))
(return))
(t
(return)))))))
(values (nreverse parms) modifiers i args)))
(defun !format (destination fmt &rest args)
(let* ((len (length fmt))
(i 0)
(end (1- len))
(arguments args))
(let ((res
(with-output-to-string (stream)
(while (< i len)
(let ((c (char fmt i)))
(if (char= c #\~)
(progn
(if (= i end) (error "Premature end of control string ~s" fmt))
(multiple-value-bind (parms modifiers pos next-arguments)
(parse-format-directive fmt (incf i) arguments)
(setq i pos
arguments next-arguments)
(let ((next (char fmt i)))
(cond
((char= next #\~)
(write-char #\~ stream))
((or (char= next #\&)
(char= next #\%))
(write-char #\newline stream))
((char= next #\*)
(pop arguments))
(t
(format-special next (car arguments) parms modifiers stream)
(pop arguments))))))
(write-char c stream))
(incf i))))))
(case destination
((t)
(write-string res)
nil)
((nil)
res)
(t
(write-string res destination))))))
#+jscl (fset 'format (fdefinition '!format))
| 4,281 | Common Lisp | .lisp | 107 | 25.130841 | 97 | 0.446287 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 8b09d11246657fe33fc61b5c363012e0fc7ab4f4d5045f995d3167a31c7c3dd5 | 18 | [
-1
] |
19 | conditions.lisp | jscl-project_jscl/src/conditions.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; conditions.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; Follow here a straighforward implementation of the condition
;;; system of Common Lisp, except that any value will work as a
;;; condition. Because, well, we do not have conditions at this point.
(/debug "loading conditions.lisp!")
;;; Condition
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %def-condition (name parents slots options)
(let*
((cpl (if (and parents) (remove name parents) '(condition)))
(report (if (and options (assoc :report options))
(cadr (assoc :report options))))
(class-options (if (and options)
(remove :report options :key 'car)))
(class `(defclass ,name
,(progn
(if (null cpl) '(condition) cpl))
,slots ,class-options))
(report-fn)
(method))
(when report
(typecase report
(string
(setq report-fn `(lambda (condition stream)
(write-string ,report stream)
,report)))
(list
(if (not (eql (car report) 'lambda))
(error "Must be LAMBDA ~s." report))
(setq report-fn `,report))
(t (error "What can I compile it: ~s ?" report)))
(setq method
`(defmethod print-object ((condition ,name) &optional (stream *standard-output*))
(if *print-escape*
(call-next-method)
(funcall #',report-fn condition stream))
nil)))
(values name class method))))
(defmacro %define-condition (name (&rest parents) (&rest slot-spec) &rest options)
(multiple-value-bind (name class method)
(%def-condition name parents slot-spec options)
`(progn
,class
,method
',name)))
;;; condition hierarhy
(defclass condition ()())
(%define-condition simple-condition (condition)
((format-control :initarg :format-control
:initform nil
:reader simple-condition-format-control)
(format-arguments :initarg :format-arguments
:initform nil
:reader simple-condition-format-arguments)))
(%define-condition serious-condition (condition) ())
(%define-condition warning (condition) ())
(%define-condition simple-warning (simple-condition warning) ())
(%define-condition error (serious-condition) ())
(%define-condition simple-error (simple-condition error) ())
(%define-condition type-error (error)
((datum :initform nil
:initarg :datum
:reader type-error-datum)
(expected-type :initform nil
:initarg :expected-type
:reader type-error-expected-type))
(:report (lambda (condition stream)
(format stream "~S does not designate a ~S.~%"
(type-error-datum condition)
(type-error-expected-type condition)))))
(defun %%make-condition (type &rest slot-initializations)
(apply #'make-instance type slot-initializations))
(defun %%coerce-condition (default datum arguments)
(cond ((symbolp datum)
(unless (find-class datum nil)
(%%error 'type-error :datum datum :expected-type 'condition))
(apply #'%%make-condition datum arguments))
((or (stringp datum)(functionp datum))
(%%make-condition default
;; todo: formater function
:format-control datum
:format-arguments arguments))
((!typep datum 'condition)
(check-type arguments null)
datum)
(t (%%error 'type-error
:datum datum
:expected-type 'condition-designator))))
;;; raise CONDITION with any type
(defun %%signal (datum &rest args)
(let ((condition (%%coerce-condition 'simple-condition datum args)))
(dolist (binding *handler-bindings*)
(let ((type (car binding))
(handler (cdr binding)))
;; Here TYPE is one of: SYMBOL or (OR symbol ... symbol)
(when (typep condition type)
(funcall handler condition))))))
(defun %%warn (datum &rest arguments)
(let ((stream *standard-output*)
(condition (%%coerce-condition 'simple-warning datum arguments)))
;; prevent all conditions ERROR class
(check-type condition warning)
(%%signal condition)
(format stream "WARNING: ")
(apply 'format stream (simple-condition-format-control condition)
(simple-condition-format-arguments condition))
(write-char #\newline stream)
nil))
(defun %%error (datum &rest args)
(let ((stream *standard-output*)
(condition (%%coerce-condition 'simple-error datum args)))
;; prevent all condition WARNING class
(check-type condition error)
(%%signal condition)
;;(format stream "~&ERROR: ~a~%" (type-of condition))
(typecase condition
(simple-error
(format stream (simple-condition-format-control condition)
(simple-condition-format-arguments condition)))
(type-error
(format stream "Type error. ~a does not designate a ~a" (type-error-datum condition)
(type-error-expected-type condition))))
nil))
;;; handlers
(defvar *handler-bindings* nil)
(defmacro %%handler-bind (bindings &body body)
(let ((install-handlers nil))
(dolist (binding bindings)
(destructuring-bind (type handler) binding
(if (consp type)
;; TYPEP OR form
;; (error warning) -> (or error warning)
;; unless form - if someone smart has already used OR
(unless (eq (car type) 'or) (setq type (push 'or type))))
(push `(push (cons ',type #',handler) *handler-bindings*)
install-handlers)))
`(let ((*handler-bindings* *handler-bindings*))
,@install-handlers
(%js-try
(progn ,@body)
(catch (err)
(if (%%nlx-p err)
(%%throw err)
(%%error (or (oget err "message") err))))))))
(defmacro %%handler-case-1 (form &body cases)
(let ((datum (gensym))
(nlx (gensym))
(tagbody-content nil))
(flet (
;; Given a case, return a condition handler for it. It will
;; also update the TAGBODY-CONTENT variable. This variable
;; contains the body of a tagbody form. The condition
;; handlers will GO to labels there in order to perform non
;; local exit and handle the condition.
(translate-case (case)
(destructuring-bind (type (&optional (var (gensym))) &body body)
case
(let ((label (gensym)))
(push label tagbody-content)
(push `(return-from ,nlx
(let ((,var ,datum))
,@body))
tagbody-content)
`(,type (lambda (temp)
(setq ,datum temp)
(go ,label)))))))
`(block ,nlx
(let (,datum)
(tagbody
(%%handler-bind ,(mapcar #'translate-case cases)
(return-from ,nlx ,form))
,@(reverse tagbody-content)))))))
(defmacro %%handler-case (form &body cases)
(let ((last-case (car (last cases))))
(if (and last-case (eq (car last-case) :no-error))
(destructuring-bind (lambda-list &body body) (cdr last-case)
(let ((error-return (gensym))
(normal-return (gensym)))
`(block ,error-return
(multiple-value-call (lambda ,lambda-list ,@body)
(block ,normal-return
(return-from ,error-return
(%%handler-case-1 (return-from ,normal-return ,form)
,@(butlast cases))))))))
`(%%handler-case-1 ,form ,@cases))))
(defmacro %%ignore-errors (&body forms)
`(%%handler-case
(progn ,@forms)
(error (condition) (values nil condition))))
;;; Simple ASSERT release
(defun %%assert-error (form datum &rest args)
(error
(if datum
(%%coerce-condition 'simple-error datum args)
(%%make-condition 'simple-error
:format-control "Assert failed: ~s."
:format-arguments (list form)))))
;;; @vlad-km macro %%assert moved to boot.lisp
#+jscl
(progn
(defmacro define-condition (name (&rest parents) (&rest slot-spec) &rest options)
`(%define-condition ,name (,@parents)
(,@slot-spec) ,@options))
(defmacro handler-bind (&rest body)
`(%%handler-bind ,@body))
(defmacro handler-case (&rest body)
`(%%handler-case ,@body))
(defmacro ignore-errors (&rest forms)
`(%%ignore-errors ,@forms))
(fset 'make-condition #'%%make-condition)
(fset 'signal #'%%signal)
(fset 'warn #'%%warn)
(fset 'error #'%%error))
;;; EOF
| 9,619 | Common Lisp | .lisp | 227 | 32.92511 | 95 | 0.590729 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 239c1d66c87f6975f3da57fe858a9fe49d950ee62766c9ce5b8d27947f77aedb | 19 | [
-1
] |
20 | numbers.lisp | jscl-project_jscl/src/numbers.lisp | ;;; numbers.lisp
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading numbers.lisp!")
;;;; Various numeric functions and constants
(macrolet ((def (operator initial-value)
(let ((init-sym (gensym))
(dolist-sym (gensym)))
`(defun ,operator (&rest args)
(let ((,init-sym ,initial-value))
(dolist (,dolist-sym args)
(setq ,init-sym (,operator ,init-sym ,dolist-sym)))
,init-sym)))))
(def + 0)
(def * 1))
;; - and / work differently from the above macro.
;; If only one arg is given, it negates it or takes its reciprocal.
;; Otherwise all the other args are subtracted from or divided by it.
(macrolet ((def (operator unary-form)
`(defun ,operator (x &rest args)
(cond
((null args) ,unary-form)
(t (dolist (y args)
(setq x (,operator x y)))
x)))))
(def - (- x))
(def / (/ 1 x)))
(defconstant most-positive-fixnum
(oget (%js-vref "Number" t) "MAX_SAFE_INTEGER"))
(defconstant most-negative-fixnum
(oget (%js-vref "Number" t) "MIN_SAFE_INTEGER"))
(defun fixnump (n)
(and (integerp n)(>= most-negative-fixnum) (<= most-positive-fixnum)))
(defun non-negative-fixnump (n)
(if (fixnump n)
(and (>= n 0)
(<= n most-positive-fixnum))))
;;; Yeat another Root of the Evil
(defun bignump (n)
(and (integerp n)(or (< most-negative-fixnum) (> most-positive-fixnum))))
(defun 1+ (x) (+ x 1))
(defun 1- (x) (- x 1))
(defun rem (number divisor)
(rem0 number divisor))
(defun mod (number divisor)
(multiple-value-bind (quotient remainder)
(floor number divisor)
remainder))
(defun floor (x &optional (y 1))
(let ((quotient (%floor (/ x y))))
(values quotient
(- x (* quotient y)))))
(defun ceiling (x &optional (y 1))
(%ceiling (/ x y)))
;;; @vkm 30.11
;;; test case
;;; (floor number divisor) second value is (mod number divisor)
;;; celing second value is remainder
;;; (rem number divisor) return second result of truncate
;;; (mod number divisor) return second result of floor
(defun truncate (number &optional (divisor 1))
(let ((res (%truncate (/ number divisor))))
(values res (- number (* res divisor)))))
;;; @vkm 30.11 end
(defun numberp (x) (numberp x))
(defun integerp (x) (%integer-p x))
(defun realp (x) (numberp x))
(defun rationalp (x) (%integer-p x))
(defun floatp (x)
(and (numberp x) (not (integerp x))))
(defun minusp (x) (< x 0))
(defun zerop (x) (= x 0))
(defun plusp (x) (< 0 x))
(defun signum (x)
(if (zerop x) x (/ x (abs x))))
(macrolet ((def (operator)
`(defun ,operator (x &rest args)
(dolist (y args)
(if (,operator x y)
(setq x (car args))
(return-from ,operator nil)))
t)))
(def >)
(def >=)
(def =)
(def <)
(def <=)
(def /=))
(defconstant pi 3.141592653589793)
(defun evenp (x) (= (mod x 2) 0))
(defun oddp (x) (not (evenp x)))
(macrolet ((def (name comparison)
`(defun ,name (x &rest xs)
(dolist (y xs)
(when (,comparison y x)
(setq x y)))
x)))
(def max >)
(def min <))
(defun abs (x) (if (> x 0) x (- x)))
(defun expt (base power) (expt base power))
(defun exp (power) (expt 2.718281828459045 power))
(defun sqrt (x) (sqrt x))
(defun gcd-2 (a b)
(if (zerop b)
(abs a)
(gcd-2 b (rem a b))))
(defun gcd (&rest integers)
(cond ((null integers)
0)
((null (cdr integers))
(abs (first integers)))
((null (cddr integers))
(gcd-2 (first integers) (second integers)))
(t
(apply #'gcd (gcd (first integers) (second integers)) (nthcdr 2 integers)))))
(defun lcm-2 (a b)
(if (or (zerop a) (zerop b))
0
(/ (abs (* a b)) (gcd a b))))
(defun lcm (&rest integers)
(cond ((null integers)
1)
((null (cdr integers))
(abs (first integers)))
((null (cddr integers))
(lcm-2 (first integers) (second integers)))
(t
(apply #'lcm (lcm (first integers) (second integers)) (nthcdr 2 integers)))))
;;; @VKM path 30.11
;;; round number/division to nearest integer
;;; second value is remainder
(defun round (number &optional (divisor 1))
(multiple-value-bind (integer remainder) (truncate number divisor)
(if (zerop remainder)
(values integer remainder)
(let ((thresh (/ (abs divisor) 2)))
(cond ((or (> remainder thresh)
(and (= remainder thresh) (oddp integer)))
(if (minusp divisor)
(values (- integer 1) (+ remainder divisor))
(values (+ integer 1) (- remainder divisor))))
((let ((negative (- thresh)))
(or (< remainder negative)
(and (= remainder negative) (oddp integer))))
(if (minusp divisor)
(values (+ integer 1) (- remainder divisor))
(values (- integer 1) (+ remainder divisor))))
(t (values integer remainder)))))))
(defconstant most-integer-length (expt 2 30))
;;; ash
(defun ash (x y)
(let* ((minus-p (minusp y))
(y (if minus-p (- y) y)))
(if minus-p
(%ash-right x y)
(%ash-left x y))))
;;; log
(defun log (number &optional (base nil base-p))
"Return the logarithm of NUMBER in the base BASE, which defaults to e."
(if base-p
(/ (log number) (log base))
(if (numberp number)
(#j:Math:log number)
(error "`~S' is not a number." number))))
;;; lognot
(defun lognot (x) (%lognot x))
;;; logxor
(defun logxor (&rest others)
(if (null others) (return-from logxor 0)
(let ((result (car others)))
(do ((integers others (cdr integers))
(result 0 (%logxor result (car integers))))
((endp integers) result)))))
;;; logand
(defun logand (&rest others)
(if (null others) (return-from logand -1)
(let ((integer (car others)))
(do ((integers others (cdr integers))
(result integer (%Logand result (car integers))))
((endp integers) result)))))
;;; logeqv
(defun %logeqv (x y) (%lognot (%logxor x y)))
(defun logeqv (&rest others)
(if (null others) (return-from logeqv -1)
(let ((integer (car others)))
(do ((integers (cdr others) (cdr integers))
(result integer (%logeqv result (car integers))))
((endp integers) result)))))
;;; logior
(defun logior (&rest others)
(if (null others) (return-from logior 0)
(let ((integer (car others)))
(do ((integers others (cdr integers))
(result integer (%logior result (car integers))))
((endp integers) result)))))
;;; integer-length
;;; note: ONLY 32 bits
;;; note: its very simple and incorrect function
;;; todo: We need version with corrected doing fixnum & bignum numbers
(defun integer-length (integer)
(let ((negative (minusp integer)))
(if negative
(setq integer (- integer)))
(if (> integer most-integer-length)
;; prevent infinity loop with (integer-length (expt 2 31))
(error "integer-length: bad numeric limit ~a" integer))
(do ((len 0 (1+ len))
(original integer))
((zerop integer)
;; Negative powers of two require one less bit.
(if (and negative
;; Test if original is power-of-two.
(zerop (%logand original (1- original))))
(1- len)
len))
(setq integer (ash integer -1)))))
;;; logtest
;;; Return T if logand of integer1 and integer2 is not zero
(defun logtest (integer1 integer2)
(not (zerop (%logand integer1 integer2))))
;;; logbitp
(defun logbitp (index integer)
(if (< index most-positive-fixnum)
(not (zerop (%logand integer (ash 1 index))))
(minusp integer)))
;;; LOGCOUNT
;;; note: ONLY 32 bits
;;; note: its very simple and incorrect function
;;; todo: We need version with corrected doing fixnum & bignum numbers
;;; Count the number of 1 bits if INTEGER is non-negative,
;;; and the number of 0 bits if INTEGER is negative
(defun %logcount (integer)
(let ((length (integer-length integer))
(result 0))
(dotimes (bit length)
(if (logbitp bit integer) (incf result)))
result))
(defun logcount (integer)
(%logcount (if (minusp integer) (%lognot integer) integer)))
(defconstant boole-1 0) ;; integer-1
(defconstant boole-2 1) ;; integer-2
(defconstant boole-andc1 2) ;; and complement of integer-1 with integer-2
(defconstant boole-andc2 3) ;; and integer-1 with complement of integer-2
(defconstant boole-and 4) ;; and
(defconstant boole-c1 5) ;; complement of integer-1
(defconstant boole-c2 6) ;; complement of integer-2
(defconstant boole-clr 7) ;; always 0 (all zero bits)
(defconstant boole-eqv 8) ;; equivalence (exclusive nor)
(defconstant boole-ior 9) ;; inclusive or
(defconstant boole-nand 10) ;; not-and
(defconstant boole-nor 11) ;; not-or
(defconstant boole-orc1 12) ;; or complement of integer-1 with integer-2
(defconstant boole-orc2 13) ;; or integer-1 with complement of integer-2
(defconstant boole-set 14) ;; always -1 (all one bits)
(defconstant boole-xor 15) ;; exclusive or
;;; fns definition: lognand, lognor, logandc*, logorc*
(defun lognand (x y) (%lognot (%logand x y)))
(defun lognor (x y) (%lognot (%logior x y)))
(defun logandc1 (x y) (%logand (%lognot x) y))
(defun logandc2 (x y) (%logand x (%lognot y)))
(defun logiorc1 (x y) (%logior (%lognot x) y))
(defun logiorc2 (x y) (%logior x (%lognot y)))
;;; BOOLE
(defun boole (op i1 i2)
(cond
((eq op boole-clr) 0)
((eq op boole-set) -1)
((eq op boole-1) i1)
((eq op boole-2) i2)
((eq op boole-c1) (%lognot i1))
((eq op boole-c2) (%lognot i2))
((eq op boole-and) (%logand i1 i2))
((eq op boole-ior) (%logior i1 i2))
((eq op boole-xor) (%logxor i1 i2))
((eq op boole-eqv) (%logeqv i1 i2))
((eq op boole-nand) (%lognot (%logand i1 i2)))
((eq op boole-nor) (%lognot (%logior i1 i2)))
((eq op boole-andc1) (%logand (%lognot i1) i2))
((eq op boole-andc2) (%logand i1 (%lognot i2)))
((eq op boole-orc1) (%logior (%lognot i1) i2))
((eq op boole-orc2) (%logior i1 (%lognot i2)))
(t (error "~S is an illegal control code to BOOLE." op))))
;;; RANDOM
(defun random (n)
(let ((rn (#j:Math:random n)))
(#j:Math:floor (* rn n))))
;;; BYTE
;;; return byte specifier
(defun byte (size position)
(cons size position))
;;; BYTE-SIZE
;;; return the size part of the byte specifier
(defun byte-size (spec)
(car spec))
;;; BYTE-POSITION
;;; return thhe position part of the byte specifier
(defun byte-position (spec)
(cdr spec))
;;; CLZ32
;;; count leading zero
;;; ONLY 32 bits
(defun clz32 (number)
(#j:Math:clz32 number))
;;; MASK-FIELD
;;; extract the specified byte from integer
;;; result not right justify
(defun %mask-field (size posn integer)
(%logand integer (ash (1- (ash 1 size)) posn)))
;;; todo: (setf)
(defun mask-field (byte integer)
(%logand integer (ash (1- (ash 1 (car byte))) (cdr byte))))
;;; LDB
;;; extract the specified byte from integer
;;; result right justify
(defun %ldb (size pos integer)
(%logand (ash integer (- pos))
(1- (ash 1 size))))
(defun ldb (byte integer)
(%ldb (car byte) (cdr byte) integer))
;;; LDB-TEST
;;; todo: (setf)
(defun ldb-test (byte number)
(not (zerop (ldb byte number))))
;;; DPB
;;; return new integer with newbyte in specified position
;;; newbyte is right justify
(defun %dpb (newbyte size posn integer)
(let ((mask (1- (ash 1 size))))
(%logior (%logand integer (%lognot (ash mask posn)))
(ash (%logand newbyte mask) posn))))
(defun dpb (newbyte byte integer)
(%dpb newbyte (car byte) (cdr byte) integer))
;;; DEPOSIT-FIELD
;;; return new integer with newbyte in specified position
;;; newbyte isnt right justify
(defun %deposit-field (newbyte size posn integer)
(let ((mask (ash (%ldb size 0 -1) posn)))
(%logior (%logand newbyte mask)
(%logand integer (%lognot mask)))))
(defun deposit-field (newbyte byte integer)
(%deposit-field newbyte (car byte) (cdr byte) integer))
;;; @vkm 30.11 end
;;; EOF
| 13,455 | Common Lisp | .lisp | 354 | 31.816384 | 79 | 0.590961 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 148f4676cee3710a6814977b6c2e9964d31147a21d199b6b560cbed768f3eb53 | 20 | [
-1
] |
21 | stream.lisp | jscl-project_jscl/src/stream.lisp | ;;; stream.lisp ---
;; copyright (C) 2012, 2013 David Vazquez
;; Copyright (C) 2012 Raimon Grau
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; TODO: Use structures to represent streams, but we would need
;;; inheritance.
(/debug "loading stream.lisp!")
(defvar *standard-output*)
(defvar *standard-input*)
(def!struct (stream (:predicate streamp))
write-fn
read-char-fn
peek-char-fn
kind
data
(direction :out)
at-line-start)
;;; @vkm path stream.lisp 04-09-2022
(defun start-line-p (&optional (stream *standard-output*))
(stream-at-line-start stream))
(defun stream-p (obj)
(if (and (structure-p obj)
(eql (car obj) 'stream))
t
nil))
(defun output-stream-p (obj)
(and (stream-p obj)
(eql (stream-direction obj) :out)))
;;; end @vkm path
;;; Input streams
(defun make-string-input-stream (string)
(let ((index 0))
(flet ((peek (eof-error-p)
(cond
((< index (length string))
(char string index))
(eof-error-p
(error "make-string-input-stream end of file."))
(t
nil))))
(make-stream
:read-char-fn (lambda (eof-error-p)
(prog1 (peek eof-error-p)
(incf index)))
:peek-char-fn (lambda (eof-error-p)
(peek eof-error-p))))))
(defun peek-char (&optional type (stream *standard-input*) (eof-error-p t))
(unless (null type)
(error "peek-char with non-null TYPE is not implemented."))
(funcall (stream-peek-char-fn stream) eof-error-p))
(defun read-char (&optional (stream *standard-input*) (eof-error-p t))
(funcall (stream-read-char-fn stream) eof-error-p))
;;; Output streams
(defun write-char (char &optional (stream *standard-output*))
(setf (stream-at-line-start stream) nil)
(if (eql char #\Newline)
(setf (stream-at-line-start stream) t))
(funcall (stream-write-fn stream) (string char))
char)
(defun !write-string (string &optional (stream *standard-output*))
(if (eql (char string (1- (length string))) #\Newline)
(setf (stream-at-line-start stream) t)
(setf (stream-at-line-start stream) nil))
(funcall (stream-write-fn stream) string)
string)
(defun write-string (string &optional (stream *standard-output* stream-p) &rest keys)
(let ((sl (length string)))
(let* ((no-keys (null keys))
(start)
(end)
(write-string-invalid-range-seq)
(write-string-nondecreasing-order-seq))
(cond (stream-p
(if (streamp stream) t
(error "write-string - malformed stream ~a. Use full (string stream ...) form." stream))))
(cond ((eq sl 0) "")
(no-keys (!write-string string stream))
(t (setq start (getf keys :start 0)
end (getf keys :end sl)
write-string-invalid-range-seq (/= start end)
write-string-nondecreasing-order-seq (<= 0 start end sl))
(assert write-string-invalid-range-seq)
(assert write-string-nondecreasing-order-seq)
(!write-string (subseq string start end) stream))))))
(defun write-line (string &optional (stream *standard-output*) &rest keys)
(prog1
(if (null keys)
(!write-string string stream)
(let ((start (getf keys :start 0))
(end (getf keys :end (length string))))
(!write-string (subseq string start end) stream)
(write-char #\Newline stream)))))
(defun make-string-output-stream ()
(let ((buffer (make-array 0 :element-type 'character :fill-pointer 0)))
(make-stream
:write-fn (lambda (string)
(dotimes (i (length string))
(vector-push-extend (aref string i) buffer)))
:kind 'string-stream
:data buffer
:at-line-start t)))
(defmacro with-input-from-string ((var string) &body body)
;; TODO: &key start end index
`(let ((,var (make-string-input-stream ,string)))
,@body))
(defun get-output-stream-string (stream)
(prog1 (stream-data stream)
(setf (stream-data stream) (make-string 0))))
(defmacro with-output-to-string ((var) &body body)
`(let ((,var (make-string-output-stream)))
,@body
(get-output-stream-string ,var)))
;;; EOF
| 4,900 | Common Lisp | .lisp | 124 | 33.008065 | 105 | 0.629949 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 8193ce7eb3ecfe195c2fd1e411c41cba8ada2777303f29fb48c4243fd69baf72 | 21 | [
-1
] |
22 | ffi.lisp | jscl-project_jscl/src/ffi.lisp | ;;; ffi.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading ffi.lisp!")
(defvar *root*)
(define-setf-expander oget (object key &rest keys)
(let* ((keys (cons key keys))
(g!object (gensym))
(g!keys (mapcar (lambda (s)
(declare (ignore s))
(gensym))
keys))
(g!value (gensym)))
(values `(,g!object ,@g!keys)
`(,object ,@keys)
`(,g!value)
`(oset ,g!value ,g!object ,@g!keys)
`(oget ,g!object ,@g!keys))))
(define-setf-expander oget* (object key &rest keys)
(let* ((keys (cons key keys))
(g!object (gensym))
(g!keys (mapcar (lambda (s)
(declare (ignore s))
(gensym))
keys))
(g!value (gensym)))
(values `(,g!object ,@g!keys)
`(,object ,@keys)
`(,g!value)
`(oset* ,g!value ,g!object ,@g!keys)
`(oget* ,g!object ,@g!keys))))
(defun make-new (constructor &rest args)
(apply (%js-internal "newInstance") constructor args))
(defun lisp-to-js (x)
(lisp-to-js x))
(defun js-to-lisp (x)
(js-to-lisp x))
(%js-vset "eval_in_lisp"
(lambda (form)
(eval (read-from-string form))))
(defun js-object-p (obj)
(if (or (sequencep obj)
(numberp obj)
(symbolp obj)
(functionp obj)
(characterp obj)
(packagep obj))
nil
t))
(defun js-null-p (obj) (js-null-p obj))
(defun js-undefined-p (obj) (js-undefined-p obj))
;;; EOF
| 2,216 | Common Lisp | .lisp | 62 | 27.870968 | 69 | 0.567757 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 951a622b5ccd495905e906e9ac60c5cab199bd7e5b7c85a9cdda3bc932207c93 | 22 | [
-1
] |
23 | types-prelude.lisp | jscl-project_jscl/src/types-prelude.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; Preliminary for types & defstruct @vkm
;;;
;;; JSCL is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; JSCL is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; DEFTYPE
#-jscl
(progn
(defvar *types* (make-hash-table :test #'equal))
;;; DEFSTRUCT
;;(defvar *structures* (make-hash-table :test #'equal))
(defvar *structures* nil "DEFSTRUCT STORE")
;;; DEFCLASS
(defvar *class-table* (make-hash-table :test #'equal)))
#+jscl
(progn
(defvar *types* (make-hash-table :test #'eql))
;;; DEFSTRUCT
(defvar *structures* (make-hash-table :test #'eql))
;;; DEFCLASS
(defvar *class-table* (make-hash-table :test #'eql)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun get-structure-dsd (name)
(gethash name *structures*)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun exists-structure-p (name)
(multiple-value-bind (v e-p) (gethash name *structures*)
e-p)))
;;; another member from ccl
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun memq (item list)
(while list
(if (eq item (car list)) (return list))
(setq list (cdr list)))))
;;; lightweight mapcar
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %lmapcar (fn list)
(let* ((ret-list (list nil))
(temp ret-list)
(res nil))
(while list
(setq res (funcall fn (car list))
list (cdr list))
(setf (cdr temp) (list res)
temp (cdr temp)))
(cdr ret-list))))
;;; internal unsafe defstruct version
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %struct-generator (kind options slots)
(let* ((constructor (cadr (assoc :constructor options)))
(keys (cadr (assoc :form options)))
(names (mapcar (lambda (x) (if (consp x) (car x) x)) slots))
(option (if keys keys '&optional))
(maker)
(makname (if constructor
(intern (symbol-name constructor))
(intern (concat "%MAKE-" (symbol-name `,kind)))))
(getter)
(position 0)
(q))
(unless (memq option '(&key &optional)) (error "Something went wrong: ~a." options))
(setq maker
`(defun ,makname (,option ,@slots) (list ,@names)))
(dolist (it names)
(setq getter (intern (concat (symbol-name kind) "-" (symbol-name it))))
(push `(defun ,getter (storage)(nth ,position storage)) q)
(push `(defun (setf ,getter) (value storage)
(rplaca (nthcdr ,position storage) value) value)
q)
(incf position))
(values maker (reverse q)))))
(defmacro %i-struct (name-options &rest slots)
(let* ((name-options (ensure-list name-options))
(name (car name-options))
(options (rest name-options)))
(multiple-value-bind (maker accessors) (%struct-generator name options slots)
`(progn
,maker
,@accessors))))
(%i-struct (type-info (:form &key)) name expand compound predicate)
(defun %deftype-info (name &optional (create t))
(unless (symbolp name) (error "Not a symbol ~a." name))
(let ((exists (gethash name *types*)))
(cond ((and (not exists) create)
(setq exists (%make-type-info :name name))
(setf (gethash name *types*) exists))
(t exists))))
(defun %deftype (name &key expander compound predicate)
(let ((type (%deftype-info name)))
(when expander
(setf (type-info-expand type) expander) )
(when compound
(setf (type-info-compound type) compound))
(when predicate
(setf (type-info-predicate type) predicate))))
;;; EOF
| 4,231 | Common Lisp | .lisp | 106 | 33.981132 | 90 | 0.630504 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 9c6a042dcd0bdea13f45b67293999d993034a81b647a32648d6bd005d5f961f1 | 23 | [
-1
] |
24 | setf.lisp | jscl-project_jscl/src/setf.lisp | ;;; setf.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading setf!")
;;; Generalized references (SETF)
(eval-when(:compile-toplevel :load-toplevel :execute)
(defvar *setf-expanders* nil)
(defun !get-setf-expansion (place)
(if (symbolp place)
(let ((value (gensym)))
(values nil
nil
`(,value)
`(setq ,place ,value)
place))
(let* ((access-fn (car place))
(expander (cdr (assoc access-fn *setf-expanders*))))
(if expander
(apply expander (cdr place))
;; Only after the setf expansion is unkonwn, we should
;; try to macroexpand the form. See:
;;
;; 5.1.2.7 Macro Forms as Places:
;;
;; http://clhs.lisp.se/Body/05_abg.htm
;;
(multiple-value-bind (macroexpansion macroexpanded)
(!macroexpand-1 place)
(if macroexpanded
(!get-setf-expansion macroexpansion)
(error "Unknown generalized reference."))))))))
(fset 'get-setf-expansion (fdefinition '!get-setf-expansion))
(defmacro define-setf-expander (access-fn lambda-list &body body)
(unless (symbolp access-fn)
(error "ACCESS-FN `~S' must be a symbol." access-fn))
(let ((g!args (gensym)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(push (cons ',access-fn (lambda (&rest ,g!args)
(destructuring-bind ,lambda-list ,g!args
,@body)))
*setf-expanders*)
',access-fn)))
(defmacro short-defsetf (access-fn update-fn &optional documentation)
(declare (ignore documentation))
`(define-setf-expander ,access-fn (&rest args)
(let ((g!new (gensym))
(g!args (mapcar (lambda (s)
(declare (ignore s))
(gensym))
args)))
(values g!args
args
(list g!new)
(cons ',update-fn (append g!args (list g!new)))
(cons ',access-fn g!args)))))
(defmacro long-defsetf (access-fn lambda-list (&rest store-variables) &body body)
;; TODO: Write me. But you will need to hack lambda-list.lisp to
;; support defsetf lambda lists.
;;
;; http://www.lispworks.com/documentation/HyperSpec/Body/03_dg.htm
;;
(error "The long form of defsetf is not implemented"))
(defmacro defsetf (&whole args first second &rest others)
(declare (ignore others))
(if (consp second)
`(long-defsetf ,@args)
`(short-defsetf ,@args)))
(defmacro setf (&rest pairs)
(cond
((null pairs)
nil)
((null (cdr pairs))
(error "Odd number of arguments to setf."))
((null (cddr pairs))
(let ((place (!macroexpand-1 (first pairs)))
(value (second pairs)))
(multiple-value-bind (vars vals store-vars writer-form reader-form)
(!get-setf-expansion place)
(declare (ignorable reader-form))
;; TODO: Optimize the expansion a little bit to avoid let*
;; or multiple-value-bind when unnecesary.
`(let* ,(mapcar #'list vars vals)
(multiple-value-bind ,store-vars
,value
,writer-form)))))
(t
`(progn
,@(do ((pairs pairs (cddr pairs))
(result '() (cons `(setf ,(car pairs) ,(cadr pairs)) result)))
((null pairs)
(reverse result)))))))
;;; SETF-Based macros
(defmacro incf (place &optional (delta 1))
(multiple-value-bind (dummies vals newval setter getter)
(!get-setf-expansion place)
(let ((d (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,d ,delta)
(,(car newval) (+ ,getter ,d))
,@(cdr newval))
,setter))))
(defmacro decf (place &optional (delta 1))
(multiple-value-bind (dummies vals newval setter getter)
(!get-setf-expansion place)
(let ((d (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,d ,delta)
(,(car newval) (- ,getter ,d))
,@(cdr newval))
,setter))))
(defmacro push (x place)
(multiple-value-bind (dummies vals newval setter getter)
(!get-setf-expansion place)
(let ((g (gensym)))
`(let* ((,g ,x)
,@(mapcar #'list dummies vals)
(,(car newval) (cons ,g ,getter))
,@(cdr newval))
,setter))))
(defmacro pop (place)
(multiple-value-bind (dummies vals newval setter getter)
(!get-setf-expansion place)
(let ((head (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,head ,getter)
(,(car newval) (cdr ,head))
,@(cdr newval))
,setter
(car ,head)))))
(defmacro pushnew (x place &rest keys &key key test test-not)
(declare (ignore key test test-not))
(multiple-value-bind (dummies vals newval setter getter)
(!get-setf-expansion place)
(let ((g (gensym))
(v (gensym)))
`(let* ((,g ,x)
,@(mapcar #'list dummies vals)
,@(cdr newval)
(,v ,getter))
(if (member ,g ,v ,@keys)
,v
(let ((,(car newval) (cons ,g ,getter)))
,setter))))))
| 5,988 | Common Lisp | .lisp | 153 | 29.862745 | 81 | 0.562876 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 2a9e46026e992c72ffce55d1f3563ec97f76086babad881f232e7ddcff91a496 | 24 | [
-1
] |
25 | compat.lisp | jscl-project_jscl/src/compat.lisp | ;;; compat.lisp --- Create some definitions to fix CL compatibility
;; Copyright (C) 2012, 2013 David Vazquez
;; Copyright (C) 2012 Raimon Grau
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; Duplicate from boot.lisp by now
(defmacro while (condition &body body)
`(do ()
((not ,condition))
,@body))
(defun aset (array idx value)
(setf (aref array idx) value))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun concat (&rest strs)
(apply #'concatenate 'string strs)))
(defun /debug (x)
(declare (ignorable x))
;; (write-line x)
)
(defun j-reader (stream subchar arg)
(declare (ignorable subchar arg))
(assert (char= #\: (read-char stream nil :eof)) nil "FFI descriptor must start with a semicolon.")
(loop :for ch := (read-char stream nil #\Space)
:until (terminalp ch)))
(set-dispatch-macro-character #\# #\J #'j-reader)
#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :sb-posix))
(defun get-source-data-epoch ()
(let (sde)
#+ccl (setq sde (ccl::getenv "SOURCE_DATE_EPOCH"))
#+sbcl (setq sde (sb-posix:getenv "SOURCE_DATE_EPOCH"))
;; other compiler - will be nil
(if sde
(+ (parse-integer sde) 2208988800))))
| 1,802 | Common Lisp | .lisp | 45 | 37.266667 | 100 | 0.703492 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | f5428f342b265c7663a3d463b462f647529f89a2dcdfe7504ccadc0577439ade | 25 | [
-1
] |
26 | list.lisp | jscl-project_jscl/src/list.lisp | ;;; list.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading list.lisp!")
;;;; Various list functions
(defun cons (x y) (cons x y))
(defun consp (x) (consp x))
(defun listp (x)
(or (consp x) (null x)))
(defun null (x)
(eq x nil))
(defun endp (object)
"It returns true if OBJECT is NIL, false if OBJECT is a CONS, and an error
for any other type of OBJECT.
This is the recommended way to test for the end of a proper list."
(cond ((null object) t)
((consp object) nil)
(t (error "The value `~S' is not a type list." object))))
(defun car (x)
"Return the CAR part of a cons, or NIL if X is null."
(car x))
(defun cdr (x) (cdr x))
(defun rplaca (cons x)
(rplaca cons x))
(defun rplacd (cons x)
(rplacd cons x))
(defun first (x) (car x))
(defun second (x) (cadr x))
(defun third (x) (caddr x))
(defun fourth (x) (cadddr x))
(defun fifth (x) (car (cddddr x)))
(defun sixth (x) (cadr (cddddr x)))
(defun seventh (x) (caddr (cddddr x)))
(defun eighth (x) (cadddr (cddddr x)))
(defun ninth (x) (car (cddddr (cddddr x))))
(defun tenth (x) (cadr (cddddr (cddddr x))))
(defun rest (x) (cdr x))
(defun list (&rest args)
args)
(defun list* (arg &rest others)
(cond ((null others) arg)
((null (cdr others)) (cons arg (car others)))
(t (do ((x others (cdr x)))
((null (cddr x)) (rplacd x (cadr x))))
(cons arg others))))
(defun list-length (list)
(let ((l 0))
(while (not (null list))
(incf l)
(setq list (cdr list)))
l))
(defun nthcdr (n list)
(while (and (plusp n) list)
(setq n (1- n))
(setq list (cdr list)))
list)
(defun nth (n list)
(car (nthcdr n list)))
(define-setf-expander nth (n list)
(let ((g!list (gensym))
(g!index (gensym))
(g!value (gensym)))
(values (list g!list g!index)
(list list n)
(list g!value)
`(rplaca (nthcdr ,g!index ,g!list) ,g!value)
`(nth ,g!index ,g!list))))
(defun caar (x) (car (car x)))
(defun cadr (x) (car (cdr x)))
(defun cdar (x) (cdr (car x)))
(defun cddr (x) (cdr (cdr x)))
(defun caaar (x) (car (caar x)))
(defun caadr (x) (car (cadr x)))
(defun cadar (x) (car (cdar x)))
(defun caddr (x) (car (cddr x)))
(defun cdaar (x) (cdr (caar x)))
(defun cdadr (x) (cdr (cadr x)))
(defun cddar (x) (cdr (cdar x)))
(defun cdddr (x) (cdr (cddr x)))
(defun caaaar (x) (car (caaar x)))
(defun caaadr (x) (car (caadr x)))
(defun caadar (x) (car (cadar x)))
(defun caaddr (x) (car (caddr x)))
(defun cadaar (x) (car (cdaar x)))
(defun cadadr (x) (car (cdadr x)))
(defun caddar (x) (car (cddar x)))
(defun cadddr (x) (car (cdddr x)))
(defun cdaaar (x) (cdr (caaar x)))
(defun cdaadr (x) (cdr (caadr x)))
(defun cdadar (x) (cdr (cadar x)))
(defun cdaddr (x) (cdr (caddr x)))
(defun cddaar (x) (cdr (cdaar x)))
(defun cddadr (x) (cdr (cdadr x)))
(defun cdddar (x) (cdr (cddar x)))
(defun cddddr (x) (cdr (cdddr x)))
(defun append-two (list1 list2)
(if (null list1)
list2
(cons (car list1)
(append (cdr list1) list2))))
(defun append (&rest lists)
(!reduce #'append-two lists nil))
(defun revappend (list1 list2)
(while list1
(push (car list1) list2)
(setq list1 (cdr list1)))
list2)
(defun sublis (alist tree &key key (test #'eql testp) (test-not #'eql test-not-p))
(when (and testp test-not-p)
(error "Both test and test-not are set"))
(labels ((s (tree)
(let* ((key-val (if key (funcall key tree) tree))
(replace (if test-not-p
(assoc key-val alist :test-not test-not)
(assoc key-val alist :test test)))
(x (if replace (cdr replace) tree)))
(if (atom x)
x
(cons (s (car x)) (s (cdr x)))))))
(s tree)))
(defun subst (new old tree &key key (test #'eql testp) (test-not #'eql test-not-p))
(labels ((s (x)
(cond ((satisfies-test-p old x :key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
new)
((atom x) x)
(t (let ((a (s (car x)))
(b (s (cdr x))))
(if (and (eq a (car x))
(eq b (cdr x)))
x
(cons a b)))))))
(s tree)))
(defun copy-list (x)
(if (null x)
nil
(let* ((new-list (list (car x)))
(last-cell new-list))
(do ((orig (cdr x) (cdr orig)))
((atom orig) (rplacd last-cell orig))
(rplacd last-cell (cons (car orig) nil))
(setq last-cell (cdr last-cell)))
new-list)))
(defun copy-tree (tree)
(if (consp tree)
(cons (copy-tree (car tree))
(copy-tree (cdr tree)))
tree))
(defun tree-equal (tree1 tree2 &key (test #'eql testp)
(test-not #'eql test-not-p))
(when (and testp test-not-p) (error "Both test and test-not are set"))
(let ((func (if test-not-p (complement test-not) test)))
(labels ((%tree-equal (tree1 tree2)
(if (atom tree1)
(and (atom tree2) (funcall func tree1 tree2))
(and (consp tree2)
(%tree-equal (car tree1) (car tree2))
(%tree-equal (cdr tree1) (cdr tree2))))))
(%tree-equal tree1 tree2))))
(defun tailp (object list)
(do ((tail list (cdr tail)))
((atom tail) (eq object tail))
(when (eql tail object)
(return-from tailp t))))
(defun make-list (size &key (initial-element nil))
"Create a list of size `size` of `initial-element`s."
(when (< size 0)
(error "Size must be non-negative"))
(let ((newlist))
(dotimes (i size newlist)
(push initial-element newlist))))
(defun last (x)
(while (consp (cdr x))
(setq x (cdr x)))
x)
(defun butlast (x &optional (n 1))
"Returns x, less the n last elements in the list."
(nbutlast (copy-list x) n))
(defun nbutlast (x &optional (n 1))
"Destructively returns x, less the n last elements in the list."
(cond
((not (and (integerp n) (>= n 0)))
;; TODO: turn this error into a type error, per CLHS spec.
(error "n must be a non-negative integer"))
;; trivial optimizations
((zerop n) x)
(t
;; O(n) walk of the linked list, trimming out the link where appropriate
(let* ((head x)
(trailing (nthcdr n x)))
;; If there are enough conses
(when (consp trailing)
(while (consp (cdr trailing))
(setq head (cdr head))
(setq trailing (cdr trailing)))
;; snip
(rplacd head nil)
x)))))
(defun member (x list &key key (test #'eql testp) (test-not #'eql test-not-p))
(while list
(when (satisfies-test-p x (car list) :key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
(return list))
(setq list (cdr list))))
(defun assoc (x alist &key key (test #'eql testp) (test-not #'eql test-not-p))
(while alist
(if (satisfies-test-p x (caar alist) :key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
(return)
(setq alist (cdr alist))))
(car alist))
(defun rassoc (x alist &key key (test #'eql) (test #'eql testp)
(test-not #'eql test-not-p))
(while alist
(if (satisfies-test-p x (cdar alist) :key key :test test :testp testp
:test-not test-not :test-not-p test-not-p)
(return)
(setq alist (cdr alist))))
(car alist))
(defun acons (key datum alist)
(cons (cons key datum) alist))
(defun pairlis (keys data &optional (alist ()))
(while keys
(setq alist (acons (car keys) (car data) alist))
(setq keys (cdr keys))
(setq data (cdr data)))
alist)
(defun copy-alist (alist)
"Return a new association list which is EQUAL to ALIST."
(with-collect
(while alist
(collect (cons (caar alist) (cdar alist)))
(setq alist (cdr alist)))))
(define-setf-expander car (x)
(let ((cons (gensym))
(new-value (gensym)))
(values (list cons)
(list x)
(list new-value)
`(progn (rplaca ,cons ,new-value) ,new-value)
`(car ,cons))))
(define-setf-expander cdr (x)
(let ((cons (gensym))
(new-value (gensym)))
(values (list cons)
(list x)
(list new-value)
`(progn (rplacd ,cons ,new-value) ,new-value)
`(cdr ,cons))))
;;; setf expanders for CAR and CDR variants
;;; why using `!get-setf-expansion' ?
;;; https://github.com/jscl-project/jscl/issues/118
(define-setf-expander caar (x)
(!get-setf-expansion `(car (car ,x))))
(define-setf-expander cadr (x)
(!get-setf-expansion `(car (cdr ,x))))
(define-setf-expander cdar (x)
(!get-setf-expansion `(cdr (car ,x))))
(define-setf-expander cddr (x)
(!get-setf-expansion `(cdr (cdr ,x))))
(define-setf-expander caaar (x)
(!get-setf-expansion `(car (car (car ,x)))))
(define-setf-expander caadr (x)
(!get-setf-expansion `(car (car (cdr ,x)))))
(define-setf-expander cadar (x)
(!get-setf-expansion `(car (cdr (car ,x)))))
(define-setf-expander caddr (x)
(!get-setf-expansion `(car (cdr (cdr ,x)))))
(define-setf-expander cdaar (x)
(!get-setf-expansion `(cdr (car (car ,x)))))
(define-setf-expander cdadr (x)
(!get-setf-expansion `(cdr (car (cdr ,x)))))
(define-setf-expander cddar (x)
(!get-setf-expansion `(cdr (cdr (car ,x)))))
(define-setf-expander cdddr (x)
(!get-setf-expansion `(cdr (cdr (cdr ,x)))))
(define-setf-expander caaaar (x)
(!get-setf-expansion `(car (car (car (car ,x))))))
(define-setf-expander caaadr (x)
(!get-setf-expansion `(car (car (car (cdr ,x))))))
(define-setf-expander caadar (x)
(!get-setf-expansion `(car (car (cdr (car ,x))))))
(define-setf-expander caaddr (x)
(!get-setf-expansion `(car (car (cdr (cdr ,x))))))
(define-setf-expander cadaar (x)
(!get-setf-expansion `(car (cdr (car (car ,x))))))
(define-setf-expander cadadr (x)
(!get-setf-expansion `(car (cdr (car (cdr ,x))))))
(define-setf-expander caddar (x)
(!get-setf-expansion `(car (cdr (cdr (car ,x))))))
(define-setf-expander cadddr (x)
(!get-setf-expansion `(car (cdr (cdr (cdr ,x))))))
(define-setf-expander cdaaar (x)
(!get-setf-expansion `(cdr (car (car (car ,x))))))
(define-setf-expander cdaadr (x)
(!get-setf-expansion `(cdr (car (car (cdr ,x))))))
(define-setf-expander cdadar (x)
(!get-setf-expansion `(cdr (car (cdr (car ,x))))))
(define-setf-expander cdaddr (x)
(!get-setf-expansion `(cdr (car (cdr (cdr ,x))))))
(define-setf-expander cddaar (x)
(!get-setf-expansion `(cdr (cdr (car (car ,x))))))
(define-setf-expander cddadr (x)
(!get-setf-expansion `(cdr (cdr (car (cdr ,x))))))
(define-setf-expander cdddar (x)
(!get-setf-expansion `(cdr (cdr (cdr (car ,x))))))
(define-setf-expander cddddr (x)
(!get-setf-expansion `(cdr (cdr (cdr (cdr ,x))))))
(define-setf-expander first (x)
(get-setf-expansion `(car ,x)))
(define-setf-expander rest (x)
(get-setf-expansion `(cdr ,x)))
;; The NCONC function is based on the SBCL's one.
(defun nconc (&rest lists)
(flet ((fail (object)
(error "type-error in nconc")))
(do ((top lists (cdr top)))
((null top) nil)
(let ((top-of-top (car top)))
(typecase top-of-top
(cons
(let* ((result top-of-top)
(splice result))
(do ((elements (cdr top) (cdr elements)))
((endp elements))
(let ((ele (car elements)))
(typecase ele
(cons (rplacd (last splice) ele)
(setf splice ele))
(null (rplacd (last splice) nil))
(atom (if (cdr elements)
(fail ele)
(rplacd (last splice) ele))))))
(return result)))
(null)
(atom
(if (cdr top)
(fail top-of-top)
(return top-of-top))))))))
(defun nreconc (x y)
(do ((1st (cdr x) (if (endp 1st) 1st (cdr 1st)))
(2nd x 1st) ; 2nd follows first down the list.
(3rd y 2nd)) ;3rd follows 2nd down the list.
((atom 2nd) 3rd)
(rplacd 2nd 3rd)))
(defun adjoin (item list &key (test #'eql) (key #'identity))
(if (member item list :key key :test test)
list
(cons item list)))
(defun intersection (list1 list2 &key (test #'eql) (key #'identity))
(let ((new-list ()))
(dolist (x list1)
(when (member (funcall key x) list2 :test test :key key)
(push x new-list)))
new-list))
(defun get-properties (plist indicator-list)
(do* ((plist plist (cddr plist))
(cdr (cdr plist) (cdr plist))
(car (car plist) (car plist)))
((null plist) (values nil nil nil))
(when (null cdr)
(error "malformed property list ~S" plist))
(let ((found (member car indicator-list :test #'eq)))
(when found
(return (values car (cadr plist) plist))))))
(defun getf (plist indicator &optional default)
(do* ((plist plist (cddr plist))
(cdr (cdr plist) (cdr plist))
(car (car plist) (car plist)))
((null plist) default)
(when (null cdr)
(error "malformed property list ~S" plist))
(when (eq indicator car)
(return (cadr plist)))))
(defun %putf (plist indicator new-value)
(do* ((tail plist (cddr tail))
(cdr (cdr tail) (cdr tail))
(car (car tail) (car tail)))
((null tail) (list* indicator new-value plist))
(when (null cdr)
(error "malformed property list ~S" tail))
(when (eq indicator car)
;; TODO: should be cadr, needs a defsetf for that
(setf (car (cdr tail)) new-value)
(return plist))))
(define-setf-expander getf (plist indicator &optional default)
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion plist)
(let ((store (gensym))
(indicator-sym (gensym))
(default-sym (and default (gensym))))
(values `(,indicator-sym ,@(and default `(,default-sym)) ,@dummies)
`(,indicator ,@(and default `(,default)) ,@vals)
`(,store)
`(let ((,(car newval) (%putf ,getter ,indicator-sym ,store))
,@(cdr newval))
,setter
,store)
`(getf ,getter ,indicator-sym ,@(and default `(,default-sym)))))))
;;;
;;; The following code has been taken from SBCL
;;;
;;; mapping functions
;;; a helper function for implementation of MAPC, MAPCAR, MAPCAN,
;;; MAPL, MAPLIST, and MAPCON
;;;
;;; Map the designated function over the arglists in the appropriate
;;; way. It is done when any of the arglists runs out. Until then, it
;;; CDRs down the arglists calling the function and accumulating
;;; results as desired.
(defun map1 (fun-designator arglists accumulate take-car)
(do* ((fun fun-designator)
(non-acc-result (car arglists))
(ret-list (list nil))
(temp ret-list)
(res nil)
(args (make-list (length arglists))))
((dolist (x arglists) (or x (return t)))
(if accumulate
(cdr ret-list)
non-acc-result))
(do ((l arglists (cdr l))
(arg args (cdr arg)))
((null l))
(setf (car arg) (if take-car (caar l) (car l)))
(setf (car l) (cdar l)))
(setq res (apply fun args))
(case accumulate
(:nconc
(when res
(setf (cdr temp) res)
;; KLUDGE: it is said that MAPCON is equivalent to
;; (apply #'nconc (maplist ...)) which means (nconc 1) would
;; return 1, but (nconc 1 1) should signal an error.
;; The transformed MAP code returns the last result, do that
;; here as well for consistency and simplicity.
(when (consp res)
(setf temp (last res)))))
(:list (setf (cdr temp) (list res)
temp (cdr temp))))))
(defun mapc (function list &rest more-lists)
"Apply FUNCTION to successive elements of lists. Return the second argument."
(map1 function (cons list more-lists) nil t))
(defun mapcar (function list &rest more-lists)
"Apply FUNCTION to successive elements of LIST. Return list of FUNCTION
return values."
(map1 function (cons list more-lists) :list t))
(defun mapcan (function list &rest more-lists)
"Apply FUNCTION to successive elements of LIST. Return NCONC of FUNCTION
results."
(map1 function (cons list more-lists) :nconc t))
(defun maplist (function list &rest more-lists)
"Apply FUNCTION to successive CDRs of list. Return list of results."
(map1 function (cons list more-lists) :list nil))
(defun mapcon (function list &rest more-lists)
"Apply FUNCTION to successive CDRs of lists. Return NCONC of results."
(map1 function (cons list more-lists) :nconc nil))
;;; set-difference
(defun set-difference (list1 list2 &key key (test #'eq))
(cond (list2
(let ((result '()))
(dolist (it list1)
(when (not (member it list2 :key key :test test))
(push it result)))
result))
(t list1)))
;;; makeset
(defun makeset (lst &key (test #'eq))
(prog ((result)
(seq lst))
feed
(when (null seq) (return (reverse result)))
(if (not (member (car seq) result :test test))
(setq result (cons (car seq) result)))
(setq seq (cdr seq))
(go feed)))
;;; union
(defun union (list1 list2 &key key (test #'eq))
(cond ((and list1 list2)
(let ((result (makeset list2 :test #'equal)))
(dolist (it list1)
(when (not (member it list2 :key key :test test))
(push it result)))
result))
(list1)
(list2)))
;;; selection sort algoritm
;;; see https://en.wikipedia.org/wiki/Selection_sort
;;; also many examples: http://rosettacode.org/wiki/Category:Sorting_Algorithms
;;;
;;; Release note:
;;;
;;; Usually i use (#j:sort). Implementation of this function is done as it is used in CLOS.
;;; Considering that in two last years, no one has opened issue about the absence of a sort function,
;;; I consider the price of the question to be minimal. The selection criteria is very simple:
;;; a) do not used additional memory b) without recursion c)simple pseudocode and fast implementation.
;;; So, was implemented selection_sort algoritm. If somebody needs a better sort, they can do it later.
;;;
;;; VKM
;;;
(defun sort (lst fn &key (key 'identity))
(if (vectorp lst)
(error "Array sort yet not implemented."))
(if (endp lst)
'()
(block selection-sort
(let* ((j lst)
(imin j))
(while t
(when (null j)
(return lst))
(tagbody
(let ((i (cdr j)))
(while t
(if (null i) (return nil))
(if (funcall fn
(funcall key (car i))
(funcall key (car imin)))
(setq imin i))
(setq i (cdr i))))
(when (not (eq imin j))
(let ((swap-j (car j))
(swap-imin (car imin)))
(setf (car j) swap-imin (car imin) swap-j))))
(setq j (cdr j) imin j)))) ))
| 20,136 | Common Lisp | .lisp | 535 | 30.927103 | 103 | 0.581863 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 2e3d7ed47f690c18bf76e51f8c59434e7a4da68f119f5c348335859e002480e7 | 26 | [
-1
] |
27 | structures.lisp | jscl-project_jscl/src/structures.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; Tiny DEFSTRUCT for JSCL @vkm
;;; Released: :named :type :include :initial-offset
;;; :constructor with BOA
;;; slot default type read-only syntax
;;;
;;; JSCL is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; JSCL is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading structures.lisp!")
#-jscl
(setq *structures* (make-hash-table :test #'equal))
#+jscl
(setq *structures* (make-hash-table :test #'eql))
;;; list length 1
(defun singleton-p (list)
(and (consp list) (null (cdr list))))
;;; list length 2
(defun doubleton-p (list)
(and (consp list)
(let ((rest (cdr list)))
(and (consp rest)
(null (cdr rest))))))
;;; properly list predicate from alexandria pkg
(defun proper-list-p (object)
"Returns true if OBJECT is a proper list."
(cond ((not object) t)
((consp object)
(do ((fast object (cddr fast))
(slow (cons (car object) (cdr object)) (cdr slow)))
(nil)
(unless (and (listp fast)
(consp (cdr fast)))
(return (and (listp fast)
(not (cdr fast)))))
(when (eq fast slow)
(return nil))))
(t nil)))
(defun proper-list-length-p (x min &optional (max min))
(cond ((minusp max) nil)
((null x) (zerop min))
((consp x)
(and (plusp max)
(proper-list-length-p (cdr x)
(if (plusp (1- min))
(1- min)
0)
(1- max))))
(t nil)))
(defun das!lambda-list-args (from-boa-list)
(let* ((ll (parse-destructuring-lambda-list from-boa-list))
(r)
(req (lambda-list-reqvars ll))
(opt (dolist (it (lambda-list-optvars ll) (reverse r))
(push (list (optvar-variable it) (optvar-initform it)) r)))
(key (progn (setq r nil)
(dolist (it (lambda-list-keyvars ll) (reverse r))
(push (list (keyvar-variable it) (keyvar-initform it)) r))))
(aux (progn (setq r nil)
(dolist (it (lambda-list-auxvars ll) (reverse r))
(push (list (auxvar-variable it) (auxvar-initform it)) r)))
))
(values req opt key aux)))
(defun das!reassemble-boa-list (boa-list slots)
(let ((new-boa-list nil)
(unmatch-p t) (key-p) (opt-p) (aux-p) (rest-p)
(lkw-p nil)
(sd))
(flet ((%match (name d)
(push (list name (dsd-slot-initform d)) new-boa-list))
(%save (x) (push x new-boa-list))
(%switch (x)
(setq key-p (if (eq x '&key) t) opt-p (if (eq x '&optional) t)
aux-p (if (eq x '&aux) t) rest-p (if (eq x '&rest) t)))
(%find-slot-by-name (name)
(find-if (lambda (slot) (if (eq name (dsd-slot-name slot)) slot)) slots)))
(dolist (it boa-list (reverse new-boa-list))
(cond
((atom it)
(setq lkw-p (memq it '(&key &rest &optional &aux)))
(%switch it)
(cond (unmatch-p
(%save it)
(if lkw-p (setq unmatch-p nil lkw-p nil)))
(t (cond (lkw-p
(%save it)
(setq lkw-p nil))
(t (%match it (%find-slot-by-name it)))))))
((listp it)
(setq sd (%find-slot-by-name (if (atom (car it)) (car it) (cadar it))))
(if (null sd)
;; skip supplimentary lambda key var
(push it new-boa-list)
;; else proceed slot
(cond
;;(name) -> (name default-from sd)
((proper-list-length-p it 1)
(if (atom (car it))
;; (name)
(%match (car it) (%find-slot-by-name (car it)))
;;((name name))
(%match (car it) (%find-slot-by-name (cadar it)))))
;;(name default) -> (name default)
;;(name default s-p) (name default s-p)
((or (proper-list-length-p it 2) (proper-list-length-p it 3))
(%save it) )))))))))
(defun neq (x y) (not (eq x y)))
;;; symbols concatenate
(defun %symbolize (&rest rest)
(intern
(apply
'concat
(%lmapcar (lambda (x)
(typecase x
(symbol (symbol-name x))
(string x)
(t (error 'type-error :datum x :expected-type `(or symbol string)))))
rest))))
;;; make check-type sign string
;;; for debug identicale
(defun das!struct-generate-signed (name)
(concat "(" (symbol-name name) ")"))
;;; boa parse
(defun das!parse-struct-lambda-list (from-boa-list)
(let* ((ll (parse-destructuring-lambda-list from-boa-list))
(r)
(req (lambda-list-reqvars ll))
(opt (dolist (it (lambda-list-optvars ll) (reverse r))
(push (list (optvar-variable it) (optvar-initform it)) r)))
(key (progn (setq r nil)
(dolist (it (lambda-list-keyvars ll) (reverse r))
(push (list (keyvar-variable it) (keyvar-initform it)) r))))
(aux (progn (setq r nil)
(dolist (it (lambda-list-auxvars ll) (reverse r))
(push (list (auxvar-variable it) (auxvar-initform it)) r)))))
(values req opt key aux)))
(%i-struct (dsd (:form &key))
name
type
named-p
seen-options
conc-name
predicate
copier
(initial-offset 0)
constructor
parent
(childs '())
slots
(slot-nums 0)
include
inherit-slots
(inherit-slot-nums 0)
(instance-len 0)
storage
prototype
descriptor
map-names)
;;; dd-slot slot descriptor
(%i-struct (dsd-slot (:form &key)) name accessor initform type read-only)
;;; structure storage descriptor.
(%i-struct (dsd-storage-descriptor (:form &key))
leader ;; -leader::= structure name, if structure is :named
n ;; -n::= storage slots number include named & initial-offset
offset) ;; -offset::= some initial-offset
;;; structure-include
(%i-struct (dsd-include (:form &key)) name assigned inherited sd descriptor)
;;; name::= name included structure
;;; inherited:: all slot-definitions from included structure-type-slots
;;; used for make-constructor == ((descriptor) slot-definitions*)
;;; assigned::= the names of the slots that were specified in the option :include
;;; filled in when parsing (:include name slots*)
;;; descriptor::= storage-descriptor from included structure-type-descriptor
;;; note: not used
;;; sd::= parent slot-definitions without descriptor
;;; structure-prototype
(%i-struct (dsd-prototype (:form &key)) n map storage)
;;; structure-constructor.
(%i-struct (dsd-constructor (:form &key)) name boa required optional key aux)
#-jscl
(defun %dsd-my-be-rewrite (name)
(declare (ignore name))
t)
#+jscl
(defun %dsd-my-be-rewrite (name)
(let ((dd (get-structure-dsd name)))
;; structure not exists, so may be rewrite
(or (null dd)
(and
;; only list/vector base
(memq (dsd-type dd) '(list vector))
;; childs structures - not exists
(null (dsd-childs dd))))))
(defun %hash-table-keys (table)
(let ((keys nil))
(maphash
(lambda (k v)
(declare (ignore v))
(push k keys))
table)
keys))
(defun das!include-possible-p (d1 d2)
(let ((s1 (%lmapcar 'dsd-slot-name (dsd-slots d1)))
(s2 (%lmapcar 'dsd-slot-name (dsd-slots d2))))
(null (intersection s1 s2))))
(deftype exists-structure-name ()
`(and symbol (satisfies exists-structure-p)))
(defun raise-bad-dsd-option (&rest datum)
(signal 'simple-error
:format-control "Malformed DEFSTRUCT option ~a.~%"
:format-arguments datum))
(defun raise-bad-include-slot (&rest datum)
(signal 'simple-error
:format-control "Malformed DEFSTRUCT :include option~% Bad name ~a.~%"
:format-arguments datum))
(deftype sop-symbolic-name ()
`(and symbol (not (member t nil)) (not keyword)))
(defun non-empty-string (string)
(and (stringp string) (> (length string) 0)))
(deftype conc-name-designator ()
`(or (satisfies non-empty-string)
character
(and symbol (not (member t nil)) (not keyword))))
(defun %conc-name-designator (conc-name)
(check-type conc-name conc-name-designator)
(typecase conc-name
(string (intern conc-name))
(symbol conc-name)
(character (intern (string conc-name)))))
;;;(defparameter +dsd-option-names+ #(:include :initial-offset :type :conc-name :copier :predicate))
;;; atomic option catched on top
(defun das!parse-option (option dd seen)
(let* ((keyword (car option))
(opnames #(:include :initial-offset :type :conc-name :copier :predicate))
(bit (position keyword opnames))
(args (cdr option))
(arg-p (consp args))
(arg (if arg-p (car args))))
(when bit
(if (logbitp bit seen)
(error "More than one ~S option is not allowed" keyword))
(setq seen (logior seen (ash 1 bit)))
(multiple-value-bind (syntax-group winp)
(cond ((= bit 0) (values 0 (and arg-p (proper-list-p args))))
((< bit 3) (values 1 (and arg-p (not (cdr args)))))
(t (values 2 (or (not args) (singleton-p args)))))
(unless winp
(if (proper-list-p option)
(error "DEFSTRUCT option ~S ~D one argument" keyword
(aref #("requires at least" "requires exactly" "accepts at most") syntax-group))
(error "Invalid syntax in DEFSTRUCT option ~S" option)))))
(case keyword
(:named (error "DEFSTRUCT option :named takes no arguments."))
(:conc-name
(cond ((neq arg-p t) (setf (dsd-copier dd) nil))
((and arg-p (eq arg nil)) (setf (dsd-copier dd) nil))
(t (setf (dsd-conc-name dd) (%conc-name-designator arg)))))
(:copier
(cond ((neq arg-p t) (setf (dsd-copier dd) nil))
((and arg-p (eq arg nil)) (setf (dsd-copier dd) nil))
(t (check-type arg sop-symbolic-name "(:copier)")
(setf (dsd-copier dd) arg))) )
(:predicate
(cond ((neq arg-p t)(setf (dsd-predicate dd) nil))
((and arg-p (eq arg nil))(setf (dsd-predicate dd) nil))
(t (check-type arg sop-symbolic-name)
(setf (dsd-predicate dd) arg))) )
(:initial-offset
(check-type arg (integer 0 128))
(setf (dsd-initial-offset dd) arg) )
(:include
;; (:include name) | (:include name slots*)
(setf (dsd-include dd) args) ) ;; end :include
(:constructor
(unless (proper-list-length-p args 0 2)
(error "Syntax error a DEFSTRUCT option ~s." option))
(destructuring-bind (&optional (cname (%symbolize "MAKE-" (dsd-name dd)) cname-p)
(boa nil boa-p)) args
(setq boa
(cond ((not cname)
(if boa-p (error "Syntax error a DEFSTRUCT option ~s." option))
(if cname-p :disable))
((or (not boa-p) (null boa)) :default)
(t boa)))
(check-type cname (or (eql nil) (and symbol (not keyword))))
(push (cons cname boa) (dsd-constructor dd)))) ;;end :constructor
(:type
(cond ((memq arg '(vector list)) (setf (dsd-type dd) arg))
;; may be (:type (vector type))
((and (listp arg) (eq (car arg) 'vector)) (setf (dsd-type dd) (car arg)))
(t (error "Malformed DEFSTRUCT option ~a.~%" option))) ) ;; end :type
(otherwise (error "Unknown or unsupplied DEFSTRUCT option ~s." option)))
seen))
(defun das!parse-defstruct-options (options dd)
(let ((seen 0)
(named-p nil))
(dolist (option options)
(if (eq option :named)
(setf named-p t (dsd-named-p dd) t)
(setq seen
(das!parse-option
(cond ((consp option) option)
((memq option '(:conc-name :constructor :copier :predicate))
(list option))
(t (error "Bad syntax DEFSTRUCT option: ~S." option)))
dd seen))))
;; prepare :constructors
(let ((no-constructors nil)
(default nil)
(default-p nil)
(custom nil)
(cname nil) (boa-list :default))
(dolist (cpair (dsd-constructor dd))
;; bug: destructuring-bind not parsing (a . b)
(setq cname (car cpair) boa-list (cdr cpair))
(cond ((not cname) (setq no-constructors t))
((eq boa-list :default)
(if default-p
(error "Multiple default constructor defined."))
(setq default cpair)
(setq default-p t))
;; parse custom boa
(t (multiple-value-bind (req opt key aux)
(das!parse-struct-lambda-list boa-list)
(push
(%make-dsd-constructor :name cname :boa boa-list :required req
:optional opt :key key :aux aux)
custom)) )))
(setf (dsd-constructor dd)
;; now dsd-constructor::= (default|nil custom|nil)
(if (eq no-constructors t)
(progn
(when (or (not (null default)) (not (null custom)))
(error "(:constructor nil) combined with other :constructro's."))
nil)
(cond ((and (null default) (null custom))
(setq default (cons (%symbolize "MAKE-" (dsd-name dd)) :default))
(list default nil))
(t (list default custom))))))
(flet ((option-present-p (bit-name)
(let ((opnames #(:include :initial-offset :type :conc-name :copier :predicate)))
(logbitp (position bit-name opnames) seen))))
(if (option-present-p :include)
(cond ((or (dsd-named-p dd) (null (dsd-type dd)))
;; present structure is named or clos based
(let* ((parent-name (car (dsd-include dd)))
(parent nil)
(include-slots (cdr (dsd-include dd)))
(include-name-table)
(slot-name)
(include))
(if (exists-structure-p parent-name)
(setq parent (get-structure-dsd parent-name))
(error "Structure ~s not exists." parent-name))
(setq include-name-table (dsd-map-names parent))
(unless (eql (dsd-type dd) (dsd-type parent))
(error "Incompatible structure type (~a ~a : ~a ~a)"
(dsd-name dd) (dsd-type dd)
(dsd-name parent)(dsd-type parent)))
(unless (or (dsd-named-p parent) (null (dsd-type parent)))
;; included is unnamed
(error "Unnamed structure ~a not included." parent-name))
(setq include (%make-dsd-include :name parent-name))
(setf (dsd-include-assigned include)
;; checking that the slot name is valid for the structure
(let ((sd)
(r))
(dolist (it include-slots (reverse r))
(typecase it
(list (setq slot-name (car it)))
(symbol (setq slot-name it))
(t (raise-bad-include-slot it)))
(unless (gethash slot-name include-name-table)
(raise-bad-include-slot it))
(setq sd (das!parse-struct-slot it))
(push sd r))))
(setf (dsd-include dd) include)
(setf (dsd-include-inherited include) (copy-tree (dsd-inherit-slots parent)))
(setf (dsd-parent dd) parent-name)))
(t (error "DEFSTRUCT :include option provide only for named or clos structure."))))
;; predicate, copier, conc-name for named lisp structure
(unless (option-present-p :conc-name)
(setf (dsd-conc-name dd) (%symbolize (dsd-name dd) "-")))
(unless (option-present-p :copier)
(setf (dsd-copier dd) (%symbolize "COPY-" (dsd-name dd))))
(when (memq (dsd-type dd) '(list vector))
(when (option-present-p :predicate)
(unless named-p (error "DEFSTRUCT option :predicate provide only for named structure.~%")))
(when named-p
(unless (option-present-p :predicate)
(setf (dsd-predicate dd) (%symbolize (dsd-name dd) "-P")))))
;; initial-offset, predicate for clos structure
(when (null (dsd-type dd))
(when (option-present-p :initial-offset)
(warn "DEFSTRUCT option :INITIAL-OFFSET provided only for list/vector based structure.~%"))
(unless (option-present-p :predicate)
(setf (dsd-predicate dd) (%symbolize (dsd-name dd) "-P")))))
(setf (dsd-seen-options dd) seen)
seen))
(defun %atom-or-car (seq)
(mapcar
(lambda (x)
(if (atom x)
x
(if (listp (car x))
(error "Unsupported BOA form ~a." x)
(car x) )))
seq))
(defun das!canonicalize-slots (slots)
(let* ((dv)
(r (%lmapcar
(lambda (slot)
(list (dsd-slot-name slot)
:initform (typecase (setq dv (dsd-slot-initform slot))
(null nil)
(symbol (list 'quote dv))
(t dv))
:initarg (intern (symbol-name (dsd-slot-name slot)) "KEYWORD")))
slots)))
r))
#+jscl
(defclass structure-class (standard-class) nil)
(defun das!make-structure-class (name slots include)
(let ((class-slots (das!canonicalize-slots slots))
(cpl (if include (list (dsd-include-name include)) nil)))
`(defclass ,name ,cpl ,class-slots (:metaclass structure-class))))
;;; accessors for each slots structure
(defun das!%make-read-accessor-clos (name slot-name)
`(defun ,name (obj)
(slot-value obj ',slot-name)))
(defun das!%make-write-accessor-clos (name slot-name chk-t)
(let ((sign (das!struct-generate-signed name)))
`(defun (setf ,name) (value obj)
,@(if chk-t (list `(check-type value ,chk-t ,sign)))
(setf (slot-value obj ',slot-name) value) )))
(defun das!make-struct-accessors-clos (slots)
(let ((slot-name)
(result)
(chk-t)
(accessor-name))
(dolist (it slots)
(setq accessor-name (dsd-slot-accessor it)
chk-t (dsd-slot-type it)
slot-name (dsd-slot-name it))
(push (das!%make-read-accessor-clos accessor-name slot-name) result)
(unless (dsd-slot-read-only it)
(push (das!%make-write-accessor-clos accessor-name slot-name chk-t) result)))
(reverse result)))
;;; each constructor from (:constructor) forms
(defun das!make-clos-constructor (class-name constructor slots)
;; at this point slots::= (append include-slots own-slots)
;; constructor::= structure-constructor
(let* ((make-name (dsd-constructor-name constructor))
(boa (dsd-constructor-boa constructor))
(req (dsd-constructor-required constructor))
(opt (%atom-or-car (dsd-constructor-optional constructor)))
(key (%atom-or-car (dsd-constructor-key constructor)))
(aux (%atom-or-car (dsd-constructor-aux constructor)))
(assigned-slots (append req opt key aux))
(keyargs))
;; make :key arg pair
(dolist (it assigned-slots)
;;(push it keyargs)
(push (intern (symbol-name it) "KEYWORD") keyargs)
(push it keyargs))
`(defun ,make-name ,(das!reassemble-boa-list boa slots)
,@(loop
;; check-type's for slots if :type assigned
for slot in slots
when (and (memq (dsd-slot-name slot) assigned-slots)
(dsd-slot-type slot)
(not (dsd-slot-read-only slot)))
collect `(check-type ,(dsd-slot-name slot) ,(dsd-slot-type slot) ))
(make-instance ',class-name ,@(reverse keyargs)))))
;;; make standard structure predicate and copier
(defun das!make-structure-class-predicate (structure-name predicate-p)
`(defun ,predicate-p (obj)
(when (eq (class-name (class-of (class-of obj))) 'structure-class)
(eq (class-name (class-of obj)) ',structure-name))))
(defun das!clone-clos-base (object)
(let ((r (das!clone-list-base object)))
#+jscl (set-object-type-code r :mop-object)
(setf (nth 2 r) (list-to-vector (vector-to-list (nth 2 object))))
r))
(defun das!make-structure-class-copier (structure-name copier-p)
`(defun ,copier-p (obj)
(cond ((eq (class-name (class-of (class-of obj))) 'structure-class)
(if (eq (class-name (class-of obj)) ',structure-name)
(das!clone-clos-base obj)
(error "Object ~a not a structure ~a." obj ',structure-name)))
(t (error "Object ~a not a structure class." obj)))))
;;; end CLOS section
;;; Lisp structure section
;;; ACCESSORS
(defun das!%make-read-accessor-vector (name index)
`(defun ,name (obj) (storage-vector-ref obj ,index)))
(defun das!%make-write-accessor-vector (name index chk-t)
(let ((sign (das!struct-generate-signed name)))
`(defun (setf ,name) (value obj)
,@(if chk-t (list `(check-type value ,chk-t ,sign)))
(storage-vector-set! obj ,index value))))
(defun das!%make-read-accessor-list (name index)
`(defun ,name (obj)
(nth ,index obj)) )
(defun das!%make-write-accessor-list (name index chk-t)
(let ((sign (das!struct-generate-signed name)))
`(defun (setf ,name) (value obj)
,@(if chk-t (list `(check-type value ,chk-t ,sign)))
(rplaca (nthcdr ,index obj) value) )))
(defun das!make-struct-accessors-lv (storage-type hash slots)
(let ((index)
(result)
(chk-t)
(accessor-name)
(fn-read 'das!%make-read-accessor-vector)
(fn-write 'das!%make-write-accessor-vector))
(cond ((eql storage-type 'list)
(setq fn-read 'das!%make-read-accessor-list)
(setq fn-write 'das!%make-write-accessor-list)))
(dolist (it slots)
(setq accessor-name (dsd-slot-accessor it)
chk-t (dsd-slot-type it)
index (gethash (dsd-slot-name it) hash))
(unless index
(error "Hash malformed : slot-name ~a accessor ~a" (dsd-slot-name it) accessor-name))
(push (funcall fn-read accessor-name index) result)
(unless (dsd-slot-read-only it)
(push (funcall fn-write accessor-name index chk-t) result)))
(reverse result)))
;;; PREDICATE
;;; A predicate can be defined only if the structure is named;
;;; if :type is supplied and :named is not supplied,
;;; then :predicate must either be unsupplied or have the value nil
(defun das!make-struct-predicate (prototype structure-type storage-type leader-p predicate)
(when predicate
(when (and (memq storage-type '(vector list)) (not leader-p))
(warn "predicate ~a unsupplied for unnamed vector/list structure " predicate)
(return-from das!make-struct-predicate nil))
(let* ((imap 0))
(dolist (cell (dsd-prototype-map prototype))
(if (eql cell -3)
(return))
(incf imap))
(cond ((eql 'vector storage-type)
`(defun ,predicate (obj)
(and (storage-vector-p obj)
(> (length obj) ,imap)
(eql (storage-vector-ref obj ,imap) ',structure-type))))
((eql 'list storage-type)
`(defun ,predicate (obj)
(and (proper-list-p obj)
(> (length obj) ,imap)
(eql (nth ,imap obj) ',structure-type))))))))
;;; COPIER
#-jscl
(defun das!clone-list-base (object) (declare (ignore object)))
#+jscl
(defun das!clone-list-base (object)
(vector-to-list (list-to-vector object)))
#-jscl
(defun das!clone-vector-base (object) (declare (ignore object)))
#+jscl
(defun das!clone-vector-base (object)
(list-to-vector (vector-to-list object)))
(defun das!make-struct-copier (name storage-type leader-p copier)
(declare (ignore name leader-p))
(when copier
(cond ((eq storage-type 'list)
`(defun ,copier (object) (das!clone-list-base object)))
((eq storage-type 'vector)
`(defun ,copier (object) (das!clone-vector-base object))))))
;;; CONSTRUCTORS
(defun das!make-constructor-lv-for (prototype storage-type constructor slots)
(let* ((make-name (dsd-constructor-name constructor))
(boa (dsd-constructor-boa constructor))
(req (dsd-constructor-required constructor))
(opt (%atom-or-car (dsd-constructor-optional constructor)))
(key (%atom-or-car (dsd-constructor-key constructor)))
(aux (%atom-or-car (dsd-constructor-aux constructor)))
(assigned-slots (append req opt key aux))
(default-slots
(set-difference (%lmapcar 'dsd-slot-name slots)
(remove nil assigned-slots)))
(signed (das!struct-generate-signed make-name))
(storage)
(protos (dsd-prototype-storage prototype))
(map-position 0)
(sym))
(dolist (it (dsd-prototype-map prototype))
(cond ((eql it -1)
(push nil storage))
((eql it -2)
(setq sym (nth map-position protos))
(push `',sym storage))
((eql it -3)
(setq sym (nth map-position protos))
(push `',sym storage))
(t (setq sym (nth map-position protos))
(let (default)
(cond ((memq sym default-slots)
(setq default (assoc sym slots))
(push (dsd-slot-initform default) storage))
(t (push (nth map-position protos) storage))))))
(incf map-position))
(setq storage (reverse storage))
`(defun ,make-name ,(das!reassemble-boa-list boa slots)
,@(loop
;; check-type's for slots if :type assigned
for slot in slots
;;when (and (not (member (structure-slot-name slot) default-slots))
;; (structure-slot-type slot))
when (and (memq (dsd-slot-name slot) assigned-slots)
(dsd-slot-type slot)
(not (dsd-slot-read-only slot)))
collect `(check-type ,(dsd-slot-name slot) ,(dsd-slot-type slot) ,signed))
;; and prototype into required form
(,storage-type ,@storage))))
;;; generating structure constructors for list-vector storage
(defun %update-include-slots (slots asis)
(let (sname sval)
(dolist (a asis)
(cond ((consp a)
(setq sname (dsd-slot-name a) sval (dsd-slot-initform a))
(map 'nil
(lambda (slot)
(cond ((eq (dsd-slot-name slot) sname)
(if (dsd-slot-type slot)
(unless (typep sval (dsd-slot-type slot))
(error 'type-error :datum a :expected-type (dsd-slot-type slot))))
(setf (dsd-slot-initform slot) sval))))
slots)))))
slots)
(defun das!make-struct-constructors (structure-type prototype storage-type constructors slots asis)
;; structure-type::=structure-name
;; constructors::= ((default)(custom))
(declare (ignore structure-type))
(let ((result)
#+nil (storage (dsd-prototype-storage prototype))
(slots (%update-include-slots slots asis)))
(if (null constructors)
(list nil)
(destructuring-bind (default custom) constructors
(when custom
(dolist (constructor custom)
;; specialized constructor
(push (das!make-constructor-lv-for prototype storage-type constructor slots)
result)))
;; default make-constructor
(when default
;; default::=(cname . :default)
(let ((boa
(list* '&key
(%lmapcar (lambda (x)
(list (dsd-slot-name x) (dsd-slot-initform x)))
slots)))
(constructor))
(multiple-value-bind (req opt key) (das!parse-struct-lambda-list boa)
(setq constructor
(%make-dsd-constructor :name (car default)
:boa boa :required req :optional opt :key key)))
(push (das!make-constructor-lv-for prototype storage-type constructor slots)
result)))))
result))
;;; entry point for lisp base object's
(defun %conc-accessor-names (slot conc-name)
(if conc-name
(setf (dsd-slot-accessor slot) (%symbolize conc-name (dsd-slot-name slot)))
(setf (dsd-slot-accessor slot) (dsd-slot-name slot)))
slot)
(defun das!make-lisp-base-structure (dd)
(let ((slots)
(asis (if (dsd-include dd) (dsd-include-assigned (dsd-include dd))))
(conc-name (dsd-conc-name dd))
(q))
(setq slots
(if (dsd-inherit-slots dd)
;; slots merged with parent slots
(dolist (i (dsd-inherit-slots dd) (reverse slots))
(mapcar (lambda (x) (push x slots)) (cdr i)))
;; slots without parent slots
(dsd-slots dd)))
(mapcar (lambda (x) (%conc-accessor-names x conc-name)) slots)
(setq q
(append
(das!make-struct-constructors (dsd-name dd) (dsd-prototype dd) (dsd-type dd)
(dsd-constructor dd) slots asis)
(das!make-struct-accessors-lv (dsd-type dd) (dsd-map-names dd) slots)
(list (das!make-struct-predicate (dsd-prototype dd) (dsd-name dd) (dsd-type dd)
(dsd-named-p dd) (dsd-predicate dd)))
(list (das!make-struct-copier (dsd-name dd) (dsd-type dd) (dsd-named-p dd) (dsd-copier dd)))
(list
(if (and (dsd-type dd) (dsd-named-p dd)(dsd-predicate dd))
`(deftype ,(dsd-name dd) () '(satisfies ,(dsd-predicate dd)))
nil))))
(remove nil q)
))
;;; entry point for clos base
(defun das!make-standard-structure (dd)
(let ((name (dsd-name dd))
(slots)
(asis (if (dsd-include dd) (dsd-include-assigned (dsd-include dd))))
(conc-name (dsd-conc-name dd))
(constructors (dsd-constructor dd))
(q))
(setq slots
(if (dsd-inherit-slots dd)
(dolist (i (dsd-inherit-slots dd) (reverse slots))
(mapcar (lambda (x) (push x slots)) (cdr i)))
(dsd-slots dd)))
(mapcar (lambda (x) (%conc-accessor-names x conc-name)) slots)
(setq slots (%update-include-slots slots asis))
(push (das!make-structure-class name (dsd-slots dd) (dsd-include dd)) q)
(dolist (it (das!make-struct-accessors-clos slots))
(push it q))
(if constructors
(destructuring-bind (default custom) constructors
(when custom
(dolist (constructor custom)
(push (das!make-clos-constructor name constructor slots) q)))
(when default
(let ((boa
(list* '&key
(mapcar (lambda (x)
(list (dsd-slot-name x) (dsd-slot-initform x)))
slots)))
(constructor))
(multiple-value-bind (req opt key) (das!parse-struct-lambda-list boa)
(setq constructor
(%make-dsd-constructor :name (car default)
:boa boa :required req :optional opt :key key)))
(push (das!make-clos-constructor name constructor slots) q))) ))
(when (dsd-predicate dd)
(push (das!make-structure-class-predicate name (dsd-predicate dd)) q))
(when (dsd-copier dd)
(push (das!make-structure-class-copier name (dsd-copier dd)) q))
(reverse q)))
;;; DD BUNDLE
;;; parse slot definitions from rest das!struct
(define-condition bad-dsd-slot-desc (error)
((datum :initform nil :initarg :datum :reader bad-dsd-slot-desc-datum))
(:report (lambda (condition stream)
(format stream "Malformed DEFSTRUCT slot descriptor~% ~a."
(bad-dsd-slot-desc-datum condition)))))
;;; Parse slot definition
;;; catch bug (defstruct name (:copier cname) slot1 ... slotn)
(defun das!parse-struct-slot (slot)
(multiple-value-bind (name default default-p type type-p read-only ro-p)
(typecase slot
(symbol
(typecase slot
((or (member :conc-name :constructor :copier :predicate :named :include :type :initial-offset)
keyword)
(error "DEFSTRUCT slot ~S syntax error" slot)))
slot)
(cons
(destructuring-bind (name &optional (default nil default-p)
&key (type nil type-p) (read-only nil read-only-p))
slot
(typecase name
((member :conc-name :constructor :copier :predicate :include :named :type :initial-offset)
;;catch bug (defstruct name (:copier cname) slot1 ... slotn)
(error "Slot name of ~S indicates probable syntax error in DEFSTRUCT" name))
(keyword (error "DEFSTRUCT slot ~S syntax error." slot)))
(values name default default-p type type-p read-only read-only-p)))
(t (error " ~S is not a legal slot description." slot)))
(%make-dsd-slot :name name :accessor name :initform default :type type :read-only read-only)))
;;; compare include assigned and imherit slots
;;; check only :type & :read-only tags
;;; subtype (initform type) done it %update-include-slots
(defun das!compare-asins (assigned inherit)
(dolist (as assigned)
(map 'nil
(lambda (in)
;; in - inherit slot from parent
;; as -assigned slot from :include
(let ((seen 0))
(unless (subtypep (dsd-slot-type as) (dsd-slot-type in))
(setq seen (logior seen (ash 1 0))))
(unless (eq (dsd-slot-read-only as) (dsd-slot-read-only in))
(setq seen (logior seen (ash 1 0))))
(if (> seen 0)
(multiple-value-bind (tag datum expected)
(case seen
(1 (values "type" (dsd-slot-type as) (dsd-slot-type in)))
(3 (values "read-only" (dsd-slot-read-only as) (dsd-slot-read-only in)))
(otherwise "Panic" as in))
(error "Incompatible ~a tag ~a ~a." tag datum expected)))))
inherit)))
;;; check duplicate & identical slot names
(defun das!parse-struct-slots (dd slots)
(let* ((sd (mapcar 'das!parse-struct-slot slots))
(raw (mapcar #'car sd))
(parent (dsd-include dd))
(inherit)
(clear (remove-duplicates raw)))
(if (/= (length raw) (length clear))(error "Duplicate slot names ~a" raw))
;; check identical names
(when parent
;; parent slots without descriptor
(setq inherit (rest (dsd-include-inherited parent)))
(let ((dup (intersection raw (mapcar #'car inherit))))
(if (not (null dup))
(error "Have the some slot names ~a." dup)))
(das!compare-asins (dsd-include-assigned (dsd-include dd)) inherit))
(setf (dsd-slots dd) sd
(dsd-slot-nums dd) (length sd))))
;;; update structure slots
;;; => (slots-with-accessor-names)
(defun das%update-accessor-names (conc-name slots)
(dolist (slot slots)
(setf (dsd-slot-accessor slot)
(%symbolize conc-name (dsd-slot-name slot)))))
;;; compute structure storage
;;; make prototype
;;; compute storage prototype for structure list-vector storage base
;;;
;;; das!compute-storage-prototype &key include self
;;; include::= (descriptor slots)
;;; self:: (descriptor slots)
;;; descriptor::= structure-storage-descriptor
;;; slots::= (structure-slot*)
;;; => (n-cells map prototype)
;;; n-cells ::= length of structure storage
;;; map::= tag*
;;; tag::= offset-tag | leader-tag | slot-position
;;; offset-tag::= -1
;;; leader-tag::= -2
;;; slot-position::= non-negative-integer
;;; prototype::= (offset-cells|leader-cell sn* )*
;;; offset-cells::= offset-tag *initial-offest | nothing if :initial-offset unused
;;; leader-cell::= real structure-name | nothing if :named unused
;;; sn::= real slot-name
;;; for
;;; (das!struct-storage-generate-prototype
;;; :include '(((binop nil 2)(binop-a nil nil nil)(binop-b nil nil nil))
;;; ((maps nil 3) (maps-a nil nil nil)(maps-b nil nil nil)))
;;; :self '(((pas nil 0) (pas-a nil nil nil)(pas-b nil nil nil))))
;;; from (defstruct (pas :named (:include maps) pas-a pas-b pas-c))
;;;
;;; n-cells::= 14
;;; map::= (-1 -1 -2 3 4 -1 -1 -1 -2 9 10 -2 12 13)
;;; prototype::= (NIL NIL BINOP BINOP-A BINOP-B NIL NIL NIL MAPS MAPS-A MAPS-B PAS PAS-A PAS-B))
;;;
(defun %storage-generate-prototype (d &optional storage (n-cell 0) i-map)
(let ((descriptor)(slots)(offset))
(dolist (it d)
(setq descriptor (car it) slots (rest it))
(setq offset (dsd-storage-descriptor-offset descriptor))
(dotimes (i offset)
(push nil storage)
(push -1 i-map)
(incf n-cell))
(when (dsd-storage-descriptor-leader descriptor)
(push (dsd-storage-descriptor-leader descriptor) storage)
(push -2 i-map)
(incf n-cell))
(dolist (slot slots)
(push (dsd-slot-name slot) storage)
(push n-cell i-map)
(incf n-cell))))
(list n-cell i-map storage))
;;; compute storage prototype for structure list-vector storage base
(defun das%compute-storage-prototype (&key include self)
(destructuring-bind (n-cells-1 i-map-1 i-storage-1)
(%storage-generate-prototype include)
(destructuring-bind (n-cells-2 i-map-2 i-storage-2)
(%storage-generate-prototype self i-storage-1 n-cells-1 i-map-1)
(let ((icell 0))
(dolist (cell i-map-2)
(if (eql cell -2)
(progn (setf (nth icell i-map-2) -3) (return)))
(incf icell)))
(%make-dsd-prototype :n n-cells-2 :map (reverse i-map-2) :storage (reverse i-storage-2)))))
;;; compute structure-type-hash
;;; => hash-table (slot-name : storage position)
(defun das%compute-storage-hash (prototype)
(let ((hash (make-hash-table :test #'eql))
(slot-names
(remove nil
(mapcar (lambda (x y)
(if (>= x 0)
;; the slot-position, return symbol from y
;; cons name(y) position(x)
(cons y x)
nil))
(dsd-prototype-map prototype)
(dsd-prototype-storage prototype)))))
(dolist (pair slot-names)
(setf (gethash (car pair) hash) (cdr pair)))
hash))
;;; merge two `slots` - from included structure & self slots
#+nil
(defun das%merge-slots (include own)
(append (structure-include-inherited include) own))
;;; make Slot Order Descriptor &optional (q :zero) for first record
;;; into dsd-inherit-slots (if structure has not include other structure)
(defun das%make-sod (descriptor slots &optional q)
(let ((o (append (list descriptor)(mapcar (lambda (x) x) slots))))
(if q
(list o)
o)))
;;; merge two sod's
(defun das%merge-sod (&key new exists)
(let (r)
(dolist (it exists)
(push it r))
(push new r)
(reverse r)))
;;; finalize
(defun das!finalize-structure (dd)
(let ((parent-name (dsd-parent dd)))
(when parent-name
(push (dsd-name dd) (dsd-childs (get-structure-dsd parent-name))))
#+nil
(if (and (dsd-type dd) (dsd-named-p dd)(dsd-predicate dd))
(%deftype (dsd-name dd)
:expander (function (lambda (xz)
(declare (ignore xz))
`(satisfies ,(dsd-predicate dd))))))
(setf (gethash (dsd-name dd) *structures*) dd)))
(defun das!defstruct-expand (name options slots)
(let ((dd) (include) (parent) (prototype) (descriptor)(standard) (lisp-type)
(to-inherit-slots))
#+jscl (unless (%dsd-my-be-rewrite name) (error "Structure ~a can't be overridden" name))
(setq dd (%make-dsd :name name))
(das!parse-defstruct-options options dd)
(when (dsd-named-p dd)
(setf (dsd-named-p dd) (dsd-name dd))
(incf (dsd-instance-len dd)))
(das!parse-struct-slots dd slots)
(incf (dsd-instance-len dd) (dsd-slot-nums dd))
(setq lisp-type (if (memq (dsd-type dd) '(list vector)) t nil))
(setq descriptor (%make-dsd-storage-descriptor
:leader (dsd-named-p dd)
:n (dsd-instance-len dd)
:offset (dsd-initial-offset dd)))
(cond ((dsd-parent dd)
(setq parent (get-structure-dsd (dsd-parent dd))
include (dsd-include dd))
(unless (das!include-possible-p dd parent)
(error "This structures have overlapping names."))
;; the structure included other structure
(setq to-inherit-slots (das%merge-sod
:new (das%make-sod descriptor (dsd-slots dd))
:exists (dsd-include-inherited include)))
;; build storage prototype with included slots
(setq prototype (das%compute-storage-prototype
:include (dsd-include-inherited include)
:self (das%make-sod descriptor (dsd-slots dd) :zero))))
;; structure without inherite
(t (setq to-inherit-slots (das%make-sod descriptor (dsd-slots dd) :zero)
prototype (das%compute-storage-prototype
:self (das%make-sod descriptor (dsd-slots dd) :zero)))))
(setf (dsd-map-names dd) (das%compute-storage-hash prototype)
(dsd-inherit-slots dd) (copy-tree to-inherit-slots)
(dsd-prototype dd) (if lisp-type (copy-tree prototype) (list nil))
(dsd-descriptor dd) (copy-tree descriptor))
(setq standard (if lisp-type
(das!make-lisp-base-structure dd)
(das!make-standard-structure dd)))
(das!finalize-structure dd)
standard
))
(defmacro das!struct (name-and-options &rest slots)
(let* ((name-and-options (ensure-list name-and-options))
(options (rest name-and-options))
(name (car name-and-options)))
`(progn
,@(das!defstruct-expand `,name `,options `,slots)
',name
)))
#+jscl
(defmacro defstruct (name-options &rest slots)
`(das!struct ,name-options ,@slots))
;;; EOF
| 44,466 | Common Lisp | .lisp | 984 | 34.849593 | 105 | 0.564197 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 855d1402fb6e35e4017d56230cb14d2e14ee1b9843115650256d2b3b929a3db9 | 27 | [
-1
] |
28 | boot.lisp | jscl-project_jscl/src/boot.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; boot.lisp --- First forms to be cross compiled
;; Copyright (C) 2012, 2013 David Vazquez
;; Copyright (C) 2012 Raimon Grau
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; This code is executed when JSCL compiles this file itself. The
;;; compiler provides compilation of some special forms, as well as
;;; funcalls and macroexpansion, but no functions. So, we define the
;;; Lisp world from scratch. This code has to define enough language
;;; to the compiler to be able to run.
(/debug "loading boot.lisp!")
(eval-when (:compile-toplevel)
(let ((defmacro-macroexpander
'#'(lambda (form)
(destructuring-bind (name args &body body)
form
(multiple-value-bind (body decls docstring)
(parse-body body :declarations t :docstring t)
(let* ((whole (gensym))
(expander `(function
(lambda (,whole)
,docstring
(block ,name
(destructuring-bind ,args ,whole
,@decls
,@body))))))
;; If we are bootstrapping JSCL, we need to quote the
;; macroexpander, because the macroexpander will
;; need to be dumped in the final environment
;; somehow.
(when (find :jscl-xc *features*)
(setq expander `(quote ,expander)))
`(eval-when (:compile-toplevel :execute)
(%compile-defmacro ',name ,expander))
))))))
(%compile-defmacro 'defmacro defmacro-macroexpander)))
(defmacro declaim (&rest decls)
`(eval-when (:compile-toplevel :execute)
,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
(defmacro defconstant (name value &optional docstring)
`(progn
(declaim (special ,name))
(declaim (constant ,name))
(setq ,name ,value)
,@(when (stringp docstring) `((oset ,docstring ',name "vardoc")))
',name))
(defconstant t 't)
(defconstant nil 'nil)
(%js-vset "nil" nil)
(%js-vset "t" t)
(defmacro lambda (args &body body)
`(function (lambda ,args ,@body)))
(defmacro when (condition &body body)
`(if ,condition (progn ,@body) nil))
(defmacro unless (condition &body body)
`(if ,condition nil (progn ,@body)))
(defmacro defvar (name &optional (value nil value-p) docstring)
`(progn
(declaim (special ,name))
,@(when value-p `((unless (boundp ',name) (setq ,name ,value))))
,@(when (stringp docstring) `((oset ,docstring ',name "vardoc")))
',name))
(defmacro defparameter (name value &optional docstring)
`(progn
(declaim (special ,name))
(setq ,name ,value)
,@(when (stringp docstring) `((oset ,docstring ',name "vardoc")))
',name))
;;; Basic DEFUN for regular function names (not SETF)
(defmacro %defun (name args &rest body)
`(progn
(eval-when (:compile-toplevel)
(fn-info ',name :defined t))
(fset ',name #'(named-lambda ,name ,args ,@body))
',name))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro %defun-setf-symbol (name)
`(intern
(concat "(" (symbol-name (car ,name)) "_" (symbol-name (cadr ,name)) ")")
(symbol-package (cadr ,name)))))
(defmacro defun (name args &rest body)
(cond ((symbolp name)
`(%defun ,name ,args ,@body))
((and (consp name) (eq (car name) 'setf))
;; HACK: This stores SETF functions within regular symbols,
;; built from using (SETF name) as a string. This of course
;; is incorrect, and (SETF name) functions should be stored
;; in a different place.
;;
;; Also, the SETF expansion could be defined on demand in
;; get-setf-expansion by consulting this register of SETF
;; definitions.
(let ((sfn (%defun-setf-symbol name)))
`(progn
(%defun ,sfn ,args ,@body)
(define-setf-expander ,(cadr name) (&rest arguments)
(let ((g!args (mapcar (lambda (it)
(declare (ignore it))
(gensym))
arguments))
(g!newvalue (gensym))
(g!setter ',sfn)
(g!getter ',(cadr name)))
(values
(list g!args)
arguments
(list g!newvalue)
`(,g!setter ,g!newvalue ,@arguments)
`(,g!getter ,@arguments)))))))
(t (error "defun ~a unknown function specifier" name))))
(defmacro return (&optional value)
`(return-from nil ,value))
(defmacro while (condition &body body)
`(block nil (%while ,condition ,@body)))
(defvar *gensym-counter* 0)
(defun gensym (&optional (prefix "G"))
(setq *gensym-counter* (+ *gensym-counter* 1))
(make-symbol (concat prefix (integer-to-string *gensym-counter*))))
(defun boundp (x)
(boundp x))
(defun fboundp (x)
(if (functionp x)
(error "FBOUNDP - invalid function name ~a." x))
(%fboundp x))
(defun eq (x y) (eq x y))
(defun eql (x y) (eq x y))
(defun not (x) (if x nil t))
(defun funcall (function &rest args)
(apply function args))
(defun apply (function arg &rest args)
(apply function (apply #'list* arg args)))
(defun symbol-name (x)
(symbol-name x))
;; Basic macros
(defmacro dolist ((var list &optional result) &body body)
(let ((g!list (gensym)))
(unless (symbolp var) (error "`~S' is not a symbol." var))
`(block nil
(let ((,g!list ,list)
(,var nil))
(%while ,g!list
(setq ,var (car ,g!list))
(tagbody ,@body)
(setq ,g!list (cdr ,g!list)))
,result))))
(defmacro dotimes ((var count &optional result) &body body)
(let ((g!count (gensym)))
(unless (symbolp var) (error "`~S' is not a symbol." var))
`(block nil
(let ((,var 0)
(,g!count ,count))
(%while (< ,var ,g!count)
(tagbody ,@body)
(incf ,var))
,result))))
(defmacro cond (&rest clausules)
(unless (null clausules)
(destructuring-bind (condition &body body)
(first clausules)
(cond
((eq condition t)
`(progn ,@body))
((null body)
(let ((test-symbol (gensym)))
`(let ((,test-symbol ,condition))
(if ,test-symbol
,test-symbol
(cond ,@(rest clausules))))))
(t
`(if ,condition
(progn ,@body)
(cond ,@(rest clausules))))))))
(defmacro case (form &rest clausules)
(let ((!form (gensym)))
`(let ((,!form ,form))
(cond
,@(mapcar (lambda (clausule)
(destructuring-bind (keys &body body)
clausule
(if (or (eq keys 't) (eq keys 'otherwise))
`(t nil ,@body)
(let ((keys (if (listp keys) keys (list keys))))
`((or ,@(mapcar (lambda (key) `(eql ,!form ',key)) keys))
nil ,@body)))))
clausules)))))
(defmacro ecase (form &rest clausules)
(let ((g!form (gensym)))
`(let ((,g!form ,form))
(case ,g!form
,@(append
clausules
`((t
(error "ECASE expression failed for the object `~S'." ,g!form))))))))
(defmacro and (&rest forms)
(cond
((null forms)
t)
((null (cdr forms))
(car forms))
(t
`(if ,(car forms)
(and ,@(cdr forms))
nil))))
(defmacro or (&rest forms)
(cond
((null forms)
nil)
((null (cdr forms))
(car forms))
(t
(let ((g (gensym)))
`(let ((,g ,(car forms)))
(if ,g ,g (or ,@(cdr forms))))))))
(defmacro prog1 (form &body body)
(let ((value (gensym)))
`(let ((,value ,form))
,@body
,value)))
(defmacro prog2 (form1 result &body body)
`(prog1 (progn ,form1 ,result) ,@body))
(defmacro prog (inits &rest body )
(multiple-value-bind (forms decls docstring) (parse-body body)
`(block nil
(let ,inits
,@decls
(tagbody ,@forms)))))
(defmacro psetq (&rest pairs)
(let (;; For each pair, we store here a list of the form
;; (VARIABLE GENSYM VALUE).
(assignments '()))
(while t
(cond
((null pairs) (return))
((null (cdr pairs))
(error "Odd pairs in PSETQ"))
(t
(let ((variable (car pairs))
(value (cadr pairs)))
(push `(,variable ,(gensym) ,value) assignments)
(setq pairs (cddr pairs))))))
(setq assignments (reverse assignments))
;;
`(let ,(mapcar #'cdr assignments)
(setq ,@(!reduce #'append (mapcar #'butlast assignments) nil)))))
(defmacro do (varlist endlist &body body)
`(block nil
(let ,(mapcar (lambda (x) (if (symbolp x)
(list x nil)
(list (first x) (second x)))) varlist)
(while t
(when ,(car endlist)
(return (progn ,@(cdr endlist))))
(tagbody ,@body)
(psetq
,@(apply #'append
(mapcar (lambda (v)
(and (listp v)
(consp (cddr v))
(list (first v) (third v))))
varlist)))))))
(defmacro do* (varlist endlist &body body)
`(block nil
(let* ,(mapcar (lambda (x1) (if (symbolp x1)
(list x1 nil)
(list (first x1) (second x1)))) varlist)
(while t
(when ,(car endlist)
(return (progn ,@(cdr endlist))))
(tagbody ,@body)
(setq
,@(apply #'append
(mapcar (lambda (v)
(and (listp v)
(consp (cddr v))
(list (first v) (third v))))
varlist)))))))
(defun identity (x) x)
(defun complement (x)
(lambda (&rest args)
(not (apply x args))))
(defun constantly (x)
(lambda (&rest args)
x))
(defun code-char (x)
(code-char x))
(defun char-code (x)
(char-code x))
(defun char= (x y)
(eql x y))
(defun char< (x y)
(< (char-code x) (char-code y)))
(defun atom (x)
(not (consp x)))
(defun alpha-char-p (x)
(or (<= (char-code #\a) (char-code x) (char-code #\z))
(<= (char-code #\A) (char-code x) (char-code #\Z))))
(defun digit-char-p (x)
(and (<= (char-code #\0) (char-code x) (char-code #\9))
(- (char-code x) (char-code #\0))))
(defun digit-char (weight)
(and (<= 0 weight 9)
(char "0123456789" weight)))
(defun equal (x y)
(cond
((eql x y) t)
((consp x)
(and (consp y)
(equal (car x) (car y))
(equal (cdr x) (cdr y))))
((stringp x)
(and (stringp y) (string= x y)))
(t nil)))
(defun fdefinition (x)
(cond
((functionp x)
x)
((symbolp x)
(symbol-function x))
((and (consp x) (eq (car x) 'setf))
(symbol-function (%defun-setf-symbol x)))
(t
(error "Invalid function `~S'." x))))
(defun disassemble (function)
(write-line (lambda-code (fdefinition function)))
nil)
(defmacro multiple-value-bind (variables value-from &body body)
`(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
,@body)
,value-from))
(defmacro multiple-value-list (value-from)
`(multiple-value-call #'list ,value-from))
(defmacro multiple-value-setq ((&rest vars) &rest form)
(let ((gvars (mapcar (lambda (x) (gensym)) vars))
(setqs '()))
(do ((vars vars (cdr vars))
(gvars gvars (cdr gvars)))
((or (null vars) (null gvars)))
(push `(setq ,(car vars) ,(car gvars))
setqs))
(setq setqs (reverse setqs))
`(multiple-value-call (lambda ,gvars ,@setqs)
,@form)))
(defun notany (fn seq)
(not (some fn seq)))
(defconstant internal-time-units-per-second 1000)
(defun values-list (list)
(values-array (list-to-vector list)))
(defun values (&rest args)
(values-list args))
(defmacro nth-value (n form)
`(multiple-value-call (lambda (&rest values)
(nth ,n values))
,form))
(defun constantp (x)
;; TODO: Consider quoted forms, &environment and many other
;; semantics of this function.
(cond
((symbolp x)
(cond
((eq x t) t)
((eq x nil) t)))
((atom x)
t)
(t
nil)))
(defparameter *features* '(:jscl :common-lisp))
;;; symbol-function from compiler macro
(defun functionp (f) (functionp f))
;;; types family section
;;; tag's utils
(defun object-type-code (object) (oget object "dt_Name"))
(defun set-object-type-code (object tag) (oset tag object "dt_Name"))
;;; types predicate's
(defun mop-object-p (obj)
(and (consp obj)
(eql (object-type-code obj) :mop-object)
(= (length obj) 5)))
(defun clos-object-p (object) (eql (object-type-code object) :clos_object))
;;; macro's
(defun %check-type-error (place value typespec string)
(error "Check type error.~%The value of ~s is ~s, is not ~a ~a."
place value typespec (if (null string) "" string)))
(defmacro %check-type (place typespec &optional (string ""))
(let ((value (gensym)))
(if (symbolp place)
`(do ((,value ,place ,place))
((!typep ,value ',typespec))
(setf ,place (%check-type-error ',place ,value ',typespec ,string)))
(if (!typep place typespec)
t
(%check-type-error place place typespec string)))))
#+jscl
(defmacro check-type (place typespec &optional (string ""))
`(%check-type ,place ,typespec ,string))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro %push-end (thing place) `(setq ,place (append ,place (list ,thing))))
(defparameter *basic-type-predicates*
'((hash-table . hash-table-p) (package . packagep) (stream . streamp)
(atom . atom) (structure . structure-p) (js-object . js-object-p)
;; todo: subtypep - remove mop-object from tables
(clos-object . mop-object-p) (mop-object . mop-object-p) (character . characterp)
(symbol . symbolp) (keyword . keywordp)
(function . functionp)
(number . numberp) (real . realp) (rational . rationalp) (float . floatp)
(integer . integerp)
(sequence . sequencep) (list . listp) (cons . consp) (array . arrayp)
(vector . vectorp) (string . stringp) (null . null)))
(defun simple-base-predicate-p (expr)
(if (symbolp expr)
(let ((pair (assoc expr *basic-type-predicates*)))
(if pair (cdr pair) nil))))
(defun typecase-expander (object clausules)
(let ((key)
(body)
(std-p)
(g!x (gensym "TYPECASE"))
(result '()))
(dolist (it clausules (reverse result))
(setq key (car it)
body (cdr it)
std-p (simple-base-predicate-p key))
;; (typecase keyform (type-spec form*))
;; when: type-spec is symbol in *basic-type-predicates*, its predicate
;; -> (cond ((predicate keyform) form*))
;; otherwise: (cond ((typep keyform (type-spec form*))))
(cond (std-p (%push-end `((,std-p ,g!x) ,@body) result))
((or (eq key 't) (eq key 'otherwise))
(%push-end `(t ,@body) result))
(t (%push-end `((!typep ,g!x ',key) ,@body) result))))
`(let ((,g!x ,object))
(cond ,@result))))
)
(defmacro typecase (form &rest clausules)
(typecase-expander `,form `,clausules))
(defmacro etypecase (x &rest clausules)
`(typecase ,x
,@clausules
(t (error "~S fell through etypecase expression." ,x))))
;;; it remains so. not all at once. with these - live...
(defun subtypep (type1 type2)
(cond
((null type1)
(values t t))
((eq type1 type2)
(values t t))
((eq type2 'number)
(values (and (member type1 '(fixnum integer)) t)
t))
(t
(values nil nil))))
;;; Early error definition.
(defun %coerce-panic-arg (arg)
(cond ((symbolp arg) (concat "symbol: " (symbol-name arg)))
((consp arg ) (concat "cons: " (car arg)))
((numberp arg) (concat "number:" arg))
(t " @ ")))
(defun error (fmt &rest args)
(if (fboundp 'format)
(%throw (apply #'format nil fmt args))
(%throw (lisp-to-js (concat "BOOT PANIC! "
(string fmt)
" "
(%coerce-panic-arg (car args)))))))
;;; print-unreadable-object
(defmacro !print-unreadable-object ((object stream &key type identity) &body body)
(let ((g!stream (gensym))
(g!object (gensym)))
`(let ((,g!stream ,stream)
(,g!object ,object))
(simple-format ,g!stream "#<")
,(when type
`(simple-format ,g!stream "~S" (type-of g!object)))
,(when (and type (or body identity))
`(simple-format ,g!stream " "))
,@body
,(when (and identity body)
`(simple-format ,g!stream " "))
(simple-format ,g!stream ">")
nil)))
#+jscl
(defmacro print-unreadable-object ((object stream &key type identity) &body body)
`(!print-unreadable-object (,object ,stream :type ,type :identity ,identity) ,@body))
(defmacro %%assert (test &optional ignore datum &rest args)
(let ((value (gensym "ASSERT-VALUE")))
`(let ((,value ,test))
(when (not ,value)
(jscl::%%assert-error ',test ,datum ,@args)))))
#+jscl
(defmacro assert (test &optional ignore datum &rest args)
`(%%assert ,test ,ignore ,datum ,@args))
;;; EOF
| 18,680 | Common Lisp | .lisp | 502 | 28.727092 | 89 | 0.551972 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | fa3220ce1db8cab247f410ea0f263e5bf69f50692e344fd5eb0c9db92e3b82af | 28 | [
-1
] |
29 | misc.lisp | jscl-project_jscl/src/misc.lisp | ;;; misc.lisp --
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading misc.lisp!")
(defun lisp-implementation-type ()
"JSCL")
(defun lisp-implementation-version ()
#.*version*)
(defun short-site-name ()
nil)
(defun long-site-name ()
nil)
;;; Javascript has not access to the hardware. Would it make sense to
;;; have the browser data as machine abstraction instead?
(defun machine-instance ()
nil)
(defun machine-version ()
nil)
(defun machine-type ()
nil)
;;; Return browser information here?
(defun software-type ()
nil)
(defun software-version ()
nil)
(defmacro time (form)
(let ((start (gensym))
(end (gensym)))
`(let ((,start (get-internal-real-time))
(,end))
(prog1 (progn ,form)
(setq ,end (get-internal-real-time))
(format t "Execution took ~a seconds.~%" (/ (- ,end ,start) 1000.0))))))
;;;; TRACE
;;; This trace implementation works on symbols, replacing the function
;;; with a wrapper. So it will not trace calls to the function if they
;;; got the function object before it was traced.
;;; An alist of the form (NAME FUNCTION), where NAME is the name of a
;;; function, and FUNCTION is the function traced.
(defvar *traced-functions* nil)
(defvar *trace-level* 0)
;;; @vlad-km 04-09-2022
;;; Prevent RangeError: Maximum call stack size exceeded
;;; on trace call
(defvar *prevent-trace-stop-list*
'(trace
princ prin1 prin1-to-string princ-to-string
print
format !format
write write-char write-string write-integer write-symbol write-line write-to-string
terpri fresh-line))
(defun %prevent-infinite-trace (name)
(typecase name
(symbol
(if (jscl::memq name *prevent-trace-stop-list*)
(error "Trace - `~S` this function is not traceable." name)))
(otherwise (error "Trace - the traceable function name `~S` must be a symbol." name))))
(defun trace-report-call (name args)
(dotimes (i *trace-level*) (write-string " "))
(format t "~a: ~S~%" *trace-level* (cons name args)))
(defun trace-report-return (name values)
(dotimes (i *trace-level*) (write-string " "))
(format t "~a: ~S returned " *trace-level* name)
(dolist (value values) (format t "~S " value))
(format t "~%"))
(defun trace-functions (names)
(if (null names)
(mapcar #'car *traced-functions*)
(dolist (name names names)
(%prevent-infinite-trace name)
(if (find name *traced-functions* :key #'car)
(format t "`~S' is already traced.~%" name)
(let ((func (fdefinition name)))
(fset name (lambda (&rest args)
(let (values)
(trace-report-call name args)
(let ((*trace-level* (1+ *trace-level*)))
(setq values (multiple-value-list (apply func args))))
(trace-report-return name values)
(values-list values))))
(push (cons name func) *traced-functions*))))))
(defun untrace-functions (names)
(when (null names)
(setq names (mapcar #'car *traced-functions*)))
(dolist (name names)
(let ((func (cdr (find name *traced-functions* :key #'car))))
(if func
(fset name func)
(format t "~S is not being traced.~%" name)))))
(defmacro trace (&rest names)
`(trace-functions ',names))
(defmacro untrace (&rest names)
`(untrace-functions ',names))
;;; Time related functions
(defun get-internal-real-time ()
(get-internal-real-time))
(defun get-unix-time ()
(truncate (/ (get-internal-real-time) 1000)))
(defun get-universal-time ()
(+ (get-unix-time) 2208988800))
;;;; STEP
;; Adding STEP macro entry here with no useful code for now, only for ANSI compliance as
;; in other Lisp platforms (like Clozure CL). The expansion of this macro will be only the code passed
;; as the argument
(defmacro step (form)
"Stepping is no currently available"
form)
| 4,565 | Common Lisp | .lisp | 117 | 33.991453 | 102 | 0.657978 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | f182e7c9e84e97cf27f28eb0bbc6c70534e48acb4a542503886313b49c8fd283 | 29 | [
-1
] |
30 | defstruct.lisp | jscl-project_jscl/src/defstruct.lisp | ;;; defstruct.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading defstruct.lisp!")
(defun structure-p (obj)
(and (consp obj)
(eql (object-type-code obj) :structure)))
;; A very simple defstruct built on lists. It supports just slot with
;; an optional default initform, and it will create a constructor,
;; predicate and accessors for you.
(defmacro def!struct (name-and-options &rest slots)
(let* ((name-and-options (ensure-list name-and-options))
(name (first name-and-options))
(name-string (symbol-name name))
(options (rest name-and-options))
(constructor (if (assoc :constructor options)
(second (assoc :constructor options))
(intern (concat "MAKE-" name-string))))
(predicate (if (assoc :predicate options)
(second (assoc :predicate options))
(intern (concat name-string "-P"))))
(copier (if (assoc :copier options)
(second (assoc :copier options))
(intern (concat "COPY-" name-string)))))
(unless predicate
(setq predicate (gensym "PREDICATE")))
(let* ((slot-descriptions
(mapcar (lambda (sd)
(cond
((symbolp sd)
(list sd))
((and (listp sd) (car sd) (null (cddr sd)))
sd)
(t
(error "Bad slot description `~S'." sd))))
slots))
constructor-expansion
predicate-expansion
copier-expansion)
;; mark object as :structure
(when constructor
(setq constructor-expansion
`(defun ,constructor (&key ,@slot-descriptions)
(let ((obj (list ',name ,@(mapcar #'car slot-descriptions))))
#+jscl (set-object-type-code obj :structure)
obj))))
(when predicate
(setq predicate-expansion
`(defun ,predicate (x)
(and (consp x) (eq (car x) ',name)))))
;; mark copy as :structure
(when copier
(setq copier-expansion
`(defun ,copier (x)
(let ((obj (copy-list x)))
#+jscl (oset :structure obj "tagName")
obj))))
`(progn
,constructor-expansion
,predicate-expansion
,copier-expansion
;; Slot accessors
,@(with-collect
(let ((index 1))
(dolist (slot slot-descriptions)
(let* ((name (car slot))
(accessor-name (intern (concat name-string "-" (string name)))))
(collect
`(defun ,accessor-name (x)
(unless (,predicate x)
(error "The object `~S' is not of type `~S'" x ,name-string))
(nth ,index x)))
;; TODO: Implement this with a higher level
;; abstraction like defsetf or (defun (setf ..))
(collect
`(define-setf-expander ,accessor-name (x)
(let ((object (gensym))
(new-value (gensym)))
(values (list object)
(list x)
(list new-value)
`(progn
(rplaca (nthcdr ,',index ,object) ,new-value)
,new-value)
`(,',accessor-name ,object)))))
(incf index)))))
',name))))
#+jscl
(defmacro defstruct (name-and-options &rest slots)
`(def!struct ,name-and-options ,@slots))
| 4,497 | Common Lisp | .lisp | 100 | 30.36 | 89 | 0.507766 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | ae7d0694629b6eab55473472361cb805987da31053d2e02ec1a650e6bada1c66 | 30 | [
-1
] |
31 | worker.lisp | jscl-project_jscl/src/worker.lisp | ;;; worker.lisp ---
;; Copyright (C) 2018 David Vazquez
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading worker.lisp!")
(defun web-worker-p ()
(and (string= (%js-typeof |document|) "undefined")
(string= (%js-typeof |module|) "undefined")
(not (find :deno *features*))))
(defvar *web-worker-session-id*)
(defvar *web-worker-output-class* "jqconsole-output")
(defun %web-worker-write-string (string)
(let ((obj (new)))
(setf (oget obj "command") "output")
(setf (oget obj "stringclass") *web-worker-output-class*)
(setf (oget obj "string") string)
(#j:postMessage obj)))
(defun web-worker-repl ()
(loop
(let ((*web-worker-output-class* "jqconsole-prompt"))
(format t "~a> " (package-name *package*)))
(%js-try
(progn
(handler-case
(let ((results (multiple-value-list
(eval-interactive (read)))))
(dolist (result results)
(print result)))
(error (err)
(let ((*web-worker-output-class* "jqconsole-error"))
(clear-buffer)
(format t "ERROR: ")
(apply #'format t (!condition-args err))
(terpri)))))
(catch (err)
(let (((*web-worker-output-class* "jqconsole-error"))
(message (or (oget err "message") err)))
(clear-buffer)
(format t "ERROR[!]: ~a~%" message))))))
(defun sw-request-sync (command &optional (options (new)))
(let ((xhr (make-new #j:XMLHttpRequest))
(payload (new)))
(setf (oget payload "command") command)
(setf (oget payload "sessionId") *web-worker-session-id*)
(setf (oget payload "options") options)
((oget xhr "open") "POST" "__jscl" nil)
((oget xhr "setRequestHeader") "ContentType" "application/json")
((oget xhr "send") (#j:JSON:stringify payload))
(if (eql (oget xhr "status") 200)
(let* ((text (oget xhr "responseText"))
(json (#j:JSON:parse text)))
(oget json "value"))
(error "Could not contact with the service worker."))))
(defun sleep (seconds)
(let ((options (new)))
(setf (oget options "seconds") seconds)
(sw-request-sync "sleep" options)))
(defvar *stdin-buffer* "")
(defun read-stdin ()
(let ((input (sw-request-sync "readStdin")))
(setf *stdin-buffer* (concat *stdin-buffer* input))
*stdin-buffer*))
(defun clear-buffer ()
(setf *stdin-buffer* ""))
(defun %peek-char-stdin (&rest args)
(if (< 0 (length *stdin-buffer*))
(char *stdin-buffer* 0)
(progn
(read-stdin)
(apply #'%peek-char-stdin args))))
(defun %read-char-stdin (&rest args)
(prog1 (apply #'%peek-char-stdin args)
(setf *stdin-buffer* (subseq *stdin-buffer* 1))))
(defun initialize-web-worker ()
(setq *standard-output*
(make-stream :write-fn #'%web-worker-write-string))
(setq *standard-input*
(make-stream
:read-char-fn #'%read-char-stdin
:peek-char-fn #'%peek-char-stdin))
(welcome-message)
(setf #j:onmessage
(lambda (event)
(let* ((data (oget event "data"))
(command (oget data "command"))
(sessionId (oget data "sessionId")))
(when (string= command "init")
(setf *web-worker-session-id* sessionId)
(web-worker-repl))))))
| 3,970 | Common Lisp | .lisp | 99 | 33.424242 | 69 | 0.611342 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 1d86aa71cca2a4458e0043f46b43a272cb255f07994f20955272037a1a9de4b5 | 31 | [
-1
] |
32 | char.lisp | jscl-project_jscl/src/char.lisp | (/debug "loading char.lisp!")
(defun characterp (ch) (characterp ch))
;; These comparison functions heavily borrowed from SBCL/CMUCL (public domain).
(defun char= (character &rest more-characters)
(dolist (c more-characters t)
(unless (eql c character) (return nil))))
(defun char/= (character &rest more-characters)
(do* ((head character (car list))
(list more-characters (cdr list)))
((null list) t)
(dolist (c list)
(when (eql head c) (return-from char/= nil)))))
(defun char< (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (< (char-int c)
(char-int (car list)))
(return nil))))
(defun char> (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (> (char-int c)
(char-int (car list)))
(return nil))))
(defun char<= (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (<= (char-int c)
(char-int (car list)))
(return nil))))
(defun char>= (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (>= (char-int c)
(char-int (car list)))
(return nil))))
(defun equal-char-code (character)
(char-code (char-upcase character)))
(defun two-arg-char-equal (c1 c2)
(= (equal-char-code c1) (equal-char-code c2)))
(defun char-equal (character &rest more-characters)
(do ((clist more-characters (cdr clist)))
((null clist) t)
(unless (two-arg-char-equal (car clist) character)
(return nil))))
(defun char-not-equal (character &rest more-characters)
(do* ((head character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (do* ((l list (cdr l)))
((null l) t)
(when (two-arg-char-equal head (car l))
(return nil)))
(return nil))))
(defun two-arg-char-lessp (c1 c2)
(< (equal-char-code c1) (equal-char-code c2)))
(defun char-lessp (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (two-arg-char-lessp c (car list))
(return nil))))
(defun two-arg-char-greaterp (c1 c2)
(> (equal-char-code c1) (equal-char-code c2)))
(defun char-greaterp (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (two-arg-char-greaterp c (car list))
(return nil))))
(defun two-arg-char-not-greaterp (c1 c2)
(<= (equal-char-code c1) (equal-char-code c2)))
(defun char-not-greaterp (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (two-arg-char-not-greaterp c (car list))
(return nil))))
(defun two-arg-char-not-lessp (c1 c2)
(>= (equal-char-code c1) (equal-char-code c2)))
(defun char-not-lessp (character &rest more-characters)
(do* ((c character (car list))
(list more-characters (cdr list)))
((null list) t)
(unless (two-arg-char-not-lessp c (car list))
(return nil))))
(defun character (character)
(cond ((characterp character)
character)
((and (stringp character)
(= 1 (length character)))
(char character 0))
((and (symbolp character)
(= 1 (length (symbol-name character))))
(symbol-name character))
(t
(error "not a valid character designator"))))
;; This list comes from SBCL: everything that's ALPHA-CHAR-P, but
;; not SB-IMPL::UCD-DECIMAL-DIGIT (to work around <https://bugs.launchpad.net/sbcl/+bug/1177986>),
;; then combined into a much smaller set of ranges. Yes, this can be compressed better.
(defconstant +unicode-alphas+
'((65 . 90) (97 . 122) (170 . 170) (181 . 181) (186 . 186) (192 . 214)
(216 . 246) (248 . 705) (710 . 721) (736 . 740) (748 . 748) (750 . 750)
(880 . 884) (886 . 887) (890 . 893) (902 . 902) (904 . 906) (908 . 908)
(910 . 929) (931 . 1013) (1015 . 1153) (1162 . 1317) (1329 . 1366)
(1369 . 1369) (1377 . 1415) (1488 . 1514) (1520 . 1522) (1569 . 1610)
(1646 . 1647) (1649 . 1747) (1749 . 1749) (1765 . 1766) (1774 . 1775)
(1786 . 1788) (1791 . 1791) (1808 . 1808) (1810 . 1839) (1869 . 1957)
(1969 . 1969) (1994 . 2026) (2036 . 2037) (2042 . 2042) (2048 . 2069)
(2074 . 2074) (2084 . 2084) (2088 . 2088) (2308 . 2361) (2365 . 2365)
(2384 . 2384) (2392 . 2401) (2417 . 2418) (2425 . 2431) (2437 . 2444)
(2447 . 2448) (2451 . 2472) (2474 . 2480) (2482 . 2482) (2486 . 2489)
(2493 . 2493) (2510 . 2510) (2524 . 2525) (2527 . 2529) (2544 . 2545)
(2565 . 2570) (2575 . 2576) (2579 . 2600) (2602 . 2608) (2610 . 2611)
(2613 . 2614) (2616 . 2617) (2649 . 2652) (2654 . 2654) (2674 . 2676)
(2693 . 2701) (2703 . 2705) (2707 . 2728) (2730 . 2736) (2738 . 2739)
(2741 . 2745) (2749 . 2749) (2768 . 2768) (2784 . 2785) (2821 . 2828)
(2831 . 2832) (2835 . 2856) (2858 . 2864) (2866 . 2867) (2869 . 2873)
(2877 . 2877) (2908 . 2909) (2911 . 2913) (2929 . 2929) (2947 . 2947)
(2949 . 2954) (2958 . 2960) (2962 . 2965) (2969 . 2970) (2972 . 2972)
(2974 . 2975) (2979 . 2980) (2984 . 2986) (2990 . 3001) (3024 . 3024)
(3077 . 3084) (3086 . 3088) (3090 . 3112) (3114 . 3123) (3125 . 3129)
(3133 . 3133) (3160 . 3161) (3168 . 3169) (3205 . 3212) (3214 . 3216)
(3218 . 3240) (3242 . 3251) (3253 . 3257) (3261 . 3261) (3294 . 3294)
(3296 . 3297) (3333 . 3340) (3342 . 3344) (3346 . 3368) (3370 . 3385)
(3389 . 3389) (3424 . 3425) (3450 . 3455) (3461 . 3478) (3482 . 3505)
(3507 . 3515) (3517 . 3517) (3520 . 3526) (3585 . 3632) (3634 . 3635)
(3648 . 3654) (3713 . 3714) (3716 . 3716) (3719 . 3720) (3722 . 3722)
(3725 . 3725) (3732 . 3735) (3737 . 3743) (3745 . 3747) (3749 . 3749)
(3751 . 3751) (3754 . 3755) (3757 . 3760) (3762 . 3763) (3773 . 3773)
(3776 . 3780) (3782 . 3782) (3804 . 3805) (3840 . 3840) (3904 . 3911)
(3913 . 3948) (3976 . 3979) (4096 . 4138) (4159 . 4159) (4176 . 4181)
(4186 . 4189) (4193 . 4193) (4197 . 4198) (4206 . 4208) (4213 . 4225)
(4238 . 4238) (4256 . 4293) (4304 . 4346) (4348 . 4348) (4352 . 4680)
(4682 . 4685) (4688 . 4694) (4696 . 4696) (4698 . 4701) (4704 . 4744)
(4746 . 4749) (4752 . 4784) (4786 . 4789) (4792 . 4798) (4800 . 4800)
(4802 . 4805) (4808 . 4822) (4824 . 4880) (4882 . 4885) (4888 . 4954)
(4992 . 5007) (5024 . 5108) (5121 . 5740) (5743 . 5759) (5761 . 5786)
(5792 . 5866) (5888 . 5900) (5902 . 5905) (5920 . 5937) (5952 . 5969)
(5984 . 5996) (5998 . 6000) (6016 . 6067) (6103 . 6103) (6108 . 6108)
(6176 . 6263) (6272 . 6312) (6314 . 6314) (6320 . 6389) (6400 . 6428)
(6480 . 6509) (6512 . 6516) (6528 . 6571) (6593 . 6599) (6656 . 6678)
(6688 . 6740) (6823 . 6823) (6917 . 6963) (6981 . 6987) (7043 . 7072)
(7086 . 7087) (7168 . 7203) (7245 . 7247) (7258 . 7293) (7401 . 7404)
(7406 . 7409) (7424 . 7615) (7680 . 7957) (7960 . 7965) (7968 . 8005)
(8008 . 8013) (8016 . 8023) (8025 . 8025) (8027 . 8027) (8029 . 8029)
(8031 . 8061) (8064 . 8116) (8118 . 8124) (8126 . 8126) (8130 . 8132)
(8134 . 8140) (8144 . 8147) (8150 . 8155) (8160 . 8172) (8178 . 8180)
(8182 . 8188) (8305 . 8305) (8319 . 8319) (8336 . 8340) (8450 . 8450)
(8455 . 8455) (8458 . 8467) (8469 . 8469) (8473 . 8477) (8484 . 8484)
(8486 . 8486) (8488 . 8488) (8490 . 8493) (8495 . 8505) (8508 . 8511)
(8517 . 8521) (8526 . 8526) (8579 . 8580) (11264 . 11310) (11312 . 11358)
(11360 . 11492) (11499 . 11502) (11520 . 11557) (11568 . 11621)
(11631 . 11631) (11648 . 11670) (11680 . 11686) (11688 . 11694)
(11696 . 11702) (11704 . 11710) (11712 . 11718) (11720 . 11726)
(11728 . 11734) (11736 . 11742) (11823 . 11823) (12293 . 12294)
(12337 . 12341) (12347 . 12348) (12353 . 12438) (12445 . 12447)
(12449 . 12538) (12540 . 12543) (12549 . 12589) (12593 . 12686)
(12704 . 12727) (12784 . 12799) (13312 . 19893) (19968 . 40907)
(40960 . 42124) (42192 . 42237) (42240 . 42508) (42512 . 42527)
(42538 . 42539) (42560 . 42591) (42594 . 42606) (42623 . 42647)
(42656 . 42725) (42775 . 42783) (42786 . 42888) (42891 . 42892)
(43003 . 43009) (43011 . 43013) (43015 . 43018) (43020 . 43042)
(43072 . 43123) (43138 . 43187) (43250 . 43255) (43259 . 43259)
(43274 . 43301) (43312 . 43334) (43360 . 43388) (43396 . 43442)
(43471 . 43471) (43520 . 43560) (43584 . 43586) (43588 . 43595)
(43616 . 43638) (43642 . 43642) (43648 . 43695) (43697 . 43697)
(43701 . 43702) (43705 . 43709) (43712 . 43712) (43714 . 43714)
(43739 . 43741) (43968 . 44002) (44032 . 55203) (55216 . 55238)
(55243 . 55291) (63744 . 64045) (64048 . 64109) (64112 . 64217)
(64256 . 64262) (64275 . 64279) (64285 . 64285) (64287 . 64296)
(64298 . 64310) (64312 . 64316) (64318 . 64318) (64320 . 64321)
(64323 . 64324) (64326 . 64433) (64467 . 64829) (64848 . 64911)
(64914 . 64967) (65008 . 65019) (65136 . 65140) (65142 . 65276)
(65313 . 65338) (65345 . 65370) (65382 . 65470) (65474 . 65479)
(65482 . 65487) (65490 . 65495) (65498 . 65500) (65536 . 65547)
(65549 . 65574) (65576 . 65594) (65596 . 65597) (65599 . 65613)
(65616 . 65629) (65664 . 65786) (66176 . 66204) (66208 . 66256)
(66304 . 66334) (66352 . 66368) (66370 . 66377) (66432 . 66461)
(66464 . 66499) (66504 . 66511) (66560 . 66717) (67584 . 67589)
(67592 . 67592) (67594 . 67637) (67639 . 67640) (67644 . 67644)
(67647 . 67669) (67840 . 67861) (67872 . 67897) (68096 . 68096)
(68112 . 68115) (68117 . 68119) (68121 . 68147) (68192 . 68220)
(68352 . 68405) (68416 . 68437) (68448 . 68466) (68608 . 68680)
(69763 . 69807) (73728 . 74606) (77824 . 78894) (119808 . 119892)
(119894 . 119964) (119966 . 119967) (119970 . 119970) (119973 . 119974)
(119977 . 119980) (119982 . 119993) (119995 . 119995) (119997 . 120003)
(120005 . 120069) (120071 . 120074) (120077 . 120084) (120086 . 120092)
(120094 . 120121) (120123 . 120126) (120128 . 120132) (120134 . 120134)
(120138 . 120144) (120146 . 120485) (120488 . 120512) (120514 . 120538)
(120540 . 120570) (120572 . 120596) (120598 . 120628) (120630 . 120654)
(120656 . 120686) (120688 . 120712) (120714 . 120744) (120746 . 120770)
(120772 . 120779) (131072 . 173782) (173824 . 177972) (194560 . 195101))
"(Start . End) ranges of codepoints for alphabetic characters, as of Unicode 6.2.")
(defun alpha-char-p (char)
(let ((code (char-code char)))
(dolist (alpha-pair +unicode-alphas+)
(when (<= (car alpha-pair) code (cdr alpha-pair))
(return-from alpha-char-p t)))
nil))
(defun alphanumericp (char)
;; from the hyperspec:
(or (alpha-char-p char)
(not (null (digit-char-p char)))))
;; I made this list by running DIGIT-CHAR-P in SBCL on every codepoint up to CHAR-CODE-LIMIT,
;; filtering on only those with SB-IMPL::UCD-GENERAL-CATEGORY 12 (Nd), and then grouping
;; consecutive sets. There's 37 spans of 10, plus 1 extra digit (6618).
(defconstant +unicode-zeroes+
'(48 1632 1776 1984 2406 2534 2662 2790 2918 3046 3174 3302 3430 3664
3792 3872 4160 4240 6112 6160 6470 6608 6784 6800 6992 7088 7232 7248
42528 43216 43264 43472 43600 44016 65296 66720 120782)
"Unicode codepoints which have Digit value 0, followed by 1, 2, ..., 9, as of Unicode 6.2")
;; The "Digit value" of a (Unicode) character, or NIL, if it doesn't have one.
(defun unicode-digit-value (char)
(let ((code (char-code char)))
(if (= code 6618)
1 ;; it's special!
(dolist (z +unicode-zeroes+)
(when (<= z code (+ z 9))
(return-from unicode-digit-value (- code z)))))))
;; from SBCL/CMUCL:
(defun digit-char (weight &optional (radix 10))
"All arguments must be integers. Returns a character object that represents
a digit of the given weight in the specified radix. Returns NIL if no such
character exists."
(and ;; (typep weight 'fixnum)
(>= weight 0) (< weight radix) (< weight 36)
(code-char (if (< weight 10) (+ 48 weight) (+ 55 weight)))))
;; From comment #4 on <https://bugs.launchpad.net/sbcl/+bug/1177986>:
(defun digit-char-p (char &optional (radix 10))
"Includes ASCII 0-9 a-z A-Z, plus Unicode HexDigit characters (fullwidth variants of 0-9 and A-F)."
(let* ((number (unicode-digit-value char))
(code (char-code char))
(upper (char-upcase char))
(code-upper (char-code upper))
(potential (cond (number number)
((char<= #\0 char #\9)
(- code (char-code #\0)))
((<= 65296 code 65305) ;; FULLWIDTH_DIGIT_ZERO, FULLWIDTH_DIGIT_NINE
(- code 65296))
((char<= #\A upper #\Z)
(+ 10 (- code-upper (char-code #\A))))
((<= 65313 (char-code upper) 65318) ;; FULLWIDTH_LATIN_CAPITAL_LETTER_A, FULLWIDTH_LATIN_CAPITAL_LETTER_F
(+ 10 (- code-upper 65313)))
(t nil))))
(if (and potential (< potential radix))
potential
nil)))
(defun graphic-char-p (char)
;; from SBCL/CMUCL:
(let ((n (char-code char)))
(or (< 31 n 127)
(< 159 n))))
(defun standard-char-p (char)
;; from SBCL/CMUCL:
(and (let ((n (char-code char)))
(or (< 31 n 127)
(= n 10)))))
(defun upper-case-p (character)
(char/= character (char-downcase character)))
(defun lower-case-p (character)
(char/= character (char-upcase character)))
(defun both-case-p (character)
(or (upper-case-p character) (lower-case-p character)))
(defun char-int (character)
;; no implementation-defined character attributes
(char-code character))
(defconstant char-code-limit 1114111) ;; 0x10FFFF
(defconstant +ascii-names+
#("NULL" "START_OF_HEADING" "START_OF_TEXT" "END_OF_TEXT" "END_OF_TRANSMISSION" "ENQUIRY" "ACKNOWLEDGE"
"BELL" "Backspace" "Tab" "Newline" "LINE_TABULATION" "Page" "Return" "SHIFT_OUT" "SHIFT_IN"
"DATA_LINK_ESCAPE" "DEVICE_CONTROL_ONE" "DEVICE_CONTROL_TWO" "DEVICE_CONTROL_THREE" "DEVICE_CONTROL_FOUR"
"NEGATIVE_ACKNOWLEDGE" "SYNCHRONOUS_IDLE" "END_OF_TRANSMISSION_BLOCK" "CANCEL" "END_OF_MEDIUM" "SUBSTITUTE"
"ESCAPE" "INFORMATION_SEPARATOR_FOUR" "INFORMATION_SEPARATOR_THREE" "INFORMATION_SEPARATOR_TWO"
"INFORMATION_SEPARATOR_ONE" "Space" "EXCLAMATION_MARK" "QUOTATION_MARK" "NUMBER_SIGN" "DOLLAR_SIGN"
"PERCENT_SIGN" "AMPERSAND" "APOSTROPHE" "LEFT_PARENTHESIS" "RIGHT_PARENTHESIS" "ASTERISK" "PLUS_SIGN"
"COMMA" "HYPHEN-MINUS" "FULL_STOP" "SOLIDUS" "DIGIT_ZERO" "DIGIT_ONE" "DIGIT_TWO" "DIGIT_THREE" "DIGIT_FOUR"
"DIGIT_FIVE" "DIGIT_SIX" "DIGIT_SEVEN" "DIGIT_EIGHT" "DIGIT_NINE" "COLON" "SEMICOLON" "LESS-THAN_SIGN"
"EQUALS_SIGN" "GREATER-THAN_SIGN" "QUESTION_MARK" "COMMERCIAL_AT" "LATIN_CAPITAL_LETTER_A"
"LATIN_CAPITAL_LETTER_B" "LATIN_CAPITAL_LETTER_C" "LATIN_CAPITAL_LETTER_D" "LATIN_CAPITAL_LETTER_E"
"LATIN_CAPITAL_LETTER_F" "LATIN_CAPITAL_LETTER_G" "LATIN_CAPITAL_LETTER_H" "LATIN_CAPITAL_LETTER_I"
"LATIN_CAPITAL_LETTER_J" "LATIN_CAPITAL_LETTER_K" "LATIN_CAPITAL_LETTER_L" "LATIN_CAPITAL_LETTER_M"
"LATIN_CAPITAL_LETTER_N" "LATIN_CAPITAL_LETTER_O" "LATIN_CAPITAL_LETTER_P" "LATIN_CAPITAL_LETTER_Q"
"LATIN_CAPITAL_LETTER_R" "LATIN_CAPITAL_LETTER_S" "LATIN_CAPITAL_LETTER_T" "LATIN_CAPITAL_LETTER_U"
"LATIN_CAPITAL_LETTER_V" "LATIN_CAPITAL_LETTER_W" "LATIN_CAPITAL_LETTER_X" "LATIN_CAPITAL_LETTER_Y"
"LATIN_CAPITAL_LETTER_Z" "LEFT_SQUARE_BRACKET" "REVERSE_SOLIDUS" "RIGHT_SQUARE_BRACKET" "CIRCUMFLEX_ACCENT"
"LOW_LINE" "GRAVE_ACCENT" "LATIN_SMALL_LETTER_A" "LATIN_SMALL_LETTER_B" "LATIN_SMALL_LETTER_C"
"LATIN_SMALL_LETTER_D" "LATIN_SMALL_LETTER_E" "LATIN_SMALL_LETTER_F" "LATIN_SMALL_LETTER_G"
"LATIN_SMALL_LETTER_H" "LATIN_SMALL_LETTER_I" "LATIN_SMALL_LETTER_J" "LATIN_SMALL_LETTER_K"
"LATIN_SMALL_LETTER_L" "LATIN_SMALL_LETTER_M" "LATIN_SMALL_LETTER_N" "LATIN_SMALL_LETTER_O"
"LATIN_SMALL_LETTER_P" "LATIN_SMALL_LETTER_Q" "LATIN_SMALL_LETTER_R" "LATIN_SMALL_LETTER_S"
"LATIN_SMALL_LETTER_T" "LATIN_SMALL_LETTER_U" "LATIN_SMALL_LETTER_V" "LATIN_SMALL_LETTER_W"
"LATIN_SMALL_LETTER_X" "LATIN_SMALL_LETTER_Y" "LATIN_SMALL_LETTER_Z" "LEFT_CURLY_BRACKET" "VERTICAL_LINE"
"RIGHT_CURLY_BRACKET" "TILDE" "Rubout")
"Names/codepoints of the first 128 characters from Unicode 6.2,
except with Common Lisp's suggested changes.
For the first 32 characters ('C0 controls'), the first
'Commonly used alternative alias' is used -- note that this differs from SBCL, which uses abbreviations.")
;; I hope being slightly different from SBCL doesn't bite me down the road.
;; I'll figure out a good way to add the other 21701 names later.
(defun char-name (char)
;; For consistency, I'm using the SBCL convention of the Unicode
;; name, with spaces as underscores. It would be nice to use
;; their "Uxxxx" convention for names I don't know, but there's
;; not much in FORMAT yet. I'm only implementing ASCII names right
;; now, since Unicode is kind of big.
(let ((code (char-code char)))
(if (<= code 127)
(aref +ascii-names+ code)
nil))) ;; for now, no name
(defun name-char (name)
(let ((name-upcase (string-upcase (string name))))
(dotimes (i (length +ascii-names+))
(when (string= name-upcase (string-upcase (aref +ascii-names+ i))) ;; poor man's STRING-EQUAL
(return-from name-char (code-char i))))
nil))
| 17,950 | Common Lisp | .lisp | 320 | 50.05 | 132 | 0.616985 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | f792fafa9f9c6ea8f677f2c0e726b5e463ec800ca6f16bfc76bfecac5bc1ef48 | 32 | [
-1
] |
33 | string.lisp | jscl-project_jscl/src/string.lisp | ;;; string.lisp
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading string.lisp!")
(defun stringp (s)
(stringp s))
(defun string-length (string)
(storage-vector-size string))
(defun make-string (n &key initial-element)
(make-array n :element-type 'character :initial-element initial-element))
(defun char (string index)
(unless (stringp string) (error "~S is not a string" string))
(storage-vector-ref string index))
(defun string (x)
(cond ((stringp x) x)
((symbolp x) (symbol-name x))
(t (make-string 1 :initial-element x))))
(defun string= (s1 s2 &key (start1 0) end1 (start2 0) end2)
(let* ((s1 (string s1))
(s2 (string s2))
(n1 (length s1))
(n2 (length s2))
(end1 (or end1 n1))
(end2 (or end2 n2)))
(when (= (- end2 start2) (- end1 start1))
(dotimes (i (- end2 start2) t)
(unless (char= (char s1 (+ start1 i)) (char s2 (+ start2 i)))
(return-from string= nil))))))
(defun string/= (s1 s2 &key (start1 0) end1 (start2 0) end2)
(let* ((s1 (string s1))
(s2 (string s2))
(n1 (length s1))
(n2 (length s2))
(end1 (or end1 n1))
(end2 (or end2 n2)))
(dotimes (i (max (- end1 start1) (- end2 start2)) nil)
(when (or (>= (+ start1 i) n1)
(>= (+ start2 i) n2))
(return-from string/= (+ start1 i)))
(unless (char= (char s1 (+ start1 i)) (char s2 (+ start2 i)))
(return-from string/= (+ start1 i))))))
(defun compare-strings (s1 s2 start1 end1 start2 end2 char-eq char-lt if-eq if-a-sub-b if-b-sub-a)
;; step through strings S1 and S2, using bounds START1 END1 START2 END2.
;; using character comparison functions CHAR-EQ (equality) and CHAR-LT (less-than),
;; find the first difference, if any, and return its index.
;; the IF-* params say what to do if the strings are equal, or a strict prefix substring of the other:
;; if T, it returns the first different index. if NIL, it returns NIL.
(let* ((s1 (string s1))
(s2 (string s2))
(end1 (or end1 (length s1)))
(end2 (or end2 (length s2)))
(len-1 (- end1 start1))
(len-2 (- end2 start2)))
(dotimes (i (max len-1 len-2) (if if-eq (+ start1 i) nil))
(when (= i len-1) ;; ran off the end of s1
(return-from compare-strings (if if-a-sub-b (+ start1 i) nil)))
(when (= i len-2) ;; ran off the end of s2
(return-from compare-strings (if if-b-sub-a (+ start1 i) nil)))
(let ((c1 (char s1 (+ start1 i)))
(c2 (char s2 (+ start2 i))))
(when (not (funcall char-eq c1 c2)) ;; found a difference
(return-from compare-strings
(if (not (funcall char-lt c1 c2))
(+ start1 i)
nil)))))))
(defun string< (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char= #'char> nil t nil))
(defun string> (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char= #'char< nil nil t))
(defun string<= (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char= #'char> t t nil))
(defun string>= (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char= #'char< t nil t))
(defun string-lessp (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char-equal #'char-greaterp nil t nil))
(defun string-greaterp (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char-equal #'char-lessp nil nil t))
(defun string-not-greaterp (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char-equal #'char-greaterp t t nil))
(defun string-not-lessp (s1 s2 &key (start1 0) end1 (start2 0) end2)
(compare-strings s1 s2 start1 end1 start2 end2
#'char-equal #'char-lessp t nil t))
(define-setf-expander char (string index)
(let ((g!string (gensym))
(g!index (gensym))
(g!value (gensym)))
(values (list g!string g!index)
(list string index)
(list g!value)
`(aset ,g!string ,g!index ,g!value)
`(char ,g!string ,g!index))))
(defun concat (&rest strs)
(flet ((concat-two (str1 str2)
(concatenate-storage-vector str1 str2)))
(!reduce #'concat-two strs "")))
(defun string-upcase (string &key (start 0) end)
(let* ((string (string string))
(new (make-string (length string))))
(dotimes (i (length string) new)
(aset new i
(if (and (or (null start) (>= i start))
(or (null end) (< i end)))
(char-upcase (char string i))
(char string i))))))
(defun nstring-upcase (string &key (start 0) end)
(let ((end (or end (length string))))
(dotimes (i (- end start) string)
(aset string (+ start i)
(char-upcase (char string (+ start i)))))))
(defun string-downcase (string &key (start 0) end)
(let* ((string (string string))
(new (make-string (length string))))
(dotimes (i (length string) new)
(aset new i
(if (and (or (null start) (>= i start))
(or (null end) (< i end)))
(char-downcase (char string i))
(char string i))))))
(defun nstring-downcase (string &key (start 0) end)
(let ((end (or end (length string))))
(dotimes (i (- end start) string)
(aset string (+ start i)
(char-downcase (char string (+ start i)))))))
(defun string-capitalize (string &key (start 0) end)
(let* ((string (string string))
(new (make-string (length string)))
(just-saw-alphanum-p nil))
(dotimes (i (length string) new)
(aset new i
(cond ((or (and start (< i start))
(and end (> i end)))
(char string i))
((or (= i start)
(not just-saw-alphanum-p))
(char-upcase (char string i)))
(t
(char-downcase (char string i)))))
(setq just-saw-alphanum-p (alphanumericp (char string i))))))
(defun nstring-capitalize (string &key (start 0) end)
(let ((end (or end (length string)))
(just-saw-alphanum-p nil))
(dotimes (i (- end start) string)
(aset string (+ start i)
(if (or (zerop i)
(not just-saw-alphanum-p))
(char-upcase (char string (+ start i)))
(char-downcase (char string (+ start i)))))
(setq just-saw-alphanum-p (alphanumericp (char string (+ start i)))))))
(defun string-equal (s1 s2 &key start1 end1 start2 end2)
(let* ((s1 (string s1))
(s2 (string s2))
(n1 (length s1))
(n2 (length s2))
(start1 (or start1 0))
(end1 (or end1 n1))
(start2 (or start2 0))
(end2 (or end2 n2)))
(when (= (- end2 start2) (- end1 start1))
(dotimes (i (- end2 start2) t)
(unless (char-equal (char s1 (+ start1 i)) (char s2 (+ start2 i)))
(return-from string-equal nil))))))
;; just like string/= but with char-equal instead of char=
(defun string-not-equal (s1 s2 &key (start1 0) end1 (start2 0) end2)
(let* ((s1 (string s1))
(s2 (string s2))
(n1 (length s1))
(n2 (length s2))
(end1 (or end1 n1))
(end2 (or end2 n2)))
(dotimes (i (max (- end1 start1) (- end2 start2)) nil)
(when (or (>= (+ start1 i) n1)
(>= (+ start2 i) n2))
(return-from string-not-equal (+ start1 i)))
(unless (char-equal (char s1 (+ start1 i)) (char s2 (+ start2 i)))
(return-from string-not-equal (+ start1 i))))))
(defun string-trim (character-bag string)
(string-left-trim character-bag (string-right-trim character-bag string)))
(defun string-left-trim (character-bag string)
(let* ((string (string string))
(n (length string))
(start (or (position-if-not (lambda (c) (find c character-bag)) string) n)))
(subseq string start)))
(defun string-right-trim (character-bag string)
(let* ((string (string string))
(n (length string)))
(dotimes (i n "")
(when (not (find (char string (- n i 1)) character-bag))
(return-from string-right-trim (subseq string 0 (- n i)))))))
| 9,186 | Common Lisp | .lisp | 205 | 36.868293 | 104 | 0.580883 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 971a43786c7947c1652253a8525cea415843e8af1814d0b08c7f3c8a73736e01 | 33 | [
-1
] |
34 | bootstrap.lisp | jscl-project_jscl/src/clos/bootstrap.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;;
;;; CLOS Bootstrap
;;; Original code closette.lisp, lines 1317-1403
;;; Major modification for JSCL @vlad-km, 2019
;;;
;;; note: it works ? don't touch it!!!
(/debug "build standard mop hierarchy")
;;; timestamp. todo: remove it
(defvar *boot-stage-timestamp* (get-internal-real-time))
(defun boot-stage-1 ()
;; 1. Figure out standard-class's slots.
;; 2. Create the standard-class metaobject by hand.
(setq *the-class-standard-class*
(allocate-std-instance
:class 'tba
:slots (make-array (length *the-slots-of-standard-class*)
:initial-element *secret-unbound-value*)))
;; 3. Install standard-class's (circular) class-of link.
(setf (std-instance-class *the-class-standard-class*) *the-class-standard-class*)
;; 4. Fill in standard-class's class-slots.
(setf-class-slots *the-class-standard-class* *the-slots-of-standard-class*)
(hash-class-slots-names *the-class-standard-class*)
;; 5. Hand build the class t so that it has no direct superclasses.
(setf-find-class 't
(let ((class (std-allocate-instance *the-class-standard-class*)))
(setf-class-name class 't)
(setf-class-direct-subclasses class ())
(setf-class-direct-superclasses class ())
(setf-class-direct-methods class ())
(setf-class-direct-slots class ())
(setf-class-precedence-list class ())
(setf-class-slots class ())
(hash-class-slots-names class)
class))
;; 6. Create the other superclass of standard-class (i.e., standard-object).
(ensure-class 'standard-object
:direct-superclasses (list (!find-class 't))
:direct-slots '())
;; 7.
(setq *the-class-standard-class*
(ensure-class 'standard-class
:direct-superclasses nil
:direct-slots
(LIST
(LIST :NAME (QUOTE NAME) :INITARGS (QUOTE (:NAME)))
(LIST :NAME (QUOTE DIRECT-SUPERCLASSES) :INITARGS (QUOTE (:DIRECT-SUPERCLASSES)))
(LIST :NAME (QUOTE DIRECT-SLOTS))
(LIST :NAME (QUOTE CLASS-PRECEDENCE-LIST))
(LIST :NAME (QUOTE EFFECTIVE-SLOTS))
(LIST :NAME (QUOTE DIRECT-SUBCLASSES) :INITFORM (QUOTE NIL) :INITFUNCTION (FUNCTION (LAMBDA NIL NIL)))
(LIST :NAME (QUOTE DIRECT-METHODS) :INITFORM (QUOTE NIL) :INITFUNCTION (FUNCTION (LAMBDA NIL NIL))))
))
;; 8. Replace all (3) existing pointers to the skeleton with real one.
(setf (std-instance-class (!find-class 't))
*the-class-standard-class*)
(setf (std-instance-class (!find-class 'standard-object))
*the-class-standard-class*)
(setf (std-instance-class *the-class-standard-class*)
*the-class-standard-class*)
) ;; end boot-stage 1
(defun boot-stage-2 ()
(ensure-class 'symbol
:direct-superclasses '()
:direct-slots '())
(ensure-class 'sequence
:direct-superclasses '()
:direct-slots '())
(ensure-class 'array
:direct-superclasses '()
:direct-slots '())
(ensure-class 'number
:direct-superclasses '()
:direct-slots '())
(ensure-class 'character
:direct-superclasses '()
:direct-slots '())
(ensure-class 'js-object
:direct-superclasses '()
:direct-slots '())
(ensure-class 'function
:direct-superclasses '()
:direct-slots '())
(ensure-class 'hash-table
:direct-superclasses '()
:direct-slots '())
(ensure-class 'stream
:direct-superclasses '()
:direct-slots '())
(ensure-class 'structure
:direct-superclasses '()
:direct-slots '())
(ensure-class 'package
:direct-superclasses '()
:direct-slots '())
(ensure-class 'keyword
:direct-superclasses (LIST (!FIND-CLASS (QUOTE symbol)))
:direct-slots '())
(ensure-class 'list
:direct-superclasses (LIST (!FIND-CLASS (QUOTE sequence)))
:direct-slots '())
(ensure-class 'null
:direct-superclasses (LIST (!FIND-CLASS (QUOTE SYMBOL)) (!FIND-CLASS (QUOTE LIST)))
:direct-slots '())
(ensure-class 'cons
:direct-superclasses (LIST (!FIND-CLASS (QUOTE list)))
:direct-slots '())
(ensure-class 'vector
:direct-superclasses (LIST (!FIND-CLASS (QUOTE array)) (!FIND-CLASS (QUOTE sequence)))
:direct-slots '())
(ensure-class 'string
:direct-superclasses (LIST (!FIND-CLASS (QUOTE vector)))
:direct-slots '())
(ensure-class 'real
:direct-superclasses (LIST (!FIND-CLASS (QUOTE number)))
:direct-slots '())
(ensure-class 'rational
:direct-superclasses (LIST (!FIND-CLASS (QUOTE real)))
:direct-slots '())
(ensure-class 'integer
:direct-superclasses (LIST (!FIND-CLASS (QUOTE rational)))
:direct-slots '())
(ensure-class 'float
:direct-superclasses (LIST (!FIND-CLASS (QUOTE real)))
:direct-slots '())
;; 10. Define the other standard metaobject classes.
(setq *the-class-standard-gf*
(ensure-class 'standard-generic-function
:direct-superclasses '()
:direct-slots (LIST
(LIST :NAME (QUOTE NAME) :INITARGS (QUOTE (:NAME)))
(LIST :NAME (QUOTE LAMBDA-LIST) :INITARGS (QUOTE (:LAMBDA-LIST)))
(LIST :NAME (QUOTE METHODS)
:INITFORM (QUOTE NIL)
:INITFUNCTION (FUNCTION (LAMBDA NIL NIL)))
(LIST :NAME (QUOTE METHOD-CLASS)
:INITARGS (QUOTE (:METHOD-CLASS)))
(LIST :NAME (QUOTE DISCRIMINATING-FUNCTION))
(LIST :NAME (QUOTE CLASSES-TO-EMF-TABLE)
:INITFORM (QUOTE (MAKE-HASH-TABLE :TEST (FUNCTION EQUAL)))
:INITFUNCTION (FUNCTION (LAMBDA NIL (MAKE-HASH-TABLE :TEST (FUNCTION EQUAL))))))))
(setq *the-class-standard-method*
(ensure-class 'standard-method
:direct-superclasses '()
:direct-slots (LIST
(LIST :NAME (QUOTE LAMBDA-LIST) :INITARGS (QUOTE (:LAMBDA-LIST)))
(LIST :NAME (QUOTE QUALIFIERS) :INITARGS (QUOTE (:QUALIFIERS)))
(LIST :NAME (QUOTE SPECIALIZERS) :INITARGS (QUOTE (:SPECIALIZERS)))
(LIST :NAME (QUOTE BODY) :INITARGS (QUOTE (:BODY)))
(LIST :NAME (QUOTE GENERIC-FUNCTION)
:INITFORM (QUOTE NIL)
:INITFUNCTION (FUNCTION (LAMBDA NIL NIL)))
(LIST :NAME (QUOTE FUNCTION)))))
) ;; end boot-stage-2
(boot-stage-1)
(boot-stage-2)
;;; timestamp. todo: remove it
(/debug (concat " elapsed time:"
(/ (- (get-internal-real-time) *boot-stage-timestamp*) internal-time-units-per-second 1.0) " sec."))
;; Voila! The class hierarchy is in place.
;; (It's now okay to define generic functions and methods.)
;;; EOF
| 7,903 | Common Lisp | .lisp | 162 | 34.728395 | 125 | 0.533134 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | f90f72b51a86ea59f74787c107dc0617a80088d42a18ec370ffac0efad92d19f | 34 | [
-1
] |
35 | std-generic.lisp | jscl-project_jscl/src/clos/std-generic.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;;
;;; Generic function metaobjects and standard-generic-function
;;;
;;; Original code closette.lisp, lines 729-918
;;; Modification for JSCL @vlad-km, 2019
;;;
;;; JSCL compilation mode - :both
;;;
;;; Release note
;;; - The names of some functions have been changed from !name to !name, to prevent naming conflicts
;;; when host compiling. See FSET section from macros.lisp for full list.
;;; - Some forms (setf ...) have been replaced by (setf-...).
;;; So, added setf-... functions
;;; - In some places the argument lists were corrected for JSCL.
;;; - Macro DEFGENERIC moved to macros.lisp
;;; - all modification marked with tag @vlad-km
;;;
(/debug "loading std-generic")
;;; @vlad-km note: its artefact from original
;;;not used in jscl release
#+nil
(defparameter *the-defclass-standard-generic-function*
'(!defclass standard-generic-function ()
((name :initarg :name) ; :accessor generic-function-name
(lambda-list ; :accessor generic-function-lambda-list
:initarg :lambda-list)
(methods :initform ()) ; :accessor generic-function-methods
(method-class ; :accessor generic-function-method-class
:initarg :method-class)
(discriminating-function) ; :accessor generic-function-
; -discriminating-function
(classes-to-emf-table ; :accessor classes-to-emf-table
:initform (make-hash-table :test #'equal)))))
(defvar *the-class-standard-gf*) ;standard-generic-function's class metaobject
;;; generic-function-name
(defun generic-function-name (gf)
(!slot-value gf 'name))
;;; @vlad-km
(defun setf-generic-function-name (gf new-value)
(setf-slot-value gf 'name new-value))
;;; generic-function-lambda-list
(defun generic-function-lambda-list (gf)
(!slot-value gf 'lambda-list))
;;; @vlad-km
(defun setf-generic-function-lambda-list (gf new-value)
(setf-slot-value gf 'lambda-list new-value))
;;; generic-function-methods
(defun generic-function-methods (gf)
(!slot-value gf 'methods))
;;; @vlad-km
(defun setf-generic-function-methods (gf new-value)
(setf-slot-value gf 'methods new-value))
;;; for (push method (generic-function-method gf))
(defun push-generic-function-methods (new-value gf)
(let ((lst (!slot-value gf 'methods)))
(setf-slot-value gf 'methods (cons new-value lst))))
;;; generic-function-discriminating-function
(defun generic-function-discriminating-function (gf)
(!slot-value gf 'discriminating-function))
;;; @vlad-km
(defun setf-generic-function-discriminating-function (gf new-value)
(setf-slot-value gf 'discriminating-function new-value))
;;; generic-function-method-class
(defun generic-function-method-class (gf)
(!slot-value gf 'method-class))
;;; @vlad-km
(defun setf-generic-function-method-class (gf new-value)
(setf-slot-value gf 'method-class new-value))
;;; Internal accessor for effective method function table
(defun classes-to-emf-table (gf)
(!slot-value gf 'classes-to-emf-table))
;;; @vlad-km
(defun setf-classes-to-emf-table (gf new-value)
(setf-slot-value gf 'classes-to-emf-table new-value))
;;;
;;; Method metaobjects and standard-method
;;;
;;; @vlad-km. This artefact from original
#+nil
(defparameter *the-defclass-standard-method*
'(!defclass standard-method ()
((lambda-list :initarg :lambda-list) ; :accessor method-lambda-list
(qualifiers :initarg :qualifiers) ; :accessor method-qualifiers
(specializers :initarg :specializers) ; :accessor method-specializers
(body :initarg :body) ; :accessor method-body
(generic-function :initform nil) ; :accessor method-generic-function
(function)))) ; :accessor method-function
(defvar *the-class-standard-method*) ;standard-method's class metaobject
;;; method-lambda-list
(defun method-lambda-list (method)
(!slot-value method 'lambda-list))
;;; @vlad-km
(defun setf-method-lambda-list (method new-value)
(setf-slot-value method 'lambda-list new-value))
;;; method-qualifiers
(defun !method-qualifiers (method)
(!slot-value method 'qualifiers))
;;; @vlad-km
(defun setf-method-qualifiers (method new-value)
(setf-slot-value method 'qualifiers new-value))
;;; method-specializers
(defun !method-specializers (method)
(!slot-value method 'specializers))
;;; @vlad-km
(defun setf-method-specializers (method new-value)
(setf-slot-value method 'specializers new-value))
;;; method-body
(defun method-body (method)
(!slot-value method 'body))
;;; @vlad-km
(defun setf-method-body (method new-value)
(setf-slot-value method 'body new-value))
;;; method-generic-function
(defun method-generic-function (method)
(!slot-value method 'generic-function))
;;; @vlad-km
(defun setf-method-generic-function (method new-value)
(setf-slot-value method 'generic-function new-value))
;;; method-function
(defun method-function (method)
(!slot-value method 'function))
;;; @vlad-km
(defun setf-method-function (method new-value)
(setf-slot-value method 'function new-value))
;;; @vlad-km
(defun (setf method-function) (new-value method)
(setf-slot-value method 'function new-value))
(eval-always
(defun canonicalize-defgeneric-ll (lst)
(if lst
`',lst
'())))
(eval-always
(defun canonicalize-defgeneric-option (option)
(case (car option)
(:generic-function-class
(list ':generic-function-class
`(!find-class ',(cadr option))))
(:method-class
(list ':method-class
`(!find-class ',(cadr option))))
(t (list `',(car option) `',(cadr option)))))
(defun canonicalize-defgeneric-options (options)
(mapappend #'canonicalize-defgeneric-option options)))
;;; find-generic-function looks up a generic function by name. It's an
;;; artifact of the fact that our generic function metaobjects can't legally
;;; be stored a symbol's function value.
;;; @vlad-km. must be equal predicate. its worked? dont touch it!
(defparameter *generic-function-table* (make-hash-table :test #'equal))
(defun find-generic-function (symbol &optional (errorp t))
(let ((gf (gethash symbol *generic-function-table* nil)))
(if (and (null gf) errorp)
(error "No generic function named ~S." symbol)
gf)))
;;; @vlad-km
(defun setf-find-generic-function (symbol new-value)
(setf (gethash symbol *generic-function-table*) new-value))
;;; ensure-generic-function
;;; @vlad-km
(defun !ensure-generic-function (function-name &rest all-keys)
(let ((egf (find-generic-function function-name nil)))
(if egf
;; return exists
egf
;; or create this
(let*
((generic-function-class (get-keyword-from all-keys :generic-function-class *the-class-standard-gf*))
(method-class (get-keyword-from all-keys :method-class *the-class-standard-method*))
(gf (apply (if (eq generic-function-class *the-class-standard-gf*)
#'make-instance-standard-generic-function
#'make-instance)
generic-function-class
:name function-name
:method-class method-class
all-keys)))
(setf-find-generic-function function-name gf)
gf))))
;;; finalize-generic-function
;;; N.B. Same basic idea as finalize-inheritance. Takes care of recomputing
;;; and storing the discriminating function, and clearing the effective method
;;; function table.
;;; @vlad-km
;;; hardcode version macro for (setf generic name) syntax
;;; note: no good idea.
(defun makdefgf (sfn sname fn)
(let ()
(FSET sfn fn)
(PUSH (CONS sname
(LAMBDA (&REST args)
(DESTRUCTURING-BIND (&REST ARGUMENTS) args
(LET ((G!ARGS (MAPCAR (LAMBDA (IT) (GENSYM)) ARGUMENTS))
(G!NEWVALUE (GENSYM))
(G!SETTER sfn)
(G!GETTER sname))
(VALUES
(list G!ARGS)
ARGUMENTS
(LIST G!NEWVALUE)
(LIST* G!SETTER G!NEWVALUE ARGUMENTS)
(CONS G!GETTER ARGUMENTS))))))
JSCL::*SETF-EXPANDERS*) ))
;;; @vlad-km
(defun finalize-generic-function (gf)
(setf-generic-function-discriminating-function gf
(funcall (if (eq (!class-of gf) *the-class-standard-gf*)
#'std-compute-discriminating-function
#'compute-discriminating-function)
gf))
(let* ((fname (generic-function-name gf))
(sfname (setf-function-symbol fname)))
(cond ((and (consp fname) (equal (car fname) 'setf))
(makdefgf sfname (cadr fname) (generic-function-discriminating-function gf)))
(t
(fset sfname (generic-function-discriminating-function gf))))
;; @vlad-km
;; classes-to-emf-table must be under equal hash-function
;; for function cashed
(setf-classes-to-emf-table gf (make-hash-table :test #'equal))
(values)))
;;; make-instance-standard-generic-function creates and initializes an
;;; instance of standard-generic-function without falling into method lookup.
;;; However, it cannot be called until standard-generic-function exists.
;;; @vlad-km
(defun make-instance-standard-generic-function (generic-function-class &rest all-keys)
(declare (ignore generic-function-class))
(let ((name (get-keyword-from all-keys :name))
(lambda-list (get-keyword-from all-keys :lambda-list))
(method-class (get-keyword-from all-keys :method-class))
(gf (std-allocate-instance *the-class-standard-gf*)))
(setf-generic-function-name gf name)
(setf-generic-function-lambda-list gf lambda-list)
(setf-generic-function-methods gf ())
(setf-generic-function-method-class gf method-class)
(finalize-generic-function gf)
gf))
;;; EOF
| 10,197 | Common Lisp | .lisp | 237 | 36.805907 | 113 | 0.660024 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 43ecd0af37cad0c3395f531fa431e3606e01deba0ebac7e7aa8f75f418c43409 | 35 | [
-1
] |
36 | tools.lisp | jscl-project_jscl/src/clos/tools.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; debug tools
;;; From closette-test.lisp
(defun subclasses* (class)
(remove-duplicates
(cons class
(mapappend #'subclasses*
(class-direct-subclasses class)))))
;;; (export '(subclasses))
(defun subclasses (class &optional names)
(let ((result (remove class (subclasses* class))))
(if names (mapcar #'class-name result)
result)))
;;; (export '(in-order-p))
(defun in-order-p (c1 c2)
(flet ((in-order-at-subclass-p (sub)
(let ((cpl (class-precedence-list sub)))
(not (null (member c2 (cdr (member c1 cpl))))))))
(or (eq c1 c2)
(every #'in-order-at-subclass-p
(intersection (subclasses* c1)
(subclasses* c2))))))
;;; display defclass
(export '(display-defclass))
(defun display-defclass (class-name)
(printer-defclass (generate-defclass (find-class class-name)))
(values))
(defun printer-defclass (expr)
(print* 'defclass (first expr))
(print* " " (second expr))
(dolist (it (car (nthcdr 2 expr)))
(print* " " it)))
(defun generate-defclass (class)
`(,(class-name class)
,(mapcar #'class-name (cdr (class-precedence-list class)))
,(mapcar #'(lambda (slot)
(generate-inherited-slot-specification class slot))
(class-slots class))))
(defun generate-slot-specification (slot)
`(,(slot-definition-name slot)
,@(when (slot-definition-initfunction slot)
`(:initform ,(slot-definition-initform slot)))
,@(when (slot-definition-initargs slot)
(mapappend #'(lambda (initarg) `(:initarg ,initarg))
(slot-definition-initargs slot)))
,@(unless (eq (slot-definition-allocation slot) ':instance)
`(:allocation ,(slot-definition-allocation slot)))
,@(when (slot-definition-readers slot)
(mapappend #'(lambda (reader) `(:reader ,reader))
(slot-definition-readers slot)))
,@(when (slot-definition-writers slot)
(mapappend #'(lambda (writer) `(:writer ,writer))
(slot-definition-writers slot)))))
(defun generate-inherited-slot-specification (class slot)
(let* ((source-class
(find-if #'(lambda (superclass)
(find (slot-definition-name slot)
(class-direct-slots superclass)
:key #'slot-definition-name))
(class-precedence-list class)))
(generated-slot-spec
(generate-slot-specification slot)))
(if (eq source-class class)
generated-slot-spec
(append generated-slot-spec
`(:inherited-from ,(class-name source-class))))))
;;; display generate-defgeneric
(defun generate-defgeneric (gf)
`(defgeneric ,(generic-function-name gf)
,(generic-function-lambda-list gf)))
(export '(display-defgeneric))
(defun display-defgeneric (arg)
(let ((gf (if (symbolp arg) (find-generic-function arg) arg)))
(print (generate-defgeneric gf))
(terpri)
(values)))
;;; display-generic-function
(defun generate-defmethod (method &key show-body)
`(defmethod ,(generic-function-name (method-generic-function method))
,@(method-qualifiers method)
,(generate-specialized-arglist method)
,@(when show-body (list (method-body method)))))
(defun generate-specialized-arglist (method)
(let* ((specializers (method-specializers method))
(lambda-list (method-lambda-list method))
(number-required (length specializers)))
(append (mapcar #'(lambda (arg class)
(if (eq class (find-class 't))
arg
`(,arg ,(class-name class))))
(subseq lambda-list 0 number-required)
specializers)
(subseq lambda-list number-required))))
(defun generate-specialized-arglist-1 (specializers lambda-list)
(let ((number-required (length specializers)))
(append (mapcar #'(lambda (arg class)
(if (eq class (find-class 't))
arg
`(,arg ,(class-name class))))
(subseq lambda-list 0 number-required)
specializers)
(subseq lambda-list number-required))))
(export '(display-generic-function))
(defun display-generic-function (gf-name &key show-body)
(display-defgeneric gf-name)
(dolist (method (generic-function-methods (find-generic-function gf-name)))
(print (generate-defmethod method :show-body show-body)))
(values))
;;; all-generic
(defun all-generic-functions (&key names)
(let ((result))
(setq result
(remove-duplicates
(mapappend #'class-direct-generic-functions
(subclasses* (find-class 't)))))
(if names
(mapcar #'generic-function-name result)
result)))
(defun class-direct-generic-functions (class)
(remove-duplicates
(mapcar #'method-generic-function
(class-direct-methods class))))
;;; relevant generic function
(defun reader-method-p (method)
(let ((specializers (method-specializers method)))
(and (= (length specializers) 1)
(member (generic-function-name (method-generic-function method))
(mapappend #'slot-definition-readers
(class-direct-slots (car specializers)))
:test #'equal))))
(defun writer-method-p (method)
(let ((specializers (method-specializers method)))
(and (= (length specializers) 2)
(member (generic-function-name (method-generic-function method))
(mapappend #'slot-definition-writers
(class-direct-slots (cadr specializers)))
:test #'equal))))
(defun relevant-generic-functions (class ceiling &key elide-accessors-p (names nil))
(let ((fclass (if (symbolp class) (find-class class) class))
(fceiling (if (symbolp ceiling) (find-class ceiling) ceiling))
(result))
(setq result
(remove-duplicates
(mapcar #'method-generic-function
(remove-if
#'(lambda (m)
(and elide-accessors-p
(or (reader-method-p m)
(writer-method-p m))))
(mapappend #'class-direct-methods
(set-difference (class-precedence-list fclass)
(class-precedence-list fceiling)))))))
(if names
(mapcar #'generic-function-name result)
result)))
;;; EOF
| 7,101 | Common Lisp | .lisp | 156 | 32.99359 | 89 | 0.560619 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 66f11f0f65cbb9ff4cbc30677e7bb9a689a6128ede142067b037e672d78660e5 | 36 | [
-1
] |
37 | std-method.lisp | jscl-project_jscl/src/clos/std-method.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; DEFMETHOD
;;; Original code closette.lisp, lines 919-1316
;;; Modification for JSCL @vlad-km, 2019
;;;
;;; JSCL compilation mode - :both
;;;
;;; Release note
;;; - The names of some functions have been changed from !name to !name, to prevent naming conflicts
;;; when host compiling. See FSET section from macros.lisp for full list.
;;; - Some forms (setf ...) have been replaced by (setf-...).
;;; So, added setf-... functions
;;; - In some places the argument lists were corrected for JSCL.
;;; - Macro DEFMETHOD moved to macros.lisp
;;; - all modification marked with tag @vlad-km
;;;
(/debug "loading std-method")
(eval-always
(defun canonicalize-specializer (specializer)
`(!find-class ',specializer))
(defun canonicalize-specializers (specializers)
(if specializers
`(list ,@(mapcar #'canonicalize-specializer specializers))
'())))
(eval-always
(defun parse-defmethod (args)
(let ((fn-spec (car args))
(qualifiers ())
(specialized-lambda-list nil)
(body ())
(parse-state :qualifiers))
(dolist (arg (cdr args))
(ecase parse-state
(:qualifiers
(if (and (atom arg) (not (null arg)))
(push-on-end arg qualifiers)
(progn (setq specialized-lambda-list arg)
(setq parse-state :body))))
(:body (push-on-end arg body))))
(values fn-spec
qualifiers
(extract-lambda-list specialized-lambda-list)
(extract-specializers specialized-lambda-list)
(list* 'block
(if (consp fn-spec)
(cadr fn-spec)
fn-spec)
body)))))
;;; Several tedious functions for analyzing lambda lists
(defun required-portion (gf args)
(let ((number-required (length (gf-required-arglist gf))))
(when (< (length args) number-required)
(error "Too few arguments to generic function ~S." gf))
(subseq args 0 number-required)))
(defun gf-required-arglist (gf)
(let ((plist
(analyze-lambda-list
(generic-function-lambda-list gf))))
(getf plist ':required-args)))
(eval-always
(defun extract-lambda-list (specialized-lambda-list)
(let* ((plist (analyze-lambda-list specialized-lambda-list))
(requireds (getf plist ':required-names))
(rv (getf plist ':rest-var))
(ks (getf plist ':key-args))
(aok (getf plist ':allow-other-keys))
(opts (getf plist ':optional-args))
(auxs (getf plist ':auxiliary-args)))
`(,@requireds
,@(if rv `(&rest ,rv) ())
,@(if (or ks aok) `(&key ,@ks) ())
,@(if aok '(&allow-other-keys) ())
,@(if opts `(&optional ,@opts) ())
,@(if auxs `(&aux ,@auxs) ())))))
(eval-always
(defun extract-specializers (specialized-lambda-list)
(let ((plist (analyze-lambda-list specialized-lambda-list)))
(getf plist ':specializers))))
(eval-always
(defvar *lambda-list-keywords* '(&optional &rest &key &aux &allow-other-keys)))
(eval-always
(defun analyze-lambda-list (lambda-list)
(labels ((make-keyword (symbol)
(intern (symbol-name symbol)
(find-package 'keyword)))
(get-keyword-from-arg (arg)
(if (listp arg)
(if (listp (car arg))
(caar arg)
(make-keyword (car arg)))
(make-keyword arg))))
(let ((keys ()) ; Just the keywords
(key-args ()) ; Keywords argument specs
(required-names ()) ; Just the variable names
(required-args ()) ; Variable names & specializers
(specializers ()) ; Just the specializers
(rest-var nil)
(optionals ())
(auxs ())
(allow-other-keys nil)
(state :parsing-required))
(dolist (arg lambda-list)
(if (member arg *lambda-list-keywords*)
(ecase arg
(&optional
(setq state :parsing-optional))
(&rest
(setq state :parsing-rest))
(&key
(setq state :parsing-key))
(&allow-other-keys
(setq allow-other-keys 't))
(&aux
(setq state :parsing-aux)))
(case state
(:parsing-required
(push-on-end arg required-args)
(if (listp arg)
(progn (push-on-end (car arg) required-names)
(push-on-end (cadr arg) specializers))
(progn (push-on-end arg required-names)
(push-on-end 't specializers))))
(:parsing-optional (push-on-end arg optionals))
(:parsing-rest (setq rest-var arg))
(:parsing-key
(push-on-end (get-keyword-from-arg arg) keys)
(push-on-end arg key-args))
(:parsing-aux (push-on-end arg auxs)))))
(list :required-names required-names
:required-args required-args
:specializers specializers
:rest-var rest-var
:keywords keys
:key-args key-args
:auxiliary-args auxs
:optional-args optionals
:allow-other-keys allow-other-keys)))))
;;; ensure method
;;; @vlad-km
;;; TODO: refactor this - remove canonical helpers from macro
;;; add !ensure-generic-function call, if GF not exists
(defun ensure-method (gf &rest all-keys)
(let ((new-method
(apply
(if (eq (generic-function-method-class gf) *the-class-standard-method*)
'make-instance-standard-method
'make-instance)
(generic-function-method-class gf)
all-keys)))
(!add-method gf new-method)
new-method))
;;; make-instance-standard-method creates and initializes an instance of
;;; standard-method without falling into method lookup. However, it cannot
;;; be called until standard-method exists.
;;;
;;; @vlad-km
(defun make-instance-standard-method (method-class &key lambda-list qualifiers specializers body cmf)
(declare (ignore method-class))
(let ((method (std-allocate-instance *the-class-standard-method*)))
(setf-method-lambda-list method lambda-list)
(setf-method-qualifiers method qualifiers)
(setf-method-specializers method specializers)
(setf-method-body method body)
(setf-method-generic-function method nil)
(setf-method-function method cmf)
method))
;;; add-method
;;; N.B. This version first removes any existing method on the generic function
;;; with the same qualifiers and specializers. It's a pain to develop
;;; programs without this feature of full CLOS.
;;;
;;; @vlad-km
(defun !add-method (gf method)
(let ((old-method
(!find-method gf
(!method-qualifiers method)
(!method-specializers method)
nil) ))
(when old-method (!remove-method gf old-method)))
(setf-method-generic-function method gf)
;; note: push method
(push-generic-function-methods method gf)
(dolist (specializer (!method-specializers method))
(pushnew-class-direct-methods method specializer))
(finalize-generic-function gf)
method)
;;; @vlad-km
(defun !remove-method (gf method)
(setf-generic-function-methods gf
(remove method (generic-function-methods gf)))
(setf-method-generic-function method nil)
(dolist (class (!method-specializers method))
(setf-class-direct-methods
class
(remove method (class-direct-methods class))))
(finalize-generic-function gf)
method)
;;;
(defun !find-method (gf qualifiers specializers &optional (errorp t))
(let ((method
(find-if #'(lambda (it)
(and (equal qualifiers
(!method-qualifiers it))
(equal specializers
(!method-specializers it))))
(generic-function-methods gf))))
(if (and (null method) errorp)
(error "No such method for ~S." (generic-function-name gf))
method)))
;;; Reader and write methods
;;; @vlad-km. added :cmf
;;; note: accessor form (setf ) dont work under jscl:compile-application
;;;
(defun add-reader-method (class fn-name slot-name)
(let* ((slname `(quote ,slot-name))
(body `(!slot-value object ,slname))
(fname fn-name))
(ensure-method
(!ensure-generic-function fn-name :lambda-list '(object))
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body body
:cmf (lambda (args &optional ignore-it)
(apply #'(lambda (object) (!slot-value object slot-name))
args)))))
;;; @vlad-km. added :cmf
(defun add-writer-method (class fn-name slot-name)
(let* ((slname `(quote ,slot-name))
(body `(!slot-value object ,slname))
(fname fn-name))
(ensure-method
(!ensure-generic-function fname :lambda-list '(new-value object))
:lambda-list '(new-value object)
:qualifiers ()
:specializers (list (!find-class 't) class)
:body body
:cmf #'(lambda (args &optional ignore-it)
(apply #'(lambda (new-value object) (setf (!slot-value object slot-name) new-value))
args)))))
;;; Generic function invocation
;;; apply-generic-function ???
(defun apply-generic-function (gf args)
(apply (generic-function-discriminating-function gf) args))
;;; compute-discriminating-function
;;;
;;; @vlad-km. added function.
(defun mak-classes-mask (classes)
(let ((local))
(dolist (it classes) (push (class-name it) local))
;; @vlad-km note: its too much. do compare on the reverse list
;;just return local. its gain 0.01s
(reverse local)))
;;; @vlad-km. fix emfun hash
(defun std-compute-discriminating-function (gf)
#'(lambda (&rest args)
(let* ((classes (mapcar #'!class-of
(required-portion gf args)))
(emfun (gethash (mak-classes-mask classes) (classes-to-emf-table gf) nil)))
(if emfun
(funcall emfun args)
(slow-method-lookup gf args classes)))))
;;; @vlad-km. fix emfun hash
(defun slow-method-lookup (gf args classes)
(let* ((applicable-methods
(compute-applicable-methods-using-classes gf classes))
(emfun
(funcall
(if (eq (!class-of gf) *the-class-standard-gf*)
#'std-compute-effective-method-function
#'compute-effective-method-function)
gf applicable-methods)))
(setf (gethash (mak-classes-mask classes) (classes-to-emf-table gf)) emfun)
(funcall emfun args)))
(defun compute-applicable-methods-using-classes (gf required-classes)
(sort
(copy-list
(remove-if-not #'(lambda (method)
(every
#'(lambda (c1 c2)
(subclassp c1 c2))
required-classes
(!method-specializers method)))
(generic-function-methods gf)))
#'(lambda (m1 m2)
(funcall
(if (eq (!class-of gf) *the-class-standard-gf*)
#'std-method-more-specific-p
#'method-more-specific-p)
gf m1 m2 required-classes))))
(defun std-method-more-specific-p (gf method1 method2 required-classes)
(declare (ignore gf))
(mapc #'(lambda (spec1 spec2 arg-class)
(unless (eq spec1 spec2)
(return-from std-method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class))))
(!method-specializers method1)
(!method-specializers method2)
required-classes)
nil)
;;; apply-methods and compute-effective-method-function
(defun apply-methods (gf args methods)
(funcall (compute-effective-method-function gf methods)
args))
(defun primary-method-p (method)
(null (!method-qualifiers method)))
(defun before-method-p (method)
(equal '(:before) (!method-qualifiers method)))
(defun after-method-p (method)
(equal '(:after) (!method-qualifiers method)))
(defun around-method-p (method)
(equal '(:around) (!method-qualifiers method)))
(defun std-compute-effective-method-function (gf methods)
(let ((primaries (remove-if-not #'primary-method-p methods))
(around (find-if #'around-method-p methods)))
(when (null primaries)
(error "No primary methods for the generic function ~S." (generic-function-name gf)))
(if around
(let ((next-emfun
(funcall
(if (eq (!class-of gf) *the-class-standard-gf*)
#'std-compute-effective-method-function
#'compute-effective-method-function)
gf (remove around methods))))
#'(lambda (args)
(funcall (method-function around) args next-emfun)))
(let ((next-emfun (compute-primary-emfun (cdr primaries)))
(befores (remove-if-not #'before-method-p methods))
(reverse-afters
(reverse (remove-if-not #'after-method-p methods))))
#'(lambda (args)
(dolist (before befores)
(funcall (method-function before) args nil))
(multiple-value-prog1
(funcall (method-function (car primaries)) args next-emfun)
(dolist (after reverse-afters)
(funcall (method-function after) args nil))))))))
;;; compute an effective method function from a list of primary methods:
(defun compute-primary-emfun (methods)
(if (null methods)
nil
(let ((next-emfun (compute-primary-emfun (cdr methods))))
#'(lambda (args)
(funcall (method-function (car methods)) args next-emfun)))))
;;; apply-method and compute-method-function
(defun apply-method (method args next-methods)
(funcall (method-function method)
args
(if (null next-methods)
nil
(compute-effective-method-function
(method-generic-function method) next-methods))))
;;; @vlad-km
;;; std-compute-method-function now return method-function value
;;; bye, artefact
(defun std-compute-method-function (method)
(method-function method))
;;; N.B. The function kludge-arglist is used to pave over the differences
;;; between argument keyword compatibility for regular functions versus
;;; generic functions.
(eval-always
(defun kludge-arglist (lambda-list)
(if (and (member '&key lambda-list)
(not (member '&allow-other-keys lambda-list)))
(append lambda-list '(&allow-other-keys))
(if (and (not (member '&rest lambda-list))
(not (member '&key lambda-list)))
(append lambda-list '(&key &allow-other-keys))
lambda-list))))
;;; @vlad-km
;;; Bye, artefact
#+nil
(defun compile-in-lexical-environment (lambda-expr)
"Be evil, use eval"
(eval `(function ,lambda-expr)))
;;; @vlad-km
;;; for toplevel compilation (defgeneric ...)
(defmacro compile-method-function (fname ll fn-body)
`(lambda (args next-emfun)
(flet ((call-next-method (&rest cnm-args)
(if (null next-emfun)
(error "No next method for the generic function ~S." ',fname)
(funcall next-emfun (or cnm-args args))))
(next-method-p ()
(not (null next-emfun))))
(apply #'(lambda ,ll
,fn-body)
args))))
;;; EOF
| 15,772 | Common Lisp | .lisp | 389 | 31.750643 | 101 | 0.596998 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 0a3a75b86d2e7becf2efe83af018787eab444a2e7df49f0251067596c093a052 | 37 | [
-1
] |
38 | methods.lisp | jscl-project_jscl/src/clos/methods.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; CLOS standard method
;;; Original code closette.lisp, lines 1405-1637
;;; Minor revision for JSCL @vlad-km, 2019
;;;
;;; JSCL compilation mode - :target
;;;
(/debug "compile standard clos methods!")
;;; timestamp. todo: remove it
(defvar *mop-awake-time* (get-internal-real-time))
;;; @vlad-km.
;;; moved from std-object.
#+nil
(defun (setf slot-value) (new-value object slot-name)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(setf-std-slot-value object slot-name new-value)
(setf-slot-value-using-class new-value (!class-of object) object slot-name)))
(defsetf slot-value setf-slot-value)
;;; @vlad-km
;;; moved from std-object.lisp
;;; removed
#+nil
(defun (setf find-class) (new-value symbol)
(setf (gethash symbol *class-table*) new-value))
;;; print-object
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric print-object (instance &optional stream))
(defmethod print-object ((instance standard-object) &optional (stream *standard-output*))
(print-unreadable-object (instance stream :identity t)
(format stream "(~S)"
(class-name (class-of instance))))
instance)
(defmethod print-object ((instance standard-object) &optional (stream *standard-output*))
(if (built-in-class-of instance)
(print-unreadable-object (instance stream :identity t)
(format stream "(~S) ~a"
(class-name (class-of instance))
instance))
(print-unreadable-object (instance stream :identity t)
(format stream "(~S)"
(class-name (class-of instance)))))
instance)
;;; Slot access
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric slot-value-using-class (class instance slot-name))
(defmethod slot-value-using-class ((class standard-class) instance slot-name)
(std-slot-value instance slot-name))
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric (setf slot-value-using-class) (new-value class instance slot-name))
(defmethod (setf slot-value-using-class) (new-value (class standard-class) instance slot-name)
(setf-std-slot-value instance slot-name new-value))
;;; N.B. To avoid making a forward reference to a (setf xxx) generic function:
(defun setf-slot-value-using-class (new-value class object slot-name)
(setf-std-slot-value object slot-name new-value))
(defgeneric slot-exists-p-using-class (class instance slot-name))
(defmethod slot-exists-p-using-class
((class standard-class) instance slot-name)
(std-slot-exists-p instance slot-name))
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric slot-boundp-using-class (class instance slot-name))
(defmethod slot-boundp-using-class
((class standard-class) instance slot-name)
(std-slot-boundp instance slot-name))
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric slot-makunbound-using-class (class instance slot-name))
(defmethod slot-makunbound-using-class
((class standard-class) instance slot-name)
(std-slot-makunbound instance slot-name))
;;; Instance creation and initialization
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric allocate-instance (class))
(defmethod allocate-instance ((class standard-class))
(std-allocate-instance class))
;;;@vlad-km
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric make-instance (class &key))
(defmethod make-instance ((class standard-class) &rest initargs)
(let ((instance (allocate-instance class)))
(apply #'initialize-instance instance initargs)
instance))
(defmethod make-instance ((class symbol) &rest initargs)
(apply #'make-instance (find-class class) initargs))
;;; initialize-instance
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric initialize-instance (instance &key))
(defmethod initialize-instance ((instance standard-object) &rest initargs)
(apply #'shared-initialize instance t initargs))
(defmethod initialize-instance :after ((class standard-class) &rest args)
(apply #'std-after-initialization-for-classes class args))
(defgeneric reinitialize-instance (instance &key))
(defmethod reinitialize-instance ((instance standard-object) &rest initargs)
(apply #'shared-initialize instance () initargs))
;;; shared-initialize
;;; @vlad-km 2022 experimental - pre-upgrade to new version
#+nil
(defgeneric shared-initialize (instance slot-names &key))
(defmethod shared-initialize ((instance standard-object) slot-names &rest all-keys)
(dolist (slot (class-slots (class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties all-keys (slot-definition-initargs slot))
(if foundp
;; todo: (setf ) -> (set-slot-value)
(setf (slot-value instance slot-name) init-value)
(when (and (not (slot-boundp instance slot-name))
(not (null (slot-definition-initfunction slot)))
(or (eq slot-names t)
(member slot-name slot-names)))
;; todo: (setf ) -> (set-slot-value)
(setf (slot-value instance slot-name)
(funcall (slot-definition-initfunction slot))))))))
instance)
;;; change-class
(defgeneric change-class (instance new-class &key))
(defmethod change-class ((old-instance standard-object) (new-class standard-class) &rest initargs)
(let ((new-instance (allocate-instance new-class)))
(dolist (slot-name (mapcar #'slot-definition-name
(class-slots new-class)))
(when (and (slot-exists-p old-instance slot-name)
(slot-boundp old-instance slot-name))
(setf (slot-value new-instance slot-name)
(slot-value old-instance slot-name))))
(!rotatef (std-instance-slots new-instance)
(std-instance-slots old-instance))
(!rotatef (std-instance-class new-instance)
(std-instance-class old-instance))
(apply #'update-instance-for-different-class
new-instance old-instance initargs)
old-instance))
(defmethod change-class ((instance standard-object) (new-class symbol) &rest initargs)
(apply #'change-class instance (find-class new-class) initargs))
;;; update instance
(defgeneric update-instance-for-different-class (old new &key))
(defmethod update-instance-for-different-class ((old standard-object)
(new standard-object)
&rest initargs)
(let ((added-slots
(remove-if #'(lambda (slot-name)
(slot-exists-p old slot-name))
(mapcar #'slot-definition-name
(class-slots (class-of new))))))
(apply #'shared-initialize new added-slots initargs)))
;;;
;;; Methods having to do with class metaobjects.
;;;
(defmethod print-object ((class standard-class) &optional (stream *standard-output*))
(print-unreadable-object (class stream :identity t)
(format stream "(~S) ~S"
(class-name (class-of class))
(class-name class)))
class)
;;; Finalize inheritance
(defgeneric finalize-inheritance (class &rest))
(defmethod finalize-inheritance ((class standard-class) &rest all-keys)
(std-finalize-inheritance class all-keys)
(values))
;;; Class precedence lists
(defgeneric compute-class-precedence-list (class))
(defmethod compute-class-precedence-list ((class standard-class))
(std-compute-class-precedence-list class))
;;; Slot inheritance
(defgeneric compute-slots (class))
(defmethod compute-slots ((class standard-class))
(std-compute-slots class))
(defgeneric compute-effective-slot-definition (class direct-slots))
(defmethod compute-effective-slot-definition ((class standard-class) direct-slots)
(std-compute-effective-slot-definition class direct-slots))
;;;
;;; Methods having to do with generic function metaobjects.
;;;
(defmethod print-object ((gf standard-generic-function) &optional (stream *standard-output*))
(print-unreadable-object (gf stream :identity t)
(format stream "(~S) ~S"
(class-name (class-of gf))
(generic-function-name gf)))
gf)
;;; initialize-instance
;;; mvk change &key to &rest args
(defmethod initialize-instance :after ((gf standard-generic-function) &rest args)
(finalize-generic-function gf))
;;;
;;; Methods having to do with method metaobjects.
;;;
(defmethod print-object ((method standard-method) &optional (stream *standard-output*))
(print-unreadable-object (method stream :identity t)
(format stream "(~S) ~S ~S ~S"
(class-name (class-of method))
(generic-function-name
(method-generic-function method))
(method-qualifiers method)
(mapcar #'class-name
(method-specializers method))))
method)
;;; @vlad-km. added &rest
(defmethod initialize-instance :after ((method standard-method) &rest args)
(setf (method-function method) (compute-method-function method)))
;;;
;;; Methods having to do with generic function invocation.
;;;
(defgeneric compute-discriminating-function (gf))
(defmethod compute-discriminating-function ((gf standard-generic-function))
(std-compute-discriminating-function gf))
(defgeneric method-more-specific-p (gf method1 method2 required-classes))
(defmethod method-more-specific-p ((gf
standard-generic-function)
method1
method2
required-classes)
(std-method-more-specific-p gf method1 method2 required-classes))
(defgeneric compute-effective-method-function (gf methods))
(defmethod compute-effective-method-function ((gf standard-generic-function) methods)
(std-compute-effective-method-function gf methods))
(defgeneric compute-method-function (method))
(defmethod compute-method-function ((method standard-method))
(std-compute-method-function method))
;;; timestamp. todo: remove it
(/debug (concat " elapsed time:" (/ (- (get-internal-real-time) *mop-awake-time*) internal-time-units-per-second 1.0) " sec."))
;;; ancient as a mammoth shit
;;; EOF
| 10,432 | Common Lisp | .lisp | 227 | 40.154185 | 139 | 0.693175 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | ea841cf4aff53139fd2d29d265787e47e2ccf4bbf6614f693fdf47c7985b7d25 | 38 | [
-1
] |
39 | exports.lisp | jscl-project_jscl/src/clos/exports.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;;
;;; Export CLOS symbols
;;; Original code closette.lisp, lines 69-111
;;;
;;; JSCL compilation mode - :target
;;;
;;; todo: compare with var exports from original closette.lisp
;;; the export list uncomplite
(export
'(find-class class-of
call-next-method next-method-p
slot-value slot-boundp slot-exists-p slot-makunbound
make-instance change-class
initialize-instance reinitialize-instance shared-initialize
update-instance-for-different-class
print-object
describe-object
standard-object
standard-class standard-generic-function standard-method
class-name
class-direct-superclasses class-direct-slots
class-precedence-list class-slots class-direct-subclasses
class-direct-methods
generic-function-name generic-function-lambda-list
generic-function-methods generic-function-discriminating-function
generic-function-method-class
method-lambda-list method-qualifiers method-specializers method-body
method-environment method-generic-function method-function
slot-definition-name slot-definition-initfunction
slot-definition-initform slot-definition-initargs
slot-definition-readers slot-definition-writers
slot-definition-allocation
;; Class-related metaobject protocol
compute-class-precedence-list compute-slots
compute-effective-slot-definition
finalize-inheritance allocate-instance
slot-value-using-class slot-boundp-using-class
slot-exists-p-using-class slot-makunbound-using-class
;; Generic function related metaobject protocol
compute-discriminating-function
compute-applicable-methods-using-classes
method-more-specific-p
ensure-generic-function
add-method
remove-method
find-method
compute-effective-method-function compute-method-function
apply-methods
apply-method
find-generic-function
))
;;; EOF
| 1,915 | Common Lisp | .lisp | 53 | 32.660377 | 74 | 0.783827 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 29db68efc334a12715d98bd2059081d6d2a98d7b8ea42f3839af9109fef00f6b | 39 | [
-1
] |
40 | kludges.lisp | jscl-project_jscl/src/clos/kludges.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro eval-always (&rest body)
`(eval-when (:compile-toplevel :load-toplevel :execute)
,@body)))
;;; kludge for (defun (setf name) ...) syntax
(defun setf-function-symbol (spec)
(if (consp spec)
(let ((fname (concat "(" (symbol-name (car spec)) "_" (symbol-name (cadr spec)) ")")))
(intern fname
(symbol-package (cadr spec))))
spec))
;;; kludge for invalid &allow-other-keys
(defun get-keyword-from (args key &optional default)
(let ((val (getf args key)))
(if val val default)))
;;; push-on-end is like push except it uses the other end:
(eval-always
(defmacro push-on-end (value location)
`(setf ,location (nconc ,location (list ,value)))))
;;; (setf getf*) is like (setf getf) except that it always changes the list,
;;; which must be non-nil.
(defun (setf getf*) (new-value plist key)
(block body
(do ((x plist (cddr x)))
((null x))
(when (eq (car x) key)
(setf (car (cdr x)) new-value)
(return-from body new-value)))
(push-on-end key plist)
(push-on-end new-value plist)
new-value))
;;; mapappend is like mapcar except that the results are appended together:
(eval-always
(defun mapappend (fun &rest args)
(if (some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args))))))
;;; mapplist is mapcar for property lists:
(defun mapplist (fun x)
(if (null x)
()
(cons (funcall fun (car x) (cadr x))
(mapplist fun (cddr x)))))
;;; find-if-not
(defun !find-if-not (predicate sequence &key key)
(find-if (complement predicate) sequence :key key))
;;; Dumb release standard macros psetf & rotatef
;;; Warning! Not use with (incf/decf) !
(defmacro !psetf (&rest pairs)
(when pairs
(when (null (cdr pairs))
(error "PSETF odd arguments"))
(let ((g!val (gensym)))
`(let ((,g!val ,(cadr pairs)))
(!psetf ,@(cddr pairs))
(setf ,(car pairs) ,g!val)
nil))))
(eval-always
(defun %rotatef-args-parser (args)
(let ((res))
(when args
(dolist (it args)
(push it res)
(push it res))
(push (car args) res)
(setq res (reverse res))
(setf (car res) '!psetf))
res ))
(defmacro !rotatef (&rest assigments)
`(progn
,(%rotatef-args-parser `,assigments) nil)))
;;; EOF
| 2,479 | Common Lisp | .lisp | 74 | 28.513514 | 92 | 0.611947 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | bb24f1e3f470f50f5498f9c6e4fe4d5ce74a58f2292cdd43066368583d81023a | 40 | [
-1
] |
41 | macros.lisp | jscl-project_jscl/src/clos/macros.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;;
;;; CLOS macros
;;; Modification for JSCL @vlad-km, 2019, 2022
;;;
;;; JSCL compilation mode :target
;;;
;;; defclass
;;; from std-object.lisp
;;; from original closette.lisp lines 370-383
(defmacro defclass (name direct-superclasses direct-slots &rest options)
`(ensure-class ',name
:direct-superclasses ,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots ,(canonicalize-direct-slots direct-slots)
,@(canonicalize-defclass-options options)))
;;; defgeneric
;;; from std-generic.lisp
;;; from original closette.lisp lines 825-832
(defmacro defgeneric (function-name lambda-list &rest options)
`(!ensure-generic-function ',function-name
:lambda-list ,(canonicalize-defgeneric-ll lambda-list)
,@(canonicalize-defgeneric-options options)))
;;; defmethod
;;; from std-method.lisp
;;; from original closette.lisp lines 919-931
;;; @vlad-km. modify :body. added :cmf
;;; add call without prior DEFGENERIC
#+nil
(defmacro defmethod (&rest args)
(multiple-value-bind (function-name qualifiers lambda-list specializers body)
(parse-defmethod args)
`(let ((gf (find-generic-function ',function-name)))
(ensure-method gf
:lambda-list ,(canonicalize-defgeneric-ll lambda-list)
:qualifiers ,(canonicalize-defgeneric-ll qualifiers)
:specializers ,(canonicalize-specializers specializers)
:body ',body
:cmf (compile-method-function ,function-name
,(kludge-arglist lambda-list)
,body)))))
(defmacro defmethod (&rest args)
(multiple-value-bind (function-name qualifiers lambda-list specializers body)
(parse-defmethod args)
`(let ((gf (find-generic-function ',function-name nil)))
(unless gf
(setq gf (defgeneric ,function-name
,(mapcar
(lambda (x)
(if (consp x) (car x) x))
lambda-list) )))
(ensure-method gf
:lambda-list ,(canonicalize-defgeneric-ll lambda-list)
:qualifiers ,(canonicalize-defgeneric-ll qualifiers)
:specializers ,(canonicalize-specializers specializers)
:body ',body
:cmf (compile-method-function ,function-name
,(kludge-arglist lambda-list)
,body)))))
;;; @vlad-km
;;; added standard macro - with-slots
(defmacro with-slots ((&rest slots) instance-name &body forms)
(let ((instance (gensym)))
`(let ((,instance ,instance-name))
(symbol-macrolet
,(loop for slot-name in slots
collect (if (symbolp slot-name)
`(,slot-name (!slot-value ,instance ',slot-name))
`(,(first slot-name) (!slot-value ,instance ',(second slot-name)))))
,@forms))))
;;; @vlad-km
;;; added standard macro - with-accessors
(defmacro with-accessors ((&rest Readers) instance-name &body forms)
(let ((instance (gensym)))
`(let ((,instance ,instance-name))
(symbol-macrolet
,(loop for (var reader) in Readers
collect `(,var (,reader ,instance)))
,@forms))))
;;; psetf
;;: todo: remove to ?
#+nil
(defmacro psetf (&rest pairs)
`(!psetf ,@pairs))
;;; rotatef
;;: todo: remove to ?
#+nil
(defmacro rotatef (&rest assigments)
`(!rotatef ,@assigments))
;;; FSET section
(jscl::fset 'class-of (fdefinition '!class-of))
(jscl::fset 'class-name (fdefinition '!class-name))
(jscl::fset 'find-class (fdefinition '!find-class))
(jscl::fset 'slot-value (fdefinition '!slot-value))
(jscl::fset 'slot-boundp (fdefinition '!slot-boundp))
(jscl::fset 'slot-makunbound (fdefinition '!slot-makunbound))
(jscl::fset 'slot-exists-p (fdefinition '!slot-exists-p))
(jscl::fset 'slot-exists-p (fdefinition '!slot-exists-p))
(jscl::fset 'ensure-generic-function (fdefinition '!ensure-generic-function))
(jscl::fset 'find-method (fdefinition '!find-method))
(jscl::fset 'add-method (fdefinition '!add-method))
(jscl::fset 'remove-method (fdefinition '!remove-method))
(jscl::fset 'method-qualifiers (fdefinition '!method-qualifiers))
(jscl::fset 'method-specializers (fdefinition '!method-specializers))
(push :mop *features*)
;;; EOF
| 4,633 | Common Lisp | .lisp | 105 | 34.742857 | 98 | 0.604218 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | d6034b600f1ec71d4cef8dceb03007dcce5f86b5a75aa4342e6e92894debf787 | 41 | [
-1
] |
42 | mop-utils.lisp | jscl-project_jscl/src/clos/mop-utils.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; mop object printer
;;;
;;; JSCL compilation mode :both
;;;
(defun mop-class-name (class)
(std-slot-value class 'name))
(defun mop-class-of (x)
(if (std-instance-p x)
(std-instance-class x)
(built-in-class-of x)))
(defun mop-object-slots (slot)
(unless (arrayp slot)
(error "its not slot"))
(let* ((size (length slot))
(place)
(result))
(dotimes (idx size)
(setq place (aref slot idx))
(cond ((std-instance-p place)
(push (mop-object-class-name place) result))
((consp place)
(push "(..) " result))
((arrayp place)
(push "#(..) " result))
((or (numberp place)
(symbolp place))
(push (concat (string place) " ") result))
((stringp place)
(push (concat place " ") result))
(t (push "@ " result))))
(apply 'concat (reverse result))))
(defun mop-object-class-name (place)
(concat (string (mop-class-name (mop-class-of place)))
" "
(string (mop-class-name (mop-class-of (mop-class-of place)))) ))
(defun mop-object-struct-slots (form)
(let* ((slots (slot-value (mop-class-of form) 'direct-slots))
(slot-values (std-instance-slots form))
(num-slots (length slots))
(result ""))
(dotimes (idx num-slots result)
(setq result (concat result ":" ))
(setq result (concat result (getf (nth idx slots) :name)))
(setq result (concat result " " ))
(setq result (concat result (write-to-string (aref slot-values idx))))
(when (<= idx (- num-slots 2)) ; dont print final space
(setq result (concat result " " ))))))
;;; mop object printer
(defun mop-object-printer (form stream)
(let ((res (case (mop-class-name (mop-class-of form))
(standard-class
(concat "#<standard-class " (write-to-string (mop-class-name form)) ">"))
(standard-generic-function
(concat "#<standard-generic-function " (write-to-string (generic-function-name form)) ">"))
(standard-method
(concat "#<standard-method " (write-to-string (generic-function-name (method-generic-function form)))
(write-to-string (generate-specialized-arglist form)) ">"))
(otherwise
(case (mop-class-name (mop-class-of (mop-class-of form)))
(structure-class (concat "#S("
(write-to-string (mop-class-name (mop-class-of form)))
" " (mop-object-struct-slots form) ")"))
(otherwise
(concat "#<instance " (write-to-string (mop-class-name (mop-class-of form))) " "
(mop-object-slots (std-instance-slots form)) ">")))))))
(simple-format stream res)))
;;; EOF
| 2,946 | Common Lisp | .lisp | 68 | 33.25 | 117 | 0.547295 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c6de894443d76c0429e143cf8455211f2aba7949329bcac983b2447f9052ee0d | 42 | [
-1
] |
43 | std-object.lisp | jscl-project_jscl/src/clos/std-object.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;;
;;; Standard instances
;;; Original code closette.lisp, lines 155-728
;;; Modification @vlad-km, 2019
;;; version for JSCL
;;;
;;; JSCL compilation mode - :both
;;;
;;; Release note
;;; - The names of some functions have been changed from !name to !name, to prevent naming conflicts
;;; when host compiling. See FSET section from macros.lisp
;;; - Changed the algorithm for working with the slot position in the instance.
;;; implementation through a hash table.
;;; - Some forms (setf ...) have been replaced by (setf-...).
;;; So, added setf-... functions
;;; - In some places the argument lists were corrected for JSCL.
;;; - Macro DEFCLASS moved to macros.lisp
;;;
(/debug "loading std-object")
;;; @vlad-km
;;; add hash/cn slots
(def!struct (std-instance (:constructor allocate-std-instance (class slots hash cn))
(:predicate std-instance-p))
class
slots
hash
cn)
;;; Standard instance allocation
(defparameter *secret-unbound-value* (list "slot unbound"))
(defun instance-slot-p (slot)
(eql (slot-definition-allocation slot) ':instance))
;;; @vlad-km
;;; version for JSCL
(defun std-allocate-instance (class)
#-jscl
(allocate-std-instance
:class class
:slots (allocate-slot-storage (count-if #'instance-slot-p (class-slots class))
*secret-unbound-value*)
:hash nil
:cn nil)
#+jscl
(let ((instance
(allocate-std-instance
:class class
:slots (allocate-slot-storage (count-if #'instance-slot-p (class-slots class))
*secret-unbound-value*)
:hash nil
:cn nil )))
(set-object-type-code instance :mop-object)
instance ))
;;; Simple vectors are used for slot storage.
(defun allocate-slot-storage (size initial-value)
(make-array size :initial-element initial-value))
;;; Standard instance slot access
;;; N.B. The location of the effective-slots slots in the class metaobject for
;;; standard-class must be determined without making any further slot
;;; references.
;;; @vlad-km
;;; this artefact from orginal.
;;;(defvar *the-slots-of-standard-class*) ;standard-class's class-slots
;;; replace on below
(defvar *the-slots-of-standard-class*
'((:NAME NAME :INITARGS (:NAME) :INITFORM NIL :INITFUNCTION NIL :ALLOCATION :INSTANCE)
(:NAME DIRECT-SUPERCLASSES :INITARGS (:DIRECT-SUPERCLASSES) :INITFORM NIL :INITFUNCTION NIL :ALLOCATION :INSTANCE)
(:NAME DIRECT-SLOTS :INITARGS NIL :INITFORM NIL :INITFUNCTION NIL :ALLOCATION :INSTANCE)
(:NAME CLASS-PRECEDENCE-LIST :INITARGS NIL :INITFORM NIL :INITFUNCTION NIL :ALLOCATION :INSTANCE)
(:NAME EFFECTIVE-SLOTS :INITARGS NIL :INITFORM NIL :INITFUNCTION NIL :ALLOCATION :INSTANCE)
(:NAME DIRECT-SUBCLASSES :INITARGS NIL :INITFORM NIL :INITFUNCTION NIL :ALLOCATION :INSTANCE)
(:NAME DIRECT-METHODS :INITARGS NIL :INITFORM NIL :INITFUNCTION NIL :ALLOCATION :INSTANCE))
"standard-class's class-slots descriptor")
;;; @vlad-km
;;; add hash-table for class-slots-position
(defvar *position-slots-of-standard-class* (make-hash-table :test #'eq)
"standard-class's class-slots position")
;;; @vlad-km
#+jscl
(mapcar (lambda (x) (setf (gethash (car x) *position-slots-of-standard-class*) (cadr x)))
'((NAME 0)
(DIRECT-SUPERCLASSES 1)
(DIRECT-SLOTS 2)
(CLASS-PRECEDENCE-LIST 3)
(EFFECTIVE-SLOTS 4)
(DIRECT-SUBCLASSES 5)
(DIRECT-METHODS 6)))
(defvar *the-class-standard-class*) ;standard-class class metaobject
;;; @vlad-km
;;; add function std-slot-position
(defun std-slot-position (slot-name)
(gethash slot-name *position-slots-of-standard-class*))
;;; @vlad-km
;;; add function setf-std-instance-hash
(defun setf-std-instance-hash (class ht idx)
;; store hash-table
(setf (std-instance-hash class) ht)
;; store slots number
(setf (std-instance-cn class) idx))
;;; @vlad-km
;;; add constant for slot-location
(defconstant +effective-slot-pos+ 4)
;;; @vlad-km
;;; new version slot-location
(defun slot-location (class slot-name)
(let ((pos)
(hash-slots (std-instance-hash class)))
(cond ((and (eq slot-name 'effective-slots)
(eq class *the-class-standard-class*))
(setq pos +effective-slot-pos+))
(hash-slots
(setq pos (gethash slot-name hash-slots))
(unless pos
;; debug for boot stage when *standard-output* undef
(/debug (format nil "The slot ~S is not an instance slot in the class " slot-name))
(error "The slot ~S is not an instance slot in the class ~S." slot-name class)))
(t
(/debug (format nil "The class has not slots table for ~a" slot-name) )
(error "The class ~a has not slots table" class)))
pos))
;;; slot-contents
(defun slot-contents (slots location)
(aref slots location))
;;; @vlad-km
(defun setf-slot-contents (slots location new-value)
(setf (aref slots location) new-value))
;;; std-slot-value
;;; @vlad-km. replaced (setf ...) form
(defun setf-std-slot-value (instance slot-name new-value)
(let ((location (slot-location (!class-of instance) slot-name))
(slots (std-instance-slots instance)))
(setf-slot-contents slots location new-value)))
(defun std-slot-value (instance slot-name)
(let* ((location (slot-location (!class-of instance) slot-name))
(slots (std-instance-slots instance))
(val (slot-contents slots location)))
(if (equal *secret-unbound-value* val)
(error "The slot ~S is unbound in the object ~S."
slot-name instance)
val)))
;;; slot-value
(defun !slot-value (object slot-name)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(std-slot-value object slot-name)
(slot-value-using-class (!class-of object) object slot-name)))
;;; @vlad-km. add (setf-...)
(defun setf-slot-value (object slot-name new-value)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(setf-std-slot-value object slot-name new-value)
(setf-slot-value-using-class new-value (!class-of object) object slot-name)))
;;; @vlad-km.
;;; Moved to methods.lisp
#+nil
(defun (setf slot-value) (new-value object slot-name)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(setf-std-slot-value object slot-name new-value)
(setf-slot-value-using-class new-value (!class-of object) object slot-name)))
;;; @vlad-km. add for add-writer-method
(defun (setf !slot-value) (new-value object slot-name)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(setf-std-slot-value object slot-name new-value)
(setf-slot-value-using-class new-value (!class-of object) object slot-name)))
;;; std-slot-boundp
(defun std-slot-boundp (instance slot-name)
(let ((location (slot-location (!class-of instance) slot-name))
(slots (std-instance-slots instance)))
(not (equal *secret-unbound-value* (slot-contents slots location)))))
(defun !slot-boundp (object slot-name)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(std-slot-boundp object slot-name)
(slot-boundp-using-class (!class-of object) object slot-name)))
;;; std-slot-makunbound
(defun std-slot-makunbound (instance slot-name)
(let ((location (slot-location (!class-of instance) slot-name))
(slots (std-instance-slots instance)))
(setf-slot-contents slots location *secret-unbound-value*))
instance)
(defun !slot-makunbound (object slot-name)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(std-slot-makunbound object slot-name)
(slot-makunbound-using-class (!class-of object) object slot-name)))
;;; std-slot-exists-p
(defun std-slot-exists-p (instance slot-name)
(not (null (find slot-name (class-slots (!class-of instance))
:key #'slot-definition-name))))
(defun !slot-exists-p (object slot-name)
(if (eq (!class-of (!class-of object)) *the-class-standard-class*)
(std-slot-exists-p object slot-name)
(slot-exists-p-using-class (!class-of object) object slot-name)))
;;; class-of
(defun !class-of (x)
(if (std-instance-p x)
(std-instance-class x)
(built-in-class-of x)))
;;; subclassp and sub-specializer-p
(defun subclassp (c1 c2)
(not (null (find c2 (class-precedence-list c1)))))
(defun sub-specializer-p (c1 c2 c-arg)
(let ((cpl (class-precedence-list c-arg)))
(not (null (find c2 (cdr (member c1 cpl)))))))
;;;
;;; Class metaobjects and standard-class
;;;
;;; @vlad-km
;;; note: Artefact from original closette.lisp
;;; Now not used
#+nil
(defparameter *the-defclass-standard-class* ;standard-class's defclass form
'(!defclass standard-class ()
((name :initarg :name) ; :accessor class-name
(direct-superclasses ; :accessor class-direct-superclasses
:initarg :direct-superclasses)
(direct-slots) ; :accessor class-direct-slots
(class-precedence-list) ; :accessor class-precedence-list
(effective-slots) ; :accessor class-slots
(direct-subclasses :initform ()) ; :accessor class-direct-subclasses
(direct-methods :initform ())))) ; :accessor class-direct-methods
;;; Defining the metaobject slot accessor function as regular functions
;;; greatly simplifies the implementation without removing functionality.
;;; class-name
(defun setf-class-name (class new-value)
(setf-slot-value class 'name new-value))
(defun !class-name (class)
(std-slot-value class 'name))
;;; class-direct-superclasses
(defun class-direct-superclasses (class)
(!slot-value class 'direct-superclasses))
(defun setf-class-direct-superclasses (class new-value)
(setf-slot-value class 'direct-superclasses new-value))
;;; class-direct-slots
(defun class-direct-slots (class)
(!slot-value class 'direct-slots))
(defun setf-class-direct-slots (class new-value)
(setf-slot-value class 'direct-slots new-value))
;;; class-precedence-list
(defun class-precedence-list (class)
(!slot-value class 'class-precedence-list))
(defun setf-class-precedence-list (class new-value)
(setf-slot-value class 'class-precedence-list new-value))
;;; class-slots
(defun class-slots (class)
(!slot-value class 'effective-slots))
(defun setf-class-slots (class new-value)
(setf-slot-value class 'effective-slots new-value))
;;; class-direct-subclasses
(defun class-direct-subclasses (class)
(!slot-value class 'direct-subclasses))
(defun setf-class-direct-subclasses (class new-value)
(setf-slot-value class 'direct-subclasses new-value))
(defun (setf class-direct-subclasses) (new-value class)
(setf-slot-value class 'direct-subclasses new-value))
;;; class-direct-methods
(defun class-direct-methods (class)
(!slot-value class 'direct-methods))
(defun setf-class-direct-methods (class new-value)
(setf-slot-value class 'direct-methods new-value))
;;; @vlad-km. pushnew
(defun pushnew-class-direct-methods (new-value class)
(let ((lst (!slot-value class 'direct-methods)))
(pushnew new-value lst)
(setf-slot-value class 'direct-methods lst)))
;;; defclass
(eval-always
(defun canonicalize-direct-superclass (class-name)
`(!find-class ',class-name))
(defun canonicalize-direct-superclasses (direct-superclasses)
(if direct-superclasses
`(list ,@(mapcar 'canonicalize-direct-superclass direct-superclasses))
())))
(eval-always
(defun canonicalize-direct-slot (spec)
(if (symbolp spec)
`(list :name ',spec)
(let ((name (car spec))
(initfunction nil)
(initform nil)
(initargs ())
(readers ())
(writers ())
(other-options ()))
(do ((olist (cdr spec) (cddr olist)))
((null olist))
(case (car olist)
(:initform
(setq initfunction
`(function (lambda () ,(cadr olist))))
(setq initform `',(cadr olist)))
(:initarg (push-on-end (cadr olist) initargs))
(:reader (push-on-end (cadr olist) readers))
(:writer (push-on-end (cadr olist) writers))
(:accessor
;; accessor reader fn
(push-on-end (cadr olist) readers)
;; accessor writer fn
;; make (setf name) symbolic name
(push-on-end `(setf ,(cadr olist)) writers))
(:documentation)
(otherwise
(push-on-end `',(car olist) other-options)
(push-on-end `',(cadr olist) other-options))))
`(list
:name ',name
,@(when initfunction
`(:initform ,initform
:initfunction ,initfunction))
,@(when initargs `(:initargs ',initargs))
,@(when readers `(:readers ',readers))
,@(when writers `(:writers ',writers))
,@other-options)))))
(eval-always
(defun canonicalize-direct-slots (direct-slots)
(if direct-slots
`(list ,@(mapcar #'canonicalize-direct-slot direct-slots))
())))
(eval-always
(defun canonicalize-defclass-option (option)
(case (car option)
(:documentation)
(:metaclass (list ':metaclass `(!find-class ',(cadr option))))
(:default-initargs
(list ':direct-default-initargs
`(list ,@(mapappend #'(lambda (x) x)
(mapplist #'(lambda (key value) `(',key ,value))
(cdr option))))))
(t (list `',(car option) `',(cadr option))))))
(eval-always
(defun canonicalize-defclass-options (options)
(mapappend #'canonicalize-defclass-option options)))
;;; find-class
(defun !find-class (symbol &optional (errorp t))
(let ((class (gethash symbol *class-table* nil)))
(if (and (null class) errorp)
(error "No class named ~S." symbol)
class)))
(defun setf-find-class (symbol new-value)
(setf (gethash symbol *class-table*) new-value))
;;; @vlad-km
;;; remove to methods.lisp
;;;
#+nil
(defun (setf find-class) (new-value symbol)
(setf (gethash symbol *class-table*) new-value))
;;; Ensure class
;;; @vlad-km remove (setf...) form
(defun ensure-class (name &rest all-keys)
(if (!find-class name nil)
(error "Can't redefine the class named ~S." name)
(let* ((metaclass (get-keyword-from all-keys :metaclass *the-class-standard-class*))
(class (apply (if (eq metaclass *the-class-standard-class*)
#'make-instance-standard-class
#'make-instance)
metaclass :name name all-keys)))
(setf-find-class name class)
class)))
;;; make-instance-standard-class creates and initializes an instance of
;;; standard-class without falling into method lookup. However, it cannot be
;;; called until standard-class itself exists.
(defun make-instance-standard-class (metaclass &rest all-keys)
(declare (ignore metaclass ))
(let ((name (get-keyword-from all-keys :name))
(direct-superclasses (get-keyword-from all-keys :direct-superclasses))
(direct-slots (get-keyword-from all-keys :direct-slots))
(class (std-allocate-instance *the-class-standard-class*)))
(setf-class-name class name)
(setf-class-direct-subclasses class ())
(setf-class-direct-methods class ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
class))
(defun std-after-initialization-for-classes (class &rest all-keys)
(let* ((direct-superclasses (get-keyword-from all-keys :direct-superclasses))
(direct-slots (get-keyword-from all-keys :direct-slots))
(supers (or direct-superclasses
(list (!find-class 'standard-object)))))
;; todo: make push-class-direct-subclasses!
(dolist (it supers)
(push class (class-direct-subclasses it)))
(setf-class-direct-superclasses class supers)
(let ((slots (mapcar (lambda (slot-properties)
(apply 'make-direct-slot-definition slot-properties))
direct-slots)))
(setf-class-direct-slots class slots)
(dolist (direct-slot slots)
(dolist (reader (slot-definition-readers direct-slot))
(add-reader-method class reader (slot-definition-name direct-slot)))
(dolist (writer (slot-definition-writers direct-slot))
(add-writer-method class writer (slot-definition-name direct-slot)))))
(funcall (if (eq (!class-of class) *the-class-standard-class*)
'std-finalize-inheritance
'finalize-inheritance)
class)
(values)))
;;; Slot definition metaobjects
;;; N.B. Quietly retain all unknown slot options (rather than signaling an
;;; error), so that it's easy to add new ones.
;;; BUG: this lambda form is not working - &allow-other-keys parsed incorrectly
(defun make-direct-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil) (readers ()) (writers ()) (allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':readers) readers)
(setf (getf* slot ':writers) writers)
(setf (getf* slot ':allocation) allocation)
slot))
;;; BUG: this lambda form is not working - &allow-other-keys parsed incorrectly
(defun make-effective-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil) (allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':allocation) allocation)
slot))
;;; slot-definition-name
(defun slot-definition-name (slot)
(getf slot ':name))
(defun setf-slot-definition-name (slot new-value)
(setf (getf* slot ':name) new-value))
;;; slot-definition-initfunction
(defun slot-definition-initfunction (slot)
(getf slot ':initfunction))
(defun setf-slot-definition-initfunction (slot new-value)
(setf (getf* slot ':initfunction) new-value))
;;; slot-definition-initform
(defun slot-definition-initform (slot)
(getf slot ':initform))
(defun setf-slot-definition-initform (slot new-value)
(setf (getf* slot ':initform) new-value))
;;; slot-definition-initargs
(defun slot-definition-initargs (slot)
(getf slot ':initargs))
(defun setf-slot-definition-initargs (slot new-value)
(setf (getf* slot ':initargs) new-value))
;;; slot-definition-readers
(defun slot-definition-readers (slot)
(getf slot ':readers))
(defun setf-slot-definition-readers (slot new-value)
(setf (getf* slot ':readers) new-value))
;;; slot-definition-writers
(defun slot-definition-writers (slot)
(getf slot ':writers))
(defun setf-slot-definition-writers (slot new-value)
(setf (getf* slot ':writers) new-value))
;;; slot-definition-allocation
(defun slot-definition-allocation (slot)
(getf slot ':allocation))
(defun setf-slot-definition-allocation (slot new-value)
(setf (getf* slot ':allocation) new-value))
;;; finalize-inheritance
;;; @vlad-km. add class slots position hash
;;; replaced (setf ...) forms on (setf-...)
(defun std-finalize-inheritance (class &rest all-keys)
(setf-class-precedence-list
class
(funcall (if (eq (!class-of class) *the-class-standard-class*)
'std-compute-class-precedence-list
'compute-class-precedence-list)
class))
(setf-class-slots
class
(funcall (if (eq (!class-of class) *the-class-standard-class*)
'std-compute-slots
'compute-slots)
class))
(hash-class-slots-names class)
(values))
;;; @vlad-km. Add function.
;;; Build slots position hash for class
(defun hash-class-slots-names (class)
(let ((slots (mapcar (lambda (x) (getf x ':name)) (class-slots class)))
(idx 0)
(hh))
(when slots
(setq hh (make-hash-table :test #'eql))
(dolist (it slots) (setf (gethash it hh) idx)
(setq idx (1+ idx)))
(setf-std-instance-hash class hh idx) )))
;;; Class precedence lists
(defun std-compute-class-precedence-list (class)
(let ((classes-to-order (collect-superclasses* class)))
(topological-sort classes-to-order
(remove-duplicates
(mapappend 'local-precedence-ordering
classes-to-order))
'std-tie-breaker-rule)))
;;; topological-sort implements the standard algorithm for topologically
;;; sorting an arbitrary set of elements while honoring the precedence
;;; constraints given by a set of (X,Y) pairs that indicate that element
;;; X must precede element Y. The tie-breaker procedure is called when it
;;; is necessary to choose from multiple minimal elements; both a list of
;;; candidates and the ordering so far are provided as arguments.
(defun topological-sort (elements constraints tie-breaker)
(let ((remaining-constraints constraints)
(remaining-elements elements)
(result ()))
;; @vlad-km. replace (loop
(while t
(let ((minimal-elements
(remove-if
(lambda (class)
(member class remaining-constraints
:key #'cadr))
remaining-elements)))
(when (null minimal-elements)
(if (null remaining-elements)
(return-from topological-sort result)
(error "Inconsistent precedence graph.")))
(let ((choice (if (null (cdr minimal-elements))
(car minimal-elements)
(funcall tie-breaker
minimal-elements
result))))
(setq result (append result (list choice)))
(setq remaining-elements
(remove choice remaining-elements))
(setq remaining-constraints
(remove choice
remaining-constraints
:test #'member)))))))
;;; In the event of a tie while topologically sorting class precedence lists,
;;; the CLOS Specification says to "select the one that has a direct subclass
;;; rightmost in the class precedence list computed so far." The same result
;;; is obtained by inspecting the partially constructed class precedence list
;;; from right to left, looking for the first minimal element to show up among
;;; the direct superclasses of the class precedence list constituent.
;;; (There's a lemma that shows that this rule yields a unique result.)
(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
(dolist (cpl-constituent (reverse cpl-so-far))
(let* ((supers (class-direct-superclasses cpl-constituent))
(common (intersection minimal-elements supers)))
(when (not (null common))
(return-from std-tie-breaker-rule (car common))))))
;;; This version of collect-superclasses* isn't bothered by cycles in the class
;;; hierarchy, which sometimes happen by accident.
(defun collect-superclasses* (class)
(labels ((all-superclasses-loop (seen superclasses)
(let ((to-be-processed
(set-difference superclasses seen)))
(if (null to-be-processed)
superclasses
(let ((class-to-process
(car to-be-processed)))
(all-superclasses-loop
(cons class-to-process seen)
(union (class-direct-superclasses
class-to-process)
superclasses)))))))
(all-superclasses-loop () (list class))))
;;; The local precedence ordering of a class C with direct superclasses C_1,
;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
(defun local-precedence-ordering (class)
(mapcar #'list
(cons class
(butlast (class-direct-superclasses class)))
(class-direct-superclasses class)))
;;; Slot inheritance
(defun std-compute-slots (class)
(let* ((all-slots (mapappend #'class-direct-slots
(class-precedence-list class)))
(all-names (remove-duplicates
(mapcar #'slot-definition-name all-slots))))
(mapcar #'(lambda (name)
(funcall
(if (eq (!class-of class) *the-class-standard-class*)
#'std-compute-effective-slot-definition
#'compute-effective-slot-definition)
class
(remove name all-slots
:key #'slot-definition-name
:test-not #'eq)))
all-names)))
(defun std-compute-effective-slot-definition (class direct-slots)
(declare (ignore class))
(let ((initer (!find-if-not #'null direct-slots
:key #'slot-definition-initfunction)))
(make-effective-slot-definition
:name (slot-definition-name (car direct-slots))
:initform (if initer
(slot-definition-initform initer)
nil)
:initfunction (if initer
(slot-definition-initfunction initer)
nil)
:initargs (remove-duplicates
(mapappend #'slot-definition-initargs
direct-slots))
:allocation (slot-definition-allocation (car direct-slots)))))
;;; EOF
| 26,136 | Common Lisp | .lisp | 596 | 36.83557 | 118 | 0.647687 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | eb7812c15361b689f1fe257b927d7d7d32a7e57cf15b8b951c59f3bf73ac6915 | 43 | [
-1
] |
44 | describe.lisp | jscl-project_jscl/src/clos/describe.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;;; describe.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; Implementation of the `describe` standard function
;;; js-object signature
;;; return js-object signature like [object object]
;;;
;;; also the workaround for know problem with js-object
;;; created with Object.create(Null)
;;; for example look *package-table* into prelude.js
;;; attempt print this, caused error
(defun js-object-signature (obj)
(if (not (js-object-p obj))
nil
(handler-case
(progn
;; legal signature
;; [object Object]
;; [object HTMLxxxx]
;; undefined
(#j:String obj))
(error (msg)
;; js-object created with Object.create(Null) ?
;; legal signature 'simple-object'
"[object Simple-object]"))))
;;; some utils
(defmacro with-pp-buffer ((var) &body body)
`(let ((,var (make-string-output-stream)))
,@body))
(defmacro flush-pp-buffer (var stream)
`(princ (get-output-stream-string ,var) ,stream))
(defun pp/builtin-baner (class &optional (stream *standard-output*))
(format stream "Class: #<builtin-in-class ~a>~%" class))
(defun pp/terpri (stream)
(format stream "~%"))
(defun pp/presentation (obj class stream)
(format stream "~a~%Class: #<builtin-in-class ~a>~%" obj class))
;;; CLOS describe-object
(defgeneric describe-object (object &optional stream))
(defmethod describe-object ((object standard-object) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(format buf "A CLOS object
Printed representation: ~S
Class: ~S
Structure "
object
(class-of object))
(dolist (sn (mapcar #'slot-definition-name (class-slots (class-of object))))
(format buf "~% ~S <- [~S]"
sn
(if (slot-boundp object sn)
(slot-value object sn)
"slot unbound")))
(format buf "~%")
(flush-pp-buffer buf stream))
(values))
(defmethod describe-object ((object t) &optional (stream *standard-output*))
(describe object stream)
(values))
;;; Describe
(defgeneric describe (what &optional (stream *standard-output*)))
;;; mop-object
(defmethod describe (what &optional (stream *standard-output*))
(with-pp-buffer (buf)
(if (mop-object-p what)
(describe-object what buf)
(progn
;; its possible bug
(warn "`describe` for this object yet not implemented")
(prin1 what)
(pp/terpri buf)))
(flush-pp-buffer buf stream))
(values))
;;; js-object
(defmethod describe ((obj js-object) &optional (stream *standard-output*))
(let ((keys (#j:Object:keys obj)))
(with-pp-buffer (buf)
(pp/presentation obj 'js-object buf)
(format buf "Signature: ~a~%" (js-object-signature obj))
(if (and keys (> (length keys) 0))
(format buf "Keys: ~a~%" (map 'list (lambda (obj) (js-to-lisp obj)) keys)))
(flush-pp-buffer buf stream)
(values) )))
;;; number integer
;;;
;;; Note for "toString" conversion
;;; If the numObj is negative, the sign is preserved. This is the case even if the radix is 2;
;;; the string returned is the positive binary representation of the numObj preceded by a - sign,
;;; not the two's complement of the numObj.
;;; See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
(defmethod describe ((obj integer) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/builtin-baner 'integer buf)
(format buf "Fixnum: ~a~%" obj)
(labels
((make-number (value)
(make-new #j:Number value))
(number-to-fixed (value &optional (digits 0))
((oget (make-Number value) "toFixed") digits))
(number-to-exponent (value)
((oget (make-Number value) "toExponential")))
(number-by-radix (value &optional (radix 10))
((oget (make-Number value) "toString") radix)))
(format buf "Exponential: ~a~%" (number-to-exponent obj))
(when (> obj 0)
;; not display for negative value
;;See note for toString conversion
(format buf "Binary: ~a~%Decimal: ~a~%Octal: ~a~%Hex: ~a~%"
(number-by-radix obj 2)
(number-to-fixed obj 1)
(number-by-radix obj 8)
(number-by-radix obj 16))
;; char code restrict
(if (<= obj 2028)
(format buf "Character: ~a~%" (code-char obj)))
(format buf "As time: ~a~%" (string (make-new #j:Date obj)))))
(flush-pp-buffer buf stream)
(values)))
;;; number float
;;; wtf: (floatp 0.0) => nil ???
;;; its bug or feature ???
(defmethod describe ((obj float) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/builtin-baner 'float stream)
;; note: use truncate its no good idea
(format stream "Float: ~a~%Nearest integer: ~a~%" obj (truncate obj))
(flush-pp-buffer buf stream))
(values))
;;; symbol & keyword
(defmethod describe ((obj symbol) &optional (stream *standard-output*))
(let ((pkg (symbol-package obj))
(sym-name (symbol-name obj)))
(with-pp-buffer (buf)
(pp/presentation obj 'symbol buf)
(multiple-value-bind (symbol used) (intern sym-name pkg)
(format buf "~a in package ~a~%Print name: ~s~%" used (package-name pkg) sym-name))
;; check t/nil
(when (or (eq obj 't) (eq obj 'nil))
(format buf "Constant~%Value: ~a" obj)
(format buf "~%Class: <#builtin-in-class ~a>~%" (if obj "T" "NULL"))
(flush-pp-buffer buf stream)
(return-from describe (values)))
;; check what symbol is macro
(when (find obj (lexenv-function *environment*) :key #'binding-name)
(format buf "~A names a Macro function~%" obj)
(flush-pp-buffer buf stream)
(return-from describe (values)))
;; check plist
(let ((plist (symbol-plist obj)))
(when plist
(format buf "Plist: ~a~%" plist)))
;; check bounded
(when (boundp obj)
(format buf "~A names a special variable~%" (symbol-name obj))
(let ((doc (oget obj "vardoc")))
(when doc
(format buf "Documentation: ~a~%" doc)))
(format buf "Value: ~a~%" (symbol-value obj))
(when (not (keywordp obj))
(describe (symbol-value obj) buf)
(flush-pp-buffer buf stream)
(return-from describe (values)) ))
;; check bounded function
(when (fboundp obj)
(cond ((find-generic-function obj nil)
(format buf "~A names a generic function~%" obj)
(describe-object (find-generic-function obj) buf))
(t
(format buf "~A names a function~%" obj)
(describe (fdefinition obj) buf))))
(flush-pp-buffer buf stream) ))
(values))
;;; character
(defmethod describe ((obj character) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/builtin-baner 'character buf)
(format buf "Character: ~a~%Code char: ~a~%" obj (char-code obj))
(flush-pp-buffer buf stream))
(values))
;;; hash-table
#+nil
(defmethod describe ((obj hash-table) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/builtin-baner 'hash-table buf)
(format buf "Size: ~a~%Hash fn: ~a~%"
(hash-table-count obj)
(let ((test (cadr obj)))
(cond ((eq test #'jscl::eq-hash) 'eq)
((eq test #'jscl::eql-hash) 'eql)
(t 'equal))))
(flush-pp-buffer buf stream))
(values))
(defmethod describe ((obj hash-table) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/builtin-baner 'hash-table buf)
(format buf "Items: ~a~%Test fn: ~a~%"
(hash-table-count obj)
(hash-table-test obj))
(flush-pp-buffer buf stream))
(values))
;;; structure
(defmethod describe ((obj structure) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/presentation obj 'structure buf)
(let* ((slots (cdr obj))
(len (length slots)))
(format buf "Type: ~a~%Num fields: ~a~%" (car obj) len)
(dotimes (idx len)
(format buf "~d: ~s~%" idx (nth idx slots)))
(flush-pp-buffer buf stream) ))
(values))
;;; package
(defmethod describe ((obj package) &optional (stream *standard-output*))
(let ()
(labels ((count-it (object)
(let ((n 0))
(dolist (it (vector-to-list (#j:Object:keys object)))
(setq n (1+ n)))
n)))
(with-pp-buffer (buf)
(pp/presentation obj 'package buf)
(format buf "Package name: ~a~%" (package-name obj))
(format buf "Internal Symbols: ~a~%External Symbols: ~a~%Used: ~a~%"
(count-it (oget obj "symbols"))
(count-it (oget obj "exports"))
(oget obj "use"))
(flush-pp-buffer buf stream)))
(values) ))
;;; function
(defmethod describe ((obj function) &optional (stream *standard-output*))
(let ((name (oget obj "fname"))
(doc (oget obj "docstring")))
(with-pp-buffer (buf)
(pp/presentation obj 'function stream)
(format buf "Name:~a~%" (if name name "anonimous"))
(when doc
(format buf "Documentation: ~a~%" doc))
(flush-pp-buffer buf stream))
(values)))
;;; sequences
(defmethod describe ((obj string) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/presentation obj 'string buf)
(format buf "Length: ~a~%" (length obj))
(dotimes (idx (length obj))
(format buf "~d: ~d~%" idx (aref obj idx)))
(flush-pp-buffer buf stream))
(values))
(defmethod describe ((obj vector) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(pp/presentation obj 'vector stream)
(format buf "Length: ~a~%" (length obj))
(flush-pp-buffer buf stream))
(values))
(defmethod describe ((obj array) &optional (stream *standard-output*))
(let ((dimensions (array-dimensions obj))
(type (array-element-type obj))
(size (length obj)))
(with-pp-buffer (buf)
(pp/presentation obj 'array buf)
(format buf "Dimensions: ~a~%Length: ~a~%Element-type: ~a~%"
dimensions size type)
(flush-pp-buffer buf stream))
(values) ))
(defmethod describe :after ((obj array) &optional (stream *standard-output*))
(if (= (length obj) 0)
(let ((keys (#j:Object:keys obj)))
(when (and keys (> (length keys) 0))
(with-pp-buffer (buf)
(format buf "Associative JS array~%Keys: ~a~%"
(map 'list (lambda (obj) (js-to-lisp obj)) keys))
(flush-pp-buffer buf stream)))))
(values) )
;;; list/cons
;;; with dirty hack for recognize list or cons
(defmethod describe ((obj list) &optional (stream *standard-output*))
(with-pp-buffer (buf)
(cond ((true-cons-p obj)
(pp/presentation obj 'cons buf)
(format buf "Car: ~s~%Cdr: ~s~%" (car obj) (cdr obj)))
(t
(let ((len (list-length obj)))
(pp/presentation obj 'list buf)
(format buf "Length: ~a~%" len)
(dotimes (idx len)
(format buf "~d: ~s~%" idx (nth idx obj))))))
(flush-pp-buffer buf stream))
(values))
;;; EOF
| 11,994 | Common Lisp | .lisp | 300 | 33.156667 | 104 | 0.605426 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | f2c455dca5e2f3d54066ed9a69754062ebd3019932575e75f174890efc03b9f6 | 44 | [
-1
] |
45 | newcl.lisp | jscl-project_jscl/src/clos/closette/newcl.lisp | ;;;-*-Mode:LISP; Package:NEWCL; Base:10; Syntax:Common-lisp -*-
;;; This is the file newcl.lisp
;;; Revisions of September 27, 1991 by desRivieres@parc.xerox.com:
;;; - add clause to make print-unreadable-object work for AKCL
;;; - standardize on uppercase names in setf-function-symbol
(in-package 'newcl :use '(lisp))
(shadow '(defun fmakunbound fboundp))
(export '(fdefinition defun fmakunbound fboundp print-unreadable-object))
;;; New macros to support function names like (setf foo).
(lisp:defun setf-function-symbol (function-specifier)
(if (consp function-specifier)
(let ((print-name (format nil "~:@(~A~)" function-specifier)))
(intern print-name
(symbol-package (cadr function-specifier))))
function-specifier))
(lisp:defun fboundp (function-specifier)
(if (consp function-specifier)
(lisp:fboundp (setf-function-symbol function-specifier))
(lisp:fboundp function-specifier)))
(lisp:defun fdefinition (function-specifier)
(if (consp function-specifier)
(lisp:symbol-function (setf-function-symbol function-specifier))
(lisp:symbol-function function-specifier)))
(lisp:defun fmakunbound (function-specifier)
(if (consp function-specifier)
(lisp:fmakunbound (setf-function-symbol function-specifier))
(lisp:fmakunbound function-specifier)))
(defsetf fdefinition (function-specifier) (new-value)
`(set-fdefinition ,new-value ,function-specifier))
(lisp:defun set-fdefinition (new-value function-specifier)
(if (consp function-specifier)
(progn
(setf (symbol-function (setf-function-symbol function-specifier))
new-value)
(eval `(defsetf ,(cadr function-specifier)
(&rest all-args)
(new-value)
`(,',(setf-function-symbol function-specifier)
,new-value
,@all-args))))
(setf (symbol-function function-specifier) new-value)))
(defmacro defun (name formals &body body)
(cond ((symbolp name)
`(lisp:defun ,name ,formals ,@body))
((and (consp name) (eq (car name) 'setf))
`(progn
(lisp:defun ,(setf-function-symbol name) ,formals ,@body)
(defsetf ,(cadr name) ,(cdr formals) (,(car formals))
(list ',(setf-function-symbol name) ,@formals))))))
#| Minimal tests:
(macroexpand '(defun (setf foo) (nv x y) (+ x y)))
(defun (setf baz) (new-value arg)
(format t "setting value of ~A to ~A" arg new-value))
(macroexpand '(setf (baz (+ 2 2)) (* 3 3)))
|#
;;;
;;; print-unreadable-object
;;;
;;; print-unreadable-object is the standard way in the new Common Lisp
;;; to generate #< > around objects that can't be read back in. The option
;;; (:identity t) causes the inclusion of a representation of the object's
;;; identity, typically some sort of machine-dependent storage address.
(defmacro print-unreadable-object
((object stream &key type identity) &body body)
`(let ((.stream. ,stream)
(.object. ,object))
(format .stream. "#<")
,(when type
'(format .stream. "~S" (type-of .object.)))
,(when (and type (or body identity))
'(format .stream. " "))
,@body
,(when (and identity body)
'(format .stream. " "))
,(when identity
#+Genera '(format .stream. "~O" (si:%pointer .object.))
#+Lucid '(format .stream. "~O" (sys:%pointer .object.))
#+Excl '(format .stream. "~O" (excl::pointer-to-fixnum .object.))
#+:coral '(format .stream. "~O" (ccl::%ptr-to-int .object.))
#+kcl '(format .stream. "~O" (si:address .object.))
)
(format .stream. ">")
nil))
| 3,697 | Common Lisp | .lisp | 83 | 38.168675 | 75 | 0.641011 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | bd5ca0306367a5c4eb456ad76a5a04040aea3c9eb6ccdf85fd311ecc66f9ba76 | 45 | [
-1
] |
46 | closette-tests.lisp | jscl-project_jscl/src/clos/closette/closette-tests.lisp | ;;;-*-Mode:LISP; Package: CLOSETTE; Base:10; Syntax:Common-lisp -*-
(in-package 'closette :use '(lisp))
;;; CLOSette tests
;;; From chapter 1
(defclass rectangle ()
((height :initform 0.0 :initarg :height)
(width :initform 0.0 :initarg :width)))
(defclass color-mixin ()
((cyan :initform 0 :initarg :cyan)
(magenta :initform 0 :initarg :magenta)
(yellow :initform 0 :initarg :yellow)))
(defclass color-rectangle (color-mixin rectangle)
((clearp :initform (y-or-n-p "But is it transparent?")
:initarg :clearp :accessor clearp)))
(defgeneric paint (x))
(defmethod paint ((x rectangle)) ;Method #1
(vertical-stroke (slot-value x 'height)
(slot-value x 'width)))
(defmethod paint :before ((x color-mixin)) ;Method #2
(set-brush-color (slot-value x 'cyan)
(slot-value x 'magenta)
(slot-value x 'yellow)))
(defmethod paint ((x color-rectangle)) ;Method #3
(unless (clearp x) (call-next-method)))
(setq door
(make-instance 'color-rectangle
:width 38 :height 84 :cyan 60 :yellow 55 :clearp nil))
(defun vertical-stroke (x y) (declare (ignore x y)) (values))
(defun set-brush-color (x y z) (declare (ignore x y z)) (values))
(paint door)
;;; test method combination
(defgeneric mctest (x))
(defmethod mctest :around ((x integer))
(format t "(:around integer)")
(call-next-method))
(defmethod mctest :around ((x number))
(format t "(:around number)")
(call-next-method))
(defmethod mctest :before ((x number))
(format t "(:before number)"))
(defmethod mctest ((x number))
(format t "(primary number)")
(1+ (call-next-method)))
(defmethod mctest :after ((x number))
(format t "(:after number)"))
(defmethod mctest :before ((x t))
(format t "(:before t)"))
(defmethod mctest ((x t))
(format t "(primary t)")
100)
(defmethod mctest :after ((x t))
(format t "(:after t)"))
(mctest 1)
#|(:around integer)(:around number)(:before number)(:before t)
(primary number)(primary t)(:after t)(:after number)
101|#
;;; following chapter 1
(pprint (macroexpand
'(defclass color-rectangle (color-mixin rectangle)
((clearp :initform (y-or-n-p "But is it transparent?")
:initarg :clearp :accessor clearp)))))
#|(ensure-class 'color-rectangle
:direct-superclasses
(list (find-class 'color-mixin) (find-class 'rectangle))
:direct-slots
(list
(list :name 'clearp :initform
'(y-or-n-p "But is it transparent?")
:initfunction
(function
(lambda nil (y-or-n-p "But is it transparent?")))
:initargs
'(:clearp)
:readers
'(clearp)
:writers
'((setf clearp)))))
|#
;;; original compute-slots
(defun original-compute-slots (class)
(mapcar #'(lambda (slot)
(make-effective-slot-definition
:name (slot-definition-name slot)
:initform (slot-definition-initform slot)
:initfunction (slot-definition-initfunction slot)
:initargs (slot-definition-initargs slot)))
(remove-duplicates
(mapappend #'class-direct-slots
(class-precedence-list class))
:key #'slot-definition-name
:from-end t)))
(equal (original-compute-slots (find-class 'color-rectangle))
(compute-slots (find-class 'color-rectangle)))
#|T|#
(pprint (macroexpand
'(defgeneric paint (x))))
#|(ensure-generic-function 'paint :lambda-list '(x))|#
(pprint (macroexpand
'(defmethod paint :before ((x color-mixin)) ; Method#2
(set-brush-color (slot-value x 'cyan)
(slot-value x 'magenta)
(slot-value x 'yellow)))))
#|(ensure-method (find-generic-function 'paint)
:lambda-list
'(x)
:qualifiers
'(:before)
:specializers
(list (find-class 'color-mixin))
:body
'(block paint
(set-brush-color (slot-value x 'cyan)
(slot-value x 'magenta)
(slot-value x 'yellow)))
:environment
(top-level-environment))
|#
(find-generic-function 'clearp)
#|#<Closette:Standard-Generic-Function CLOSETTE::CLEARP 16060700>|#
(clearp (make-instance 'color-rectangle :clearp t))
#|T|#
;;; change-class
(setq o1 (make-instance 'rectangle :height 10 :width 20))
(describe-object o1 *standard-output*)
#| A CLOS object
Printed representation: #<Rectangle 16166710>
Class: #<Standard-Class rectangle 15253764>
Structure
height <- 10
width <- 20
|#
(change-class o1 'color-mixin)
(describe-object o1 *standard-output*)
#| A CLOS object
Printed representation: #<Color-Mixin 16166710>
Class: #<Standard-Class color-mixin 15274440>
Structure
cyan <- 0
magenta <- 0
yellow <- 0
|#
(change-class o1 'standard-object)
(describe-object o1 *standard-output*)
#| A CLOS object
Printed representation: #<Standard-Object 16166710>
Class: #<Standard-Class standard-object 15071700>
Structure
|#
(sub-specializer-p (find-class 'color-mixin)
(find-class 'rectangle)
(find-class 'color-rectangle))
#|T|#
(sub-specializer-p (find-class 'rectangle)
(find-class 'rectangle)
(find-class 'color-rectangle))
#|NIL|#
;;; exercise
(defvar all-tables (make-hash-table :test #'eq))
(defun classes-to-applicable-methods-table (gf)
(let ((table (gethash gf all-tables nil)))
(unless table
(setq table (make-hash-table :test #'equal))
(setf (gethash gf all-tables) table))
table))
(defun better-apply-generic-function (gf args)
(let* ((required-classes
(mapcar #'class-of (required-portion gf args)))
(applicable-methods
(or (gethash required-classes
(classes-to-applicable-methods-table gf)
nil)
(setf (gethash required-classes
(classes-to-applicable-methods-table gf))
(compute-applicable-methods-using-classes
gf required-classes)))))
(if (null applicable-methods)
(error "No matching method for the~@
generic function ~S,~@
when called with arguments ~:S." gf args)
(apply-methods gf args applicable-methods))))
(better-apply-generic-function
(find-generic-function 'make-instance)
(list 'rectangle))
;;; From chapter 2:
(defun subclasses* (class)
(remove-duplicates
(cons class
(mapappend #'subclasses*
(class-direct-subclasses class)))))
(defun subclasses (class) (remove class (subclasses* class)))
(subclasses (find-class 'rectangle))
#|(#<Standard-Class COLOR-RECTANGLE>)|#
(defvar my-classes
(mapcar #'class-name
(subclasses (find-class 'standard-object))))
my-classes
#|(color-mixin rectangle
color-rectangle
standard-method
standard-generic-function
standard-class)
|#
(defun display-defclass (class-name)
(pprint (generate-defclass (find-class class-name)))
(values))
(defun generate-defclass (class)
`(defclass ,(class-name class)
,(mapcar #'class-name (class-direct-superclasses class))
,(mapcar #'generate-slot-specification (class-direct-slots class))))
(defun generate-slot-specification (slot)
`(,(slot-definition-name slot)
,@(when (slot-definition-initfunction slot)
`(:initform ,(slot-definition-initform slot)))
,@(when (slot-definition-initargs slot)
(mapappend #'(lambda (initarg) `(:initarg ,initarg))
(slot-definition-initargs slot)))
,@(unless (eq (slot-definition-allocation slot) ':instance)
`(:allocation ,(slot-definition-allocation slot)))
,@(when (slot-definition-readers slot)
(mapappend #'(lambda (reader) `(:reader ,reader))
(slot-definition-readers slot)))
,@(when (slot-definition-writers slot)
(mapappend #'(lambda (writer) `(:writer ,writer))
(slot-definition-writers slot)))))
(display-defclass 'rectangle)
#|(DEFCLASS RECTANGLE (STANDARD-OBJECT)
((HEIGTH :INITFORM 0.0 :INITARG :HEIGTH)
(WIDTH :INITFORM 0.0 :INITARG :WIDTH)))|#
(display-defclass 't)
#|(DEFCLASS T () ())|#
(display-defclass 'standard-object)
#|(DEFCLASS STANDARD-OBJECT (T) ()) |#
(defun display-defclass* (class-name)
(pprint (generate-defclass* (find-class class-name)))
(values))
(defun generate-defclass* (class)
`(defclass* ,(class-name class)
,(mapcar #'class-name (cdr (class-precedence-list class)))
,(mapcar #'(lambda (slot)
(generate-inherited-slot-specification class slot))
(class-slots class))))
(defun generate-inherited-slot-specification (class slot)
(let* ((source-class
(find-if #'(lambda (superclass)
(find (slot-definition-name slot)
(class-direct-slots superclass)
:key #'slot-definition-name))
(class-precedence-list class)))
(generated-slot-spec
(generate-slot-specification slot)))
(if (eq source-class class)
generated-slot-spec
(append generated-slot-spec
`(:inherited-from ,(class-name source-class))))))
(display-defclass* 'color-rectangle)
#|(defclass* color-rectangle
(color-mixin rectangle standard-object t)
((clearp :initform
(y-or-n-p "But is it transparent?")
:initarg
:clearp)
(cyan :initform
0
:initarg
:cyan
:inherited-from
color-mixin)
(magenta :initform
0
:initarg
:magenta
:inherited-from
color-mixin)
(yellow :initform
0
:initarg
:yellow
:inherited-from
color-mixin)
(height :initform
0.0
:initarg
:height
:inherited-from
rectangle)
(width :initform
0.0
:initarg
:width
:inherited-from
rectangle)))
|#
(defclass color-chart (rectangle color-mixin) ())
(mapcar #'class-name (class-precedence-list
(find-class 'color-rectangle)))
#|(COLOR-RECTANGLE COLOR-MIXIN RECTANGLE STANDARD-OBJECT T)|#
(mapcar #'class-name (class-precedence-list
(find-class 'color-chart)))
#|(COLOR-CHART RECTANGLE COLOR-MIXIN STANDARD-OBJECT T)|#
(defun in-order-p (c1 c2)
(flet ((in-order-at-subclass-p (sub)
(let ((cpl (class-precedence-list sub)))
(not (null (member c2 (cdr (member c1 cpl))))))))
(or (eq c1 c2)
(every #'in-order-at-subclass-p
(intersection (subclasses* c1)
(subclasses* c2))))))
(in-order-p (find-class 'color-mixin)
(find-class 'rectangle))
#|NIL|#
(in-order-p (find-class 'standard-object)
(find-class 't))
#|T|#
(defclass position ()
(x y))
(defclass cad-element (position) ())
(defclass display-element (position) ())
(defclass displayable-cad-element (display-element cad-element) ())
(defun has-diamond-p (class)
(some #'(lambda (pair)
(not (null (common-subclasses* (car pair)
(cadr pair)))))
(all-distinct-pairs (class-direct-subclasses class))))
(defun common-subclasses* (class-1 class-2)
(intersection (subclasses* class-1) (subclasses* class-2)))
(defun all-distinct-pairs (set)
(if (null set)
()
(append (mapcar #'(lambda (rest)
(list (car set) rest))
(cdr set))
(all-distinct-pairs (cdr set)))))
(has-diamond-p (find-class 'position))
#|t|#
(has-diamond-p (find-class 'rectangle))
#|nil|#
(defun generate-defgeneric (gf)
`(defgeneric ,(generic-function-name gf)
,(generic-function-lambda-list gf)))
(defun generate-defmethod (method &key show-body)
`(defmethod ,(generic-function-name (method-generic-function method))
,@(method-qualifiers method)
,(generate-specialized-arglist method)
,@(when show-body (list (method-body method)))))
(defun generate-specialized-arglist (method)
(let* ((specializers (method-specializers method))
(lambda-list (method-lambda-list method))
(number-required (length specializers)))
(append (mapcar #'(lambda (arg class)
(if (eq class (find-class 't))
arg
`(,arg ,(class-name class))))
(subseq lambda-list 0 number-required)
specializers)
(subseq lambda-list number-required))))
(defun display-generic-function (gf-name &key show-body)
(display-defgeneric gf-name)
(dolist (method (generic-function-methods (find-generic-function gf-name)))
(pprint (generate-defmethod method :show-body show-body)))
(values))
(defun display-defgeneric (gf-name)
(pprint (generate-defgeneric (find-generic-function gf-name)))
(values))
(display-generic-function 'paint :show-body t)
#|(DEFGENERIC PAINT (X))
(DEFMETHOD PAINT ((X RECTANGLE))
(BLOCK PAINT
(VERTICAL-STROKE (SLOT-VALUE X 'HEIGHT)
(SLOT-VALUE X 'WIDTH))))
(DEFMETHOD PAINT :BEFORE ((X COLOR-MIXIN))
(BLOCK PAINT
(SET-BRUSH-COLOR (SLOT-VALUE X 'CYAN)
(SLOT-VALUE X 'MAGENTA)
(SLOT-VALUE X 'YELLOW))))
(DEFMETHOD PAINT ((X COLOR-RECTANGLE))
(BLOCK PAINT
(UNLESS (CLEARP X) (CALL-NEXT-METHOD))))
|#
(display-generic-function 'clearp :show-body t)
#|(DEFGENERIC CLEARP (OBJECT))
(DEFMETHOD CLEARP ((OBJECT COLOR-RECTANGLE))
(SLOT-VALUE OBJECT 'CLEARP)) |#
(display-generic-function '(setf clearp) :show-body t)
#|(DEFGENERIC (SETF CLEARP) (NEW-VALUE OBJECT))
(DEFMETHOD (SETF CLEARP) ((OBJECT COLOR-RECTANGLE))
(SETF (SLOT-VALUE OBJECT 'CLEARP) NEW-VALUE)) |#
(display-generic-function 'shared-initialize)
#|(DEFGENERIC SHARED-INITIALIZE (INSTANCE SLOT-NAMES &KEY))
(DEFMETHOD SHARED-INITIALIZE ((INSTANCE STANDARD-OBJECT)
SLOT-NAMES &REST ALL-KEYS))|#
(defun all-generic-functions ()
(remove-duplicates
(mapappend #'class-direct-generic-functions
(subclasses* (find-class 't)))))
(defun class-direct-generic-functions (class)
(remove-duplicates
(mapcar #'method-generic-function
(class-direct-methods class))))
(mapcar #'generic-function-name (all-generic-functions))
#|(CLEARP PAINT UPDATE-INSTANCE-FOR-DIFFERENT-CLASS
REINITIALIZE-INSTANCE INITIALIZE-INSTANCE CHANGE-CLASS
MAKE-INSTANCE (SETF CLEARP) SHARED-INITIALIZE
PRINT-OBJECT \ldots)|#
(defun relevant-generic-functions (class ceiling)
(remove-duplicates
(mapcar #'method-generic-function
(mapappend #'class-direct-methods
(set-difference (class-precedence-list class)
(class-precedence-list ceiling))))))
(relevant-generic-functions (find-class 'color-rectangle)
(find-class 'standard-object))
#|(#<Standard-Generic-Function paint 16031414>
#<Standard-Generic-Function (setf clearp) 16021300>
#<Standard-Generic-Function clearp 16016120>)|#
(defun display-effective-method (gf args)
(let ((applicable-methods
(compute-applicable-methods-using-classes
gf (mapcar #'class-of (required-portion gf args)))))
(pprint
(if (null applicable-methods)
'(error "No applicable methods.")
(generate-effective-method gf applicable-methods)))))
(defun generate-effective-method (gf methods)
(declare (ignore gf))
(labels ((generate-method (method)
`(method ,@(cdr (generate-defmethod
method :show-body t))))
(generate-call-method (method next-methods)
`(call-method
,(generate-method method)
,(mapcar #'generate-method next-methods))))
(let ((primaries (remove-if-not #'primary-method-p methods))
(befores (remove-if-not #'before-method-p methods))
(afters (remove-if-not #'after-method-p methods)))
(if (null primaries)
'(error "No primary method")
`(progn
,@(mapcar
#'(lambda (method)
(generate-call-method method ()))
befores)
(multiple-value-prog1
,(generate-call-method (car primaries)
(cdr primaries))
,@(mapcar
#'(lambda (method)
(generate-call-method method ()))
(reverse afters))))))))
(display-effective-method (find-generic-function 'paint)
(list (make-instance 'color-rectangle
:clearp nil)))
#|(progn
(call-method
(method paint
:before
((x color-mixin))
(block paint
(set-brush-color (slot-value x 'cyan)
(slot-value x 'magenta)
(slot-value x 'yellow))))
nil)
(multiple-value-prog1
(call-method
(method paint
((x color-rectangle))
(block paint (unless (clearp x) (call-next-method))))
((method paint
((x rectangle))
(block paint
(vertical-stroke (slot-value x 'height)
(slot-value x 'width))))))))
|#
(display-effective-method (find-generic-function 'paint)
(list (make-instance 'rectangle)))
#|(progn
(multiple-value-prog1
(call-method
(method paint
((x rectangle))
(block paint
(vertical-stroke (slot-value x 'height)
(slot-value x 'width))))
nil)))
|#
(defun reader-method-p (method)
(let ((specializers (method-specializers method)))
(and (= (length specializers) 1)
(member (generic-function-name (method-generic-function method))
(mapappend #'slot-definition-readers
(class-direct-slots (car specializers)))
:test #'equal))))
(defun writer-method-p (method)
(let ((specializers (method-specializers method)))
(and (= (length specializers) 2)
(member (generic-function-name (method-generic-function method))
(mapappend #'slot-definition-writers
(class-direct-slots (cadr specializers)))
:test #'equal))))
(defun relevant-generic-functions (class ceiling &key elide-accessors-p)
(remove-duplicates
(mapcar #'method-generic-function
(remove-if #'(lambda (m)
(and elide-accessors-p
(or (reader-method-p m)
(writer-method-p m))))
(mapappend #'class-direct-methods
(set-difference (class-precedence-list class)
(class-precedence-list ceiling)))))))
(relevant-generic-functions (find-class 'color-rectangle)
(find-class 'standard-object)
:elide-accessors-p 't)
#|(#<Standard-Generic-Function paint 15316224>)|#
(defclass shape () ())
(defclass circle (shape) ())
(defclass triangle (shape) ())
(defclass pentagon (shape) ())
(defclass label-type () ())
(defclass top-labeled (label-type) ())
(defclass center-labeled (label-type) ())
(defclass bottom-labeled (label-type) ())
(defclass color () ())
(defclass fuschia (color) ())
(defclass orange (color) ())
(defclass magenta (color) ())
(defun make-programmatic-instance (superclass-names &rest initargs)
(apply #'make-instance
(find-programmatic-class
(mapcar #'find-class superclass-names))
initargs))
(defun find-programmatic-class (superclasses)
(let ((class (find-if
#'(lambda (class)
(equal superclasses
(class-direct-superclasses class)))
(class-direct-subclasses (car superclasses)))))
(if class
class
(make-programmatic-class superclasses))))
(defun make-programmatic-class (superclasses)
(make-instance 'standard-class
:name (mapcar #'class-name superclasses)
:direct-superclasses superclasses
:direct-slots ()))
(make-programmatic-instance '(circle orange top-labeled)
:title "Color Wheel"
:radius 10)
#|#<(Circle Orange Top-Labeled) 16023764>|#
(class-direct-subclasses (find-class 'circle))
#|(#<Standard-Class (circle orange top-labeled) 16021350>)|#
(setq i1 (make-programmatic-instance
'(circle orange top-labeled))
i2 (make-programmatic-instance
'(circle magenta bottom-labeled))
i3 (make-programmatic-instance
'(circle orange top-labeled)))
(class-direct-subclasses (find-class 'circle))
#|(#<Standard-Class (circle magenta bottom-labeled) 16043060>
#<Standard-Class (circle orange top-labeled) 16021350>)|#
;;; From chapter 3
(defclass counted-class (standard-class)
((counter :initform 0)))
(setf (find-class 'counted-rectangle)
(make-instance 'counted-class
:name 'counted-rectangle
:direct-superclasses (list (find-class 'rectangle))
:direct-slots ()))
(class-of (find-class 'rectangle))
#|#<Standard-Class STANDARD-CLASS 12505420>|#
(class-of (find-class 'counted-rectangle))
#|#<Standard-Class COUNTED-CLASS 69547893> |#
#|(slot-value (find-class 'rectangle) 'counter)
Error: The slot COUNTER is missing from the class
#<Standard-Class STANDARD-CLASS 15501664>.|#
(slot-value (find-class 'counted-rectangle) 'counter)
#|0|#
(defmethod make-instance :after ((class counted-class) &rest all-keys)
(incf (slot-value class 'counter)))
(slot-value (find-class 'counted-rectangle) 'counter)
#|0|#
(make-instance 'counted-rectangle)
(slot-value (find-class 'counted-rectangle) 'counter)
#|1|#
(pprint (macroexpand
'(defclass counted-rectangle (rectangle)
()
(:metaclass counted-class))))
#|(ENSURE-CLASS 'COUNTED-RECTANGLE
:DIRECT-SUPERCLASSES
(LIST (FIND-CLASS 'RECTANGLE))
:DIRECT-SLOTS
(LIST)
:METACLASS
(FIND-CLASS 'COUNTED-CLASS))|#
(print-object (find-class 'counted-rectangle) *standard-output*)
#|#<Closette::Counted-Class CLOSETTE::COUNTED-RECTANGLE 16252370>|#
(print-object (find-class 'rectangle) *standard-output*)
#|#<Closette:Standard-Class CLOSETTE::RECTANGLE 15730444>|#
;;; alternative cpls
(defclass loops-class (standard-class) ())
(defclass flavors-class (standard-class) ())
(defmethod compute-class-precedence-list ((class loops-class))
(append (remove-duplicates
(depth-first-preorder-superclasses* class)
:from-end nil)
(list (find-class 'standard-object)
(find-class 't))))
(defmethod compute-class-precedence-list ((class flavors-class))
(append (remove-duplicates
(depth-first-preorder-superclasses* class)
:from-end t)
(list (find-class 'standard-object)
(find-class 't))))
(defun depth-first-preorder-superclasses* (class)
(if (eq class (find-class 'standard-object))
()
(cons class (mapappend #'depth-first-preorder-superclasses*
(class-direct-superclasses class)))))
(defclass a () ())
(defclass b () ())
(defclass c () ())
(defclass s (a b) ())
(defclass r (a c) ())
(defclass q-clos (s r) () (:metaclass standard-class))
(defclass q-loops (s r) () (:metaclass loops-class))
(defclass q-flavors (s r) () (:metaclass flavors-class))
(pprint (class-precedence-list (find-class 'q-flavors)))
#|(q-flavors s a b r c standard-object t)|#
(pprint (class-precedence-list (find-class 'q-loops)))
#|(q-loops s b r a c standard-object t)|#
(pprint (class-precedence-list (find-class 'q-clos)))
#|(q-clos s r a c b standard-object t)|#
(defclass vanilla-flavor () ())
(defmethod initialize-instance :around ((class flavors-class)
&rest all-keys
&key direct-superclasses)
(apply #'call-next-method
class
:direct-superclasses (or direct-superclasses
(list (find-class 'vanilla-flavor)))
all-keys))
(defclass flavors-test () () (:metaclass flavors-class))
(pprint (class-precedence-list (find-class 'flavors-test)))
#|(#<Flavors-Class flavors-test 16222110>
#<Standard-Class vanilla-object 16213600>
#<Standard-Class standard-object 15075604>
#<Standard-Class t 15060104>)|#
;;; attributes
(defclass attributes-class (standard-class) ())
(defun slot-definition-attributes (slot)
(getf slot ':attributes ()))
(defun (setf slot-definition-attributes) (new-value slot)
(setf (getf* slot ':attributes) new-value))
(defmethod compute-effective-slot-definition ((class attributes-class)
direct-slots)
(let ((normal-slot (call-next-method)))
(setf (slot-definition-attributes normal-slot)
(remove-duplicates
(mapappend #'slot-definition-attributes
direct-slots)))
normal-slot))
(defmethod compute-slots ((class attributes-class))
(let ((normal-slots (call-next-method)))
(flet ((initial-attribute-alist (slots)
(mapcar
#'(lambda (slot)
(cons (slot-definition-name slot)
(mapcar #'(lambda (attr) (cons attr nil))
(slot-definition-attributes slot))))
slots)))
(let ((alist (initial-attribute-alist normal-slots)))
(cons (make-effective-slot-definition
:name 'all-attributes
:initform alist
:initfunction #'(lambda () alist))
normal-slots)))))
(defun slot-attribute (instance slot-name attribute)
(cdr (slot-attribute-bucket instance slot-name attribute)))
(defun (setf slot-attribute) (new-value instance slot-name attribute)
(setf (cdr (slot-attribute-bucket
instance slot-name attribute))
new-value))
(defun slot-attribute-bucket (instance slot-name attribute)
(let* ((all-buckets (slot-value instance 'all-attributes))
(slot-bucket (assoc slot-name all-buckets)))
(unless slot-bucket
(error "The slot named ~A of ~S has no attributes."
slot-name instance))
(let ((attr-bucket (assoc attribute (cdr slot-bucket))))
(unless attr-bucket
(error "The slot named ~A of ~S has no attribute~@
named ~A." slot-name instance attribute))
attr-bucket)))
(defclass credit-rating ()
((level :attributes (date-set time-set)))
(:metaclass attributes-class))
(setq cr (make-instance 'credit-rating))
(slot-attribute cr 'level 'date-set)
#|NIL|#
(setf (slot-attribute cr 'level 'date-set) "12/15/90")
(slot-attribute cr 'level 'date-set)
#|"12/15/90"|#
(defclass monitored-credit-rating (credit-rating)
((level :attributes (last-checked interval)))
(:metaclass attributes-class))
(slot-value cr 'all-attributes)
#|((level . ((date-set . "12/15/90") (time-set . nil))))|#
(slot-value (make-instance 'monitored-credit-rating)
'all-attributes)
#| ((level . ((last-checked . nil) (interval . nil)
(date-set .nil ) (time-set .nil))))|#
;;; encapsulated classes
(defclass encapsulated-class (standard-class) ())
(defmethod initialize-instance :around ((class encapsulated-class)
&rest all-keys
&key direct-slots)
(let ((revised-direct-slots
(mapcar
#'(lambda (slot-properties)
(let ((pretty-name (getf slot-properties ':name))
(new-properties (copy-list slot-properties)))
(setf (getf* new-properties ':name) (gensym))
(setf (getf* new-properties ':pretty-name) pretty-name)
new-properties))
direct-slots)))
(apply #'call-next-method class
:direct-slots revised-direct-slots
all-keys)))
(defun slot-definition-pretty-name (slot)
(getf slot ':pretty-name))
(defun (setf slot-definition-pretty-name) (new-value slot)
(setf (getf* slot ':pretty-name) new-value))
(defun private-slot-value (instance slot-name class-name)
(slot-value instance (private-slot-name slot-name class-name)))
(defun private-slot-name (slot-name class-name)
(let* ((class (find-class class-name))
(slot (find slot-name
(class-direct-slots class)
:key #'slot-definition-pretty-name)))
(if slot
(slot-definition-name slot)
(error "The class ~S has no private slot named ~S."
class-name slot-name))))
(defclass c1 ()
((foo :reader foo :initform 100))
(:metaclass encapsulated-class))
(class-direct-slots (find-class 'c1))
(defclass c2 (c1)
((foo :reader foo :initform 200))
(:metaclass encapsulated-class))
(class-direct-slots (find-class 'c2))
(defgeneric mumble (o))
(defmethod mumble ((o c1))
(private-slot-value o 'foo 'c1))
(defmethod mumble ((o c2))
(+ (private-slot-value o 'foo 'c2)
(call-next-method)))
(mumble (make-instance 'c1))
#|100|#
(mumble (make-instance 'c2))
#|300|#
;;; default initargs
(pprint (macroexpand
'(defclass frame (rectangle)
()
(:metaclass default-initargs-class)
(:default-initargs :width 10))))
#|(ensure-class 'frame
:direct-superclasses
(list (find-class 'rectangle))
:direct-slots ()
:metaclass
(find-class 'default-initargs-class)
:direct-default-initargs
(list ':width 10))|#
(defclass default-initargs-class (standard-class)
((direct-default-initargs
:initarg :direct-default-initargs
:initform ()
:accessor class-direct-default-initargs)))
(defun compute-class-default-initargs (class)
(mapappend #'class-direct-default-initargs
(class-precedence-list class)))
(defmethod class-direct-default-initargs ((class standard-class))
())
(defmethod make-instance ((class default-initargs-class) &rest initargs)
(apply #'call-next-method
class
(append initargs
(compute-class-default-initargs class))))
(defclass frame (rectangle)
()
(:metaclass default-initargs-class)
(:default-initargs :width 10))
(setq f (make-instance 'frame :height 20))
(slot-value f 'height)
#|20|#
(slot-value f 'width)
#|10|#
(setq g (make-instance 'frame :height 20 :width 10))
(slot-value g 'height)
#|20|#
(slot-value g 'width)
#|10|#
;;; precomputed default initargs
(defclass default-initargs-class-2 (standard-class)
((direct-default-initargs
:initarg :direct-default-initargs
:initform ()
:accessor class-direct-default-initargs)
(effective-default-initargs
:accessor class-default-initargs)))
(defmethod finalize-inheritance :after ((class default-initargs-class-2))
(setf (class-default-initargs class)
(compute-class-default-initargs class)))
(defmethod make-instance ((class default-initargs-class-2) &rest initargs)
(apply #'call-next-method
class
(append initargs (class-default-initargs class))))
(defun compute-class-default-initargs (class)
(mapappend #'class-direct-default-initargs
(class-precedence-list class)))
(defmethod class-default-initargs ((class standard-class))
())
(defclass frame-2 (rectangle)
()
(:metaclass default-initargs-class-2)
(:default-initargs :width 10))
(setq f (make-instance 'frame-2 :height 20))
(slot-value f 'height)
#|20|#
(slot-value f 'width)
#|10|#
;;;
(defmacro new-defclass (name direct-superclasses direct-slots
&rest options)
(let* ((metaclass-option
(find ':metaclass options :key #'car))
(metaclass-name (if metaclass-option
(cadr metaclass-option)
'standard-class))
(sample-class-metaobject
(allocate-instance (find-class metaclass-name)))
(canonical-supers
(canonicalize-direct-superclasses direct-superclasses))
(canonical-slots
(canonicalize-direct-slots direct-slots))
(canonical-options
(new-canonicalize-defclass-options
sample-class-metaobject
(remove metaclass-option options))))
`(ensure-class ',name
:direct-superclasses ,canonical-supers
:direct-slots ,canonical-slots
:metaclass (find-class ',metaclass-name)
,@canonical-options)))
(defun new-canonicalize-defclass-options (sample-class options)
(mapappend #'(lambda (option)
(new-canonicalize-defclass-option sample-class option))
options))
(defgeneric new-canonicalize-defclass-option (sample-class option))
(defmethod new-canonicalize-defclass-option
((sample-class standard-class) option)
(error "Unrecognized defclass option ~S." option))
(defmethod new-canonicalize-defclass-option
((sample-class default-initargs-class) option)
(case (car option)
(:default-initargs
(list
':direct-default-initargs
`(list ,@(mapappend
#'(lambda (x) x)
(mapplist
#'(lambda (key value)
`(',key ,value))
(cdr option))))))
(t (call-next-method))))
(pprint (macroexpand
'(new-defclass frame-2 (rectangle)
()
(:metaclass default-initargs-class)
(:default-initargs :width 10))))
#|(ensure-class 'frame-2
:direct-superclasses
(list (find-class 'rectangle))
:direct-slots
(list)
:metaclass
(find-class 'default-initargs-class)
:direct-default-initargs
(list ':width 10))
|#
;;; slot access
(defclass monitored-class (standard-class) ())
(defmethod slot-value-using-class :before
((class monitored-class) instance slot-name)
(note-operation instance slot-name 'slot-value))
(defmethod (setf slot-value-using-class) :before
(new-value (class monitored-class)
instance slot-name)
(note-operation instance slot-name 'set-slot-value))
(defmethod slot-boundp-using-class :before
((class monitored-class) instance slot-name)
(note-operation instance slot-name 'slot-boundp))
(defmethod slot-makunbound-using-class :before
((class monitored-class) instance slot-name)
(note-operation instance slot-name 'slot-makunbound))
(let ((history-list ()))
(defun note-operation (instance slot-name operation)
(push `(,operation ,instance ,slot-name) history-list)
(values))
(defun reset-slot-access-history ()
(setq history-list ())
(values))
(defun slot-access-history ()
(reverse history-list))
)
(defclass foo ()
((slot1 :accessor foo-slot1 :initarg :slot1)
(slot2 :accessor foo-slot2 :initform 200))
(:metaclass monitored-class))
(reset-slot-access-history)
(setq i (make-instance 'foo :slot1 100))
#|#<FOO 3813124>|#
(setf (slot-value i 'slot1) (foo-slot2 i))
(incf (foo-slot1 i))
(pprint (slot-access-history))
#|((set-slot-value #<Foo 17122130> slot1)
(slot-boundp #<Foo 17122130> slot2)
(set-slot-value #<Foo 17122130> slot2)
(slot-value #<Foo 17122130> slot2)
(set-slot-value #<Foo 17122130> slot1)
(slot-value #<Foo 17122130> slot1)
(set-slot-value #<Foo 17122130> slot1))
|#
(defclass history-class (standard-class) ())
(defun slot-definition-history (slot)
(getf slot ':history nil))
(defun (setf slot-definition-history) (new-value slot)
(setf (getf* slot ':history) new-value))
(defun slot-definition-history-slot-name (slot)
(getf slot ':history-slot-name nil))
(defun (setf slot-definition-history-slot-name) (new-value slot)
(setf (getf* slot ':history-slot-name) new-value))
(defmethod compute-slots ((class history-class))
(let ((normal-slots (call-next-method)))
(mapappend
#'(lambda (slot)
(if (null (slot-definition-history slot))
(list slot)
(let ((extra-slot
(make-effective-slot-definition
:name (slot-definition-history-slot-name slot)
:history nil)))
(list slot extra-slot))))
normal-slots)))
(defmethod compute-effective-slot-definition ((class history-class)
direct-slots)
(let ((initer (find-if-not #'null direct-slots
:key #'slot-definition-initfunction)))
(make-effective-slot-definition
:name (slot-definition-name (car direct-slots))
:history (some #'slot-definition-history direct-slots)
:history-slot-name (gensym)
:allocation (slot-definition-allocation (car direct-slots))
:initform (if initer
(slot-definition-initform initer)
nil)
:initfunction (if initer
(slot-definition-initfunction initer)
nil)
:initargs (remove-duplicates
(mapappend #'slot-definition-initargs
direct-slots)))))
(defmethod allocate-instance ((class history-class))
(let ((instance (call-next-method)))
(dolist (slot (class-slots class))
(when (slot-definition-history slot)
(setf (slot-value
instance
(slot-definition-history-slot-name slot))
())))
instance))
(defun slot-history (instance slot-name)
(unless (slot-exists-p instance slot-name)
(error "~S has no slot named ~A." instance slot-name))
(let ((slot (find slot-name (class-slots (class-of instance))
:key #'slot-definition-name)))
(if (slot-definition-history slot)
(slot-value instance
(slot-definition-history-slot-name slot))
())))
(defmethod (setf slot-value-using-class) :before
(new-value (class history-class) instance slot-name)
(remember-previous-value instance slot-name))
(defmethod slot-makunbound-using-class :before
((class history-class) instance slot-name)
(remember-previous-value instance slot-name))
(defun remember-previous-value (instance slot-name)
(let ((slot (find slot-name (class-slots (class-of instance))
:key #'slot-definition-name)))
(when (and (not (null slot))
(slot-definition-history slot))
(push (if (slot-boundp instance slot-name)
(slot-value instance slot-name)
'unbound)
(slot-value
instance
(slot-definition-history-slot-name slot))))))
(defclass meter ()
((size :initarg meter-size)
(reading :initform 0 :history t))
(:metaclass history-class))
(class-slots (find-class 'meter))
#|((:name size
:history
nil
:history-slot-name
#:g1680
:allocation
:instance
:initform
nil
:initfunction
nil
:initargs
(meter-size))
(:name reading
:history
t
:history-slot-name
#:g1681
:allocation
:instance
:initform
0
:initfunction
#<An Anonymous Compiled Function>
:initargs
nil)
(:name #:g1681
:history
nil
:initargs
nil
:allocation
:instance))
|#
(setq meter1 (make-instance 'meter))
(setf (slot-value meter1 'reading) 200)
(slot-history meter1 'size)
(slot-history meter1 'reading)
#|(0 unbound)|#
;;; dynamic-slot-class
(defclass dynamic-slot-class (standard-class) ())
(defmethod compute-effective-slot-definition
((class dynamic-slot-class) direct-slots)
(let ((slot (call-next-method)))
(setf (slot-definition-allocation slot) ':dynamic)
slot))
(defun dynamic-slot-p (slot)
(eq (slot-definition-allocation slot) ':dynamic))
(defmethod allocate-instance ((class dynamic-slot-class) &key)
(let ((instance (call-next-method)))
(allocate-table-entry instance)
instance))
(defmethod slot-value-using-class ((class dynamic-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if slot
(read-dynamic-slot-value instance slot-name)
(call-next-method))))
(defmethod slot-boundp-using-class ((class dynamic-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if slot
(dynamic-slot-boundp instance slot-name)
(call-next-method))))
(defmethod (setf slot-value-using-class)
(new-value (class dynamic-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if slot
(write-dynamic-slot-value new-value instance slot-name)
(call-next-method))))
(defmethod slot-makunbound-using-class ((class dynamic-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if slot
(dynamic-slot-makunbound instance slot-name)
(call-next-method))))
(let ((table (make-hash-table :test #'eq)))
(defun allocate-table-entry (instance)
(setf (gethash instance table) ()))
(defun read-dynamic-slot-value (instance slot-name)
(let* ((alist (gethash instance table))
(entry (assoc slot-name alist)))
(if (null entry)
(error "The slot ~S is unbound in the object ~S."
slot-name instance)
(cdr entry))))
(defun write-dynamic-slot-value (new-value instance slot-name)
(let* ((alist (gethash instance table))
(entry (assoc slot-name alist)))
(if (null entry)
(push `(,slot-name . ,new-value)
(gethash instance table))
(setf (cdr entry) new-value))
new-value))
(defun dynamic-slot-boundp (instance slot-name)
(let* ((alist (gethash instance table))
(entry (assoc slot-name alist)))
(not (null entry))))
(defun dynamic-slot-makunbound (instance slot-name)
(let* ((alist (gethash instance table))
(entry (assoc slot-name alist)))
(unless (null entry)
(setf (gethash instance table)
(delete entry alist))))
instance)
)
(defclass biggy ()
(a1 b1 c1 d1 e1 f1 g1 h1 i1 j1 k1 l1 m1
n1 o1 p1 q1 r1 s1 t1 u1 v1 w1 x1 y1 z1
a2 b2 c2 d2 e2 f2 g2 h2 i2 j2 k2 l2 m2
n2 o2 p2 q2 r2 s2 t2 u2 v2 w2 x2 y2 z2
a3 b3 c3 d3 e3 f3 g3 h3 i3 j3 k3 l3 m3
n3 o3 p3 q3 r3 s3 t3 u3 v3 w3 x3 y3 z3
a4 b4 c4 d4 e4 f4 g4 h4 i4 j4 k4 l4 m4
n4 o4 p4 q4 r4 s4 t4 u4 v4)
(:metaclass dynamic-slot-class))
(every #'dynamic-slot-p
(class-slots (find-class 'biggy)))
#|t|#
(setq b1 (make-instance 'biggy))
(setf (slot-value b1 'f3) 'b1-f3-value)
(slot-value b1 'f3)
#|b1-f3-value|#
(defclass dynamic-slot-class-2 (standard-class) ())
(defmethod allocate-instance ((class dynamic-slot-class-2) &key)
(let ((instance (call-next-method)))
(when (some #'dynamic-slot-p (class-slots class))
(allocate-table-entry instance))
instance))
(defmethod slot-value-using-class ((class dynamic-slot-class-2)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (dynamic-slot-p slot))
(read-dynamic-slot-value instance slot-name)
(call-next-method))))
(defmethod slot-boundp-using-class ((class dynamic-slot-class-2)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (dynamic-slot-p slot))
(dynamic-slot-boundp instance slot-name)
(call-next-method))))
(defmethod (setf slot-value-using-class)
(new-value (class dynamic-slot-class-2)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (dynamic-slot-p slot))
(write-dynamic-slot-value new-value instance slot-name)
(call-next-method))))
(defmethod slot-makunbound-using-class ((class dynamic-slot-class-2)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (dynamic-slot-p slot))
(dynamic-slot-makunbound instance slot-name)
(call-next-method))))
(defclass movable-rectangle (rectangle)
((previous-height :allocation :dynamic)
(previous-width :allocation :dynamic))
(:metaclass dynamic-slot-class-2))
(setq mr (make-instance 'movable-rectangle))
(every #'dynamic-slot-p
(class-slots (find-class 'movable-rectangle)))
#|nil|#
(some #'dynamic-slot-p
(class-slots (find-class 'movable-rectangle)))
#|t|#
(setf (slot-value mr 'height) 1002)
(setf (slot-value mr 'previous-height) 999)
(slot-value mr 'height)
#|1002|#
(slot-value mr 'previous-height)
#|999|#
;;;
(defclass class-slot-class (standard-class)
((class-allocated-slot-values
:initform ()
:accessor class-allocated-slots)))
(defun class-slot-p (slot)
(eq (slot-definition-allocation slot) ':class))
(defvar unbound-class-slot (list "unbound class slot"))
(defmethod initialize-instance :after
((class class-slot-class) &key)
(setf (class-allocated-slots class)
(mapappend
#'(lambda (slot)
(if (class-slot-p slot)
(let ((initfunction
(slot-definition-initfunction slot)))
(list (cons (slot-definition-name slot)
(if (not (null initfunction))
(funcall initfunction)
unbound-class-slot))))
()))
(class-direct-slots class))))
#|(defmethod finalize-inheritance :after
((class class-slot-class))
(setf (class-allocated-slots class)
(mapappend
#'(lambda (slot)
(if (class-slot-p slot)
(let ((initfunction
(slot-definition-initfunction slot)))
(if (not (null initfunction))
(list (cons (slot-definition-name slot)
(funcall initfunction)))
(list (cons (slot-definition-name slot)
secret-unbound-value))))
()))
(class-direct-slots class))))|#
(defun class-slot-value (class slot-name)
(dolist (super (class-precedence-list class))
(let ((slot (find slot-name (class-direct-slots super)
:key #'slot-definition-name)))
(when slot
(let ((value (cdr (assoc slot-name
(class-allocated-slots super)))))
(when (eq value secret-unbound-value)
(error "Unbound class slot named ~A in class ~S."
slot-name class))
(return-from class-slot-value value))))))
(defun (setf class-slot-value) (new-value class slot-name)
(block class-slot-value
(dolist (super (class-precedence-list class))
(let ((slot (find slot-name (class-direct-slots super)
:key #'slot-definition-name)))
(when slot
(setf (cdr (assoc slot-name
(class-allocated-slots super)))
new-value)
(return-from class-slot-value new-value))))))
(defun class-slot-boundp (class slot-name)
(dolist (super (class-precedence-list class))
(let ((slot (find slot-name (class-direct-slots super)
:key #'slot-definition-name)))
(when slot
(let ((value (cdr (assoc slot-name
(class-allocated-slots super)))))
(return-from class-slot-boundp
(eq value secret-unbound-value)))))))
(defun class-slot-makunbound (class slot-name)
(dolist (super (class-precedence-list class))
(let ((slot (find slot-name (class-direct-slots super)
:key #'slot-definition-name)))
(when slot
(setf (cdr (assoc slot-name
(class-allocated-slots super)))
secret-unbound-value)
(return-from class-slot-makunbound)))))
(defmethod slot-value-using-class
((class class-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (class-slot-p slot))
(class-slot-value class slot-name)
(call-next-method))))
(defmethod (setf slot-value-using-class)
(new-value
(class class-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (class-slot-p slot))
(setf (class-slot-value class slot-name) new-value)
(call-next-method))))
(defmethod slot-boundp-using-class
((class class-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (class-slot-p slot))
(class-slot-boundp class slot-name)
(call-next-method))))
(defmethod slot-makunbound-using-class
((class class-slot-class)
instance slot-name)
(let ((slot (find slot-name (class-slots class)
:key #'slot-definition-name)))
(if (and slot (class-slot-p slot))
(progn (class-slot-makunbound class slot-name)
instance)
(call-next-method))))
(defclass labeled-rectangle (rectangle)
((font :initform 'old-english-12
:allocation :class))
(:metaclass class-slot-class))
(setq lr1 (make-instance 'labeled-rectangle))
(setq lr2 (make-instance 'labeled-rectangle))
(slot-value lr1 'font)
#|OLD-ENGLISH-12|#
(setf (slot-value lr1 'font) 'times-roman-10)
(slot-value lr2 'font)
#|TIMES-ROMAN-10|#
(defclass both-slots-class (dynamic-slot-class class-slot-class)
())
;;; chapter 4
(pprint (macroexpand
'(defgeneric paint (x)
(:generic-function-class specialized-generic-function)
(:method-class specialized-method))))
#|(ensure-generic-function 'paint
:lambda-list
'(x)
:generic-function-class
(find-class 'specialized-generic-function)
:method-class
(find-class 'specialized-method))|#
;;; counter example
(defclass counting-gf (standard-generic-function)
((call-count :initform 0 :accessor call-count)))
(defclass counting-method (standard-method)
((call-count :initform 0 :accessor call-count)))
(defmethod compute-discriminating-function ((gf counting-gf))
(let ((normal-dfun (call-next-method)))
#'(lambda (&rest args)
(incf (call-count gf))
(apply normal-dfun args))))
(defmethod compute-method-function ((method counting-method))
(let ((normal-method-function (call-next-method)))
#'(lambda (args next-methods)
(incf (call-count method))
(funcall normal-method-function args next-methods))))
(defgeneric ack (x)
(:generic-function-class counting-gf)
(:method-class counting-method))
(defmethod ack :before ((x standard-object)) nil)
(defmethod ack (x) t)
(ack (make-instance 'standard-object))
#|T|#
(ack 1)
#|T|#
(call-count (find-generic-function 'ack))
#|2|#
(mapcar #'(lambda (method)
(list (generate-defmethod method)
(call-count method)))
(generic-function-methods (find-generic-function 'ack)))
#|(((DEFMETHOD ACK :BEFORE ((X STANDARD-OBJECT))) 1)
((DEFMETHOD ACK (X)) 2))|#
;;; tracing gf exercise
(defclass traceable-gf (standard-generic-function)
((tracing :initform nil :accessor tracing-enabled-p)))
(defun trace-generic-function (gf-name new-value)
(let ((gf (find-generic-function gf-name)))
(setf (tracing-enabled-p gf) new-value)))
(defmethod compute-discriminating-function ((gf traceable-gf))
(let ((normal-dfun (call-next-method)))
#'(lambda (&rest args)
(if (not (tracing-enabled-p gf))
(apply normal-dfun args)
(progn
(format *trace-output*
"Entering generic function ~S~@
with arguments ~:S.~%" gf args)
(let ((results (multiple-value-list
(apply normal-dfun args))))
(format *trace-output*
"Leaving generic function ~S~@
value(s) being returned are: ~:S.~%"
gf results)
(values-list results)))))))
(defgeneric testf (x)
(:generic-function-class traceable-gf))
(defmethod testf (x) x)
(trace-generic-function 'testf t)
(testf 10)
#|Entering generic function #<Traceable-Gf testf 16774634>
with arguments (10).
Leaving generic function #<Traceable-Gf testf 16774634>
value(s) being returned are: (10)
10|#
(trace-generic-function 'testf nil)
(testf 20)
#|20|#
;;; trusting gfs
(defclass trusting-gf (standard-generic-function) ())
(defmethod compute-discriminating-function ((gf trusting-gf))
(let ((normal-dfun (call-next-method))
(methods (generic-function-methods gf)))
(if (and (= (length methods) 1)
(primary-method-p (car methods)))
#'(lambda (&rest args)
(apply-method (car methods) args ()))
normal-dfun)))
(defgeneric gfoo (x) (:generic-function-class trusting-gf))
(defmethod gfoo ((x standard-object))
x)
(gfoo (find-class 'standard-class))
#|#<Standard-Class STANDARD-CLASS 15102564>|#
(gfoo 100)
#|100|#
(defmethod gfoo ((x number))
(1+ x))
(gfoo 100)
#|101|#
(defclass trusting-counting-gf (trusting-gf counting-gf) ())
(defgeneric flack (x)
(:generic-function-class trusting-counting-gf)
(:method-class counting-method))
(defmethod flack (x) t)
(flack (make-instance 'standard-object))
#|T|#
(flack 1)
#|T|#
(call-count (find-generic-function 'flack))
#|0|#
(mapcar #'(lambda (method)
(list (generate-defmethod method)
(call-count method)))
(generic-function-methods
(find-generic-function 'flack)))
#|(((DEFMETHOD ACK :BEFORE ((X STANDARD-OBJECT))) 1)
((DEFMETHOD ACK (X)) 2))|#
(defclass counting-trusting-gf (counting-gf trusting-gf) ())
(defgeneric flack2 (x)
(:generic-function-class counting-trusting-gf)
(:method-class counting-method))
(defmethod flack2 (x) t)
(flack2 (make-instance 'standard-object))
#|T|#
(flack2 1)
#|T|#
(call-count (find-generic-function 'flack2))
#|2|#
;;; encapsulated methods (can't be tested because they need
;;; to add bindings to body
#|
(defclass c1 ()
((foo :initform 100))
(:metaclass encapsulated-class))
(defclass c2 (c1)
((foo :initform 200))
(:metaclass encapsulated-class))
(defgeneric f1 (x)
(:generic-function-class encapsulating-gf)
(:method-class encapsulated-method))
(defmethod f1 ((y c1))
(1- (slot 'foo)))
(defmethod f1 ((z c2))
(1+ (slot 'foo)))
(f1 (make-instance 'c1))
99
(f1 (make-instance 'c2))
201
|#
;;; Method Combination
(defclass gf-with-arounds (standard-generic-function) ())
#|(defmethod apply-methods ((gf gf-with-arounds) args methods)
(let ((around (find-if #'around-method-p methods)))
(if around
(apply-method around args (remove around methods))
(call-next-method))))|#
(defmethod compute-effective-method-function
((gf gf-with-arounds) methods)
(let ((around (find-if #'around-method-p methods)))
(if around
#'(lambda (args)
(apply-method around args (remove around methods)))
(call-next-method))))
(defgeneric gfa (x) (:generic-function-class gf-with-arounds))
(defmethod gfa :around ((x integer))
(format t "(:around integer)")
(call-next-method))
(defmethod gfa :around ((x number))
(format t "(:around number)")
(call-next-method))
(defmethod gfa :before ((x number))
(format t "(:before number)"))
(defmethod gfa ((x number))
(format t "(primary number)")
(1+ (call-next-method)))
(defmethod gfa :after ((x number))
(format t "(:after number)"))
(defmethod gfa :before ((x t))
(format t "(:before t)"))
(defmethod gfa ((x t))
(format t "(primary t)")
100)
(defmethod gfa :after ((x t))
(format t "(:after t)"))
(gfa 1)
#|(:around integer)(:around number)(:before number)(:before t)
(primary number)(primary t)(:after t)(:after number)
101|#
(defclass gf-with-append (standard-generic-function) ())
#|
(defmethod apply-methods ((gf gf-with-append) args methods)
(mapappend #'(lambda (method)
(apply-method method args ()))
methods))
|#
(defmethod compute-effective-method-function
((gf gf-with-append) methods)
#'(lambda (args)
(apply #'append
(mapcar #'(lambda (method)
(apply-method method args ()))
methods))))
(defgeneric gfappend (x)
(:generic-function-class gf-with-append))
(defmethod gfappend ((x integer))
'(integer))
(defmethod gfappend ((x number))
'(number))
(defmethod gfappend ((x t))
'(t))
(gfappend 1)
#|(INTEGER NUMBER T)|#
;;; Argument Precedence Order
(defclass apo-gf (standard-generic-function)
((argument-precedence-order
:initarg :argument-precedence-order
:accessor argument-precedence-order)))
(defmethod initialize-instance :after ((gf apo-gf) &key)
(unless (slot-boundp gf 'argument-precedence-order)
(setf (argument-precedence-order gf)
(gf-required-arglist gf))))
(defmethod method-more-specific-p
((gf apo-gf) method1 method2 required-classes)
(flet ((apo-permute (list)
(mapcar #'(lambda (arg-name)
(nth (position
arg-name
(gf-required-arglist gf))
list))
(argument-precedence-order gf))))
(mapc #'(lambda (spec1 spec2 arg-class)
(unless (eq spec1 spec2)
(return-from method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class))))
(apo-permute (method-specializers method1))
(apo-permute (method-specializers method2))
(apo-permute required-classes))
nil))
(defgeneric multigf (x y)
(:generic-function-class apo-gf)
(:argument-precedence-order (y x)))
(defmethod multigf ((x t) (y number))
(format t "(t number)")
(values))
(defmethod multigf ((x number) (y t))
(format t "(number t)")
(values))
(defmethod multigf ((x number) (y number))
(format t "(number number)")
(values))
(defmethod multigf ((x t) (y integer))
(format t "(t integer)")
(values))
(defmethod multigf ((x t) (y t))
(format t "(t t)")
(values))
(multigf 1 2)
#|(t integer)|#
(multigf 1 'a)
#|(number t)|#
(multigf 'b 'a)
#|(t t)|#
(multigf 'b 1)
#|(t integer)|#
(defgeneric multigf2 (x y))
(defmethod multigf2 ((x t) (y number))
(format t "(t number)")
(values))
(defmethod multigf2 ((x number) (y t))
(format t "(number t)")
(values))
(defmethod multigf2 ((x number) (y number))
(format t "(number number)")
(values))
(defmethod multigf2 ((x t) (y integer))
(format t "(t integer)")
(values))
(defmethod multigf2 ((x t) (y t))
(format t "(t t)")
(values))
(multigf2 1 2)
#|(number number)|#
(multigf2 1 'a)
#|(number t)|#
(multigf2 'b 'a)
#|(t t)|#
(multigf2 'b 1)
#|(t integer)|#
;;; beta
(defclass beta-gf (standard-generic-function) ())
(defmethod method-more-specific-p ((gf beta-gf) method1 method2 classes)
(if (equal (method-specializers method1)
(method-specializers method2))
nil
(not (call-next-method))))
(defmacro inner (&rest args)
`(if (next-method-p)
(call-next-method ,@args)
nil))
(defgeneric bjorn (x)
(:generic-function-class beta-gf))
(defmethod bjorn (x)
(format t " general ")
(inner))
(defmethod bjorn ((x number))
(format t " number ")
(inner))
(bjorn 1)
#| general number |#
(bjorn 'a)
#| general |#
"done"
| 61,946 | Common Lisp | .lisp | 1,629 | 29.931246 | 77 | 0.61106 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | d4d36df78ba002c75a7665d3802f20f80dfd9ed9866128c86c4c7d1ed709e242 | 46 | [
-1
] |
47 | extended-loop.lisp | jscl-project_jscl/src/ansiloop/extended-loop.lisp | ;;; -*- Mode: LISP; Syntax: Common-lisp; Package: ANSI-LOOP; Base: 10; Lowercase:T -*-
;;;>
;;;> Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute of Technology.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the M.I.T. copyright notice appear in all copies and that
;;;> both that copyright notice and this permission notice appear in
;;;> supporting documentation. The names "M.I.T." and "Massachusetts
;;;> Institute of Technology" may not be used in advertising or publicity
;;;> pertaining to distribution of the software without specific, written
;;;> prior permission. Notice must be given in supporting documentation that
;;;> copying distribution is by permission of M.I.T. M.I.T. makes no
;;;> representations about the suitability of this software for any purpose.
;;;> It is provided "as is" without express or implied warranty.
;;;>
;;;> Massachusetts Institute of Technology
;;;> 77 Massachusetts Avenue
;;;> Cambridge, Massachusetts 02139
;;;> United States of America
;;;> +1-617-253-1000
;;;>
;;;> Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics, Inc.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the Symbolics copyright notice appear in all copies and
;;;> that both that copyright notice and this permission notice appear in
;;;> supporting documentation. The name "Symbolics" may not be used in
;;;> advertising or publicity pertaining to distribution of the software
;;;> without specific, written prior permission. Notice must be given in
;;;> supporting documentation that copying distribution is by permission of
;;;> Symbolics. Symbolics makes no representations about the suitability of
;;;> this software for any purpose. It is provided "as is" without express
;;;> or implied warranty.
;;;>
;;;> Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
;;;> and Zetalisp are registered trademarks of Symbolics, Inc.
;;;>
;;;> Symbolics, Inc.
;;;> 8 New England Executive Park, East
;;;> Burlington, Massachusetts 01803
;;;> United States of America
;;;> +1-617-221-1000
(in-package :ansi-loop)
#+Cloe-Runtime ;Don't ask.
(car (push "%Z% %M% %I% %E% %U%" system::*module-identifications*))
;;; The following code could be used to set up the SYMBOLICS-LOOP package
;;; as it is expected to be. At Symbolics, in both Genera and CLOE, the
;;; package setup is done elsewhere.
#-Symbolics
(unless (find-package 'symbolics-loop)
(make-package 'symbolics-loop :use nil))
#-Symbolics
(import 'ansi-loop::loop-finish (find-package 'symbolics-loop))
#-Symbolics
(export '(symbolics-loop::loop
symbolics-loop::loop-finish
symbolics-loop::define-loop-iteration-path
symbolics-loop::define-loop-sequence-path
)
(find-package 'symbolics-loop))
;;;This is our typical "extensible" universe, which should be a proper superset of the ansi universe.
(defvar *loop-default-universe* (make-ansi-loop-universe t))
(defmacro symbolics-loop:define-loop-iteration-path (path-name function
&key alternate-names preposition-groups
inclusive-permitted user-data (loop-universe '*loop-default-universe*))
`(eval-when (eval compile load)
(add-loop-path '(,path-name ,@alternate-names) ,function ,loop-universe
:preposition-groups ',preposition-groups
:inclusive-permitted ',inclusive-permitted
:user-data ',user-data)))
(defmacro symbolics-loop:define-loop-sequence-path (path-name-or-names fetch-function size-function
&optional sequence-type element-type)
"Defines a sequence iteration path. PATH-NAME-OR-NAMES is either an
atomic path name or a list of path names. FETCHFUN is a function of
two arguments, the sequence and the index of the item to be fetched.
Indexing is assumed to be zero-origined. SIZEFUN is a function of
one argument, the sequence; it should return the number of elements in
the sequence. SEQUENCE-TYPE is the name of the data-type of the
sequence, and ELEMENT-TYPE is the name of the data-type of the elements
of the sequence."
`(eval-when (eval compile load)
(add-loop-path ',path-name-or-names 'loop-sequence-elements-path *loop-default-universe*
:preposition-groups '((:of :in) (:from :downfrom :upfrom) (:to :downto :below :above) (:by))
:inclusive-permitted nil
:user-data '(:fetch-function ,fetch-function
:size-function ,size-function
:sequence-type ,sequence-type
:element-type ,element-type))))
(defmacro symbolics-loop:loop (&environment env &rest keywords-and-forms)
#+Genera (declare (compiler:do-not-record-macroexpansions)
(zwei:indentation . zwei:indent-loop))
(loop-standard-expansion keywords-and-forms env *loop-default-universe*))
| 5,064 | Common Lisp | .lisp | 96 | 50.020833 | 101 | 0.733657 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 71c1d5164dc2d2b6fae3d8e721bba77ab0fa246c2cefcbf8af7f43da2cb86c48 | 47 | [
3153
] |
48 | compiler.lisp | jscl-project_jscl/src/compiler/compiler.lisp | ;;; compiler.lisp ---
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;;; Compiler
(/debug "loading compiler.lisp!")
;;; Translate the Lisp code to Javascript. It will compile the special
;;; forms. Some primitive functions are compiled as special forms
;;; too. The respective real functions are defined in the target (see
;;; the beginning of this file) as well as some primitive functions.
(define-js-macro selfcall (&body body)
`(call (function () ,@body)))
(define-js-macro method-call (x method &rest args)
`(call (get ,x ,method) ,@args))
(define-js-macro nargs ()
`(- (get |arguments| |length|) 1))
(define-js-macro arg (n)
`(property |arguments| (+ ,n 1)))
;;; Runtime
(define-js-macro internal (x)
`(get |internals| ,x))
(define-js-macro call-internal (name &rest args)
`(method-call |internals| ,name ,@args))
(defun convert-to-bool (expr)
`(if ,expr ,(convert t) ,(convert nil)))
;;; A Form can return a multiple values object calling VALUES, like
;;; values(arg1, arg2, ...). It will work in any context, as well as
;;; returning an individual object. However, if the special variable
;;; `*multiple-value-p*' is NIL, is granted that only the primary
;;; value will be used, so we can optimize to avoid the VALUES
;;; function call.
(defvar *multiple-value-p* nil)
;;; It is bound dynamically to the number of nested calls to
;;; `convert'. Therefore, a form is being compiled as toplevel if it
;;; is zero.
(defvar *convert-level* -1)
;;; Environment
(def!struct binding
name
type
value
declarations)
(def!struct lexenv
variable
function
block
gotag)
(defun lookup-in-lexenv (name lexenv namespace)
(find name (ecase namespace
(variable (lexenv-variable lexenv))
(function (lexenv-function lexenv))
(block (lexenv-block lexenv))
(gotag (lexenv-gotag lexenv)))
:key #'binding-name))
(defun push-to-lexenv (binding lexenv namespace)
(ecase namespace
(variable (push binding (lexenv-variable lexenv)))
(function (push binding (lexenv-function lexenv)))
(block (push binding (lexenv-block lexenv)))
(gotag (push binding (lexenv-gotag lexenv)))))
(defun extend-lexenv (bindings lexenv namespace)
(let ((env (copy-lexenv lexenv)))
(dolist (binding (reverse bindings) env)
(push-to-lexenv binding env namespace))))
(defvar *environment*)
(defvar *variable-counter*)
(defun gvarname (symbol)
(declare (ignore symbol))
(incf *variable-counter*)
(make-symbol (concat "v" (integer-to-string *variable-counter*))))
(defun translate-variable (symbol)
(awhen (lookup-in-lexenv symbol *environment* 'variable)
(binding-value it)))
(defun extend-local-env (args)
(let ((new (copy-lexenv *environment*)))
(dolist (symbol args new)
(let ((b (make-binding :name symbol :type 'variable :value (gvarname symbol))))
(push-to-lexenv b new 'variable)))))
;;; Toplevel compilations
(defvar *toplevel-compilations*)
(defun toplevel-compilation (string)
(push string *toplevel-compilations*))
(defun get-toplevel-compilations ()
(reverse *toplevel-compilations*))
(defun %compile-defmacro (name lambda)
(let ((binding (make-binding :name name :type 'macro :value lambda)))
(push-to-lexenv binding *environment* 'function))
name)
(defun global-binding (name type namespace)
(or (lookup-in-lexenv name *environment* namespace)
(let ((b (make-binding :name name :type type :value nil)))
(push-to-lexenv b *environment* namespace)
b)))
(defun claimp (symbol namespace claim)
(let ((b (lookup-in-lexenv symbol *environment* namespace)))
(and b (member claim (binding-declarations b)))))
(defun !proclaim (decl)
(case (car decl)
(special
(dolist (name (cdr decl))
(let ((b (global-binding name 'variable 'variable)))
(push 'special (binding-declarations b)))))
(notinline
(dolist (name (cdr decl))
(let ((b (global-binding name 'function 'function)))
(push 'notinline (binding-declarations b)))))
(constant
(dolist (name (cdr decl))
(let ((b (global-binding name 'variable 'variable)))
(push 'constant (binding-declarations b)))))))
#+jscl
(fset 'proclaim #'!proclaim)
(defun %define-symbol-macro (name expansion)
(let ((b (make-binding :name name :type 'macro :value expansion)))
(push-to-lexenv b *environment* 'variable)
name))
#+jscl
(defmacro define-symbol-macro (name expansion)
`(%define-symbol-macro ',name ',expansion))
;;; Report functions which are called but not defined
(defvar *fn-info* '())
(def!struct fn-info
symbol
defined
called)
(defun find-fn-info (symbol)
(let ((entry (find symbol *fn-info* :key #'fn-info-symbol)))
(unless entry
(setq entry (make-fn-info :symbol symbol))
(push entry *fn-info*))
entry))
(defun fn-info (symbol &key defined called)
(let ((info (find-fn-info symbol)))
(when defined
(setf (fn-info-defined info) defined))
(when called
(setf (fn-info-called info) called))))
(defun report-undefined-functions ()
(dolist (info *fn-info*)
(let ((symbol (fn-info-symbol info)))
(when (and (fn-info-called info)
(not (fn-info-defined info)))
(warn "The function `~a' is undefined.~%" symbol))))
(setq *fn-info* nil))
;;; Special forms
(defvar *compilations*
(make-hash-table))
(defmacro define-compilation (name args &body body)
;; Creates a new primitive `name' with parameters args and
;; @body. The body can access to the local environment through the
;; variable *ENVIRONMENT*.
`(setf (gethash ',name *compilations*)
(lambda ,args (block ,name ,@body))))
(define-compilation if (condition true &optional false)
`(if (!== ,(convert condition) ,(convert nil))
,(convert true *multiple-value-p*)
,(convert false *multiple-value-p*)))
(defvar *ll-keywords* '(&optional &rest &key))
(defun list-until-keyword (list)
(if (or (null list) (member (car list) *ll-keywords*))
nil
(cons (car list) (list-until-keyword (cdr list)))))
(defun ll-section (keyword ll)
(list-until-keyword (cdr (member keyword ll))))
(defun ll-required-arguments (ll)
(list-until-keyword ll))
(defun ll-optional-arguments-canonical (ll)
(mapcar #'ensure-list (ll-section '&optional ll)))
(defun ll-optional-arguments (ll)
(mapcar #'car (ll-optional-arguments-canonical ll)))
(defun ll-rest-argument (ll)
(let ((rest (ll-section '&rest ll)))
(when (cdr rest)
(error "Bad lambda-list `~S'." ll))
(car rest)))
(defun ll-keyword-arguments-canonical (ll)
(flet ((canonicalize (keyarg)
;; Build a canonical keyword argument descriptor, filling
;; the optional fields. The result is a list of the form
;; ((keyword-name var) init-form svar).
(let ((arg (ensure-list keyarg)))
(cons (if (listp (car arg))
(car arg)
(list (intern (symbol-name (car arg)) "KEYWORD") (car arg)))
(cdr arg)))))
(mapcar #'canonicalize (ll-section '&key ll))))
(defun ll-keyword-arguments (ll)
(mapcar (lambda (keyarg) (second (first keyarg)))
(ll-keyword-arguments-canonical ll)))
(defun ll-svars (lambda-list)
(let ((args
(append
(ll-keyword-arguments-canonical lambda-list)
(ll-optional-arguments-canonical lambda-list))))
(remove nil (mapcar #'third args))))
(defun lambda-name/docstring-wrapper (name docstring code)
(if (or name docstring)
`(selfcall
(var (func ,code))
,(when name `(= (get func "fname") ,name))
,(when docstring `(= (get func "docstring") ,docstring))
(return func))
code))
(defun lambda-check-argument-count
(n-required-arguments n-optional-arguments rest-p)
;; Note: Remember that we assume that the number of arguments of a
;; call is at least 1 (the values argument).
(let ((min n-required-arguments)
(max (if rest-p 'n/a (+ n-required-arguments n-optional-arguments))))
(block nil
;; Special case: a positive exact number of arguments.
(when (and (< 0 min) (eql min max))
(return `(call-internal |checkArgs| (nargs) ,min)))
;; General case:
`(progn
,(when (< 0 min) `(call-internal |checkArgsAtLeast| (nargs) ,min))
,(when (numberp max) `(call-internal |checkArgsAtMost| (nargs) ,max))))))
(defun compile-lambda-optional (ll)
(let* ((optional-arguments (ll-optional-arguments-canonical ll))
(n-required-arguments (length (ll-required-arguments ll)))
(n-optional-arguments (length optional-arguments))
(svars (remove nil (mapcar #'third optional-arguments))))
(when optional-arguments
`(progn
,(when svars
`(var ,@(mapcar (lambda (svar)
(list (translate-variable svar)
(convert t)))
svars)))
(switch (nargs)
,@(with-collect
(dotimes (idx n-optional-arguments)
(let ((arg (nth idx optional-arguments)))
(collect `(case ,(+ idx n-required-arguments)))
(collect `(= ,(translate-variable (car arg))
,(convert (cadr arg))))
(collect (when (third arg)
`(= ,(translate-variable (third arg))
,(convert nil))))))
(collect 'default)
(collect '(break))))))))
(defun compile-lambda-rest (ll)
(let ((n-required-arguments (length (ll-required-arguments ll)))
(n-optional-arguments (length (ll-optional-arguments ll)))
(rest-argument (ll-rest-argument ll)))
(when rest-argument
(let ((js!rest (translate-variable rest-argument)))
`(progn
(var (,js!rest ,(convert nil)))
(var i)
(for ((= i (- (nargs) 1))
(>= i ,(+ n-required-arguments n-optional-arguments))
(post-- i))
(= ,js!rest (new (call-internal |Cons| (arg i) ,js!rest)))))))))
(defun compile-lambda-parse-keywords (ll)
(let ((n-required-arguments
(length (ll-required-arguments ll)))
(n-optional-arguments
(length (ll-optional-arguments ll)))
(keyword-arguments
(ll-keyword-arguments-canonical ll)))
`(progn
;; Declare variables
,@(with-collect
(dolist (keyword-argument keyword-arguments)
(destructuring-bind ((keyword-name var) &optional initform svar)
keyword-argument
(declare (ignore keyword-name initform))
(collect `(var ,(translate-variable var)))
(when svar
(collect
`(var (,(translate-variable svar)
,(convert nil))))))))
;; Parse keywords
,(flet ((parse-keyword (keyarg)
(destructuring-bind ((keyword-name var) &optional initform svar) keyarg
;; ((keyword-name var) init-form svar)
`(progn
(for ((= i ,(+ n-required-arguments n-optional-arguments))
(< i (nargs))
(+= i 2))
;; ....
(if (=== (arg i) ,(convert keyword-name))
(progn
(= ,(translate-variable var) (arg (+ i 1)))
,(when svar `(= ,(translate-variable svar)
,(convert t)))
(break))))
(if (== i (nargs))
(= ,(translate-variable var) ,(convert initform)))))))
(when keyword-arguments
`(progn
(var i)
,@(mapcar #'parse-keyword keyword-arguments))))
;; Check for unknown keywords
,(when keyword-arguments
`(progn
(var (start ,(+ n-required-arguments n-optional-arguments)))
(if (== (% (- (nargs) start) 2) 1)
(throw "Odd number of keyword arguments."))
(for ((= i start) (< i (nargs)) (+= i 2))
(if (and ,@(mapcar (lambda (keyword-argument)
(destructuring-bind ((keyword-name var) &optional initform svar)
keyword-argument
(declare (ignore var initform svar))
`(!== (arg i) ,(convert keyword-name))))
keyword-arguments))
(throw (+ "Unknown keyword argument " (property (arg i) "name"))))))))))
(defun parse-lambda-list (ll)
(values (ll-required-arguments ll)
(ll-optional-arguments ll)
(ll-keyword-arguments ll)
(ll-rest-argument ll)))
;;; Process BODY for declarations and/or docstrings. Return as
;;; multiple values the BODY without docstrings or declarations, the
;;; list of declaration forms and the docstring.
(defun parse-body (body &key declarations docstring)
(let ((value-declarations)
(value-docstring)
(end nil))
(while (not end)
(cond
;; Docstring
((and docstring
(stringp (car body))
(not (null (cdr body))))
(when value-docstring
(error "Duplicated docstring ~S" (car body)))
(setq value-docstring (car body))
(setq body (cdr body)))
;; Declaration
((and declarations
(consp (car body))
(eq (caar body) 'declare))
(push (car body) value-declarations)
(setq body (cdr body)))
(t
(setq end t))))
(values body value-declarations value-docstring)))
(defun bind-this ()
(let* ((gvar (gvarname 'this))
(binding (make-binding :name 'this :type 'variable :value gvar)))
(push-to-lexenv binding *environment* 'variable)
`(var (,gvar |this|))))
(defun jsize-symbol (symbol prefix)
(let ((str (string symbol)))
(intern
(with-output-to-string (out)
(format out "~a" (string prefix))
(dotimes (i (length str))
(let ((ch (char str i)))
(when (char<= #\a (char-downcase ch) #\z)
(write-char ch out))))))))
;;; Compile a lambda function with lambda list LL and body BODY. If
;;; NAME is given, it should be a constant string and it will become
;;; the name of the function. If BLOCK is non-NIL, a named block is
;;; created around the body. NOTE: No block (even anonymous) is
;;; created if BLOCK is NIL.
(defun compile-lambda (ll body &key name block)
(multiple-value-bind (required-arguments
optional-arguments
keyword-arguments
rest-argument)
(parse-lambda-list ll)
(multiple-value-bind (body decls documentation)
(parse-body body :declarations t :docstring t)
(declare (ignore decls))
(let ((n-required-arguments (length required-arguments))
(n-optional-arguments (length optional-arguments))
(*environment* (extend-local-env
(append (ensure-list rest-argument)
required-arguments
optional-arguments
keyword-arguments
(ll-svars ll)))))
(lambda-name/docstring-wrapper name documentation
`(named-function ,(jsize-symbol name 'jscl_user_)
(|values| ,@(mapcar (lambda (x)
(translate-variable x))
(append required-arguments optional-arguments)))
;; Check number of arguments
,(lambda-check-argument-count n-required-arguments
n-optional-arguments
(or rest-argument keyword-arguments))
,(compile-lambda-optional ll)
,(compile-lambda-rest ll)
,(compile-lambda-parse-keywords ll)
,(bind-this)
,(let ((*multiple-value-p* t))
(if block
(convert-block `((block ,block ,@body)) t)
(convert-block body t)))))))))
(defun setq-pair (var val)
(unless (symbolp var)
(error "~a is not a symbol" var))
(let ((b (lookup-in-lexenv var *environment* 'variable)))
(cond
((and b
(eq (binding-type b) 'variable)
(not (member 'special (binding-declarations b)))
(not (member 'constant (binding-declarations b))))
`(= ,(binding-value b) ,(convert val)))
((and b (eq (binding-type b) 'macro))
(convert `(setf ,var ,val)))
(t
(convert `(set ',var ,val))))))
(define-compilation setq (&rest pairs)
(when (null pairs)
(return-from setq (convert nil)))
(with-collector (result)
(while t
(cond
((null pairs)
(return))
((null (cdr pairs))
(error "Odd pairs in SETQ"))
(t
(collect-result (setq-pair (car pairs) (cadr pairs)))
(setq pairs (cddr pairs)))))
`(progn ,@result)))
;;; Compilation of literals an object dumping
;;; BOOTSTRAP MAGIC: We record the macro definitions as lists during
;;; the bootstrap. Once everything is compiled, we want to dump the
;;; whole global environment to the output file to reproduce it in the
;;; run-time. However, the environment must contain expander functions
;;; rather than lists. We do not know how to dump function objects
;;; itself, so we mark the list definitions with this object and the
;;; compiler will be called when this object has to be dumped.
;;; Backquote/unquote does a similar magic, but this use is exclusive.
;;;
;;; Indeed, perhaps to compile the object other macros need to be
;;; evaluated. For this reason we define a valid macro-function for
;;; this symbol.
(defvar *magic-unquote-marker* (gensym "MAGIC-UNQUOTE"))
#-jscl
(setf (macro-function *magic-unquote-marker*)
(lambda (form &optional environment)
(declare (ignore environment))
(second form)))
(defvar *literal-table*)
(defvar *literal-counter*)
(defun genlit ()
(incf *literal-counter*)
(make-symbol (concat "l" (integer-to-string *literal-counter*))))
(defun dump-symbol (symbol)
(let ((package (symbol-package symbol)))
(cond
;; Uninterned symbol
((null package)
`(new (call-internal |Symbol| ,(symbol-name symbol))))
;; Special case for bootstrap. For now, we just load all the
;; code with JSCL as the current package. We will compile the
;; JSCL package as CL in the target.
#-jscl
((eq package (find-package "JSCL"))
`(call-internal |intern| ,(symbol-name symbol)))
;; Interned symbol
(t
`(call-internal |intern| ,(symbol-name symbol) ,(package-name package))))))
(defun dump-cons (cons)
(let ((head (butlast cons))
(tail (last cons)))
`(call-internal |QIList|
,@(mapcar (lambda (x) (literal x t)) head)
,(literal (car tail) t)
,(literal (cdr tail) t))))
(defun dump-array (array)
(let ((elements (vector-to-list array)))
(list-to-vector (mapcar #'literal elements))))
(defun dump-string (string)
`(call-internal |make_lisp_string| ,string))
(defun literal (sexp &optional recursive)
(cond
((integerp sexp) sexp)
((floatp sexp) sexp)
((characterp sexp) (string sexp))
(t
(or (cdr (assoc sexp *literal-table* :test #'eql))
(let ((dumped (typecase sexp
(symbol (dump-symbol sexp))
(string (dump-string sexp))
(cons
;; BOOTSTRAP MAGIC: See the root file
;; jscl.lisp and the function
;; `dump-global-environment' for further
;; information.
(if (eq (car sexp) *magic-unquote-marker*)
(convert (second sexp))
(dump-cons sexp)))
(array (dump-array sexp)))))
(if (and recursive (not (symbolp sexp)))
dumped
(let ((jsvar (genlit)))
(push (cons sexp jsvar) *literal-table*)
(toplevel-compilation `(var (,jsvar ,dumped)))
(when (keywordp sexp)
(toplevel-compilation `(= (get ,jsvar "value") ,jsvar)))
jsvar)))))))
(define-compilation quote (sexp)
(literal sexp))
(define-compilation %while (pred &rest body)
`(selfcall
(while (!== ,(convert pred) ,(convert nil))
,(convert-block body))
(return ,(convert nil))))
(define-compilation function (x)
(cond
((and (listp x) (eq (car x) 'lambda))
(compile-lambda (cadr x) (cddr x)))
((and (listp x) (eq (car x) 'named-lambda))
(destructuring-bind (name ll &rest body) (cdr x)
(compile-lambda ll body
:name (symbol-name name)
:block name)))
((symbolp x)
(let ((b (lookup-in-lexenv x *environment* 'function)))
(if b
(binding-value b)
(convert `(symbol-function ',x)))))))
(defun make-function-binding (fname)
(make-binding :name fname :type 'function :value (gvarname fname)))
(defun compile-function-definition (list)
(compile-lambda (car list) (cdr list)))
(defun translate-function (name)
(let ((b (lookup-in-lexenv name *environment* 'function)))
(and b (binding-value b))))
(define-compilation flet (definitions &rest body)
(let* ((fnames (mapcar #'car definitions))
(cfuncs (mapcar (lambda (def)
(compile-lambda (cadr def)
`((block ,(car def)
,@(cddr def)))))
definitions))
(*environment*
(extend-lexenv (mapcar #'make-function-binding fnames)
*environment*
'function)))
`(call (function ,(mapcar #'translate-function fnames)
,(convert-block body t))
,@cfuncs)))
(define-compilation labels (definitions &rest body)
(let* ((fnames (mapcar #'car definitions))
(*environment*
(extend-lexenv (mapcar #'make-function-binding fnames)
*environment*
'function)))
`(selfcall
,@(mapcar (lambda (func)
`(var (,(translate-function (car func))
,(compile-lambda (cadr func)
`((block ,(car func) ,@(cddr func)))))))
definitions)
,(convert-block body t))))
;;; Was the compiler invoked from !compile-file?
(defvar *compiling-file* nil)
;;; NOTE: It is probably wrong in many cases but we will not use this
;;; heavily. Please, do not rely on wrong cases of this
;;; implementation.
(define-compilation eval-when (situations &rest body)
;; TODO: Error checking
(cond
;; Toplevel form compiled by !compile-file.
((and *compiling-file* (zerop *convert-level*))
;; If the situation `compile-toplevel' is given. The form is
;; evaluated at compilation-time.
(when (or (find :compile-toplevel situations)
(find 'compile situations))
(eval (cons 'progn body)))
;; `load-toplevel' is given, then just compile the subforms as usual.
(when (or (find :load-toplevel situations)
(find 'load situations))
(convert-toplevel `(progn ,@body) *multiple-value-p*)))
((or (find :execute situations)
(find 'eval situations))
(convert `(progn ,@body) *multiple-value-p*))
(t
(convert nil))))
(defmacro define-transformation (name args form)
`(define-compilation ,name ,args
(convert ,form)))
(define-compilation progn (&rest body)
`(progn
,@(append (mapcar #'convert (butlast body))
(list (convert (car (last body)) *multiple-value-p*)))))
(define-compilation macrolet (definitions &rest body)
(let ((*environment* (copy-lexenv *environment*)))
(dolist (def definitions)
(destructuring-bind (name lambda-list &body body) def
(let ((binding (make-binding :name name :type 'macro :value
(let ((g!form (gensym)))
`(lambda (,g!form)
(destructuring-bind ,lambda-list ,g!form
,@body))))))
(push-to-lexenv binding *environment* 'function))))
(convert `(progn ,@body) *multiple-value-p*)))
(defun special-variable-p (x)
(and (claimp x 'variable 'special) t))
(defun normalize-bindings (arg)
(destructuring-bind (name &optional value)
(ensure-list arg)
(list name value)))
;;; Given a let-like description of bindings, return:
;;;
;;; 1. A list of lexical
;;; 2. A list of values to bind to the lexical variables
;;; 3. A alist of (special-variable . lexical-variable) to bind.
;;;
(defun process-bindings (bindings)
(let ((bindings (mapcar #'normalize-bindings bindings))
(special-bindings nil))
(values
;; Lexical Variables
(mapcar (lambda (var)
(if (special-variable-p var)
(let ((lexvar (gensym)))
(push (cons var lexvar) special-bindings)
lexvar)
var))
(mapcar #'car bindings))
;; Values
(mapcar #'cadr bindings)
;; Binding special variables to lexical variables
special-bindings)))
;;; Wrap CODE to restore the symbol values of the dynamic
;;; bindings. BINDINGS is a list of pairs of the form
;;; (SYMBOL . PLACE), where PLACE is a Javascript variable
;;; name to initialize the symbol value and where to stored
;;; the old value.
(defun let-bind-dynamic-vars (special-bindings body)
(if (null special-bindings)
(convert-block body t t)
(let ((special-variables (mapcar #'car special-bindings))
(lexical-variables (mapcar #'cdr special-bindings)))
`(return (call-internal
|bindSpecialBindings|
,(list-to-vector (mapcar #'literal special-variables))
,(list-to-vector (mapcar #'translate-variable lexical-variables))
(function () ,(convert-block body t t)))))))
(define-compilation let (bindings &rest body)
(multiple-value-bind (lexical-variables values special-bindings)
(process-bindings bindings)
(let ((compiled-values (mapcar #'convert values))
(*environment* (extend-local-env lexical-variables)))
`(call (function ,(mapcar #'translate-variable lexical-variables)
,(let-bind-dynamic-vars special-bindings body))
,@compiled-values))))
;; LET* compilation
;;
;; (let* ((*var1* value1))
;; (*var2* value2))
;; ...)
;;
;; var sbindings = [];
;;
;; try {
;; // compute value1
;; // bind to var1
;; // add var1 to sbindings
;;
;; // compute value2
;; // bind to var2
;; // add var2 to sbindings
;;
;; // ...
;;
;; } finally {
;; // ...
;; // restore bindings of sbindings
;; // ...
;; }
;;
(define-compilation let* (bindings &rest body)
(let ((bindings (mapcar #'ensure-list bindings))
(*environment* (copy-lexenv *environment*))
(sbindings (gvarname '|bindings|))
(prelude-target nil)
(postlude-target nil))
(dolist (binding bindings)
(destructuring-bind (variable &optional value) binding
(cond
((special-variable-p variable)
;; VALUE is evaluated before the variable is bound.
(let ((s (convert `',variable))
(v (convert value))
(out (gvarname 'value)))
(push `(progn
;; Store the compiled value into the temporary
;; JS variable OUT. Note that this code could
;; throw, so the following code could not run at
;; all.
(var (,out ,v))
;; Create a new binding by pushing the symbol
;; value to the stack, and scheduling the value
;; to be restored (in the postlude). Note that
;; this is done at runtime and not compile-time
;; because we could have 5 variables to bind,
;; but we could see an error for example in the
;; 3rd one only. So we do not always restore all
;; bindings necessarily.
(method-call (get ,s "stack") "push" (get ,s "value"))
(method-call ,sbindings "push" ,s)
;; Assign the value to the recently created
;; binding.
(= (get ,s "value") ,out))
prelude-target)))
(t
(let* ((jsvar (gvarname variable))
(binding (make-binding :name variable :type 'variable :value jsvar)))
(push `(var (,jsvar ,(convert value)))
prelude-target)
(push-to-lexenv binding *environment* 'variable))))))
;; The postlude will undo all the completed bindings from the
;; prelude.
(push `(method-call ,sbindings "forEach"
(function (s)
(= (get s "value")
(method-call (get s "stack") "pop"))))
postlude-target)
(let ((body
`(progn
,@(reverse prelude-target)
,(convert-block body t t))))
(if (find-if #'special-variable-p bindings :key #'first)
`(selfcall
(var (,sbindings #()))
(try ,body)
(finally ,@(reverse postlude-target)))
;; If there is no special variables, we don't need try/catch
`(selfcall ,body)))))
(define-compilation block (name &rest body)
;; We use Javascript exceptions to implement non local control
;; transfer. Exceptions has dynamic scoping, so we use a uniquely
;; generated object to identify the block. The instance of a empty
;; array is used to distinguish between nested dynamic Javascript
;; exceptions. See https://github.com/jscl-project/jscl/issues/64 for
;; further details.
(let* ((idvar (gvarname name))
(b (make-binding :name name :type 'block :value idvar)))
(when *multiple-value-p*
(push 'multiple-value (binding-declarations b)))
(let* ((*environment* (extend-lexenv (list b) *environment* 'block))
(cbody (convert-block body t)))
(if (member 'used (binding-declarations b))
`(selfcall
(try
(var (,idvar #()))
,cbody)
(catch (cf)
(if (and (instanceof cf (internal |BlockNLX|)) (== (get cf "id") ,idvar))
,(if *multiple-value-p*
`(return (method-call |values| "apply" this
(call-internal |forcemv| (get cf "values"))))
`(return (get cf "values")))
(throw cf))))
`(selfcall ,cbody)))))
(define-compilation return-from (name &optional value)
(let* ((b (lookup-in-lexenv name *environment* 'block))
(multiple-value-p (member 'multiple-value (binding-declarations b))))
(when (null b)
(error "Return from unknown block `~S'." (symbol-name name)))
(push 'used (binding-declarations b))
;; The binding value is the name of a variable, whose value is the
;; unique identifier of the block as exception. We can't use the
;; variable name itself, because it could not to be unique, so we
;; capture it in a closure.
`(selfcall
,(when multiple-value-p `(var (|values| (internal |mv|))))
(throw (new (call-internal |BlockNLX|
,(binding-value b)
,(convert value multiple-value-p)
,(symbol-name name)))))))
(define-compilation catch (id &rest body)
(let ((values (if *multiple-value-p* '|values| '(internal |pv|))))
`(selfcall
(var (id ,(convert id)))
(try
,(convert-block body t))
(catch (cf)
(if (and (instanceof cf (internal |CatchNLX|)) (== (get cf "id") id))
(return (method-call ,values "apply" this
(call-internal |forcemv| (get cf "values"))))
(throw cf))))))
(define-compilation throw (id value)
`(selfcall
(var (|values| (internal |mv|)))
(throw (new (call-internal |CatchNLX| ,(convert id) ,(convert value t))))))
(defun go-tag-p (x)
(or (integerp x) (symbolp x)))
(defun declare-tagbody-tags (tbidx body)
(let* ((go-tag-counter 0)
(bindings
(mapcar (lambda (label)
(let ((tagidx (incf go-tag-counter)))
(make-binding :name label :type 'gotag :value (list tbidx tagidx))))
(remove-if-not #'go-tag-p body))))
(extend-lexenv bindings *environment* 'gotag)))
(define-compilation tagbody (&rest body)
;; Ignore the tagbody if it does not contain any go-tag. We do this
;; because 1) it is easy and 2) many built-in forms expand to a
;; implicit tagbody, so we save some space.
(unless (some #'go-tag-p body)
(return-from tagbody (convert `(progn ,@body nil))))
;; The translation assumes the first form in BODY is a label
(unless (go-tag-p (car body))
(push (gensym "START") body))
;; Tagbody compilation
(let ((branch (gvarname 'branch))
(tbidx (gvarname 'tbidx)))
(let ((*environment* (declare-tagbody-tags tbidx body))
initag)
(let ((b (lookup-in-lexenv (first body) *environment* 'gotag)))
(setq initag (second (binding-value b))))
`(selfcall
;; TAGBODY branch to take
(var (,branch ,initag))
(var (,tbidx #()))
(label tbloop
(while true
(try
(switch ,branch
,@(with-collect
(collect `(case ,initag))
(dolist (form (cdr body))
(if (go-tag-p form)
(let ((b (lookup-in-lexenv form *environment* 'gotag)))
(collect `(case ,(second (binding-value b)))))
(collect (convert form)))))
default
(break tbloop)))
(catch (jump)
(if (and (instanceof jump (internal |TagNLX|)) (== (get jump "id") ,tbidx))
(= ,branch (get jump "label"))
(throw jump)))))
(return ,(convert nil))))))
(define-compilation go (label)
(let ((b (lookup-in-lexenv label *environment* 'gotag)))
(when (null b)
(error "Unknown tag `~S'" label))
`(selfcall
(throw (new (call-internal |TagNLX|
,(first (binding-value b))
,(second (binding-value b))))))))
(define-compilation unwind-protect (form &rest clean-up)
`(selfcall
(var (ret ,(convert nil)))
(try
(= ret ,(convert form)))
(finally
,(convert-block clean-up))
(return ret)))
(define-compilation multiple-value-call (func-form &rest forms)
`(selfcall
(var (func ,(convert func-form)))
(var (args ,(vector (if *multiple-value-p* '|values| '(internal |pv|)))))
(return
(selfcall
(var (|values| (internal |mv|)))
(var vs)
(progn
,@(with-collect
(dolist (form forms)
(collect `(= vs ,(convert form t)))
(collect `(if (and (=== (typeof vs) "object")
vs
(in "multiple-value" vs))
(= args (method-call args "concat" vs))
(method-call args "push" vs))))))
(return (method-call func "apply" null args))))))
(define-compilation multiple-value-prog1 (first-form &rest forms)
`(selfcall
(var (args ,(convert first-form *multiple-value-p*)))
(progn ,@(mapcar #'convert forms))
(return args)))
(define-compilation the (value-type form)
(convert form *multiple-value-p*))
(define-transformation backquote (form)
(bq-completely-process form))
;;; Primitives
(defvar *builtins*
(make-hash-table))
(defun !special-operator-p (name)
(nth-value 1 (gethash name *builtins*)))
#+jscl
(fset 'special-operator-p #'!special-operator-p)
(defmacro define-raw-builtin (name args &body body)
;; Creates a new primitive function `name' with parameters args and
;; @body. The body can access to the local environment through the
;; variable *ENVIRONMENT*.
`(setf (gethash ',name *builtins*)
(lambda ,args
(block ,name ,@body))))
(defmacro define-builtin (name args &body body)
`(define-raw-builtin ,name ,args
(let ,(mapcar (lambda (arg) `(,arg (convert ,arg))) args)
,@body)))
;;; VARIABLE-ARITY compiles variable arity operations. ARGS stands for
;;; a variable which holds a list of forms. It will compile them and
;;; store the result in some Javascript variables. BODY is evaluated
;;; with ARGS bound to the list of these variables to generate the
;;; code which performs the transformation on these variables.
(defun variable-arity-call (args function)
(unless (consp args)
(error "ARGS must be a non-empty list"))
(let ((counter 0))
;; XXX: Add macro with-collectors
(with-collector (fargs)
(with-collector (prelude)
(dolist (x args)
(if (or (floatp x) (numberp x))
(collect-fargs x)
(let ((v (make-symbol (concat "x" (integer-to-string (incf counter))))))
(collect-fargs v)
(collect-prelude `(var (,v ,(convert x))))
(collect-prelude `(if (!= (typeof ,v) "number")
(throw "Not a number!"))))))
`(selfcall
(progn ,@prelude)
,(funcall function fargs))))))
(defmacro variable-arity (args &body body)
(unless (symbolp args)
(error "`~S' is not a symbol." args))
`(variable-arity-call ,args (lambda (,args) `(return ,,@body))))
(define-raw-builtin + (&rest numbers)
(if (null numbers)
0
(variable-arity numbers
`(+ ,@numbers))))
(define-raw-builtin - (x &rest others)
(let ((args (cons x others)))
(variable-arity args `(- ,@args))))
(define-raw-builtin * (&rest numbers)
(if (null numbers)
1
(variable-arity numbers `(* ,@numbers))))
(define-raw-builtin / (x &rest others)
(let ((args (cons x others)))
(variable-arity args
(if (null others)
`(call-internal |handled_division| 1 ,(car args))
(reduce (lambda (x y) `(call-internal |handled_division| ,x ,y))
args)))))
(define-builtin rem0 (x y)
`(selfcall
(if (== ,y 0)
(throw "Division by zero"))
(return (% ,x ,y))))
(define-builtin %ash-left (x y)
`(call-internal |Bitwise_ash_L| ,x ,y))
(define-builtin %ash-right (x y)
`(call-internal |Bitwise_ash_R| ,x ,y))
(define-builtin %lognot (x)
`(call-internal |Bitwise_not| ,x ))
(define-builtin %logand (x y)
`(call-internal |Bitwise_and| ,x ,y))
(define-builtin %logxor (x y)
`(call-internal |Bitwise_xor| ,x ,y))
(define-builtin %logior (x y)
`(call-internal |Bitwise_ior| ,x ,y))
(defun comparison-conjuntion (vars op)
(cond
((null (cdr vars))
'true)
((null (cddr vars))
`(,op ,(car vars) ,(cadr vars)))
(t
`(and (,op ,(car vars) ,(cadr vars))
,(comparison-conjuntion (cdr vars) op)))))
(defmacro define-builtin-comparison (op sym)
`(define-raw-builtin ,op (x &rest args)
(let ((args (cons x args)))
(variable-arity args
(convert-to-bool (comparison-conjuntion args ',sym))))))
(define-builtin-comparison > >)
(define-builtin-comparison < <)
(define-builtin-comparison >= >=)
(define-builtin-comparison <= <=)
(define-builtin-comparison = ==)
(define-builtin-comparison /= !=)
(define-builtin numberp (x)
(convert-to-bool `(== (typeof ,x) "number")))
(define-builtin %integer-p (x)
(convert-to-bool `(method-call |Number| "isInteger" ,x)))
(define-builtin %truncate (x)
`(method-call |Math| "trunc" ,x))
(define-builtin %floor (x)
`(method-call |Math| "floor" ,x))
(define-builtin %ceiling (x)
`(method-call |Math| "ceil" ,x))
(define-builtin expt (x y)
`(method-call |Math| "pow" ,x ,y))
(define-builtin sqrt (x)
`(method-call |Math| "sqrt" ,x))
(define-builtin float-to-string (x)
`(call-internal |make_lisp_string| (method-call ,x |toString|)))
(define-builtin cons (x y)
`(new (call-internal |Cons| ,x ,y)))
(define-builtin consp (x)
(convert-to-bool `(instanceof ,x (internal |Cons|))))
(define-builtin car (x)
`(call-internal |car| ,x))
(define-builtin cdr (x)
`(call-internal |cdr| ,x))
(define-builtin rplaca (x new)
`(selfcall
(var (tmp ,x))
(= (get tmp "car") ,new)
(return tmp)))
(define-builtin rplacd (x new)
`(selfcall
(var (tmp ,x))
(= (get tmp "cdr") ,new)
(return tmp)))
(define-builtin symbolp (x)
(convert-to-bool `(instanceof ,x (internal |Symbol|))))
(define-builtin make-symbol (name)
`(new (call-internal |Symbol| (call-internal |lisp_to_js| ,name))))
(define-compilation symbol-name (x)
(convert `(oget ,x "name")))
(define-builtin set (symbol value)
`(= (get ,symbol "value") ,value))
(define-builtin fset (symbol value)
`(= (get ,symbol "fvalue") ,value))
(define-builtin boundp (x)
(convert-to-bool `(!== (get ,x "value") undefined)))
(define-builtin %fboundp (x)
(convert-to-bool `(call-internal |fboundp| ,x)))
(define-builtin symbol-value (x)
`(call-internal |symbolValue| ,x))
(define-builtin symbol-function (x)
`(call-internal |symbolFunction| ,x))
(define-builtin lambda-code (x)
`(call-internal |make_lisp_string| (method-call ,x "toString")))
(define-builtin eq (x y)
(convert-to-bool `(=== ,x ,y)))
(define-builtin char-code (x)
`(call-internal |char_to_codepoint| ,x))
(define-builtin code-char (x)
`(call-internal |char_from_codepoint| ,x))
(define-builtin characterp (x)
`(selfcall
(var (x ,x))
(return ,(convert-to-bool
`(and (== (typeof x) "string")
(or (== (get x "length") 1)
(== (get x "length") 2)))))))
(define-builtin char-upcase (x)
`(call-internal |safe_char_upcase| ,x))
(define-builtin char-downcase (x)
`(call-internal |safe_char_downcase| ,x))
(define-builtin stringp (x)
`(selfcall
(var (x ,x))
(return ,(convert-to-bool
`(and (and (=== (typeof x) "object")
(!== x null)
(in "length" x))
(== (get x "stringp") 1))))))
(define-raw-builtin funcall (func &rest args)
`(selfcall
(var (f ,(convert func)))
(return (call (if (=== (typeof f) "function")
f
(get f "fvalue"))
,@(cons (if *multiple-value-p* '|values| '(internal |pv|))
(mapcar #'convert args))))))
(define-raw-builtin apply (func &rest args)
(if (null args)
(convert func)
(let ((args (butlast args))
(last (car (last args))))
`(selfcall
(var (f ,(convert func)))
(var (args ,(list-to-vector
(cons (if *multiple-value-p* '|values| '(internal |pv|))
(mapcar #'convert args)))))
(var (tail ,(convert last)))
(while (!= tail ,(convert nil))
(method-call args "push" (get tail "car"))
(= tail (get tail "cdr")))
(return (method-call (if (=== (typeof f) "function")
f
(get f "fvalue"))
"apply"
this
args))))))
(define-builtin js-eval (string)
(if *multiple-value-p*
`(selfcall
(var (v (call-internal |globalEval| (call-internal |xstring| ,string))))
(return (method-call |values| "apply" this (call-internal |forcemv| v))))
`(call-internal |globalEval| (call-internal |xstring| ,string))))
(define-builtin %throw (string)
`(selfcall (throw ,string)))
(define-builtin functionp (x)
(convert-to-bool `(=== (typeof ,x) "function")))
(define-builtin /debug (x)
`(method-call |console| "log" (call-internal |xstring| ,x)))
(define-raw-builtin /log (x &rest y)
`(selfcall
(call (get |console| "log")
,x
,@(mapcar #'convert y))
(return ,(convert nil))))
;;; Storage vectors. They are used to implement arrays and (in the
;;; future) structures.
(define-builtin storage-vector-p (x)
`(selfcall
(var (x ,x))
(return ,(convert-to-bool
`(and (=== (typeof x) "object")
(!== x null)
(in "length" x))))))
(define-builtin make-storage-vector (n)
`(selfcall
(var (r #()))
(= (get r "length") ,n)
(return r)))
(define-builtin storage-vector-size (x)
`(get ,x "length"))
(define-builtin resize-storage-vector (vector new-size)
`(= (get ,vector "length") ,new-size))
(define-builtin storage-vector-ref (vector n)
`(selfcall
(var (x (property ,vector ,n)))
(if (=== x undefined) (throw "Out of range."))
(return x)))
(define-builtin storage-vector-set (vector n value)
`(selfcall
(var (x ,vector))
(var (i ,n))
(if (or (< i 0) (>= i (get x "length")))
(throw "Out of range."))
(return (= (property x i) ,value))))
(define-builtin storage-vector-set! (vector n value)
`(= (property ,vector ,n) ,value))
(define-builtin storage-vector-fill (vector value)
`(method-call ,vector "fill" ,value))
(define-builtin concatenate-storage-vector (sv1 sv2)
`(selfcall
(var (sv1 ,sv1))
(var (r (method-call sv1 "concat" ,sv2)))
(= (get r "type") (get sv1 "type"))
(= (get r "stringp") (get sv1 "stringp"))
(return r)))
(define-builtin get-internal-real-time ()
`(method-call (new (call |Date|)) "getTime"))
(define-builtin values-array (array)
(if *multiple-value-p*
`(method-call |values| "apply" this ,array)
`(method-call (internals |pv|) "apply" this ,array)))
(define-raw-builtin values (&rest args)
(if *multiple-value-p*
`(call |values| ,@(mapcar #'convert args))
`(call-internal |pv| ,@(mapcar #'convert args))))
;;; Javascript FFI
(define-builtin new ()
'(object))
(define-raw-builtin oget* (object key &rest keys)
`(selfcall
(progn
(var (tmp (property ,(convert object) (call-internal |xstring| ,(convert key)))))
,@(mapcar (lambda (key)
`(progn
(if (=== tmp undefined) (return ,(convert nil)))
(= tmp (property tmp (call-internal |xstring| ,(convert key))))))
keys))
(return (if (=== tmp undefined) ,(convert nil) tmp))))
(define-raw-builtin oset* (value object key &rest keys)
(let ((keys (cons key keys)))
`(selfcall
(progn
(var (obj ,(convert object)))
,@(mapcar (lambda (key)
`(progn
(= obj (property obj (call-internal |xstring| ,(convert key))))
(if (=== obj undefined)
(throw "Impossible to set object property."))))
(butlast keys))
(var (tmp
(= (property obj (call-internal |xstring| ,(convert (car (last keys)))))
,(convert value))))
(return (if (=== tmp undefined)
,(convert nil)
tmp))))))
(define-raw-builtin oget (object key &rest keys)
`(call-internal |js_to_lisp| ,(convert `(oget* ,object ,key ,@keys))))
(define-raw-builtin oset (value object key &rest keys)
(convert `(oset* (lisp-to-js ,value) ,object ,key ,@keys)))
(define-builtin js-null-p (x)
(convert-to-bool `(=== ,x null)))
(define-builtin objectp (x)
(convert-to-bool `(=== (typeof ,x) "object")))
(define-builtin js-undefined-p (x)
(convert-to-bool `(=== ,x undefined)))
(define-builtin %%nlx-p (x)
(convert-to-bool `(call-internal |isNLX| ,x)))
(define-builtin %%throw (x)
`(selfcall (throw ,x)))
(define-builtin lisp-to-js (x) `(call-internal |lisp_to_js| ,x))
(define-builtin js-to-lisp (x) `(call-internal |js_to_lisp| ,x))
(define-builtin in (key object)
(convert-to-bool `(in (call-internal |xstring| ,key) ,object)))
(define-builtin delete-property (key object)
`(selfcall
(delete (property ,object (call-internal |xstring| ,key)))))
(define-builtin map-for-in (function object)
`(selfcall
(var (f ,function)
(g (if (=== (typeof f) "function") f (get f "fvalue")))
(o ,object)
key)
(for-in (key o)
(call g ,(if *multiple-value-p* '|values| '(internal |pv|))
(property o key)))
(return ,(convert nil))))
(define-compilation %js-vref (var &optional raw)
(if raw
(make-symbol var)
`(call-internal |js_to_lisp| ,(make-symbol var))))
(define-compilation %js-vset (var val)
`(= ,(make-symbol var) (call-internal |lisp_to_js| ,(convert val))))
(define-setf-expander %js-vref (var)
(let ((new-value (gensym)))
(unless (stringp var)
(error "`~S' is not a string." var))
(values nil
(list var)
(list new-value)
`(%js-vset ,var ,new-value)
`(%js-vref ,var))))
(define-compilation %js-typeof (x)
`(call-internal |js_to_lisp| (typeof ,x)))
;;; Access a function defined in the internals runtime object.
(define-compilation %js-internal (name)
`(internal ,name))
;; Catch any Javascript exception. Note that because all non-local
;; exit are based on try-catch-finally, it will also catch them. We
;; could provide a JS function to detect it, so the user could rethrow
;; the error.
;;
;; (%js-try
;; (progn
;; )
;; (catch (err)
;; )
;; (finally
;; ))
;;
(define-compilation %js-try (form &optional catch-form finally-form)
(let ((catch-compilation
(and catch-form
(destructuring-bind (catch (var) &body body) catch-form
(unless (eq catch 'catch)
(error "Bad CATCH clausule `~S'." catch-form))
(let* ((*environment* (extend-local-env (list var)))
(tvar (translate-variable var)))
`(catch (,tvar)
(= ,tvar (call-internal |js_to_lisp| ,tvar))
,(convert-block body t))))))
(finally-compilation
(and finally-form
(destructuring-bind (finally &body body) finally-form
(unless (eq finally 'finally)
(error "Bad FINALLY clausule `~S'." finally-form))
`(finally
,(convert-block body))))))
`(selfcall
(try (return ,(convert form)))
,catch-compilation
,finally-compilation)))
(define-compilation symbol-macrolet (macrobindings &rest body)
(let ((new (copy-lexenv *environment*)))
(dolist (macrobinding macrobindings)
(destructuring-bind (symbol expansion) macrobinding
(let ((b (make-binding :name symbol :type 'macro :value expansion)))
(push-to-lexenv b new 'variable))))
(let ((*environment* new))
(convert-block body nil t))))
#-jscl
(defvar *macroexpander-cache*
(make-hash-table :test #'eq))
(defun !macro-function (symbol)
(unless (symbolp symbol)
(error "`~S' is not a symbol." symbol))
(let ((b (lookup-in-lexenv symbol *environment* 'function)))
(if (and b (eq (binding-type b) 'macro))
(let ((expander (binding-value b)))
(cond
#-jscl
((gethash b *macroexpander-cache*)
(setq expander (gethash b *macroexpander-cache*)))
((listp expander)
(let ((compiled (eval expander)))
;; The list representation are useful while
;; bootstrapping, as we can dump the definition of the
;; macros easily, but they are slow because we have to
;; evaluate them and compile them now and again. So, let
;; us replace the list representation version of the
;; function with the compiled one.
;;
#+jscl (setf (binding-value b) compiled)
#-jscl (setf (gethash b *macroexpander-cache*) compiled)
(setq expander compiled))))
expander)
nil)))
(defun !macroexpand-1 (form &optional env)
(let ((*environment* (or env *environment*)))
(cond
((symbolp form)
(let ((b (lookup-in-lexenv form *environment* 'variable)))
(if (and b (eq (binding-type b) 'macro))
(values (binding-value b) t)
(values form nil))))
((and (consp form) (symbolp (car form)))
(let ((macrofun (!macro-function (car form))))
(if macrofun
(values (funcall macrofun (cdr form)) t)
(values form nil))))
(t
(values form nil)))))
#+jscl
(fset 'macroexpand-1 #'!macroexpand-1)
(defun !macroexpand (form &optional env)
(let ((continue t))
(while continue
(multiple-value-setq (form continue) (!macroexpand-1 form env)))
form))
#+jscl
(fset 'macroexpand #'!macroexpand)
(defun compile-funcall (function args)
(let* ((arglist (cons (if *multiple-value-p* '|values| '(internal |pv|))
(mapcar #'convert args))))
(unless (or (symbolp function)
(and (consp function)
(member (car function) '(lambda oget))))
(error "Bad function designator `~S'" function))
(cond
((translate-function function)
`(call ,(translate-function function) ,@arglist))
((symbolp function)
(fn-info function :called t)
;; This code will work even if the symbol-function is unbound,
;; as it is represented by a function that throws the expected
;; error.
`(method-call ,(convert `',function) "fvalue" ,@arglist))
((and (consp function) (eq (car function) 'lambda))
`(call ,(convert `(function ,function)) ,@arglist))
((and (consp function) (eq (car function) 'oget))
`(call-internal |js_to_lisp|
(call ,(reduce (lambda (obj p)
`(property ,obj (call-internal |xstring| ,p)))
(mapcar #'convert (cdr function)))
,@(mapcar (lambda (s)
`(call-internal |lisp_to_js| ,(convert s)))
args))))
(t
(error "Bad function descriptor")))))
(defun convert-block (sexps &optional return-last-p decls-allowed-p)
(multiple-value-bind (sexps decls)
(parse-body sexps :declarations decls-allowed-p)
(declare (ignore decls))
(if return-last-p
`(progn
,@(mapcar #'convert (butlast sexps))
(return ,(convert (car (last sexps)) *multiple-value-p*)))
`(progn ,@(mapcar #'convert sexps)))))
(defun convert-1 (sexp &optional multiple-value-p)
(multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
(when expandedp
(return-from convert-1 (convert sexp multiple-value-p)))
;; The expression has been macroexpanded. Now compile it!
(let ((*multiple-value-p* multiple-value-p)
(*convert-level* (1+ *convert-level*)))
(cond
((symbolp sexp)
(let ((b (lookup-in-lexenv sexp *environment* 'variable)))
(cond
((and b (not (member 'special (binding-declarations b))))
(binding-value b))
((or (keywordp sexp)
(and b (member 'constant (binding-declarations b))))
`(get ,(convert `',sexp) "value"))
(t
(convert `(symbol-value ',sexp))))))
((or (integerp sexp) (floatp sexp) (characterp sexp) (stringp sexp) (arrayp sexp))
(literal sexp))
((listp sexp)
(let ((name (car sexp))
(args (cdr sexp)))
(cond
;; Special forms
((gethash name *compilations*)
(let ((comp (gethash name *compilations*)))
(apply comp args)))
;; Built-in functions
((and (gethash name *builtins*)
(not (claimp name 'function 'notinline)))
(apply (gethash name *builtins*) args))
(t
(compile-funcall name args)))))
(t
(error "How should I compile `~S'?" sexp))))))
(defun convert (sexp &optional multiple-value-p)
(convert-1 sexp multiple-value-p))
(defvar *compile-print-toplevels* nil)
(defun truncate-string (string &optional (width 60))
(let ((n (or (position #\newline string)
(min width (length string)))))
(subseq string 0 n)))
(defun convert-toplevel (sexp &optional multiple-value-p return-p)
;; Macroexpand sexp as much as possible
(multiple-value-bind (sexp expandedp) (!macroexpand-1 sexp)
(when expandedp
(return-from convert-toplevel
(convert-toplevel sexp multiple-value-p return-p))))
;; Process as toplevel
(let ((*convert-level* -1))
(cond
;; Non-empty toplevel progn
((and (consp sexp)
(eq (car sexp) 'progn)
(cdr sexp))
`(progn
;; Discard all except the last value
,@(mapcar (lambda (s) (convert-toplevel s nil))
(butlast (cdr sexp)))
;; Return the last value(s)
,(convert-toplevel (first (last (cdr sexp))) multiple-value-p return-p)))
(t
(when *compile-print-toplevels*
(let ((form-string (prin1-to-string sexp)))
(format t "Compiling ~a...~%" (truncate-string form-string))))
(let ((code (convert sexp multiple-value-p)))
(if return-p
`(return ,code)
code))))))
(defun process-toplevel (sexp &optional multiple-value-p return-p)
(let ((*toplevel-compilations* nil))
(let ((code (convert-toplevel sexp multiple-value-p return-p)))
`(progn
,@(get-toplevel-compilations)
,code))))
(defun compile-toplevel (sexp &optional multiple-value-p return-p)
(with-output-to-string (*js-output*)
(js (process-toplevel sexp multiple-value-p return-p))))
(defmacro with-compilation-environment (&body body)
`(let ((*literal-table* nil)
(*variable-counter* 0)
(*gensym-counter* 0)
(*literal-counter* 0))
,@body))
| 59,990 | Common Lisp | .lisp | 1,460 | 32.308904 | 97 | 0.578524 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 4fdb17c8d9504ae0e8467a8a537fe1767ad3e18353489e10e4e912cbc0269456 | 48 | [
-1
] |
49 | codegen.lisp | jscl-project_jscl/src/compiler/codegen.lisp | ;;; compiler-codege.lisp --- Naive Javascript unparser
;; Copyright (C) 2013, 2014 David Vazquez
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
;;; This code generator takes as input a S-expression representation
;;; of the Javascript AST and generates Javascript code without
;;; redundant syntax constructions like extra parenthesis.
;;;
;;; It is intended to be used with the new compiler. However, it is
;;; quite independent so it has been integrated early in JSCL.
(/debug "loading compiler-codegen.lisp!")
(defvar *js-macros* nil)
(defmacro define-js-macro (name lambda-list &body body)
(let ((form (gensym)))
`(push (cons ',name
(lambda (,form)
(block ,name
(destructuring-bind ,lambda-list ,form
,@body))))
*js-macros*)))
(defun js-macroexpand (js)
(if (and (consp js) (assoc (car js) *js-macros*))
(let ((expander (cdr (assoc (car js) *js-macros*))))
(multiple-value-bind (expansion stop-expand-p)
(funcall expander (cdr js))
(if stop-expand-p
expansion
(js-macroexpand expansion))))
js))
;; This is a special precedence value just above the comma operator (,). We use
;; this in some expressions to make sure expressions are wrapped in parenthesis,
;; for example, in function calls:
;; f(1,(2,3),4)
(defconstant no-comma 2)
(defvar *js-output* t)
(defvar *js-pretty-print* t)
;;; Two separate functions are needed for escaping strings:
;;; One for producing JavaScript string literals (which are singly or
;;; doubly quoted)
;;; And one for producing Lisp strings (which are only doubly quoted)
;;;
;;; The same function would suffice for both, but for javascript string
;;; literals it is neater to use either depending on the context, e.g:
;;; foo's => "foo's"
;;; "foo" => '"foo"'
;;; which avoids having to escape quotes where possible
(defun js-escape-string (string)
(let ((index 0)
(size (length string))
(seen-single-quote nil)
(seen-double-quote nil))
(flet ((%js-escape-string (string escape-single-quote-p)
(let ((output "")
(index 0))
(while (< index size)
(let ((ch (char string index)))
(when (char= ch #\\)
(setq output (concat output "\\")))
(when (and escape-single-quote-p (char= ch #\'))
(setq output (concat output "\\")))
(when (char= ch #\newline)
(setq output (concat output "\\"))
(setq ch #\n))
(setq output (concat output (string ch))))
(incf index))
output)))
;; First, scan the string for single/double quotes
(while (< index size)
(let ((ch (char string index)))
(when (char= ch #\')
(setq seen-single-quote t))
(when (char= ch #\")
(setq seen-double-quote t)))
(incf index))
;; Then pick the appropriate way to escape the quotes
(cond
((not seen-single-quote)
(concat "'" (%js-escape-string string nil) "'"))
((not seen-double-quote)
(concat "\"" (%js-escape-string string nil) "\""))
(t (concat "'" (%js-escape-string string t) "'"))))))
(defun js-format (fmt &rest args)
(apply #'format *js-output* fmt args))
;;; Check if STRING-DESIGNATOR is valid as a Javascript identifier. It
;;; returns a couple of values. The identifier itself as a string and
;;; a boolean value with the result of this check.
(defun valid-js-identifier (string-designator)
(let ((string (typecase string-designator
(symbol (symbol-name string-designator))
(string string-designator)
(t
(return-from valid-js-identifier (values nil nil))))))
(flet ((constitutentp (ch)
(or (alphanumericp ch) (member ch '(#\$ #\_)))))
(if (and (every #'constitutentp string)
(if (plusp (length string))
(not (digit-char-p (char string 0)))
t))
(values string t)
(values nil nil)))))
;;; Expression generators
;;;
;;; `js-expr' and the following auxiliary functions are the
;;; responsible for generating Javascript expression.
(defun js-identifier (string-designator)
(multiple-value-bind (string valid)
(valid-js-identifier string-designator)
(unless valid
(error "~S is not a valid Javascript identifier." string-designator))
(js-format "~a" string)))
(defun js-primary-expr (form)
(cond
((numberp form)
(if (<= 0 form)
(js-format "~a" form)
(js-expr `(- ,(abs form)))))
((stringp form)
(js-format "~a" (js-escape-string form)))
((symbolp form)
(case form
(true (js-format "true"))
(false (js-format "false"))
(null (js-format "null"))
(this (js-format "this"))
(undefined (js-format "undefined"))
(otherwise
(js-identifier form))))
(t
(error "Unknown Javascript syntax ~S." form))))
(defun js-vector-initializer (vector)
(let ((size (length vector)))
(js-format "[")
(dotimes (i (1- size))
(let ((elt (aref vector i)))
(unless (eq elt 'null)
(js-expr elt))
(js-format ",")))
(when (plusp size)
(js-expr (aref vector (1- size))))
(js-format "]")))
(defun js-object-initializer (plist &optional wrap-p)
(when wrap-p
(js-format "("))
(js-format "{")
(do* ((tail plist (cddr tail)))
((null tail))
(let ((key (car tail))
(value (cadr tail)))
(multiple-value-bind (identifier identifier-p) (valid-js-identifier key)
(declare (ignore identifier))
(if identifier-p
(js-identifier key)
(js-expr (string key))))
(js-format ": ")
(js-expr value)
(unless (null (cddr tail))
(js-format ","))))
(js-format "}")
(when wrap-p
(js-format ")")))
(defun js-function (name arguments &rest body)
(js-format "function")
(when name
(js-format " ")
(js-identifier name))
(js-format "(")
(when arguments
(js-identifier (car arguments))
(dolist (arg (cdr arguments))
(js-format ",")
(js-identifier arg)))
(js-format ")")
(js-stmt `(group ,@body) t))
(defun check-lvalue (x)
(unless (or (symbolp x)
(nth-value 1 (valid-js-identifier x))
(and (consp x)
(member (car x) '(get = property))))
(error "Bad Javascript lvalue ~S" x)))
;;; Process the Javascript AST to reduce some syntax sugar.
(defun js-expand-expr (form)
(flet ((reduce-expr (op &key from-end)
(reduce (lambda (x y) `(,op ,x ,y))
(mapcar #'js-expand-expr (cdr form))
:from-end from-end)))
(if (consp form)
(case (car form)
(+
(case (length (cdr form))
(1 `(unary+ ,(cadr form)))
(t (reduce-expr '+))))
(-
(case (length (cdr form))
(1 `(unary- ,(cadr form)))
(t (reduce-expr '-))))
(*
(case (length (cdr form))
(0 1)
(t (reduce-expr '*))))
((and or)
(reduce-expr (car form)))
((progn comma)
(reduce-expr 'comma :from-end t))
(t
(js-macroexpand form)))
form)))
;;; It is the more complicated function of the generator. It takes a
;;; operator expression and generate Javascript for it. It will
;;; consider associativity and precedence in order not to generate
;;; unnecessary parenthesis.
(defun js-operator-expression (op args precedence associativity operand-order)
(let ((op1 (car args))
(op2 (cadr args)))
(case op
;; Accessors
(property
(js-expr (car args) 20)
(js-format "[")
(js-expr (cadr args))
(js-format "]"))
(get
(multiple-value-bind (accessor accessorp)
(valid-js-identifier (cadr args))
(unless accessorp
(error "Invalid accessor ~S" (cadr args)))
(js-expr (car args) 20)
(js-format ".")
(js-identifier accessor)))
;; Function call
(call
(js-expr (car args) 20)
(js-format "(")
(when (cdr args)
(js-expr (cadr args) no-comma)
(dolist (operand (cddr args))
(js-format ",")
(js-expr operand no-comma)))
(js-format ")"))
;; Object syntax
(object
(js-object-initializer args))
;; Function expressions
(function
(js-format "(")
(apply #'js-function nil args)
(js-format ")"))
(named-function
(js-format "(")
(apply #'js-function args)
(js-format ")"))
(t
(labels ((low-precedence-p (op-precedence)
(cond
((> precedence op-precedence))
((< precedence op-precedence) nil)
(t (not (eq operand-order associativity)))))
(%unary-op (operator string operator-precedence operator-associativity post lvalue)
(when (eq op operator)
(when lvalue (check-lvalue op1))
(when (low-precedence-p operator-precedence) (js-format "("))
(cond
(post
(js-expr op1 operator-precedence operator-associativity 'left)
(js-format "~a" string))
(t
(js-format "~a" string)
(js-expr op1 operator-precedence operator-associativity 'right)))
(when (low-precedence-p operator-precedence) (js-format ")"))
(return-from js-operator-expression)))
(%binary-op (operator string operator-precedence operator-associativity lvalue)
(when (eq op operator)
(when lvalue (check-lvalue op1))
(when (low-precedence-p operator-precedence) (js-format "("))
(js-expr op1 operator-precedence operator-associativity 'left)
(js-format "~a" string)
(js-expr op2 operator-precedence operator-associativity 'right)
(when (low-precedence-p operator-precedence) (js-format ")"))
(return-from js-operator-expression))))
(macrolet ((unary-op (operator string precedence associativity &key post lvalue)
`(%unary-op ',operator ',string ',precedence ',associativity ',post ',lvalue))
(binary-op (operator string precedence associativity &key lvalue)
`(%binary-op ',operator ',string ',precedence ',associativity ',lvalue)))
;; Extracted from:
;; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
(unary-op new "new " 20 right)
(unary-op pre++ "++" 18 right :lvalue t)
(unary-op pre-- "--" 18 right :lvalue t)
(unary-op post++ "++" 18 right :lvalue t :post t)
(unary-op post-- "--" 18 right :lvalue t :post t)
;; Note that the leading space is necessary because it
;; could break with post++, for example. TODO: Avoid
;; leading space when it's possible.
(unary-op not "!" 17 right)
(unary-op bit-not "~" 17 right)
(unary-op ~ "~" 17 right)
(unary-op unary+ " +" 17 right)
(unary-op unary- " -" 17 right)
(unary-op delete "delete " 17 right)
(unary-op void "void " 17 right)
(unary-op typeof "typeof " 17 right)
(binary-op * "*" 15 left)
(binary-op / "/" 15 left)
(binary-op mod "%" 15 left)
(binary-op % "%" 15 left)
(binary-op + "+" 14 left)
(binary-op - "-" 14 left)
(binary-op << "<<" 13 left)
(binary-op >> ">>" 13 left)
(binary-op >>> ">>>" 13 left)
(binary-op <= "<=" 12 left)
(binary-op < "<" 12 left)
(binary-op > ">" 12 left)
(binary-op >= ">=" 12 left)
(binary-op instanceof " instanceof " 12 left)
(binary-op in " in " 12 left)
(binary-op == "==" 11 left)
(binary-op != "!=" 11 left)
(binary-op === "===" 11 left)
(binary-op !== "!==" 11 left)
(binary-op bit-and "&" 10 left)
(binary-op & "&" 10 left)
(binary-op bit-xor "^" 9 left)
(binary-op ^ "^" 9 left)
(binary-op bit-or "|" 8 left)
(binary-op and "&&" 7 left)
(binary-op or "||" 6 left)
(when (member op '(? if))
(when (low-precedence-p 4) (js-format "("))
(js-expr (first args) 4 'right 'left)
(js-format "?")
(js-expr (second args) 4 'right 'right)
(js-format ":")
(js-expr (third args) 4 'right 'right)
(when (low-precedence-p 4) (js-format ")"))
(return-from js-operator-expression))
(binary-op = "=" 3 right :lvalue t)
(binary-op += "+=" 3 right :lvalue t)
(binary-op incf "+=" 3 right :lvalue t)
(binary-op -= "-=" 3 right :lvalue t)
(binary-op decf "-=" 3 right :lvalue t)
(binary-op *= "*=" 3 right :lvalue t)
(binary-op /= "*=" 3 right :lvalue t)
(binary-op bit-xor= "^=" 3 right :lvalue t)
(binary-op bit-and= "&=" 3 right :lvalue t)
(binary-op bit-or= "|=" 3 right :lvalue t)
(binary-op <<= "<<=" 3 right :lvalue t)
(binary-op >>= ">>=" 3 right :lvalue t)
(binary-op >>>= ">>>=" 3 right :lvalue t)
(binary-op comma "," 1 right)
(binary-op progn "," 1 right)
(error "Unknown operator `~S'" op)))))))
(defun js-expr (form &optional (precedence 0) associativity operand-order)
(let ((form (js-expand-expr form)))
(cond
((or (symbolp form) (numberp form) (stringp form))
(js-primary-expr form))
((vectorp form)
(js-vector-initializer form))
(t
(js-operator-expression (car form) (cdr form) precedence associativity operand-order)))))
;;; Statements generators
;;;
;;; `js-stmt' generates code for Javascript statements. A form is
;;; provided to label statements. Remember that in particular,
;;; expressions can be used as statements (semicolon suffixed).
;;;
(defun js-expand-stmt (form)
(cond
((and (consp form) (eq (car form) 'progn))
(destructuring-bind (&body body) (cdr form)
(cond
((null body)
nil)
((null (cdr body))
(js-expand-stmt (car body)))
(t
`(group ,@(cdr form))))))
(t
(js-macroexpand form))))
(defun js-end-stmt ()
(js-format ";")
(when *js-pretty-print*
(js-format "~%")))
(defun js-stmt (form &optional parent)
(let ((form (js-expand-stmt form)))
(flet ((js-stmt (x) (js-stmt x form)))
(cond
((null form)
(unless (or (and (consp parent) (eq (car parent) 'group))
(null parent))
(js-end-stmt)))
((atom form)
(progn
(js-expr form)
(js-end-stmt)))
(t
(case (car form)
(label
(destructuring-bind (label &body body) (cdr form)
(js-identifier label)
(js-format ":")
(js-stmt `(progn ,@body))))
(break
(destructuring-bind (&optional label) (cdr form)
(js-format "break")
(when label
(js-format " ")
(js-identifier label))
(js-end-stmt)))
(return
(destructuring-bind (value) (cdr form)
(js-format "return ")
(js-expr value)
(js-end-stmt)))
(var
(flet ((js-var (spec)
(destructuring-bind (variable &optional initial)
(ensure-list spec)
(js-identifier variable)
(when initial
(js-format "=")
(js-expr initial no-comma)))))
(destructuring-bind (var &rest vars) (cdr form)
(js-format "var ")
(js-var var)
(dolist (var vars)
(js-format ",")
(js-var var))
(js-end-stmt))))
(if
(destructuring-bind (condition true &optional false) (cdr form)
(js-format "if (")
(js-expr condition)
(js-format ") ")
(js-stmt true)
(when false
(js-format " else ")
(js-stmt false))))
(group
(let ((in-group-p
(or (null parent)
(and (consp parent) (eq (car parent) 'group)))))
(unless in-group-p (js-format "{"))
(mapc #'js-stmt (cdr form))
(unless in-group-p (js-format "}"))))
(while
(destructuring-bind (condition &body body) (cdr form)
(js-format "while (")
(js-expr condition)
(js-format ")")
(js-stmt `(progn ,@body))))
(switch
(destructuring-bind (value &rest cases) (cdr form)
(js-format "switch(")
(js-expr value)
(js-format "){")
(dolist (case cases)
(cond
((and (consp case) (eq (car case) 'case))
(js-format "case ")
(let ((value (cadr case)))
(unless (or (stringp value) (integerp value))
(error "Non-constant switch case `~S'." value))
(js-expr value))
(js-format ":"))
((eq case 'default)
(js-format "default:"))
(t
(js-stmt case))))
(js-format "}")))
(for
(destructuring-bind ((start condition step) &body body) (cdr form)
(js-format "for (")
(js-expr start)
(js-format ";")
(js-expr condition)
(js-format ";")
(js-expr step)
(js-format ")")
(js-stmt `(progn ,@body))))
(for-in
(destructuring-bind ((x object) &body body) (cdr form)
(js-format "for (")
(js-identifier x)
(js-format " in ")
(js-expr object)
(js-format ")")
(js-stmt `(progn ,@body))))
(try
(destructuring-bind (&rest body) (cdr form)
(js-format "try")
(js-stmt `(group ,@body))))
(catch
(destructuring-bind ((var) &rest body) (cdr form)
(js-format "catch (")
(js-identifier var)
(js-format ")")
(js-stmt `(group ,@body))))
(finally
(destructuring-bind (&rest body) (cdr form)
(js-format "finally")
(js-stmt `(group ,@body))))
(throw
(destructuring-bind (object) (cdr form)
(js-format "throw ")
(js-expr object)
(js-end-stmt)))
(object
;; wrap ourselves within a pair of parens, in case JS EVAL
;; interprets us as a block of code
(js-object-initializer (cdr form) t)
(js-end-stmt))
(t
(js-expr form)
(js-end-stmt))))))))
;;; It is intended to be the entry point to the code generator.
(defun js (&rest stmts)
(mapc #'js-stmt stmts)
nil)
| 21,851 | Common Lisp | .lisp | 529 | 30.538752 | 109 | 0.493346 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | e31886572abc8b39d37a459d5ca25cedf570414b543ed1f5131d28eb6ece2c6a | 49 | [
-1
] |
50 | node.lisp | jscl-project_jscl/node/node.lisp | ;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading repl-node/repl.lisp!")
(defvar *rl*)
(defun start-repl ()
(welcome-message)
(setq *rl* (#j:readline:createInterface #j:process:stdin #j:process:stdout))
(let ((*root* *rl*))
(#j:setPrompt (format nil "~a> " (package-name *package*)))
(#j:prompt)
(#j:on "line"
(lambda (line)
(%js-try
(progn
(handler-case
(let ((results (multiple-value-list
(eval-interactive (read-from-string line)))))
(dolist (result results)
(print result)))
(error (err)
(format t "ERROR: ")
(apply #'format t (!condition-args err))
(terpri))))
(catch (err)
(let ((message (or (oget err "message") err)))
(format t "ERROR[!]: ~a~%" message))))
;; Update prompt
(let ((*root* *rl*))
(#j:setPrompt (format nil "~a> " (package-name *package*))))
;; Continue
((oget *rl* "prompt"))))))
(defun node-init ()
(setq *standard-output*
(make-stream
:write-fn (lambda (string)
(#j:process:stdout:write string))))
(let ((args (mapcar #'js-to-lisp (vector-to-list (subseq #j:process:argv 2)))))
(cond
((null args)
(start-repl))
(t
(dolist (file args)
(load file))))))
(node-init)
| 2,131 | Common Lisp | .lisp | 54 | 30.055556 | 81 | 0.553839 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c91fdf82b6ce875fc06a8d8ccc5c7e72efc3d8f8680600fd5693860a4783f005 | 50 | [
-1
] |
51 | multiple-values.lisp | jscl-project_jscl/tests/multiple-values.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/multiple-values.lisp!")
;;; Regression for issue
;;; https://github.com/jscl-project/jscl/issues/341
;;;
;;; This is written in a block/return in an attempt to isolate the
;;; problem from the context of the `test` macro:
(defun test-progn-multiple-value ()
(block nil
(return (eq 42 (progn nil (values 42))))))
(test (test-progn-multiple-value))
;;; EOF
| 425 | Common Lisp | .lisp | 12 | 33.583333 | 66 | 0.691932 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c8a07017408617aeb16d7b3453c170820638942f9bc62237e34395dd98c7424c | 51 | [
-1
] |
52 | package.lisp | jscl-project_jscl/tests/package.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/package.lisp!")
(test (listp (list-all-packages)))
(test (not (eq (list-all-packages) (list-all-packages))))
(test (equal (multiple-value-list (do-symbols (symbol *package* (values 1 2)))) '(1 2)))
(make-package 'fubar)
(test (find-package 'fubar))
(delete-package "FUBAR")
(test (null (find-package 'fubar)))
(make-package 'fubar)
(delete-package 'fubar)
(test (null (find-package 'fubar)))
(make-package 'fubar)
(delete-package (find-package 'fubar))
(test (null (find-package 'fubar)))
(when (find-package 'foo)
(delete-package (find-package 'foo)))
(test
(let ((package (make-package 'foo :use '(cl)))
foo-symbols
cl-symbols)
(do-symbols (symbol package)
(push symbol foo-symbols))
(do-external-symbols (symbol 'cl)
(push symbol cl-symbols))
(and (not (null foo-symbols))
(equal foo-symbols cl-symbols))))
(when (find-package 'bar)
(delete-package (find-package 'bar)))
(test
(let* ((package (make-package 'bar))
(baz (intern (string 'baz) package)))
(let (symbols)
(do-all-symbols (symbol)
(push symbol symbols))
(and (member 'car symbols)
(member baz symbols)))))
(test (member 'car (find-all-symbols (string 'car))))
;;; This test is failing. I have disabled temporarily.
;;; note: Fixed ? @vkm
(test (eq (eval '(in-package #:cl-user)) (find-package '#:cl-user)))
;;; EOF
| 1,437 | Common Lisp | .lisp | 42 | 30.833333 | 88 | 0.657514 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c5d448b146950f33a8644eebbbdcf72fd08d4b4e8387abd22edfc98546264c7e | 52 | [
-1
] |
53 | eval.lisp | jscl-project_jscl/tests/eval.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/eval.lisp!")
(test (= (eval '(+ 1 2)) 3))
(test (= 42 (progn
(eval '(defun test-fun (x y)
(+ x y)))
(eval '(test-fun 40 2)))))
;;; EOF
| 246 | Common Lisp | .lisp | 8 | 23.125 | 42 | 0.429787 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | dd14a00d4a03426587ce3b06f0cda3504a1090b3620d3c0a2f0b9fe5e167c839 | 53 | [
-1
] |
54 | types.lisp | jscl-project_jscl/tests/types.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/types.lisp!")
(defparameter +atomic-test-objects+
(list (cons 1 'bit)
(cons 1.2 'float)
(cons 's 'symbol)
(cons #\c 'character)
(cons :k 'keyword)
(cons (gensym) 'symbol)
(cons (make-symbol "lower") 'symbol)
(cons (lambda nil nil) 'function)
(cons (values) 'null)
(cons (values-list nil) 'null)
(cons nil 'null)
(cons t 'boolean)
(cons (make-package 'fake-pack) 'package)
(cons (make-hash-table) 'hash-table)
(cons (defstruct atomic-test-struct) 'symbol)
(cons (make-atomic-test-struct) 'jscl::atomic-test-struct)
(cons (defclass atomic-test-class nil nil) 'standard-class)
(cons (make-instance 'atomic-test-class) 'jscl::atomic-test-class)
(cons (make-list 1) 'cons)
(cons (make-array '(1)) '(vector 1))
(cons (vector) '(vector 0))
(cons "sss" '(string 3))
(cons (make-string 2) '(string 2))
(cons (jscl::new) 'jscl::js-object)
(cons (find-class 'atomic-test-class) 'standard-class)
(cons (let nil (lambda nil nil)) 'function)))
(test
(mv-eql
(let ((real-type-of)
(idx 0)
(diff1)
(diff2)
(expected-type-of
'(BIT FLOAT SYMBOL CHARACTER
KEYWORD SYMBOL SYMBOL FUNCTION
NULL NULL NULL BOOLEAN
package hash-table SYMBOL jscl::atomic-test-struct
STANDARD-CLASS jscl::ATOMIC-TEST-class CONS (VECTOR 1)
(VECTOR 0) (STRING 3) (STRING 2) JSCL::JS-OBJECT
STANDARD-CLASS FUNCTION)))
(setq real-type-of (loop for x in +atomic-test-objects+ collect (type-of (car x))))
(setq diff0
(loop for x in +atomic-test-objects+
do (incf idx)
collect (unless (equal (type-of (car x)) (cdr x)))))
(setq idx 0
diff1
(loop for x in real-type-of
for y in expected-type-of
do (incf idx)
collect (unless (equal x y) (list idx x y)) ))
(setq idx 0
diff2
(loop for x in +atomic-test-objects+
do (incf idx)
collect (unless (typep (car x) 'atom) (list idx (cdr x)))))
(values
(list (list-length +atomic-test-objects+)
(list-length real-type-of)
(list-length expected-type-of))
(remove nil diff0)
(remove nil diff1)
(remove nil diff2)))
(26 26 26)
NIL
NIL
((14 HASH-TABLE)
(16 jscl::atomic-test-struct)
(17 STANDARD-CLASS)
(18 jscl::ATOMIC-TEST-CLASS)
(19 CONS)
(25 STANDARD-CLASS))))
(test
(mv-eql
(let ((universum (list 0 1 1.1 1. 0.0 1.
0.01
#xabcd #x123 #o123 #b00101
(expt 2 32) (expt 2 32) (expt 2 15) (expt 2 52)))
(type-spec '(bit bit float integer integer integer
float
integer integer integer integer
bignum fixnum fixnum bignum)))
(values
(every #'identity (loop for x in universum collect (typep x 'atom)))
(loop for x in universum collect (type-of x))
(loop for x in universum
for type in type-spec collect (typep x type))))
T
(BIT BIT FLOAT BIT BIT BIT FLOAT INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER INTEGER)
(T T T T T T T T T T T NIL T T NIL) ))
(test
(mv-eql
(let ((universum (list "string"
(make-string 10) (concat (make-string 10) "aaaa" 1 "")
(string 1) (string 'symbol)
(symbol-name 'jjjj)))
(type-spec '(string
string string
string string
string))
(deftype-spec '((STRING 6) (STRING 10) (STRING 15) (STRING 1)
(STRING 6) (STRING 4)))
(fail-deftype-spec '((STRING 5) (STRING 11) (STRING 16) (STRING 2)
(STRING 5) (STRING 3)))
;; incorrect vector type length
(type-as-vector-0 '((vector t 5) (vector t 11) (vector t 16) (vector t 2)
(vector t 5) (vector t 3)))
;; true vector type-spec
(type-as-vector-1 '((vector character 6) (vector character 10)
(vector character 15) (vector character 1)
(vector character 6) (vector character 4)))
;; only 4 correct, other - incorrect array type-spec - wrong range
(type-as-array-0 '((array character 6) (array character 10) (array character 15)
(array character 1) (array character 6) (array character 4)))
;; correct array type-spec - correct range
(type-as-array-1 '((array character 1) (array character 1) (array character 1)
(array character 1) (array character 1) (array character 1)))
;; correct as array spec
(type-as-array-2 '((and (array character *) (array character 1) (array character (6)))
(and (array character *) (array character 1) (array character (10)))
(and (array character *) (array character 1) (array character (15)))
(and (array character 1) (array character (1)))
(or (array character 6) (array character (6)))
(array character (4))))
;; only 4 elt correct
(type-as-array-3 '((array t 6) (array t 10) (array t 15)
(array character 1) (array * 6) (array * *)))
;; first two, last two -correct spec
(type-as-array-4 '((array) (array character) (array t)
(array * *) (string *) (string)))
;; corrected spec
(type-as-array-5 '((and array (array character 1) string vector (or string (vector character 6)))
(and array vector string (vector character 10) (string 10))
(array)
(vector)
(string)
(and (or array vector (string 9))
(or (array character 1) (vector character 2) string)))))
(values
(every #'identity (loop for x in universum collect (typep x 'atom)))
(list 'type-of (loop for x in universum collect (type-of x)))
(list 'type-spec (loop for x in universum
for type in type-spec collect (typep x type)))
(list 'deftype (loop for x in universum
for type in deftype-spec collect (typep x type)))
(list 'string* (loop for x in universum collect (typep x '(string *))))
(list 'fail-deftype (loop for x in universum
for type in fail-deftype-spec collect (not (typep x type))))
(list 'vector-0 (loop for x in universum
for type in type-as-vector-0 collect (typep x type)))
(list 'vector-1 (loop for x in universum
for type in type-as-vector-1 collect (typep x type)))
(list 'array-0 (loop for x in universum
for type in type-as-array-0 collect (typep x type)))
(list 'array-1 (loop for x in universum
for type in type-as-array-1 collect (typep x type)))
(list 'array-2 (loop for x in universum
for type in type-as-array-2 collect (typep x type)))
(list 'array-3 (loop for x in universum
for type in type-as-array-3 collect (typep x type)))
(list 'array-4 (loop for x in universum
for type in type-as-array-4 collect (typep x type)))
(list 'array-5 (loop for x in universum
for type in type-as-array-5 collect (typep x type)))
(list (typep "abc" '(or (vector) (array)))
(typep "abc" '(and (vector) (array) (string)))
(typep "abc" '(and (vector character) (array character) (string *)))
(typep "abc" '(or (vector t *) (array character *)))
(typep "abc" '(and (vector) (array character *) )))))
T
(TYPE-OF ((STRING 6) (STRING 10) (STRING 15) (STRING 1) (STRING 6) (STRING 4)))
(TYPE-SPEC (T T T T T T))
(DEFTYPE (T T T T T T))
(STRING* (T T T T T T))
(FAIL-DEFTYPE (T T T T T T))
(VECTOR-0 (NIL NIL NIL NIL NIL NIL))
(VECTOR-1 (T T T T T T))
(ARRAY-0 (NIL NIL NIL T NIL NIL))
(ARRAY-1 (T T T T T T))
(ARRAY-2 (T T T T T T))
(ARRAY-3 (NIL NIL NIL T NIL NIL))
(ARRAY-4 (T T NIL NIL T T))
(ARRAY-5 (T T T T T T))
(T T T T T) ))
(test
(equal '(t (nil t t nil nil) (nil t t nil nil))
(let* ((sym (INTERN (symbol-name (gensym))))
(form `(let ((a 1))
(deftype ,sym (&optional (x a))
`(integer 0 ,x)))))
(list
(eql (eval form) sym)
(let ((a 2))
(loop for i from -1 to 3 collect (typep i `(,sym 1))))
(let ((a 2))
(loop for i from -1 to 3 collect (typep i sym)))))))
(test
(equal '(t 1)
(let ((i 0))
(list
(typep (incf i) '(and (integer 0 10) (integer -5 6)))
i))))
(test (typep 'a '(eql a)))
(test (typep 'a '(and (eql a))))
(test (typep 'a '(or (eql a))))
(typep 'a '(eql b))
(test (not (typep 'a '(and (eql b)))))
(test (not (typep 'a '(or (eql b)))))
(test (typep 'a '(satisfies symbolp)))
(test (not (typep 10 '(satisfies symbolp))))
(test (not (typep 'a '(and symbol integer))))
(test (typep 'a '(or symbol integer)))
(test (typep 'a '(or integer symbol)))
(test
(mv-eql
(let* ((sym (*gensym*))
(pkg (make-package sym)))
(values
(type-of pkg)
(typep pkg 'package)
(typecase pkg (package :good))))
package t :good))
(test
(mv-eql
(let ((ht (make-hash-table)))
(values
(type-of ht)
(typep ht 'hash-table)
(typecase ht (hash-table :good))))
hash-table t :good))
(test
(typep (cons #(1) 0.1)
'(or (cons (or fixnum vector (member a "b")))
(cons (or (and (not vector) array) (and (not integer) number))
number))))
(test
(let ((class (find-class 'symbol)))
(typep 'a class)))
(test
(let ((class (find-class 'symbol)))
(typep 'a `(and ,class))))
(test
(not
(let ((class (find-class 'symbol)))
(typep 10 class))))
(test
(not
(let ((class (find-class 'symbol)))
(typep 10 `(and ,class)))))
(test
(not
(typep 'a '(and symbol integer))))
(test (typep 'a '(or symbol integer)))
(test
(let ((c1 (find-class 'number))
(c2 (find-class 'symbol)))
(typep 'a `(or ,c1 ,c2))))
(test
(let ((c1 (find-class 'number))
(c2 (find-class 'symbol)))
(typep 'a `(or ,c2 ,c1))))
(test
(mv-eql
(let* ((sym (*gensym*))
(form `(deftype ,sym (&rest args) (if args `(member ,@args) nil))))
(values
(eqlt (eval form) sym)
(not* (typep 'a `(,sym a)))
(not* (typep 'b `(,sym a)))
(not* (typep '* `(,sym a)))
(not* (typep 'a `(,sym a b)))
(not* (typep 'b `(,sym a b)))
(not* (typep 'c `(,sym a b)))))
T T NIL NIL T T NIL)
)
(test
(mv-eql
(let* ((sym (*gensym*))
(form `(let ((a 1))
(deftype ,sym (&optional (x a))
`(integer 0 ,x)))))
(values
(eqlt (eval form) sym)
(let ((a 2))
(loop for i from -1 to 3 collect (typep i `(,sym 1))))
(let ((a 2))
(loop for i from -1 to 3 collect (typep i sym)))))
t
(nil t t nil nil)
(nil t t nil nil))
)
;;; how use return-form for deftype
(test
(mv-eql
(let* ((sym (*gensym*))
(form `(deftype ,sym () (block ,sym (return-from ,sym 'integer)))))
(values
(eqlt (eval form) sym)
(typep 123 sym)
(typep 'symbol sym)))
t t nil)
)
;;; compound tests
;;; compound numeric
(test
(mv-eql
(let* ((sym (*gensym*))
(form `(deftype ,sym ()
`(or (cons) (integer -1 1) (float -1.1 1.9)))))
(values
(eqlt (eval form) sym)
(typep 1 sym)
(typep 0 sym)
(typep -1 sym)
(typep (cons 1 2) sym)
(typep -1.00000001 sym)
(typep 0.99 sym)
(typep -2.99 sym)))
T T T T T T T NIL))
;;; string
(test
(mv-eql
(values
(typep #(1 2 3) '(array t 1))
(typep #(1 2 3) '(array t 2))
(typep #(1 2 3) '(array t (3)))
(typep #(1 2 3) '(array t (4)))
(typep "123" '(array character 1))
(typep "123" '(array character 2))
(typep "123" '(array character (3)))
(typep "123" '(or (array character (2)) (array character (4))))
(typep "123" '(string 3))
(typep "123" '(or (string 1) (string 2) (string 4)))
(typep "123" '(string *)))
T NIL T NIL T NIL T NIL T NIL T))
;;; defstruct with (:type list)
#+nil (defstruct (struct-bus :named (:type list)) type signal r1 r2 r3)
#+nil (deftype bus-alarm ()
`(cons (eql struct-bus)
(cons (eql alarm)
(cons (or (integer 0 22)
(member sigint trap segmentation)) *) )))
;;; structure as cons
#+nil (test
(mv-eql
(values
(typep (make-struct-bus :type 'alarm :signal 12) 'bus-alarm)
(typep (make-struct-bus :type 'alarm :signal 'trap) '(bus-alarm))
(typep (make-struct-bus :type 'alarm :signal 'trap-21) 'bus-alarm)
(typecase (make-struct-bus :type 'alarm :signal 12) (bus-alarm :good) (t :bad))
(typecase (make-struct-bus :type 'alarm :signal 32) ((bus-alarm) :good) (t :bad)))
t t nil :good :bad))
;;; array
(test
(mv-eql
(values
(typep (make-array '(1 2)) '(and (array t 2) (array t (2))))
(typep (make-array '(10)) '(and (array t 1) (array t (10))))
(typep (make-array '(1 2)) '(and (array t 2) (array t (1 *))))
)
nil t t))
;;; vector
(test
(mv-eql
(values
(typep #(1 2 3) '(vector t 3))
(typep #(1 2 3) '(array t 1))
(typep #(1 2 3) '(array t (3))))
t t t))
;;; list-length
(test
(mv-eql
(let* ((sym (*gensym*))
(form `(deftype ,sym ()
`(or (list-length 0) (list-length 1)))))
(values
(eqlt (eval form) sym)
(typep (list) `(,sym))
(typep (list 1) `(,sym))
(typep (list 1 2 3) `(,sym))))
t t t nil))
(deftype standard-char ()
'(member
#\Space #\Newline
#\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
#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\0
#\! #\$ #\" #\' #\( #\) #\, #\_ #\- #\. #\/ #\: #\;
#\? #\+ #\< #\= #\> #\# #\% #\& #\* #\@ #\[ #\\ #\]
#\{ #\| #\} #\` #\^ #\~))
;;; typep member
(test
(mv-eql
(values
(typep #\newline '(standard-char))
(typep #\1 '(standard-char))
(typep #\space 'standard-char))
t t t))
;;; type-of
(test
(let* ((universum (list 1 'symbol 1.2 #() (make-array '(1 1)) "string" (list) (list 0) t nil)))
(every #'identity
(mapcar (lambda (x y) (equal x y))
'(BIT SYMBOL FLOAT (VECTOR 0) (ARRAY (1 1)) (STRING 6) NULL CONS BOOLEAN NULL)
(loop for i in universum collect (type-of i))))))
(test
(mv-eql
(let* ((sym (*gensym*))
(class (eval `(defclass ,sym nil nil)))
(standard-class (type-of class)))
(values
(typep (make-instance class) (type-of (make-instance class)))
(typep (make-instance sym) sym)
(typep class standard-class)))
t t t))
;;; typecase test cases
(test (eql 'a (typecase 1 (integer 'a) (t 'b))))
(test (not (typecase 1 (symbol 'a))))
(test (eql 'b (typecase 1 (symbol 'a) (t 'b))))
(test (null (typecase 1 (t (values)))))
(test (null (typecase 1 (integer (values)) (t 'a))))
;;; predefined type bit
(test (eql 'a (typecase 1 (bit 'a) (integer 'b))))
;;; test (boolean)
(deftype boolean () `(member t nil))
(test
(mv-eql
(values
(typecase t ((member t nil) :boolean) (t :bad))
(typecase nil ((member t nil) :boolean) (t :bad))
(typecase t (boolean :boolean) (otherwise :bad))
(typecase nil ((boolean) :boolean) (otherwise :bad)))
:boolean :boolean :boolean :boolean))
(test (eql 'a (typecase 1 (otherwise 'a))))
(test (equal '(a b c) (typecase 1 (t (list 'a 'b 'c)))))
(test (equal '(a b c) (typecase 1 (integer (list 'a 'b 'c)) (t nil))))
(test
(equal '(a 1)
(let ((x 0))
(list
(typecase 1
(bit (incf x) 'a)
(integer (incf x 2) 'b)
(t (incf x 4) 'c))
x))))
;;; bug:
;;;(test (null (typecase 1 (integer) (t 'a))))
(test (null (typecase 1 (symbol 'a) (t))))
(test (null (typecase 1 (symbol 'a) (otherwise))))
;;; bug: Sharp-reader is buggy
;;; fixme:
;;;(typecase 'a
;;; (number 'bad)
;;; (#.(find-class 'symbol nil) 'good))
;;; good)
(test
(eql 'good
(block done
(tagbody
(typecase 'a (symbol (go 10)
10
(return-from done 'bad)))
10
(return-from done 'good)))))
(test
(eql 'good
(block done
(tagbody
(typecase 'a
(integer 'bad)
(t (go 10)
10
(return-from done 'bad)))
10
(return-from done 'good)))))
(test
(equal
(loop for x in '(a 1 1.4 "c")
collect (typecase x
(t :good)
(otherwise :bad)))
'(:good :good :good :good)))
(test
(eql :good
(macrolet
((%m (z) z))
(typecase (%m 2)
((integer 0 1) :bad1)
((integer 2 10) :good)
(t :bad2)))))
(test
(eql :good
(macrolet
((%m (z) z))
(typecase 2
((integer 0 1) (%m :bad1))
((integer 2 10) (%m :good))
(t (%m :bad2))))))
#+nil
(test
(let ((cells (list 1 2021 3.33 t #\c "abc" #(1))))
(typep cells '(cons (eql 1)
(cons (integer 2019 2022)
(cons (float -1.00000000001 3.4)
(cons (member t nil) *)))))))
#+nil
(test
(let ((cells (list 1 2021 3.33 t #\c "abc" #(1))))
(typep cells '(cons (eql 1)
(cons (integer 2019 2022)
(cons (float -1.00000000001 3.4)
(cons (member t nil)
(cons character
(cons array (cons vector))
))))))) )
(test
(typep (cons 1 (list 1))
'(cons (or (eql 1) (eql 2))
(or (list-length 0) (list-length 1)))))
;;; EOF
| 18,959 | Common Lisp | .lisp | 525 | 28.001905 | 106 | 0.509172 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 04648afc7d3e4ee0319b98fa9b4442750284487d8bacc52376c089e91d6066c2 | 54 | [
-1
] |
55 | seq.lisp | jscl-project_jscl/tests/seq.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/seq.lisp!")
;;; Functions used as :KEY argument in tests
(defvar halve (lambda (x) (/ x 2)))
(defvar double (lambda (x) (* x 2)))
;;; COUNT
(test (= (count #\a "how many A's are there in here?") 2))
(test (= (count #\a "how many A's are there in here?" :start 10) 1))
(test (= (count 'a '(a b c d e a e f)) 2))
(test (= (count 1 '(1 2 2 3 2 1 2 2 5 4) :key #'1-) 5))
(test (= (count #\1 "11111011" :start 2 :end 7) 4))
(test (= (count #\1 "11111011" :start 2 :end 7 :from-end t) 4))
;;; COUNT-IF, COUNT-IF-NOT
(test (= (count-if #'upper-case-p "The Crying of Lot 49" :start 4) 2))
(test (= (count-if #'not '(a b nil c d nil e)) 2))
(test (= (count-if #'evenp '(1 2 3 4 4 1 8 10 1) :key #'1+) 4))
(test (= (count-if #'evenp '(1 2 3 4 4 1 8 10 1) :key #'1+ :from-end t) 4))
(test (= (count-if-not #'oddp '((1) (2) (3) (4)) :key #'car) 2))
(test (= (count-if-not #'oddp '((1) (2) (3) (4)) :key #'car :from-end t) 2))
(test (= (count-if-not #'not '(a b nil c d nil e)) 5))
(test (= (count-if-not #'oddp '(1 2 3 4 4 1 8 10 1) :key #'1+) 4))
;;; FIND
(test (find 1 #(2 1 3)))
(test (find 1 '(2 1 3)))
(test (not (find 1 #(2 2 2))))
(test (not (find 1 '(2 2 2))))
(test (not (find 1 #(1 1 1) :test-not #'=)))
(test (not (find 1 '(1 1 1) :test-not #'=)))
(test (not (find 1 #(1 2 3) :key double)))
(test (not (find 1 '(1 2 3) :key double)))
;;; REMOVE
(test (not (find 1 (remove 1 #(1 2 3 1)))))
(test (not (find 1 (remove 1 '(1 2 3 1)))))
(test (not (find 2 (remove 1 #(1 2 3 1) :key halve))))
(test (not (find 2 (remove 1 '(1 2 3 1) :key halve))))
;;; TODO: Rewrite this test when EQUALP exists and works on vectors
(test (equal (length (remove '(1 2) #((1 2) (1 2)) :test #'equal)) 0))
(test (null (remove '(1 2) '((1 2) (1 2)) :test #'equal)))
(test (find 2 (remove 2 #(1 2 3) :test-not #'=)))
(test (find 2 (remove 2 '(1 2 3) :test-not #'=)))
;;; SUBSTITUTE
(test (equal (substitute #\_ #\- "Hello-World") "Hello_World"))
(test (equal (substitute 4 5 '(1 2 3 4)) '(1 2 3 4)))
(test (equal (substitute 99 3 '(1 2 3 4)) '(1 2 99 4)))
(test (equal (substitute 99 3 '(1 2 3 4) :test #'<=) '(1 2 99 99)))
;;; This test fails expectely as you can't compare vectors with equal.
#+nil
(test (equal (substitute 99 3 #(1 2 3 4) :test #'<=) #(1 2 99 99)))
;;; POSITION
(test (= (position 1 #(1 2 3)) 0))
(test (= (position 1 '(1 2 3)) 0))
(test (= (position 1 #(1 2 3 1)) 0))
(test (= (position 1 '(1 2 3 1)) 0))
(test (not (position 1 #(2 3 4))))
(test (not (position 1 '(2 3 4))))
(test (= (position 1 '(1 2 3) :key halve) 1))
(test (= (position 1 #(1 2 3) :key halve) 1))
(test (= (position '(1 2) '((1 2) (3 4)) :test #'equal) 0))
(test (= (position '(1 2) #((1 2) (3 4)) :test #'equal) 0))
(test (= (position 1 #(1 1 3) :test-not #'=) 2))
(test (= (position 1 '(1 1 3) :test-not #'=) 2))
(test (= (position 1 '(1 1 3) :from-end nil) 0))
(test (= (position 1 '(1 1 3) :from-end t) 1))
(test (= (position #\a "baobab" :from-end t) 4))
;;; POSITION-IF, POSITION-IF-NOT
(test (= 2 (position-if #'oddp '((1) (2) (3) (4)) :start 1 :key #'car)))
(test (= 4 (position-if-not #'integerp '(1 2 3 4 X)))) ;; (hyperspec example used "5.0", but we don't have a full numeric tower yet!)
(test (= 4 (position-if #'oddp '((1) (2) (3) (4) (5)) :start 1 :key #'car :from-end t)))
(test (= 4 (position-if-not #'integerp '(1 2 3 4 X Y)))) ;; (hyperspec example used "5.0", but we don't have a full numeric tower yet!)
(test (= 5 (position-if-not #'integerp '(1 2 3 4 X Y) :from-end t)))
;;; REMOVE-IF
(test (equal (remove-if #'zerop '(1 0 2 0 3)) '(1 2 3)))
(test (equal (remove-if-not #'zerop '(1 0 2 0 3)) '(0 0)))
;;; TODO: Rewrite these tests when EQUALP exists and works on vectors
(let ((v1 (remove-if #'zerop #(1 0 2 0 3))))
(test (and (= (aref v1 0) 1) (= (aref v1 1) 2) (= (aref v1 2) 3))))
(test (every #'zerop (remove-if-not #'zerop #(1 0 2 0 3))))
;;; SUBSEQ
(let ((nums '(1 2 3 4 5)))
(test (equal (subseq nums 3) '(4 5)))
(test (equal (subseq nums 2 4) '(3 4)))
;; Test that nums hasn't been altered: SUBSEQ should construct fresh lists
(test (equal nums '(1 2 3 4 5))))
;;; REVERSE
(test (eq (reverse nil) nil))
(test (equal (reverse '(a b c)) '(c b a)))
;;; FIXME: When replace the following two cases when implemented.
(test (zerop (length (reverse #()))))
;;; (test (equalp (reverse #(a b c)) #(c b a)))
(let ((xs (reverse #(a b c)))
(pattern #(c b a)))
(test (equal (aref xs 0) (aref pattern 0)))
(test (equal (aref xs 1) (aref pattern 1)))
(test (equal (aref xs 2) (aref pattern 2))))
(test (equal (reverse "") ""))
(test (equal (reverse "abc") "cba"))
;;; REDUCE
(test (equal (reduce (lambda (x y) `(+ ,x ,y))
'(1 2 3 4))
'(+ (+ (+ 1 2) 3) 4)))
(test (equal (reduce (lambda (x y) `(+ ,x ,y))
'(1 2 3 4)
:from-end t)
'(+ 1 (+ 2 (+ 3 4)))))
(test (equal (reduce #'+ nil) 0))
(test (equal (reduce #'+ '(1)) 1))
(test (equal (reduce #'+ nil :initial-value 1) 1))
(test (equal (reduce #'+ '()
:key #'1+
:initial-value 100)
100))
(test (equal (reduce #'+ '(100) :key #'1+)
101))
(test (= (reduce #'+ #(1 2 3))
6))
(test (equal '((Z . C) . D)
(reduce #'cons #(a b c d e f) :start 2 :end 4 :initial-value 'z)))
(test (equal '1
(reduce #'(lambda () (error "When reducing a sequence with one element the function should not be called"))
#(1))))
(test (equal 3 (reduce #'(lambda () (error "When reducing a sequence with one element the function should not be called"))
#(1 2 3 4) :start 2 :end 3)))
(test (equal (reduce #'cons '(1) :initial-value 0) '(0 . 1)))
;;; The following tests reduced reduce were copied from ANSI CL TESTS.
(test (equal (reduce #'cons '(a b c d e f) :start 1 :end 4 :from-end t)
'(b c . d)))
(test (equal (reduce #'cons '(a b c d e f) :start 1 :end 4 :from-end t
:initial-value nil)
'(b c d)))
;;; MISMATCH
(test (= (mismatch '(1 2 3) '(1 2 3 4 5 6)) 3))
(test (= (mismatch '(1 2 3) #(1 2 3 4 5 6)) 3))
(test (= (mismatch #(1 2 3) '(1 2 3 4 5 6)) 3))
(test (= (mismatch #(1 2 3) #(1 2 3 4 5 6)) 3))
;;; SEARCH
(test (= (search '(1 2 3) '(4 5 6 1 2 3)) 3))
(test (= (search '(1 2 3) #(4 5 6 1 2 3)) 3))
(test (= (search #(1 2 3) '(4 5 6 1 2 3)) 3))
(test (= (search #(1 2 3) #(4 5 6 1 2 3)) 3))
(test (not (search '(foo) '(1 2 3))))
(test (= (search '(1) '(4 5 6 1 2 3)) 3))
(test (= (search #(1) #(4 5 6 1 2 3)) 3))
;;; MAP
(test-equal
(map 'list #'list '())
nil)
(test-equal
(let ((v (map 'vector #'list '())))
(and (vectorp v)
(zerop (length v))))
t)
(test-equal
(map 'string #'code-char '())
"")
(test-equal
(map 'list #'list '(1 2 3))
'((1) (2) (3)))
(test-equal
(map 'list #'list #(1 2 3))
'((1) (2) (3)))
(test-equal
(map 'list #'list "123")
'((#\1) (#\2) (#\3)))
;;; CHAR-UPCASE cannot be sharp-quoted currently
(test-equal
(map 'string (lambda (c) (char-upcase c)) '(#\a #\b #\c))
"ABC")
(test-equal
(map 'string (lambda (c) (char-upcase c)) #(#\a #\b #\c))
"ABC")
(test-equal
(map 'string (lambda (c) (char-upcase c)) "abc")
"ABC")
(test-equal
(map '(vector character) (lambda (c) (char-upcase c)) '(#\a #\b #\c))
"ABC")
(test-equal
(map '(vector character) (lambda (c) (char-upcase c)) #(#\a #\b #\c))
"ABC")
(test-equal
(map '(vector character) (lambda (c) (char-upcase c)) "abc")
"ABC")
(test-equal
(let ((v (map 'vector #'list '(1 2 3))))
(and (vectorp v)
(equal '(1) (aref v 0))
(equal '(2) (aref v 1))
(equal '(3) (aref v 2))))
t)
(test-equal
(let ((v (map 'vector #'list #(1 2 3))))
(and (vectorp v)
(equal '(1) (aref v 0))
(equal '(2) (aref v 1))
(equal '(3) (aref v 2))))
t)
(test-equal
(let ((v (map 'vector #'list "123")))
(and (vectorp v)
(equal '(#\1) (aref v 0))
(equal '(#\2) (aref v 1))
(equal '(#\3) (aref v 2))))
t)
(test-equal
(let ((v (map '(vector) #'list '(1 2 3))))
(and (vectorp v)
(equal '(1) (aref v 0))
(equal '(2) (aref v 1))
(equal '(3) (aref v 2))))
t)
(test-equal
(let ((v (map '(vector) #'list #(1 2 3))))
(and (vectorp v)
(equal '(1) (aref v 0))
(equal '(2) (aref v 1))
(equal '(3) (aref v 2))))
t)
(test-equal
(let ((v (map '(vector) #'list "123")))
(and (vectorp v)
(equal '(#\1) (aref v 0))
(equal '(#\2) (aref v 1))
(equal '(#\3) (aref v 2))))
t)
(test-equal
(map 'list #'list '(a b c) #(1 2 3) "xyz")
'((a 1 #\x) (b 2 #\y) (c 3 #\z)))
(test-equal
(let* ((acc '())
(result (null (map nil (lambda (x) (push x acc)) '(1 2 3)))))
(list acc result))
'((3 2 1) t))
;;; CONCATENATE
(test-equal
(concatenate 'string "all" " " "together" " " "now")
"all together now")
(test-equal
(concatenate 'list "ABC" '(d e f) #(1 2 3) "1011")
'(#\A #\B #\C D E F 1 2 3 #\1 #\0 #\1 #\1))
(test-equal
(concatenate 'list)
nil)
(test-equal
(handler-case
(concatenate '(vector * 2) "a" "bc")
(error () :signalled))
:signalled)
;;; REMOVE-DUPLICATES
(test
(equal
(list
(equal (remove-duplicates "aBcDAbCd" :test #'char-equal :from-end t) "aBcD")
(equal (remove-duplicates '(a b c b d d e)) '(A C B D E))
(equal (remove-duplicates '(a b c b d d e) :from-end t) '(A B C D E))
(equal (remove-duplicates '((foo #\a) (bar #\%) (baz #\A))
:test #'char-equal :key #'cadr) '((BAR #\%) (BAZ #\A)))
(equal (remove-duplicates '((foo #\a) (bar #\%) (baz #\A))
:test #'char-equal :key #'cadr :from-end t) '((FOO #\a) (BAR #\%))))
(list t t t t t)))
;;; SETF with ELT
;;; TODO: Rewrite this test when EQUALP exists and works on vectors
;;; https://github.com/jscl-project/jscl/issues/479
(test (equal '(42 0 0)
(let ((vec (vector 0 0 0)))
(setf (elt vec 0) 42)
(jscl::vector-to-list vec))))
;;; EOF
| 9,996 | Common Lisp | .lisp | 267 | 34.164794 | 136 | 0.537579 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | cecb9c53e1a5a79efa94e79be0beea3fe5a6ab1bc5abf2f97511a12f45f6c82f | 55 | [
-1
] |
56 | strings.lisp | jscl-project_jscl/tests/strings.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/strings.lisp!")
(defvar *str* "hello world")
(defvar *str2* "h")
(test (stringp *str*))
(test (not (characterp *str*)))
(test (not (integerp *str*)))
(test (stringp *str2*))
(test (not (characterp *str2*)))
(test (not (integerp *str2*)))
(test (= (length "hello world") 11))
(test (arrayp "hello world"))
(test (string= "h" (string #\h)))
(test (string= "foo" "foo"))
(test (not (string= "Foo" "foo")))
(test (not (string= "foo" "foox")))
(test (= (string< "one" "two") 0))
(test (= (string< "oob" "ooc") 2))
(test (null (string< "" "")))
(test (null (string< "a" "")))
(test (= (string< "" "a") 0))
(test (= (string< "aaa" "aaaaa") 3))
;;; BUG: The compiler will macroexpand the forms below (char str N)
;;; will expand to internal SBCL code instead of our (setf char). It
;;; is because macrodefinitions during bootstrapping are not included
;;; in the host's environment. It should, but we have to think how to
;;; avoid conflicts (package renaming??)
;;; note: Fixed ?. @vkm
;; (let ((str "hello"))
;; (setf (char str 0) #\X)
;; (setf (char str 4) #\X)
;; (test (string= str "XellX")))
;; ----------------------------------------
;; The following tests in this file were derived from the file "must-string.lisp",
;; part of SACLA <http://homepage1.nifty.com/bmonkey/lisp/sacla/>.
;; The origial copyright notice appears below:
;; Copyright (C) 2002-2004, Yuji Minejima <ggb01164@nifty.ne.jp>
;; ALL RIGHTS RESERVED.
;;
;; $Id: must-string.lisp,v 1.7 2004/02/20 07:23:42 yuji Exp $
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;; JSCL: no SIMPLE-STRING-P yet, so disabled
;; (test (simple-string-p ""))
;; (test (simple-string-p "abc"))
;; (test (not (simple-string-p 'not-a-string)))
;; (test (let ((str (make-array 3 :element-type 'character :fill-pointer t)))
;; (if (not (simple-vector-p str))
;; (not (simple-string-p str))
;; (simple-string-p str))))
(test (char= (char "abc" 0) #\a))
(test (char= (char "abc" 1) #\b))
(test (char= (char "abc" 2) #\c))
;; JSCL: no SCHAR yet, so disabled
;; (test (char= (schar "abc" 0) #\a))
;; (test (char= (schar "abc" 1) #\b))
;; (test (char= (schar "abc" 2) #\c))
;; JSCL: no :FILL-POINTER yet, so disabled
;; (test (let ((str (make-array 10
;; :element-type 'character
;; :fill-pointer 3
;; :initial-contents "0123456789")))
;; (and (string= str "012")
;; (char= (char str 3) #\3)
;; (char= (char str 4) #\4)
;; (char= (char str 5) #\5)
;; (char= (char str 6) #\6)
;; (char= (char str 7) #\7)
;; (char= (char str 8) #\8)
;; (char= (char str 9) #\9)
;; (char= (vector-pop str) #\2))))
(test (string= (string "") ""))
(test (string= (string "abc") "abc"))
(test (string= (string "a") "a"))
(test (string= (string 'abc) "ABC"))
(test (string= (string 'a) "A"))
(test (string= (string #\a) "a"))
(test (string= (string-upcase "abcde") "ABCDE"))
(test (string= (string-upcase "Dr. Livingston, I presume?")
"DR. LIVINGSTON, I PRESUME?"))
(test (string= (string-upcase "Dr. Livingston, I presume?" :start 6 :end 10)
"Dr. LiVINGston, I presume?"))
(test (string= (string-upcase 'Kludgy-HASH-Search) "KLUDGY-HASH-SEARCH"))
(test (string= (string-upcase "abcde" :start 2 :end nil) "abCDE"))
(test (string= (string-downcase "Dr. Livingston, I presume?")
"dr. livingston, i presume?"))
(test (string= (string-downcase 'Kludgy-HASH-Search) "kludgy-hash-search"))
(test (string= (string-downcase "A FOOL" :start 2 :end nil) "A fool"))
(test (string= (string-capitalize "elm 13c arthur;fig don't")
"Elm 13c Arthur;Fig Don'T"))
(test (string= (string-capitalize " hello ") " Hello "))
(test (string= (string-capitalize
"occlUDeD cASEmenTs FOreSTAll iNADVertent DEFenestraTION")
"Occluded Casements Forestall Inadvertent Defenestration"))
(test (string= (string-capitalize 'kludgy-hash-search) "Kludgy-Hash-Search"))
(test (string= (string-capitalize "DON'T!") "Don'T!")) ;not "Don't!"
(test (string= (string-capitalize "pipe 13a, foo16c") "Pipe 13a, Foo16c"))
(test (string= (string-capitalize "a fool" :start 2 :end nil) "a Fool"))
(test (let ((str (copy-seq "0123ABCD890a")))
(and (string= (nstring-downcase str :start 5 :end 7) "0123AbcD890a")
(string= str "0123AbcD890a"))))
(test (let* ((str0 (copy-seq "abcde"))
(str (nstring-upcase str0)))
(and (eq str0 str)
(string= str "ABCDE"))))
(test (let* ((str0 (copy-seq "Dr. Livingston, I presume?"))
(str (nstring-upcase str0)))
(and (eq str0 str)
(string= str "DR. LIVINGSTON, I PRESUME?"))))
(test (let* ((str0 (copy-seq "Dr. Livingston, I presume?"))
(str (nstring-upcase str0 :start 6 :end 10)))
(and (eq str0 str)
(string= str "Dr. LiVINGston, I presume?"))))
(test (let* ((str0 (copy-seq "abcde"))
(str (nstring-upcase str0 :start 2 :end nil)))
(string= str "abCDE")))
(test (let* ((str0 (copy-seq "Dr. Livingston, I presume?"))
(str (nstring-downcase str0)))
(and (eq str0 str)
(string= str "dr. livingston, i presume?"))))
(test (let* ((str0 (copy-seq "ABCDE"))
(str (nstring-downcase str0 :start 2 :end nil)))
(string= str "ABcde")))
(test (let* ((str0 (copy-seq "elm 13c arthur;fig don't"))
(str (nstring-capitalize str0)))
(and (eq str0 str)
(string= str "Elm 13c Arthur;Fig Don'T"))))
(test (let* ((str0 (copy-seq " hello "))
(str (nstring-capitalize str0)))
(and (eq str0 str)
(string= str " Hello "))))
(test (let* ((str0 (copy-seq
"occlUDeD cASEmenTs FOreSTAll iNADVertent DEFenestraTION"))
(str (nstring-capitalize str0)))
(and (eq str0 str)
(string= str
"Occluded Casements Forestall Inadvertent Defenestration"))))
(test (let* ((str0 (copy-seq "DON'T!"))
(str (nstring-capitalize str0)))
(and (eq str0 str)
(string= str "Don'T!")))) ;not "Don't!"
(test (let* ((str0 (copy-seq "pipe 13a, foo16c"))
(str (nstring-capitalize str0)))
(and (eq str0 str)
(string= str "Pipe 13a, Foo16c"))))
(test (let* ((str0 (copy-seq "a fool"))
(str (nstring-capitalize str0 :start 2 :end nil)))
(string= str "a Fool")))
(test (string= (string-trim "abc" "abcaakaaakabcaaa") "kaaak"))
;; (test (string= (string-trim '(#\Space #\Tab #\Newline) " garbanzo beans
;; ") "garbanzo beans"))
(test (string= (string-trim " (*)" " ( *three (silly) words* ) ")
"three (silly) words"))
(test (string= (string-left-trim "abc" "labcabcabc") "labcabcabc"))
(test (string= (string-left-trim " (*)" " ( *three (silly) words* ) ")
"three (silly) words* ) "))
(test (string= (string-right-trim " (*)" " ( *three (silly) words* ) ")
" ( *three (silly) words"))
(test (string= (string-trim "ABC" "abc") "abc"))
(test (string= (string-trim "AABBCC" "abc") "abc"))
(test (string= (string-trim "" "abc") "abc"))
(test (string= (string-trim "ABC" "") ""))
(test (string= (string-trim "cba" "abc") ""))
(test (string= (string-trim "cba" "abccba") ""))
(test (string= (string-trim "ccbbba" "abccba") ""))
(test (string= (string-trim "cba" "abcxabc") "x"))
(test (string= (string-trim "xyz" "xxyabcxyyz") "abc"))
(test (string= (string-trim "CBA" 'abcxabc) "X"))
(test (string= (string-trim "a" #\a) ""))
(test (string= (string-left-trim "ABC" "abc") "abc"))
(test (string= (string-left-trim "" "abc") "abc"))
(test (string= (string-left-trim "ABC" "") ""))
(test (string= (string-left-trim "cba" "abc") ""))
(test (string= (string-left-trim "cba" "abccba") ""))
(test (string= (string-left-trim "cba" "abcxabc") "xabc"))
(test (string= (string-left-trim "xyz" "xxyabcxyz") "abcxyz"))
(test (string= (string-left-trim "CBA" 'abcxabc) "XABC"))
(test (string= (string-left-trim "a" #\a) ""))
(test (string= (string-right-trim "ABC" "abc") "abc"))
(test (string= (string-right-trim "" "abc") "abc"))
(test (string= (string-right-trim "ABC" "") ""))
(test (string= (string-right-trim "cba" "abc") ""))
(test (string= (string-right-trim "cba" "abccba") ""))
(test (string= (string-right-trim "cba" "abcxabc") "abcx"))
(test (string= (string-right-trim "xyz" "xxyabcxyz") "xxyabc"))
(test (string= (string-right-trim "CBA" 'abcxabc) "ABCX"))
(test (string= (string-right-trim "a" #\a) ""))
(test (string= (string "already a string") "already a string"))
(test (string= (string 'elm) "ELM"))
(test (string= (string #\c) "c"))
(test (string= "foo" "foo"))
(test (not (string= "foo" "Foo")))
(test (not (string= "foo" "bar")))
(test (string= "together" "frog" :start1 1 :end1 3 :start2 2))
(test (string-equal "foo" "Foo"))
(test (string= "abcd" "01234abcd9012" :start2 5 :end2 9))
(test (eql (string< "aaaa" "aaab") 3))
(test (eql (string>= "aaaaa" "aaaa") 4))
(test (eql (string-not-greaterp "Abcde" "abcdE") 5))
(test (eql (string-lessp "012AAAA789" "01aaab6"
:start1 3 :end1 7
:start2 2 :end2 6) 6))
(test (not (string-not-equal "AAAA" "aaaA")))
(test (string= "" ""))
;; JSCL: making an array of BASE-CHAR doesn't make a string, yet
;; (test (string= (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char)))
(test (not (string= "abc" "")))
(test (not (string= "" "abc")))
(test (not (string= "A" "a")))
(test (string= "abc" "xyz" :start1 3 :start2 3))
(test (string= "abc" "xyz" :start1 1 :end1 1 :start2 0 :end2 0))
(test (string= "axyza" "xyz" :start1 1 :end1 4))
(test (string= "axyza" "xyz" :start1 1 :end1 4 :start2 0 :end2 nil))
(test (string= "abxyz" "xyabz" :end1 2 :start2 2 :end2 4))
(test (not (string= "love" "hate")))
(test (string= 'love 'love))
(test (not (string= 'love "hate")))
(test (string= #\a #\a))
(test (not (string/= "" "")))
;; (test (not (string/= (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char))))
(test (eql (string/= "abc" "") 0))
(test (eql (string/= "" "abc") 0))
(test (eql (string/= "A" "a") 0))
(test (not (string/= "abc" "xyz" :start1 3 :start2 3)))
(test (not (string/= "abc" "xyz" :start1 1 :end1 1 :start2 0 :end2 0)))
(test (not (string/= "axyza" "xyz" :start1 1 :end1 4)))
(test (not (string/= "axyza" "xyz" :start1 1 :end1 4 :start2 0 :end2 nil)))
(test (not (string/= "abxyz" "xyabz" :end1 2 :start2 2 :end2 4)))
(test (eql (string/= "love" "hate") 0))
(test (eql (string/= "love" "loVe") 2))
(test (not (string/= "life" "death" :start1 3 :start2 1 :end2 2)))
(test (eql (string/= "abcxyz" "ABCxyZ" :start1 3 :start2 3) 5))
(test (eql (string/= "abcxyz" "ABCxyZ" :start1 3 :end1 nil :start2 3 :end2 nil) 5))
(test (eql (string/= "abcxyz" "ABCxyZ" :end1 nil :start2 3 :end2 3) 0))
(test (eql (string/= "abc" "abcxyz") 3))
(test (eql (string/= "abcxyz" "abc") 3))
(test (eql (string/= "abcxyz" "") 0))
(test (eql (string/= "AbcDef" "cdef" :start1 2) 3))
(test (eql (string/= "cdef" "AbcDef" :start2 2) 1))
(test (= (string/= 'love "hate") 0))
(test (not (string/= 'love 'love)))
(test (not (string/= #\a #\a)))
(test (= (string/= #\a #\b) 0))
(test (not (string< "" "")))
(test (not (string< "dog" "dog")))
(test (not (string< " " " ")))
(test (not (string< "abc" "")))
(test (eql (string< "" "abc") 0))
(test (eql (string< "ab" "abc") 2))
(test (not (string< "abc" "ab")))
(test (eql (string< "aaa" "aba") 1))
(test (not (string< "aba" "aaa")))
(test (not (string< "my cat food" "your dog food" :start1 6 :start2 8)))
(test (not (string< "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9)))
(test (eql (string< "xyzabc" "abcd" :start1 3) 6))
(test (eql (string< "abc" "abc" :end1 1) 1))
(test (eql (string< "xyzabc" "abc" :start1 3 :end1 5) 5))
(test (eql (string< "xyz" "abcxyzXYZ" :start2 3) 3))
(test (not (string< "abc" "abcxyz" :end2 3)))
(test (eql (string< "xyz" "abcxyz" :end1 2 :start2 3) 2))
(test (not (string< "xyzabc" "abcdef" :start1 3 :end2 3)))
(test (eql (string< "aaaa" "z") 0))
(test (eql (string< "pppTTTaTTTqqq" "pTTTxTTT" :start1 3 :start2 1) 6))
(test (eql (string< "pppTTTaTTTqqq" "pTTTxTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (not (string< (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char))))
(test (not (string< 'love 'hate)))
(test (= (string< 'peace 'war) 0))
(test (not (string< 'love 'love)))
(test (not (string< #\a #\a)))
(test (= (string< #\a #\b) 0))
(test (not (string> "" "")))
(test (not (string> "dog" "dog")))
(test (not (string> " " " ")))
(test (eql (string> "abc" "") 0))
(test (not (string> "" "abc")))
(test (not (string> "ab" "abc")))
(test (eql (string> "abc" "ab") 2))
(test (eql (string> "aba" "aaa") 1))
(test (not (string> "aaa" "aba")))
(test (not (string> "my cat food" "your dog food" :start1 6 :start2 8)))
(test (not (string> "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9)))
(test (eql (string> "xyzabcde" "abcd" :start1 3) 7))
(test (not (string> "abc" "abc" :end1 1)))
(test (eql (string> "xyzabc" "a" :start1 3 :end1 5) 4))
(test (eql (string> "xyzXYZ" "abcxyz" :start2 3) 3))
(test (eql (string> "abcxyz" "abcxyz" :end2 3) 3))
(test (not (string> "xyzXYZ" "abcxyz" :end1 2 :start2 3)))
(test (not (string> "xyzabc" "abcdef" :start1 3 :end2 3)))
(test (eql (string> "z" "aaaa") 0))
(test (eql (string> "pTTTxTTTqqq" "pppTTTaTTT" :start1 1 :start2 3) 4))
(test (eql (string> "pppTTTxTTTqqq" "pTTTaTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (not (string> (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char))))
(test (= (string> 'love 'hate) 0))
(test (not (string> 'peace 'war)))
(test (not (string> 'love 'love)))
(test (not (string> #\a #\a)))
(test (not (string> #\a #\b)))
(test (= (string> #\z #\a) 0))
(test (eql (string<= "" "") 0))
(test (eql (string<= "dog" "dog") 3))
(test (eql (string<= " " " ") 1))
(test (not (string<= "abc" "")))
(test (eql (string<= "ab" "abc") 2))
(test (eql (string<= "aaa" "aba") 1))
(test (not (string<= "aba" "aaa")))
(test (eql (string<= "my cat food" "your dog food" :start1 6 :start2 8) 11))
(test (eql (string<= "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9) 9))
(test (eql (string<= "xyzabc" "abcd" :start1 3) 6))
(test (eql (string<= "abc" "abc" :end1 1) 1))
(test (eql (string<= "xyzabc" "abc" :start1 3 :end1 5) 5))
(test (eql (string<= "xyz" "abcxyzXYZ" :start2 3) 3))
(test (eql (string<= "abc" "abcxyz" :end2 3) 3))
(test (eql (string<= "xyz" "abcxyz" :end1 2 :start2 3) 2))
(test (eql (string<= "xyzabc" "abcdef" :start1 3 :end2 3) 6))
(test (eql (string<= "aaaa" "z") 0))
(test (eql (string<= "pppTTTaTTTqqq" "pTTTxTTT" :start1 3 :start2 1) 6))
(test (eql (string<= "pppTTTaTTTqqq" "pTTTxTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (eql (string<= (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char)) 0))
(test (not (string<= 'love 'hate)))
(test (= (string<= 'peace 'war) 0))
(test (= (string<= 'love 'love) 4))
(test (= (string<= #\a #\a) 1))
(test (= (string<= #\a #\b) 0))
(test (not (string<= #\z #\a)))
(test (eql (string>= "" "") 0))
(test (eql (string>= "dog" "dog") 3))
(test (eql (string>= " " " ") 1))
(test (eql (string>= "abc" "") 0))
(test (not (string>= "" "abc")))
(test (not (string>= "ab" "abc")))
(test (eql (string>= "abc" "ab") 2))
(test (eql (string>= "aba" "aaa") 1))
(test (not (string>= "aaa" "aba")))
(test (eql (string>= "my cat food" "your dog food" :start1 6 :start2 8) 11))
(test (eql (string>= "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9) 9))
(test (eql (string>= "xyzabcde" "abcd" :start1 3) 7))
(test (not (string>= "abc" "abc" :end1 1)))
(test (eql (string>= "xyzabc" "a" :start1 3 :end1 5) 4))
(test (eql (string>= "xyzXYZ" "abcxyz" :start2 3) 3))
(test (eql (string>= "abcxyz" "abcxyz" :end2 3) 3))
(test (not (string>= "xyzXYZ" "abcxyz" :end1 2 :start2 3)))
(test (eql (string>= "xyzabc" "abcdef" :start1 3 :end2 3) 6))
(test (eql (string>= "z" "aaaa") 0))
(test (eql (string>= "pTTTxTTTqqq" "pppTTTaTTT" :start1 1 :start2 3) 4))
(test (eql (string>= "pppTTTxTTTqqq" "pTTTaTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (eql (string>= (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char)) 0))
(test (= (string>= 'love 'hate) 0))
(test (not (string>= 'peace 'war)))
(test (= (string>= 'love 'love) 4))
(test (= (string>= #\a #\a) 1))
(test (not (string>= #\a #\b)))
(test (= (string>= #\z #\a) 0))
(test (string-equal "" ""))
;; (test (string-equal (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char)))
(test (not (string-equal "abc" "")))
(test (not (string-equal "" "abc")))
(test (string-equal "A" "a"))
(test (string-equal "abc" "xyz" :start1 3 :start2 3))
(test (string-equal "abc" "xyz" :start1 1 :end1 1 :start2 0 :end2 0))
(test (string-equal "axyza" "xyz" :start1 1 :end1 4))
(test (string-equal "axyza" "xyz" :start1 1 :end1 4 :start2 0 :end2 nil))
(test (string-equal "abxyz" "xyabz" :end1 2 :start2 2 :end2 4))
(test (not (string-equal "love" "hate")))
(test (string-equal "xyz" "XYZ"))
(test (not (string-equal 'love 'hate)))
(test (not (string-equal 'peace 'war)))
(test (string-equal 'love 'love))
(test (string-equal #\a #\a))
(test (not (string-equal #\a #\b)))
(test (not (string-equal #\z #\a)))
(test (not (string-not-equal "" "")))
;; (test (not (string-not-equal (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char))))
(test (eql (string-not-equal "abc" "") 0))
(test (eql (string-not-equal "" "abc") 0))
(test (not (string-not-equal "A" "a")))
(test (not (string-not-equal "abc" "xyz" :start1 3 :start2 3)))
(test (not (string-not-equal "abc" "xyz" :start1 1 :end1 1 :start2 0 :end2 0)))
(test (not (string-not-equal "axyza" "xyz" :start1 1 :end1 4)))
(test (not (string-not-equal "axyza" "xyz" :start1 1 :end1 4 :start2 0 :end2 nil)))
(test (not (string-not-equal "abxyz" "xyabz" :end1 2 :start2 2 :end2 4)))
(test (eql (string-not-equal "love" "hate") 0))
(test (not (string-not-equal "love" "loVe")))
(test (not (string-not-equal "life" "death" :start1 3 :start2 1 :end2 2)))
(test (not (string-not-equal "abcxyz" "ABCxyZ" :start1 3 :start2 3)))
(test (not (string-not-equal "abcxyz" "ABCxyZ" :start1 3 :end1 nil :start2 3 :end2 nil)))
(test (eql (string-not-equal "abcxyz" "ABCxyZ" :end1 nil :start2 3 :end2 3) 0))
(test (eql (string-not-equal "abc" "abcxyz") 3))
(test (eql (string-not-equal "abcxyz" "abc") 3))
(test (eql (string-not-equal "abcxyz" "") 0))
(test (not (string-not-equal "AbcDef" "cdef" :start1 2)))
(test (not (string-not-equal "cdef" "AbcDef" :start2 2)))
(test (not (string-not-equal "ABC" "abc")))
(test (= (string-not-equal 'love 'hate) 0))
(test (= (string-not-equal 'peace 'war) 0))
(test (not (string-not-equal 'love 'love)))
(test (not (string-not-equal #\a #\a)))
(test (= (string-not-equal #\a #\b) 0))
(test (= (string-not-equal #\z #\a) 0))
(test (not (string-lessp "" "")))
(test (not (string-lessp "dog" "dog")))
(test (not (string-lessp " " " ")))
(test (not (string-lessp "abc" "")))
(test (eql (string-lessp "" "abc") 0))
(test (eql (string-lessp "ab" "abc") 2))
(test (not (string-lessp "abc" "ab")))
(test (eql (string-lessp "aaa" "aba") 1))
(test (not (string-lessp "aba" "aaa")))
(test (not (string-lessp "my cat food" "your dog food" :start1 6 :start2 8)))
(test (not (string-lessp "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9)))
(test (eql (string-lessp "xyzabc" "abcd" :start1 3) 6))
(test (eql (string-lessp "abc" "abc" :end1 1) 1))
(test (eql (string-lessp "xyzabc" "abc" :start1 3 :end1 5) 5))
(test (eql (string-lessp "xyz" "abcxyzXYZ" :start2 3) 3))
(test (not (string-lessp "abc" "abcxyz" :end2 3)))
(test (eql (string-lessp "xyz" "abcxyz" :end1 2 :start2 3) 2))
(test (not (string-lessp "xyzabc" "abcdef" :start1 3 :end2 3)))
(test (eql (string-lessp "aaaa" "z") 0))
(test (eql (string-lessp "pppTTTaTTTqqq" "pTTTxTTT" :start1 3 :start2 1) 6))
(test (eql (string-lessp "pppTTTaTTTqqq" "pTTTxTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (not (string-lessp (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char))))
(test (and (not (string-lessp "abc" "ABC"))
(not (string-lessp "ABC" "abc"))))
(test (not (string-lessp 'love 'hate)))
(test (= (string-lessp 'peace 'war) 0))
(test (not (string-lessp 'love 'love)))
(test (not (string-lessp #\a #\a)))
(test (= (string-lessp #\a #\b) 0))
(test (not (string-lessp #\z #\a)))
(test (not (string-greaterp "" "")))
(test (not (string-greaterp "dog" "dog")))
(test (not (string-greaterp " " " ")))
(test (eql (string-greaterp "abc" "") 0))
(test (not (string-greaterp "" "abc")))
(test (not (string-greaterp "ab" "abc")))
(test (eql (string-greaterp "abc" "ab") 2))
(test (eql (string-greaterp "aba" "aaa") 1))
(test (not (string-greaterp "aaa" "aba")))
(test (not (string-greaterp "my cat food" "your dog food" :start1 6 :start2 8)))
(test (not (string-greaterp "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9)))
(test (eql (string-greaterp "xyzabcde" "abcd" :start1 3) 7))
(test (not (string-greaterp "abc" "abc" :end1 1)))
(test (eql (string-greaterp "xyzabc" "a" :start1 3 :end1 5) 4))
(test (eql (string-greaterp "xyzXYZ" "abcxyz" :start2 3) 3))
(test (eql (string-greaterp "abcxyz" "abcxyz" :end2 3) 3))
(test (not (string-greaterp "xyzXYZ" "abcxyz" :end1 2 :start2 3)))
(test (not (string-greaterp "xyzabc" "abcdef" :start1 3 :end2 3)))
(test (eql (string-greaterp "z" "aaaa") 0))
(test (eql (string-greaterp "pTTTxTTTqqq" "pppTTTaTTT" :start1 1 :start2 3) 4))
(test (eql (string-greaterp "pppTTTxTTTqqq" "pTTTaTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (not (string-greaterp (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char))))
(test (and (not (string-greaterp "abc" "ABC"))
(not (string-greaterp "ABC" "abc"))))
(test (= (string-greaterp 'love 'hate) 0))
(test (not (string-greaterp 'peace 'war)))
(test (not (string-greaterp 'love 'love)))
(test (not (string-greaterp #\a #\a)))
(test (not (string-greaterp #\a #\b)))
(test (= (string-greaterp #\z #\a) 0))
(test (eql (string-not-greaterp "" "") 0))
(test (eql (string-not-greaterp "dog" "dog") 3))
(test (eql (string-not-greaterp " " " ") 1))
(test (not (string-not-greaterp "abc" "")))
(test (eql (string-not-greaterp "ab" "abc") 2))
(test (eql (string-not-greaterp "aaa" "aba") 1))
(test (not (string-not-greaterp "aba" "aaa")))
(test (eql (string-not-greaterp "my cat food" "your dog food" :start1 6 :start2 8) 11))
(test (eql (string-not-greaterp "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9) 9))
(test (eql (string-not-greaterp "xyzabc" "abcd" :start1 3) 6))
(test (eql (string-not-greaterp "abc" "abc" :end1 1) 1))
(test (eql (string-not-greaterp "xyzabc" "abc" :start1 3 :end1 5) 5))
(test (eql (string-not-greaterp "xyz" "abcxyzXYZ" :start2 3) 3))
(test (eql (string-not-greaterp "abc" "abcxyz" :end2 3) 3))
(test (eql (string-not-greaterp "xyz" "abcxyz" :end1 2 :start2 3) 2))
(test (eql (string-not-greaterp "xyzabc" "abcdef" :start1 3 :end2 3) 6))
(test (eql (string-not-greaterp "aaaa" "z") 0))
(test (eql (string-not-greaterp "pppTTTaTTTqqq" "pTTTxTTT" :start1 3 :start2 1) 6))
(test (eql (string-not-greaterp "pppTTTaTTTqqq" "pTTTxTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (eql (string-not-greaterp (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char)) 0))
(test (and (eql (string-not-greaterp "abc" "ABC") 3)
(eql (string-not-greaterp "ABC" "abc") 3)))
(test (not (string-not-greaterp 'love 'hate)))
(test (= (string-not-greaterp 'peace 'war) 0))
(test (= (string-not-greaterp 'love 'love) 4))
(test (= (string-not-greaterp #\a #\a) 1))
(test (= (string-not-greaterp #\a #\b) 0))
(test (not (string-not-greaterp #\z #\a)))
(test (eql (string-not-lessp "" "") 0))
(test (eql (string-not-lessp "dog" "dog") 3))
(test (eql (string-not-lessp " " " ") 1))
(test (eql (string-not-lessp "abc" "") 0))
(test (not (string-not-lessp "" "abc")))
(test (not (string-not-lessp "ab" "abc")))
(test (eql (string-not-lessp "abc" "ab") 2))
(test (eql (string-not-lessp "aba" "aaa") 1))
(test (not (string-not-lessp "aaa" "aba")))
(test (eql (string-not-lessp "my cat food" "your dog food" :start1 6 :start2 8) 11))
(test (eql (string-not-lessp "cat food 2 dollars" "dog food 3 dollars"
:start1 3 :end1 9 :start2 3 :end2 9) 9))
(test (eql (string-not-lessp "xyzabcde" "abcd" :start1 3) 7))
(test (not (string-not-lessp "abc" "abc" :end1 1)))
(test (eql (string-not-lessp "xyzabc" "a" :start1 3 :end1 5) 4))
(test (eql (string-not-lessp "xyzXYZ" "abcxyz" :start2 3) 3))
(test (eql (string-not-lessp "abcxyz" "abcxyz" :end2 3) 3))
(test (not (string-not-lessp "xyzXYZ" "abcxyz" :end1 2 :start2 3)))
(test (eql (string-not-lessp "xyzabc" "abcdef" :start1 3 :end2 3) 6))
(test (eql (string-not-lessp "z" "aaaa") 0))
(test (eql (string-not-lessp "pTTTxTTTqqq" "pppTTTaTTT" :start1 1 :start2 3) 4))
(test (eql (string-not-lessp "pppTTTxTTTqqq" "pTTTaTTT"
:start1 6 :end1 7
:start2 4 :end2 5) 6))
;; (test (eql (string-not-lessp (make-array 0 :element-type 'character)
;; (make-array 0 :element-type 'base-char)) 0))
(test (and (eql (string-not-lessp "abc" "ABC") 3)
(eql (string-not-lessp "ABC" "abc") 3)))
(test (= (string-not-lessp 'love 'hate) 0))
(test (not (string-not-lessp 'peace 'war)))
(test (= (string-not-lessp 'love 'love) 4))
(test (= (string-not-lessp #\a #\a) 1))
(test (not (string-not-lessp #\a #\b)))
(test (= (string-not-lessp #\z #\a) 0))
(test (stringp "aaaaaa"))
(test (stringp (make-array 0 :element-type 'character)))
;; (test (stringp (make-array 0 :element-type 'base-char)))
;; JSCL: an array of STANDARD-CHAR isn't a STRINGP yet, either
;; (test (stringp (make-array 0 :element-type 'standard-char)))
(test (not (stringp #\a)))
(test (not (stringp 'a)))
(test (not (stringp '(string))))
(test (string= (make-string 3 :initial-element #\a) "aaa"))
;; JSCL: no SCHAR, so disabled
;; (test (let ((str (make-string 3)))
;; (and (simple-string-p str)
;; (setf (schar str 0) #\x)
;; (setf (schar str 1) #\y)
;; (setf (schar str 2) #\z)
;; (string= str "xyz"))))
;; JSCL: #\Space isn't read correctly yet
;; (test (string= (make-string 1 :initial-element #\Space) " "))
(test (string= (make-string 0) ""))
;; JSCL: BUG?: this barfs inside the JS function xstring(), and i don't know why.
;; (test (subtypep (upgraded-array-element-type
;; (array-element-type (make-string 3 :element-type 'standard-char)))
;; 'character))
;;; EOF
| 28,566 | Common Lisp | .lisp | 597 | 45.400335 | 89 | 0.612608 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c5b2a0d8f1a3c228ac1597cb68c558cedefa779cc80fb0c2f65d899a8df93075 | 56 | [
-1
] |
57 | defun.lisp | jscl-project_jscl/tests/defun.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/defun.lisp!")
;;;; Tests for DEFUN
;;; Regression test for #111
(test (eql (defun foo () "foo's" ()) 'foo))
;;; Body, declarations and docstrings
(let ((actual
(multiple-value-list
(parse-body '((declare (integerp x)) "foo" 3)
:declarations t
:docstring t))))
(test (equal actual '((3) ((DECLARE (INTEGERP X))) "foo"))))
(let ((actual
(multiple-value-list
(parse-body '((declare (integerp x)) "foo")
:declarations t
:docstring t))))
(test (equal actual '(("foo") ((DECLARE (INTEGERP X))) nil))))
(let ((actual
(multiple-value-list
(parse-body '("foo" 3)
:declarations t
:docstring t))))
(test (equal actual '((3) nil "foo"))))
;;; (defun (setf )) test
(progn
(defun fn1 (arg1 arg2)
(list arg1 arg2))
(defun (setf fn1) (new arg1 arg2)
(list new arg1 arg2))
(defun (setf fn2) (new arg1 &optional (arg2 2) (arg3 3))
(list new arg1 arg2 arg3))
(defun (setf %cadr%) (value lst) (rplaca (cdr lst) value))
(test (equal '(2 3) (fn1 2 3)))
(test (equal '(1 2 3) (setf (fn1 2 3) 1)))
(test (equal '(4 1 2 3) (setf (fn2 1) 4)))
(test (equal '(4 5 6 7) (setf (fn2 5 6 7) 4)))
(let ((qq '(1 2 3)))
(test (equal '(99 3) (setf (%cadr% qq) 99)))
(test (equal '(1 99 3) qq)))
(test (fdefinition '(setf fn1))))
;;; push/pop/incf/decf test
#+jscl
(progn
;; getter
(defun getr (r idx)
(aref r idx))
;; setter
(defun (setf getr) (value r idx)
(setf (aref r idx) value))
(let ((r #(nil nil nil)))
;; initial values
(setf (getr r 0) 1)
(setf (getr r 1) (list :tail))
;; push
(dolist (it '(3 2 1))
(push it (getr r 2)))
;; pop
(dotimes (it (length (getr r 2)))
(push (pop (getr r 2)) (getr r 1)))
;; incf
(dotimes (i 10)
(incf (getr r 0)))
(equal '(11 (3 2 1 :tail) nil)
(vector-to-list r))))
;;; EOF
| 2,062 | Common Lisp | .lisp | 66 | 25.287879 | 64 | 0.532421 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 6ca203c43d48e2817b3ed324f42ea7183c8bc9755f0472722f3381801a3fc711 | 57 | [
-1
] |
58 | array.lisp | jscl-project_jscl/tests/array.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/array.lisp!")
(test (arrayp #(1 2 3 4)))
(test (vectorp #(1 2 3 4)))
(test (not (vectorp (make-array '(3 3)))))
(let ((array #(1 2 3 4)))
(setf (aref array 0) t)
(test (eq (aref array 0) t)))
(let ((vector (make-array 20 :initial-element 3 :fill-pointer 0)))
(test (= (length vector) 0))
(setf (fill-pointer vector) 20)
(test (= (length vector) 20)))
(test
(mv-eql
(let ((vector (make-array 10 :fill-pointer 1))
(new-idx))
(values
(dotimes (i 10 new-idx)
(push (vector-push i vector) new-idx))
(vector-to-list vector)))
(NIL 9 8 7 6 5 4 3 2 1)
(NIL 0 1 2 3 4 5 6 7 8)))
;;; from clhs.lisp.se
(test
(mv-eql
(let (fable fa)
(values
(vector-push (setq fable (list 'fable))
(setq fa (make-array 8
:fill-pointer 2
:initial-element 'first-one)))
(fill-pointer fa)
(eq (aref fa 2) fable)))
2 3 t))
;;; EOF
| 1,032 | Common Lisp | .lisp | 35 | 23.485714 | 69 | 0.539939 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | d317d6abe41dba0be7b733c9f8bb81969fb195448bd9c96bbb770efeff157376 | 58 | [
-1
] |
59 | control.lisp | jscl-project_jscl/tests/control.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/control.lisp!")
;;; Returning from a "dynamically" nested non local exists
(defun foo (x)
(when x (funcall x))
(foo (lambda () (return-from foo 1)))
(return-from foo 2))
(test (= (foo nil) 1))
(defun foo-2 (x)
(let (value)
(tagbody
(when x (funcall x))
(foo-2 (lambda () (go exit-2)))
(go end)
exit-2
(setq value t)
end)
value))
(test (foo-2 nil))
(test (equal (flet ((foo () (return-from foo 42)))
(foo))
42))
(test (equal (let ((out (list)))
(labels ((zfoo (n rf i)
(if (> n 0)
(progn
(push (lambda () (return-from zfoo n)) rf)
(push n out)
(zfoo (1- n) rf i)
(push (- n) out))
(progn
(push 999 out)
(funcall (nth i (reverse rf)))
(push -999 out)))))
(let ((rf (list)))
(zfoo 5 rf 3)
out)))
'(-5 -4 -3 999 1 2 3 4 5)))
;; COMPLEMENT
(test (funcall (complement #'zerop) 1))
;;; FIXME: Uncomment whenever characterp is defined
;;; NOTE: FIXED @vkm -> (defun characterp (c) (characterp c))
(test (not (funcall (complement #'characterp) #\A)))
(test (not (funcall (complement #'member) 'a '(a b c))))
(test (funcall (complement #'member) 'd '(a b c)))
;;; EOF
| 1,602 | Common Lisp | .lisp | 46 | 23.26087 | 74 | 0.440129 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | acc679d415dd251bd6a9d79b6c46f9e505bcbf1e1ec7aed8d30e01093bef2ace | 59 | [
-1
] |
60 | read.lisp | jscl-project_jscl/tests/read.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/read.lisp!")
;;; TODO: Uncomment when either read-from-string supports all these parameters
;;; fixme:
;;; or when test macro supports error handling, whichever comes first
;;; (test (equal (read-from-string " 1 3 5" t nil :start 2) (values 3 5)))
(expected-failure
(equal (multiple-value-list (read-from-string "(a b c)"))
'((A B C) 7)))
(test (equal (symbol-name (read-from-string "cl:cond")) "COND"))
(test (equal (symbol-name (read-from-string "co|N|d")) "COND"))
(test (equal (symbol-name (read-from-string "abc\\def")) "ABCdEF"))
(test (equal (symbol-name (read-from-string "|.|")) "."))
(test (equal (read-from-string "(1 .25)") '(1 0.25)))
(test (equal (read-from-string ".25") 0.25))
(test (equal (read-from-string "(1 . 25)") '(1 . 25)))
(test (equal (read-from-string "(#1=99 2 3 #1#)") '(99 2 3 99)))
(let ((v (read-from-string "#(#1=99 2 3 #1#)")))
(test (and (eql (aref v 0) 99)
(eql (aref v 1) 2)
(eql (aref v 2) 3)
(eql (aref v 3) 99))))
(test (let ((x (read-from-string "#1=(42 . #1#)")))
(and (eql (nth 99 x) 42)
(progn
(rplaca x 13)
(eql (nth 99 x) 13))
(eq x (cdr x)))))
(test (let ((x (read-from-string "#1=#(1 #2=99 #1# #2#)")))
(and (eql (aref x 0) 1)
(eql (aref x 1) 99)
(eq (aref x 2) x)
(eql (aref x 3) 99))))
(test (let ((x (read-from-string "#1=(1 2 #2=#(3 4 #1#) 5 #2#)")))
(and (eql (nth 0 x) 1)
(eql (nth 1 x) 2)
(eql (aref (nth 2 x) 0) 3)
(eql (aref (nth 2 x) 1) 4)
(eq (aref (nth 2 x) 2) x)
(eql (nth 3 x) 5)
(eq (nth 4 x) (nth 2 x)))))
; SHARPSIGN VERTICAL-BAR
(test (= (read-from-string "#||# 2") 2))
(test (= (read-from-string "#||#2") 2))
(test (= (read-from-string "#| #| |# |# 2") 2))
(test (= (read-from-string "#|#$#%^&*&|# 2") 2))
(test (= (read-from-string "#|||# 2") 2))
;; character literals
(test (char= #\SPACE #\Space #\space))
(let ((*features* '(foo)))
(test (= (read-from-string "#+foo 1 2)") 1)))
;;; sharp radix reader
(test (string= "this is 1985" (format nil "this is ~a" #o3701)))
(test
(equal '((1 2573) (1 2) (1 2573) (1 2))
(let ((fn0 (lambda (x &optional (y #x0a0d)) (list x y) ))
(fn1 (lambda (x &key (y #x0a0d)) (list x y))))
(list
(funcall fn0 1)
(funcall fn0 1 2)
(funcall fn1 1)
(funcall fn1 1 :y 2)))))
;;; radix sharp at sequence's
#+jscl
(test
(equal
'(t t t t t)
(let ((bfv #(#b1 #b10 #b11 #b100 #b101 #b110 #b111 #b1000 #b1001 #b1010))
(bfv1 #(#b1 #b10 #b11 'sharp #\# #b100 #b101 #b110 #b111 #b1000 #b1001 #b1010))
(bfv2 #(1 2 3 (QUOTE SHARP) #\# 4 5 6 7 8 9 10))
(xfv #(#xa001 #xb001 #xc001 #xd001 #xe001 #xf001)))
(list (equal
;; correct b->d conversion
(jscl::vector-to-list bfv)
'(1 2 3 4 5 6 7 8 9 10))
(equal
;; correct x->d conversion
(jscl::vector-to-list xfv)
'(40961 45057 49153 53249 57345 61441))
;; list & sharp tokens -> with sharp reader
(equal
(jscl::vector-to-list bfv1)
'(1 2 3 (QUOTE SHARP) #\# 4 5 6 7 8 9 10))
(equal
(aref bfv1 3)
'(quote sharp))
(equal
(aref bfv1 4) #\#) ))))
;;; sharp radix reader from string
;;; higly likely it redundant but let stay
#+jscl
(test
(equal
'(t)
(let*
((s1 (read-from-string "#(#b1 #b10 #b11 #b100 #b101 #b110 #b111 #b1000 #b1001 #b1010)")))
(list
(equal
(jscl::vector-to-list s1)
'(1 2 3 4 5 6 7 8 9 10))))))
;;;
;;; parse-integer
;;;
(test
(equal '(t t t t t t)
(list
(multiple-value-bind (num pos) (parse-integer " 11111000001 " :radix 2 )
(equal (list num pos) '(1985 13)))
(multiple-value-bind (num pos) (parse-integer " 7C1 " :radix 16 )
(equal (list num pos) '(1985 5)))
(multiple-value-bind (num pos) (parse-integer " 3701 " :radix 8 )
(equal (list num pos) '(1985 6)))
;;clhs examples
(multiple-value-bind (num pos) (parse-integer "123")
(equal (list num pos) '(123 3)))
(multiple-value-bind (num pos) (parse-integer "123" :start 1 :radix 5)
(equal (list num pos) '(13 3)))
(multiple-value-bind (num pos) (parse-integer "no-integer" :junk-allowed t)
(equal (list num pos) '(nil 0))))))
;;;
;;; other fun glitch's
;;;
#|
If you remove comments from the following expression there will be a compilation error.
actually any errors in the types are caught at the compilation stage.
The correct value can be used in any expressions, as is, at your discretion
|#
#|
(let ((fn
(lambda (#xag #xaf) (list #xaa #xaf))))
(funcall fn 1 2))
|#
;;; the correct value can be used in any expressions, as is, at your discretion
(let ((fn (lambda (#xaa #xaf) (list #xaa #xaf))))
(funcall fn 1 2))
;;; => (170 175)
;;; EOF
| 5,164 | Common Lisp | .lisp | 137 | 31.29927 | 95 | 0.533587 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c80125895dfe0d2be5477f005d625fadd5fed30a1b4c194ffae70c346a5b8525 | 60 | [
-1
] |
61 | print.lisp | jscl-project_jscl/tests/print.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/print.lisp!")
#|
(test (let ((x (read-from-string (prin1-to-string 'foo))))
(and (symbolp x) (equal (symbol-name x) "FOO"))))
(test (let ((x (read-from-string (prin1-to-string 'fo\o))))
(and (symbolp x) (equal (symbol-name x) "FOo"))))
(test (let ((x (read-from-string (prin1-to-string '1..2))))
(and (symbolp x) (equal (symbol-name x) "1..2"))))
(test (let ((x (read-from-string (prin1-to-string '\1))))
(and (symbolp x) (equal (symbol-name x) "1"))))
(test (let ((x (read-from-string (prin1-to-string '\-10))))
(and (symbolp x) (equal (symbol-name x) "-10"))))
(test (let ((x (read-from-string (prin1-to-string '\.\.\.))))
(and (symbolp x) (equal (symbol-name x) "..."))))
(test (let ((x (read-from-string (prin1-to-string '1E))))
(and (symbolp x) (equal (symbol-name x) "1E"))))
(test (let ((x (read-from-string (prin1-to-string '\1E+2))))
(and (symbolp x) (equal (symbol-name x) "1E+2"))))
(test (let ((x (read-from-string (prin1-to-string '1E+))))
(and (symbolp x) (equal (symbol-name x) "1E+"))))
|#
(test
(let* ((so '(
(foo . "FOO")
(fo\o . "FOo")
(1..2 . "1..2")
(\1 . "1")
(\-10 . "-10")
(\.\.\. . "...")
(\1E+2 . "1E+2")
(1E+ . "1E+")
(:kek . "KEK")
(:| | . " ")
(|case| . "case")))
(x)
(tmp)
(result)
(expected (dotimes (i (length so) tmp) (push t tmp))))
(labels ((check-it (rec pair)
(cond ((and (symbolp rec) (equal (symbol-name rec) (cdr pair))) t)
(t (print (format nil "Bad math: ~a ~a" rec pair)) nil)))
(math-it (pair)
(setq x (read-from-string (prin1-to-string (car pair))))
(push (check-it x pair) result)))
(dolist (it so)
(math-it it))
(equal result expected))))
;;; Printing strings
(test (string= "\"foobar\"" (write-to-string "foobar")))
(test (string= "\"foo\\\"bar\"" (write-to-string "foo\"bar")))
;;; Printing vectors
(test (string= "#()" (write-to-string #())))
(test (string= "#(1)" (write-to-string #(1))))
(test (string= "#(1 2 3)" (write-to-string #(1 2 3))))
;;; Lists
(test (string= "NIL" (write-to-string '())))
(test (string= "(1)" (write-to-string '(1))))
(test (string= "(1 2 3)" (write-to-string '(1 2 3))))
(test (string= "(1 2 . 3)" (write-to-string '(1 2 . 3))))
(test (string= "(1 2 3)" (write-to-string '(1 2 3))))
(test (string= "((1 . 2) 3)" (write-to-string '((1 . 2) 3))))
(test (string= "((1) 3)" (write-to-string '((1) 3))))
;;; Circular printing
(let ((vector #(1 2 nil)))
(setf (aref vector 2) vector)
(test (string= "#1=#(1 2 #1#)"
(let ((*print-circle* t))
(write-to-string vector)))))
(let ((list '(1)))
(setf (cdr list) list)
(test (string= "#1=(1 . #1#)"
(let ((*print-circle* t))
(write-to-string list)))))
;;; lisp structured objects pretty printed - outdated
#+nil
(progn
(defstruct struct name slots)
(test (string= "#<structure struct>" (write-to-string (make-struct))))
(test (string= "#<structure struct>" (write-to-string (make-struct :name 'definition :slots #(a b c))))))
;;; EOF
| 3,433 | Common Lisp | .lisp | 81 | 35.45679 | 108 | 0.502843 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 5fef392db43a42e86848cbd63ed78e35472b3388b604a2dacc86cc3f6fd1321b | 61 | [
-1
] |
62 | clos.lisp | jscl-project_jscl/tests/clos.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/clos.lisp!")
(test (string= "#<standard-class T>" (write-to-string (find-class 't))))
(test (string= "#<standard-class NULL>" (write-to-string (find-class 'null))))
(defclass obj1 ()
((val :initform nil :initarg :value :reader obj-val :writer set-obj-val)))
(defmethod initialize-instance :after ((class obj1) &rest args)
(set-obj-val 123 class))
(let ((instance (make-instance 'obj1 :value 999)))
(test (equal 123 (slot-value instance 'val)))
(test (equal 123 (obj-val instance))))
(defclass bugpack ()
((value :initform 5.5 :initarg :value)))
(let ((instance (make-instance 'bugpack :value 9.9)))
(with-slots (value) instance
(test (equal 9.9 value))
(setf value 12.5)
(test (equal 12.5 value))
(with-slots ((bug value)) instance
(setf bug 0.0)
(test (equal bug 0.0)))))
;;; Workaround the problem with :accessor
(defclass something ()
((name :initform nil :reader something-name)))
;;; Use (with-slots) form
(let ((ip (make-instance 'something)))
(with-slots (name) ip
(setf name 'ork))
(test (equal 'ork (something-name ip))))
;;; Use (defun (setf accessor-name)) form
(defun (setf something-name) (value instance)
(setf (slot-value instance 'name) value))
(let ((ip (make-instance 'something)))
(setf (something-name ip) 'elf)
(test (equal 'elf (something-name ip))))
;;;
(defclass screw () ((aaa :initform nil)
(bbb :initform nil)
(ccc :initform nil :reader screw-ccc :writer set-screw-ccc)))
(defun (setf screw-ccc) (value instance)
(set-screw-ccc value instance))
(defmethod initialize-instance :after ((class screw) &rest args)
(with-slots (aaa bbb) class
(setf aaa 2018)
(setf bbb 1009))
(set-screw-ccc 3027 class))
(let ((ip (make-instance 'screw)))
(test (equal t (with-slots (aaa bbb) ip
(and (eq aaa 2018) (eq bbb 1009)))))
(test (equal (screw-ccc ip) 3027))
(setf (screw-ccc ip) 1998.11)
;; test instance accessors
(test (equal '(t t t)
(with-slots ((a aaa) (b bbb)) ip
(setf a 22)
(setf b 33)
(list (eq a 22) (eq b 33) (eq (screw-ccc ip) 1998.11)))))
(test (equal '(1234 abcd t)
(let ((other (with-slots (aaa bbb) ip
(let ((a aaa) (b bbb))
(and (eq aaa 22) (eq b 33))))))
(with-slots ((s1 aaa)
(s2 bbb)) ip
(setf a 1234)
(setf b 'abcd)
(list a b other)))))
;; test what screw instance have slot's value (4321 dcba)
(test (equal '(4321 dcba)
(with-slots (aaa bbb (s1 aaa) (s2 bbb)) ip
(setf aaa 4321)
(setf bbb 'dcba)
(list s1 s2))))
;; test what screw instance not have nil's slots
(test (not (equal '(nil nil nil)
(with-slots ((a aaa) (b bbb) (c ccc)) ip
(list a b c))) )))
(defclass original () ((thing :initform nil)))
(defclass mixin-1 () ((prop1 :initform nil)))
(defclass mixin-2 () ((prop2 :initform nil)))
(defclass mixt (original mixin-1 mixin-2) ())
(defmethod initialize-instance :after ((class mixt))
(with-slots (thing prop1 prop2) class
(setf thing 1)
(setf prop1 2)
(setf prop2 3)))
(let ((ip (make-instance 'mixt)))
(with-slots (thing prop1 prop2) ip
(test (equal '(1 2 3)
(progn
(list thing prop1 prop2))))))
(defgeneric bot-inspect (item))
(defmethod bot-inspect ((item standard-class)) (list 'standard-class))
(defmethod bot-inspect ((item integer)) (list 'built-in-class-integer))
(defmethod bot-inspect ((item hash-table)) (list 'hash-table-object))
(test (equal '(standard-class) (bot-inspect (find-class 't))))
(test (equal '(hash-table-object) (bot-inspect (make-hash-table))))
(test (equal '(built-in-class-integer) (bot-inspect 123)))
;;; test change-class rotatef psetf
;;; rotatef test
#+jscl
(let ((a 1)
(b 2)
(c 3)
(d #(1 2 3)))
(!rotatef a b c)
(test (equal '(2 3 1) (list a b c)))
(!rotatef a b c)
(test (equal '(3 1 2) (list a b c)))
(!rotatef (aref d 0) (aref d 2))
(test (equal '(3 2 1) (jscl::vector-to-list d))))
(let* ((a '(1 2))
(b '(3 4))
(c '(a b))
(d (list a b c)))
(!rotatef (nth 0 d) (nth 2 d))
(test (equal '((a b) (3 4) (1 2)) d)))
(defclass rectangle ()
((height :initform 0.0 :initarg :height)
(width :initform 0.0 :initarg :width)))
(defclass color-mixin ()
((cyan :initform 0 :initarg :cyan)
(magenta :initform 0 :initarg :magenta)
(yellow :initform 0 :initarg :yellow)))
(let ((o (make-instance 'rectangle :height 10 :width 20)))
(test (equal 'color-mixin
(progn
(change-class o 'color-mixin)
(class-name (class-of o)))))
(test (equal 'standard-object
(progn
(change-class o 'standard-object)
(class-name (class-of o))))))
;;; test sort with method
(defgeneric msort (what predicate &key key))
(defmethod msort ((what list) predicate &key key)
(if key
(sort what predicate :key key)
(sort what predicate)))
(defmethod msort ((what vector) predicate &key key)
(let ((lst (jscl::vector-to-list what)))
(jscl::list-to-vector
(if key
(sort lst predicate :key key)
(sort lst predicate)))))
(defmethod msort ((what string) predicate &key key)
(let ((lst (jscl::vector-to-list what)))
(apply #'jscl::concat
(if key
(sort lst predicate :key key)
(sort lst predicate)))))
(test (string= "aabbccddxyz"
(msort "cdbaxaybzcd" #'char-lessp)))
(test (equal '(9 8 7 6 5 4 3 2 1)
(jscl::vector-to-list (msort #(1 2 3 4 5 6 7 8 9) #'>))))
;;; test from original closette-test.lisp
;;; method combination
(defclass log () ((buf :initform nil)))
(defvar ip (make-instance 'log))
(defgeneric mctest (x))
(defmethod mctest :around ((x integer))
(with-slots ((b buf)) ip
(push '(:around integer) b)
(call-next-method)))
(defmethod mctest :around ((x number))
(with-slots ((b buf)) ip
(push '(:around number) b)
(call-next-method)))
(defmethod mctest :before ((x number))
(with-slots ((b buf)) ip
(push '(:before number) b)))
(defmethod mctest ((x number))
(with-slots ((b buf)) ip
(push '(primary number) b)
(1+ (call-next-method))))
(defmethod mctest :after ((x number))
(with-slots ((b buf)) ip
(push '(:after number) b)))
(defmethod mctest :before ((x t))
(with-slots ((b buf)) ip
(push '(:before t) b)))
(defmethod mctest ((x t))
(with-slots ((b buf)) ip
(push '(primary t) b)
100))
(defmethod mctest :after ((x t))
(with-slots ((b buf)) ip
(push '(:after t) b)))
(test (equal 101
(let ((x (mctest 1)))
x)))
(test (equal '((:around integer)(:around number)(:before number)
(:before t)(primary number)(primary t)(:after t)
(:after number) )
(with-slots (buf) ip
(reverse buf))))
;;; test's from original closette-test.lisp
(defclass position () (x y))
(defclass cad-element (position) ())
(defclass display-element (position) ())
(defclass displayable-cad-element (display-element cad-element) ())
(defun common-subclasses* (class-1 class-2)
(intersection (subclasses* class-1) (subclasses* class-2)))
(defun all-distinct-pairs (set)
(if (null set)
()
(append (mapcar #'(lambda (rest)
(list (car set) rest))
(cdr set))
(all-distinct-pairs (cdr set)))))
(defun has-diamond-p (class)
(some #'(lambda (pair)
(not (null (common-subclasses* (car pair)
(cadr pair)))))
(all-distinct-pairs (class-direct-subclasses class))))
(test (equal t (has-diamond-p (find-class 'position))))
;;; alternative's cpl
(defclass loops-class (standard-class) ())
(defclass flavors-class (standard-class) ())
(defmethod compute-class-precedence-list ((class loops-class))
(append (remove-duplicates
(depth-first-preorder-superclasses* class)
:from-end nil)
(list (find-class 'standard-object)
(find-class 't))))
(defmethod compute-class-precedence-list ((class flavors-class))
(append (remove-duplicates
(depth-first-preorder-superclasses* class)
:from-end t)
(list (find-class 'standard-object)
(find-class 't))))
(defun depth-first-preorder-superclasses* (class)
(if (eq class (find-class 'standard-object))
()
(cons class (mapappend #'depth-first-preorder-superclasses*
(class-direct-superclasses class)))))
(defclass a () ())
(defclass b () ())
(defclass c () ())
(defclass s (a b) ())
(defclass r (a c) ())
(defclass q-clos (s r) () (:metaclass standard-class))
(defclass q-loops (s r) () (:metaclass loops-class))
(defclass q-flavors (s r) () (:metaclass flavors-class))
(test (equal '(q-flavors s a b r c standard-object t)
(mapcar (lambda (x) (class-name x))
(class-precedence-list (find-class 'q-flavors)))))
(test (equal '(q-loops s b r a c standard-object t)
(mapcar (lambda (x) (class-name x)) (class-precedence-list (find-class 'q-loops)))))
(test (equal '(q-clos s r a c b standard-object t)
(mapcar (lambda (x) (class-name x)) (class-precedence-list (find-class 'q-clos)))))
;;; EOF
| 9,730 | Common Lisp | .lisp | 251 | 32.023904 | 97 | 0.590358 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | b485641d2412f2a39605ce5ed7958824afa04a5a283b558a49fd913d2e2b87e9 | 62 | [
-1
] |
63 | format.lisp | jscl-project_jscl/tests/format.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/format.lisp!")
(test (string= "a" (format nil "a")))
(test (string= "~" (format nil "~~")))
(test (string= "a~a" (format nil "a~~a")))
(test (string= "a
a" (format nil "a~%a")))
(test (string= "this is foo" (format nil "this is ~a" "foo")))
(test (string= "this is foo" (format nil "this is ~A" "foo")))
(test (string= "this is \"foo\"" (format nil "this is ~s" "foo")))
(test (string= "this is \"foo\"" (format nil "this is ~S" "foo")))
(test (string= "this is 2" (format nil "this is ~*~A" 1 2)))
;;; ~C
(test (string= "a" (format nil "~C" #\a)))
(test (string= " " (format nil "~C" #\space)))
(test (string= "Space" (format nil "~:C" #\space)))
(test (string= "Newline" (format nil "~:C" #\newline)))
;;; Premature end of control string
#+jscl
(test
(string= "Premature end of control string \"result ~\""
(let ((result))
(handler-case
(progn
(format nil "its ok ~~")
(format nil "result ~"))
(error (msg)
(setq result
(format nil (simple-condition-format-control msg)
(car (simple-condition-format-arguments msg))))))
result)))
;;; EOF
| 1,281 | Common Lisp | .lisp | 32 | 33.3125 | 79 | 0.532688 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 443b83394ca7ff7018c55895055b796987377902897890e934f42d1aa7451de6 | 63 | [
-1
] |
64 | conditions.lisp | jscl-project_jscl/tests/conditions.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "Perform tests/conditions.lisp")
(defun condition-hierarhy-test (condition)
(handler-case
(progn
(jscl::%%signal condition))
(condition (msg)
(typecase msg
(type-error :type-error)
(error :error)
(warning :warning)
(t :condition)))))
(test
(mv-eql
(values
(condition-hierarhy-test (jscl::%%make-condition 'warning))
(condition-hierarhy-test (jscl::%%make-condition 'error))
(condition-hierarhy-test (jscl::%%make-condition 'condition))
(condition-hierarhy-test (jscl::%%make-condition 'type-error :datum 'test :expected-type :any)))
:WARNING :ERROR :CONDITION :TYPE-ERROR))
(defun frob-simple-condition (c expected-fmt &rest expected-args)
(and (typep c 'simple-condition)
(let ((format (simple-condition-format-control c))
(args (simple-condition-format-arguments c)))
(and (stringp (apply #'format nil format args))
t))))
(defun frob-simple-error (c expected-fmt &rest expected-args)
(and (typep c 'simple-error)
(apply #'frob-simple-condition c expected-fmt expected-args)))
(defun frob-simple-warning (c expected-fmt &rest expected-args)
(and (typep c 'simple-warning)
(apply #'frob-simple-condition c expected-fmt expected-args)))
(test
(mv-eql
(values
(let ((fmt "Error"))
(handler-case (error fmt)
(simple-error (c) (frob-simple-error c fmt))))
(let* ((fmt "Error")
(cnd (make-condition 'simple-error :format-control fmt)))
(handler-case
(error cnd)
(simple-error (c) (frob-simple-error c fmt))))
(let ((fmt "Error"))
(handler-case
(error 'simple-error :format-control fmt)
(simple-error (c) (frob-simple-error c fmt))))
(let ((fmt "Error: ~A"))
(handler-case
(error fmt 10)
(simple-error (c) (frob-simple-error c fmt 10))))
(handler-case
(signal 'simple-condition)
(simple-condition (c) :right)
(error (c) :wrong))
(handler-case
(signal 'simple-warning)
(error (c) :wrong)
(simple-warning (c) :right)
(condition (c) :wrong2))
(let ((fmt "Booms!"))
(handler-case
(signal 'simple-warning :format-control fmt)
(simple-warning (c) (frob-simple-warning c fmt)))) )
T T T T :RIGHT :RIGHT T ))
(defun trap-error-handler (condition)
(throw 'trap-errors nil))
(defmacro trap-errors (&rest forms)
`(catch 'trap-errors
(handler-case (progn ,@forms)
(error (msg)
(trap-error-handler msg)))))
(test
(equal '(1 nil 3)
(list (trap-errors (jscl::%%signal "Foo.") 1)
(trap-errors (jscl::%%error "Bar.") 2)
(+ 1 2))))
;;; ASSERT case
(test
(equal '(t nil t nil)
(list
(not (assert (= 1 1)))
(trap-errors (assert (= 1 2)))
(not (assert (typep 1 'integer)))
(trap-errors (assert (typep 1 'list))))))
;;; EOF
| 3,022 | Common Lisp | .lisp | 86 | 28.976744 | 99 | 0.60281 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | c19d4c3754395954f9bbc1d0f6e598b50314969477f5e7a5489f2fe9ce83e978 | 64 | [
-1
] |
65 | numbers.lisp | jscl-project_jscl/tests/numbers.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/numbers.lisp!")
;;; Tests for numeric functions
;;; ABS
(test (= (abs 3) 3))
(test (= (abs -3) 3))
;;; MAX
(test (= (max 1) 1))
(test (= (max 1 2 3) 3))
(test (= (max 3 2 1) 3))
(test (= (max 1 2 3 4 5) 5))
;;; MIN
(test (= (min 1) 1))
(test (= (min 1 2 3) 1))
(test (= (min 3 2 1) 1))
(test (= (min 9 3 8 7 6 3 3) 3))
;;; EVENP
(test (evenp 2))
(test (evenp -2))
(test (not (evenp 1)))
(test (evenp 0))
;;; ODDP
(test (oddp 3))
(test (oddp -3))
(test (not (oddp 2)))
(test (not (oddp 0)))
;;; +, -, *, /
;;; The builtin definition of these is variadic, but the function definition
;;; should be as well. So, test it using MAPCAR
(let* ((a '(1 2))
(b a)
(c a))
(test (equal (mapcar #'+ a b c) '( 3 6)))
(test (equal (mapcar #'- a b c) '(-1 -2)))
(test (equal (mapcar #'* a b c) '( 1 8)))
;; This test will need to be changed when rationals are introduced
(test (equal (mapcar #'/ a b c) '( 1 0.5))))
;;; >, >=, =, <, <=, /=
;;; As above, we need to make sure the function is called, not the builtin
(let ((a '(1 3 1 2 1))
(b '(2 2 2 2 1))
(c '(3 1 2 1 1)))
(test (equal (mapcar #'> a b c) '(nil t nil nil nil)))
(test (equal (mapcar #'>= a b c) '(nil t nil t t)))
(test (equal (mapcar #'= a b c) '(nil nil nil nil t)))
(test (equal (mapcar #'< a b c) '( t nil nil nil nil)))
(test (equal (mapcar #'<= a b c) '( t nil t nil t)))
(test (equal (mapcar #'/= a b c) '( t t nil nil nil))))
;;; INTEGERP
(test (integerp 1))
(test (integerp -1))
(test (integerp 0))
;;; FLOATP
;; It is a known bug. Javascript does not distinguish between floats
;; and integers, and we represent both numbers in the same way. So 1
;; == 1.0 and integer and float types are not disjoint.
(expected-failure (floatp 1.0))
(test (floatp 1.1))
(test (floatp pi))
(test (floatp (- pi)))
(test (not (floatp 1)))
;;; GCD
(test (= 0 (gcd)))
(test (= 6 (gcd 60 42)))
(test (= 1 (gcd 3333 -33 101)))
(test (= 11 (gcd 3333 -33 1002001)))
(test (= 7 (gcd 91 -49)))
(test (= 7 (gcd 63 -42 35)))
(test (= 5 (gcd 5)))
(test (= 4 (gcd -4)))
;;; LCM
(test (= 10 (lcm 10)))
(test (= 150 (lcm 25 30)))
(test (= 360 (lcm -24 18 10)))
(test (= 70 (lcm 14 35)))
(test (= 0 (lcm 0 5)))
(test (= 60 (lcm 1 2 3 4 5 6)))
;;; Floor, Ceil, Truncate and Round
(test (equal (multiple-value-list (floor 0)) '(0 0)))
(test (equal (multiple-value-list (floor 1)) '(1 0)))
(test (equal (multiple-value-list (floor -1)) '(-1 0)))
(test (equal (multiple-value-list (floor 4 3)) '(1 1)))
(test (equal (multiple-value-list (floor -4 3)) '(-2 2)))
(test (equal (multiple-value-list (floor 4 -3)) '(-2 -2)))
(test (equal (multiple-value-list (floor -4 -3)) '(1 -1)))
(test (multiple-value-bind (quotient reminder)
(floor 1.2)
(and (= quotient 1)
(= (+ (* quotient 1) reminder) 1.2))))
(test (multiple-value-bind (quotient reminder)
(floor -1.2)
(and (= quotient -2)
(= (+ (* quotient 1) reminder) -1.2))))
(test (= (ceiling 0) 0))
(test (= (ceiling 1) 1))
(test (= (ceiling -1) -1))
(test (= (ceiling 1.2) 2))
(test (= (ceiling -1.2) -1))
(test (= (ceiling 4 3) 2))
(test (= (ceiling -4 3) -1))
(test (= (ceiling 4 -3) -1))
(test (= (ceiling -4 -3) 2))
(test (= (truncate 0) 0))
(test (= (truncate 1) 1))
(test (= (truncate -1) -1))
(test (= (truncate 1.2) 1))
(test (= (truncate -1.2) -1))
(test (= (truncate 4 3) 1))
(test (= (truncate -4 3) -1))
(test (= (truncate 4 -3) -1))
(test (= (truncate -4 -3) 1))
(let* ((term-width 80)
(char-positions '(10 100 250 795))
(find-row (lambda (chpos columns) (ceiling chpos columns)))
(find-col (lambda (chpos columns) (rem chpos columns)))
(cursor-position (lambda (chpos width)
(values (ceiling chpos width) (rem chpos width))))
(s1 (mapcar (lambda (x)
(multiple-value-bind (row col)
(funcall cursor-position x term-width)
(list row col))) char-positions))
(s2 (mapcar (lambda (x)
(list (funcall find-row x term-width)
(funcall find-col x term-width))) char-positions)))
;; ((1 10) (2 20) (4 10) (10 75))
(test (equal s1 s2)))
(defmacro g!tl (fn number divisor result) `(list ',fn ,number ,divisor ,result))
(let* ((test-tuples
(list
(g!tl rem -1 5 -1)
(g!tl mod -1 5 4)
(g!tl mod 13 4 1)
(g!tl rem 13 4 1)
(g!tl mod -13 4 3)
(g!tl rem -13 4 -1)
(g!tl mod 13 -4 -3)
(g!tl rem 13 -4 1)
(g!tl mod -13 -4 -1)
(g!tl rem -13 -4 -1)))
(pattern (mapcar (lambda (tuple)
(let ((fn (car tuple))
(number (cadr tuple))
(divisor (caddr tuple))
(mr (cadddr tuple)))
(eql mr (truncate (funcall fn number divisor)))))
test-tuples))
(match (list T T T T T T T T T T)))
(test (equal pattern match)))
;;; test correctness coerce float - integer
(test
(multiple-value-bind (integer rest) (truncate 123.123)
(and (integerp integer) (eq integer 123))))
;;; test what (expt 10 65) corrected parsed from string
;;; Important note:
;;; sbcl: (expt 10 65) => 100000000000000000000000000000000000000000000000000000000000000000
;;; jscl: (expt 10 65) => 100000000000000000000008244226848602684002400884060400424240244468
;;;
(test
(equal t
(numberp (parse-integer (format nil "~d" (expt 10 65))))))
;;; test ASH
;;; important note:
;;; at clhs example (ash -100000000000000000000000000000000 -100) => -79
;;; but js op: -100000000000000000000000000000000 >> -100 => 0
;;;
(test
(let ((pattern '(32 16 8 0))
(result (mapcar (lambda (x y) (ash x y))
'(16 16 16 -100000000000000000000000000000000)
'(1 0 -1 -100))))
(equal pattern result)))
;;;(equal '(32 16 8 0)
;;; (mapcar (lambda (x y) (ash x y))
;;; '(16 16 16 -100000000000000000000000000000000)
;;; '(1 0 -1 -100))))
(test
(equal t
(= #x3FFFC
(ash #xFFFF 2))))
;;; test LOG
(test
(equal 0 (log 1)))
(test
(equal 2 (log 100 10)))
(test
(equal 3 (log 8.0 2)))
;;; test LOGNOT
(test
(equal '(-1 -2 0 999)
(mapcar (lambda (x) (lognot x))
(list 0 1 -1 (1+ (lognot 1000))))))
;;; test LOGAND
(test (equal t (= 16 (logand 16 31))))
;;; clhs (logxor 1 3 7 15) => 10
(test
(equal t
(= 10
(logxor (logxor (logxor 1 3) 7) 15))))
(test
(eq 10 (logxor 1 3 7 15)))
(test
(let ((pattern '(-1 -1 0 0 -1 -2 0 999)))
(equal pattern
(list (logand) ;; must be -1
(logeqv) ;; must be -1
(logior) ;; must be 0
(logxor) ;; must be 0
(lognot 0)
(lognot 1)
(lognot -1)
(lognot (1+ (lognot 1000)))))))
(test
(let ((result))
(dolist (symbol '(boole-1 boole-2 boole-and boole-andc1
boole-andc2 boole-c1 boole-c2 boole-clr
boole-eqv boole-ior boole-nand boole-nor
boole-orc1 boole-orc2 boole-set boole-xor))
(push (boole (symbol-value symbol) #b0011 #b0101) result))
(equal '(3 5 1 4 2 -4 -6 0 -7 7 -2 -8 -3 -5 -1 6)
(reverse result))))
(defconstant boole-n-vector
(vector boole-clr boole-and boole-andc1 boole-2
boole-andc2 boole-1 boole-xor boole-ior
boole-nor boole-eqv boole-c1 boole-orc1
boole-c2 boole-orc2 boole-nand boole-set))
(defun boole-n (n integer &rest more-integers)
(apply #'boole (elt boole-n-vector n) integer more-integers))
(test
(let ((pattern '(0 1 2 3 4 5 6 7 -8 -7 -6 -5 -4 -3 -2 -1))
(result (loop for n from #b0000 to #b1111 collect (boole-n n 5 3))))
(equal pattern result)))
;;;
(test (let ((n1 1) (n2 2)) (eq (lognand n1 n2) (lognot (logand n1 n2)))))
(test (let ((n1 1) (n2 2)) (eq (lognor n1 n2) (lognot (logior n1 n2)))))
(test (let ((n1 1) (n2 2)) (eq (logandc1 n1 n2) (logand (lognot n1) n2))))
(test (let ((n1 1) (n2 2)) (eq (logandc2 n1 n2) (logand n1 (lognot n2)))))
(test (let ((n1 1) (n2 2)) (eq (logiorc1 n1 n2) (logior (lognot n1) n2))))
(test (let ((n1 1) (n2 2)) (eq (logiorc2 n1 n2) (logior n1 (lognot n2)))))
(test (let ((j 1) (x 2)) (eq (logbitp j (lognot x)) (not (logbitp j x)))))
(test
(let ((pattern '(nil t t t t nil))
(result (list (logbitp 1 1) (logbitp 0 1) (logbitp 3 10)
(logbitp 1000000 -1) (logbitp 2 6) (logbitp 0 6))))
(equal pattern result)))
(test
(let ((k 2) (n 6))
(eql (logbitp k n) (ldb-test (byte 1 k) n))))
(test
(let ((option-name #(:include :initial-offset :type :conc-name :copier :predicate))
(f1 (list :initial-offset :copier))
(f2 (list :include :type :predicate))
(f3 (list :include :initial-offset :type :conc-name :copier :predicate))
(s1 0) (s2 0) (s3 0) (r)
(pattern '(t nil t nil t t)))
(flet ((%p (seq seen)
(let ((bit 0))
(dolist (it seq)
(setq bit (position it option-name))
(setq seen (logior seen (ash 1 bit))))
seen))
(%l (seen keyword)
(logbitp (position keyword option-name) seen)))
(setq s1 (%p f1 s1) ;; must be #b10010 or 18
s2 (%p f2 s2) ;; must be #b100101 or 37
s3 (%p f3 s3)) ;; must be #b111111 or 63
(setq r (list (%l s1 :copier) (%l s1 :type)
(%l s2 :type) (%l s2 :conc-name)
(%l s3 :include) (%l s3 :predicate)))
(equal pattern r))))
;;; CLZ32
(test
(let ((nums (list 0 1 10 100 200 (expt 2 10) (expt 2 20) (expt 2 30)))
(r (list))
;; pattern ::= (number (leading-zero-bits . integer-length))
(pattern '((0 (32 . 0)) (1 (31 . 1)) (10 (28 . 4)) (100 (25 . 7))
(200 (24 . 8)) (1024 (21 . 11)) (1048576 (11 . 21))
(1073741824 (1 . 31)))))
(equal pattern
(dolist (it nums (return (reverse r)))
(push (list it (cons (jscl::clz32 it) (integer-length it))) r)))))
;;; LOGCOUNT
(test
(let* ((x 123)
(r (logcount x)))
(eql (eql r (logcount (- (+ x 1))))
(eql r (logcount (lognot x))))))
(defun identity-logcount (n)
(let* ((x n)
(r (logcount x)))
(eql (eql r (logcount (- (+ x 1))))
(eql r (logcount (lognot x))))))
(test
(equal '(t)
(remove-duplicates
(jscl::with-collect
(dotimes (i 100)
(jscl::collect (identity-logcount (random 100))))))))
;;; BYTE
(test
(let ((j 1) (k 2))
(and
(eq (byte-size (byte j k)) j)
(eq (byte-position (byte j k)) k))))
;;; LOGTEST
(test
(let ((pattern '(t nil t nil))
(result (list (logtest 1 7) (logtest 1 2)
(logtest -2 -1) (logtest 0 -1))))
(equal pattern result)))
;;; test identity
(test
(let ((x 1) (y 7))
(eq (logtest x y) (not (zerop (logand x y))))))
;;; DEPOSIT-FIELD
(test
(let ((pattern '(6 15 -7))
(result
(list
(deposit-field 7 (byte 2 1) 0)
(deposit-field -1 (byte 4 0) 0)
(deposit-field 0 (byte 2 1) -3))))
(equal pattern result)))
;;; DPB
(test
(let ((pattern '(1024 2048 1024))
(result
(list (dpb 1 (byte 1 10) 0)
(dpb -2 (byte 2 10) 0)
(dpb 1 (byte 2 10) 2048))))
(equal pattern result)))
;;; LDB
(test (eq 1 (ldb (byte 2 1) 10) ))
;;; EOF
| 11,868 | Common Lisp | .lisp | 333 | 29.810811 | 96 | 0.528289 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 75078bc887a43245d67442b9e560544665fd5c7bf76f5884568b92164ac94eb5 | 65 | [
-1
] |
66 | hash-tables.lisp | jscl-project_jscl/tests/hash-tables.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/hash-tables.lisp!")
(let ((ht (make-hash-table))
(key "foo"))
(setf (gethash key ht) 10)
(test (null (gethash "foo" ht)))
(test (equal (gethash key ht) 10))
(setf (gethash 'foo ht) "lisp")
(test (string= (gethash 'foo ht) "lisp")))
(let ((ht (make-hash-table :test #'equal)))
(setf (gethash "foo" ht) 10)
(test (equal (gethash "foo" ht) 10)))
(let ((ht (make-hash-table :test #'equal)))
(setf (gethash "foo" ht) 10)
(test (eq (remhash "foo" ht) t))
(test (eq (remhash "foo" ht) nil))
(test (null (gethash "foo" ht))))
(let ((ht (make-hash-table :test #'equal))
(result))
(push (cons 1 2) (gethash "key" ht))
(push (cons 3 4) (gethash "key" ht))
(test (equal (gethash "key" ht) '((3 . 4) (1 . 2))))
(setf (gethash "baz" ht) '(1 2 3))
(push '(5 6 7) (gethash "baz" ht))
(test (equal (gethash "baz" ht) '((5 6 7) 1 2 3)))
(maphash (lambda (k v) (push (list k v) result)) ht)
(test (equal result '(("baz" ((5 6 7) 1 2 3)) ("key" ((3 . 4) (1 . 2)))))))
;;; MAPHASH
(let ((ht (make-hash-table))
(count 0))
(maphash (lambda (key value)
(declare (ignore key value))
(setq count (1+ count)))
ht)
(test (zerop count)))
(let ((ht (make-hash-table))
(count 0))
(setf (gethash :x ht) 10)
(maphash (lambda (key value)
(setq count (1+ count)))
ht)
(test (= count 1)))
(let ((ht (make-hash-table)))
(setf (gethash :x ht) 10)
(setf (gethash :y ht) 20)
(maphash (lambda (key value)
(when (eq key :x)
(test (= value 10)))
(when (eq key :y)
(test (= value 20))))
ht))
(let ((ht (make-hash-table)))
(test
(eq nil (maphash (lambda (key value)
(declare (ignore key value)))
ht))))
(test (eq (hash-table-count (make-hash-table)) 0))
(defun temp-hash-table (&key test (fill nil))
(let ((h (apply 'make-hash-table (if test (list :test test))))
(keys '(one two three four five six))
(vals '(1 2 3 4 5 6)))
(if fill
(mapcar (lambda (x y) (setf (gethash x h) y))
keys
vals))
h))
(test (eq (hash-table-count (temp-hash-table)) 0))
(test (eq (hash-table-count (temp-hash-table :fill t)) 6))
;;; test clrhash
(test
(eq
(let ((h (temp-hash-table :fill t)))
(clrhash h)
(hash-table-count h))
0))
;;; test copy-hash
(test
(equal
(let* ((ht (temp-hash-table :fill t))
(ht-copy (jscl::copy-hash-table ht))
(map nil))
(maphash
(lambda (k1 v1)
(let ((v2 (gethash k1 ht-copy)))
(push (eq v1 v2) map))) ht)
(remove-duplicates map))
'(t)))
(test
(equal
(let* ((ht (temp-hash-table :test #'equal :fill t))
(ht-copy)
(map nil))
(map nil (lambda (key)
(setf (gethash key ht) (if (symbolp key)
(symbol-name key)
key)))
'(one-key two-key set-difference multiple-value-bind :test "small string"))
(setq ht-copy (jscl::copy-hash-table ht))
(maphash
(lambda (k1 v1)
(let ((v2 (gethash k1 ht-copy)))
(push (equal v1 v2) map))) ht)
(remove-duplicates map))
'(t)))
;;; test hash-table-printer
(test (string= "#<hash-table :test eq :count 0>"
(write-to-string (temp-hash-table :test #'eq))))
(test (string= "#<hash-table :test eql :count 0>"
(write-to-string (temp-hash-table))))
(test (string= "#<hash-table :test equal :count 0>"
(write-to-string (temp-hash-table :test #'equal))))
(test (string= "#<hash-table :test eql :count 6>" (write-to-string (temp-hash-table :fill t))))
(test (string= "#<hash-table :test eql :count 5>"
(write-to-string
(let ((h (temp-hash-table :fill t)))
(remhash 'one h)
h))))
;;; Test numbers as keys
(let ((ht (make-hash-table)))
(test (eq nil (gethash 123 ht)))
(test (eq 'foo (setf (gethash 123 ht) 'foo)))
(test (eq 'foo (gethash 123 ht))))
;;; Test numbers are different than strings
(let ((ht (make-hash-table :test #'equal)))
(test (equal 'foo (setf (gethash 123 ht) 'foo)))
(test (equal 'bar (setf (gethash "123" ht) 'bar)))
(test (equal 'foo (gethash 123 ht)))
(test (equal 'bar (gethash "123" ht)))
(test (eq 2 (length (hash-table-keys ht)))))
;;; EOF
| 4,440 | Common Lisp | .lisp | 130 | 28.223077 | 96 | 0.550478 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | af788ed9ee94ee297d6dc3f29a98c301ffff12ca8ab00c899dd02e612d0ab9ed | 66 | [
-1
] |
67 | stream.lisp | jscl-project_jscl/tests/stream.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/stream.lisp!")
(with-input-from-string (in "jscl::foo jscl::bar jscl::baz")
(test (eq (read in) 'jscl::foo))
(test (eq (read in) 'jscl::bar))
(test (eq (read in) 'jscl::baz)))
;;; EOF
| 250 | Common Lisp | .lisp | 7 | 33.571429 | 60 | 0.605809 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 00e2c7518e679873bd3225ed77cddd58e1a9789d19421170073e1e8660d319e9 | 67 | [
-1
] |
68 | equal.lisp | jscl-project_jscl/tests/equal.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/equal.lisp!")
(test (equal '(1 2) '(1 2)))
(test (equal 1 1))
(test (equal "abc" "abc"))
(test (not (equal "abc" "def")))
(test (not (equal "Abc" "abc")))
;;; EOF
| 225 | Common Lisp | .lisp | 8 | 26.625 | 35 | 0.568075 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 901b9d50cccc9b3a7ad92b8f35b05178bfe8ca378781f36ee2c1d51950b07bdd | 68 | [
-1
] |
69 | ffi.lisp | jscl-project_jscl/tests/ffi.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/ffi.lisp!")
;;; Tests for Javascript FFI routines.
;;; TODO: Once these are exported under JSCL/FFI, just :USE that into the testing package. For now,
;;; using JSCL:: prefix.
(test (= ((jscl::oget (jscl::make-new #j:Date 0) "getTime")) 0))
(test (stringp (#j:Date 0)))
(test (< 32 (length (#j:Date 0))))
;;; Array
(let ((v1 #(mediane)))
((jscl::oget v1 "push") 'right)
((jscl::oget v1 "unshift") 'left)
(test (equal ((jscl::oget v1 "indexOf") 'mediane) 1))
(test (equal ((jscl::oget v1 "indexOf") 'left) 0))
(test (equal ((jscl::oget v1 "indexOf") 'right) 2))
(test (equal (map 'list #'identity v1) '(left mediane right))))
(let ((v2 (jscl::make-new #j:Array 'left "Mediane" 'right)))
(test (equal (jscl::vector-to-list v2) '(left "Mediane" right))))
;;; String
(test (string= ((oget (jscl::lisp-to-js "abcdef") "substr") 1 2) "bc"))
;;; Number's format output
;;; for future features
(let ()
(labels
((make-number (value)
(jscl::make-new #j:Number value))
(float-Exponential (value &optional (fraction 5))
((jscl::oget (make-Number value) "toExponential") fraction))
(number-to-fixed (value &optional (digits 0))
((jscl::oget (make-Number value) "toFixed") digits))
(number-by-radix (value &optional (radix 10))
((jscl::oget (make-Number value) "toString") radix)))
(test (string= "1.23e+2" (float-exponential 123.1 2)))
(test (string= "123.01" (number-to-fixed 123.012345 2)))
(test (string= "a" (number-by-radix 10 16)))
(test (string= "1100100" (number-by-radix 100 2)))))
;;; test what simple-object (Object.create(null))
(test (string= "#<JS-OBJECT [object Simple-object]>" (write-to-string *package-table*)))
(test (equal t (js-object-p *package-table*)))
;;; test what new Array isnt js-object
(let ((obj (make-new #j:Array)))
(setf (oget obj "name") 'one)
(test (and (objectp obj)
(not (js-object-p obj)))))
;;; test what new Date is js-object & have a signature
(let ((obj (make-new #j:Date)))
(test (js-object-p obj))
(test (js-object-signature obj)))
;;; test in can handle numbers
(let ((obj (make-new #j:Object)))
(test (js-object-p obj))
(test (oset 456 obj 123))
(test (equal 456 (oget obj 123))))
;;; EOF
| 2,323 | Common Lisp | .lisp | 54 | 39.425926 | 100 | 0.628381 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 2c0529bfc8fdf7c392e66fcf752e44dfad2843c93f5be821110fb40d5addeb1c | 69 | [
-1
] |
70 | apply.lisp | jscl-project_jscl/tests/apply.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/apply.lisp!")
;;; Tests for funcall/apply
(test (equal (funcall #'list 1 2 3) '(1 2 3)))
(test (equal (apply #'list 1 2 3 '(4 5 6)) '(1 2 3 4 5 6)))
(test (equal (funcall #'funcall #'list 1 2 3) '(1 2 3)))
(test (equal (funcall #'apply #'list 1 2 3 '(4 5 6)) '(1 2 3 4 5 6)))
(test (equal (apply #'funcall #'list 1 2 3 '(4 5 6)) '(1 2 3 4 5 6)))
(test (equal (apply #'apply #'list 1 2 3 '(4 5 (6))) '(1 2 3 4 5 6)))
;;; EOF
| 488 | Common Lisp | .lisp | 10 | 47.2 | 69 | 0.559322 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | fe106ebbe70bbced7b598cc8557193f07b4b0bd12b99d53eca088bb26a255d5b | 70 | [
-1
] |
71 | setf.lisp | jscl-project_jscl/tests/setf.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/setf.lisp!")
(test (= 2
(let ((x 0))
(incf x (setf x 1))
x)))
;;; EOF
| 161 | Common Lisp | .lisp | 7 | 17.285714 | 35 | 0.440789 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 54c8dfbf2b8f6f1635cd5a9bed49247650891ca6840076468a966f27ae5a3c27 | 71 | [
-1
] |
72 | conditionals.lisp | jscl-project_jscl/tests/conditionals.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/conditionals.lisp!")
;;;; Tests for conditional forms
; Boolean operators
(test (eql (and nil 1) nil))
(test (= (and 1 2) 2))
(test (= (or nil 1) 1))
(test (= (or 1 2) 1))
; COND
(test (eql nil (cond)))
(test (= 1 (cond (1))))
(test (= 1
(let ((x 0))
(cond ((incf x))))))
(test (= 2 (cond (1 2))))
(test (= 3 (cond (nil 1) (2 3))))
(test (eql nil (cond (nil 1) (nil 2))))
; CASE
(test (= (case 1 (2 3) (otherwise 42)) 42))
(test (= (case 1 (2 3) (t 42)) 42))
(test (= (case 1 (2 3) (1 42)) 42))
(test (null (case 1 (2 3))))
;;; EOF
| 643 | Common Lisp | .lisp | 23 | 25.782609 | 43 | 0.50571 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 96d9f59a7d0d17a75c7bde42af27473cb7aafa8e12671e82175c51f353c65dcf | 72 | [
-1
] |
73 | characters.lisp | jscl-project_jscl/tests/characters.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/characters.lisp!")
;; CHAR=, CHAR/=, etc.
(test (char= (code-char 127744) (code-char 127744)))
(test (char= #\d #\d))
(test (not (char= #\A #\a)))
(test (not (char= #\d #\x)))
(test (not (char= #\d #\D)))
(test (not (char/= #\d #\d)))
(test (char/= #\d #\x))
(test (char/= #\d #\D))
(test (char= #\d #\d #\d #\d))
(test (not (char/= #\d #\d #\d #\d)))
(test (not (char= #\d #\d #\x #\d)))
(test (not (char/= #\d #\d #\x #\d)))
(test (not (char= #\d #\y #\x #\c)))
(test (char/= #\d #\y #\x #\c))
(test (not (char= #\d #\c #\d)))
(test (not (char/= #\d #\c #\d)))
(test (char< #\d #\x))
(test (char<= #\d #\x))
(test (not (char< #\d #\d)))
(test (char<= #\d #\d))
(test (char< #\a #\e #\y #\z))
(test (char<= #\a #\e #\y #\z))
(test (not (char< #\a #\e #\e #\y)))
(test (char<= #\a #\e #\e #\y))
(test (char> #\e #\d))
(test (char>= #\e #\d))
(test (char> #\d #\c #\b #\a))
(test (char>= #\d #\c #\b #\a))
(test (not (char> #\d #\d #\c #\a)))
(test (char>= #\d #\d #\c #\a))
(test (not (char> #\e #\d #\b #\c #\a)))
(test (not (char>= #\e #\d #\b #\c #\a)))
;; (char> #\z #\A) => implementation-dependent
;; (char> #\Z #\a) => implementation-dependent
(test (char-equal #\A #\a))
;; (stable-sort (list #\b #\A #\B #\a #\c #\C) #'char-lessp) => (#\A #\a #\b #\B #\c #\C)
;; (stable-sort (list #\b #\A #\B #\a #\c #\C) #'char<) => implementation-dependent
;; CHARACTER
(test (equal #\a (character #\a)))
(test (equal #\a (character "a")))
;; (test (equal #\A (character 'a)))
;; (test (equal #\a (character '\a)))
;; (expected-failure (character 65.))
;; (expected-failure (character 'apple))
;; CHARACTERP
(test (characterp #\a))
(test (characterp (code-char 65)))
(test (char= #\A (code-char 65)))
(test (not (characterp 10)))
(test (not (characterp "a")))
(test (not (characterp "ab")))
(test (characterp (code-char 127744)))
;; hyperspec examples:
(test (characterp #\a))
(test (not (characterp 'a)))
(test (not (characterp "a")))
(test (not (characterp 65.)))
;; (test (characterp #\Newline))
;; ALPHA-CHAR-P
(test (alpha-char-p #\a))
(test (not (alpha-char-p #\5)))
;; (test (alpha-char-p #\Newline))
;; ALPHANUMERICP
(test (alphanumericp #\Z))
(test (alphanumericp #\9))
;; (test (not (alphanumericp #\Newline)))
(test (not (alphanumericp #\#)))
;; DIGIT-CHAR
(test (char= #\0 (digit-char 0)))
(test (char= #\A (digit-char 10 11)))
(test (null (digit-char 10 10)))
(test (char= #\7 (digit-char 7)))
(test (null (digit-char 12)))
(test (char= #\C (digit-char 12 16))) ;; not #\c
(test (null (digit-char 6 2)))
(test (char= #\1 (digit-char 1 2)))
;; DIGIT-CHAR-P
(test (= 5 (digit-char-p #\5)))
(test (null (digit-char-p #\5 2)))
(test (null (digit-char-p #\A)))
(test (null (digit-char-p #\a)))
(test (= 10 (digit-char-p #\A 11)))
(test (= 10 (digit-char-p #\a 11)))
;; (mapcar #'(lambda (radix)
;; (map 'list #'(lambda (x) (digit-char-p x radix))
;; "059AaFGZ"))
;; '(2 8 10 16 36))
;; GRAPHIC-CHAR-P
(test (graphic-char-p #\G))
(test (graphic-char-p #\#))
;; (test (graphic-char-p #\Space))
;; (test (not (graphic-char-p #\Newline))
;; STANDARD-CHAR-P
;; (test (standard-char-p #\Space))
(test (standard-char-p #\~))
;; CHAR-UPCASE
(test (char= #\A (char-upcase #\a)))
(test (char= #\A (char-upcase #\A)))
(test (char= (code-char 223) (char-upcase (code-char 223)))) ;; changes length, so you get the original back
(test (char= (code-char 127744) (char-upcase (code-char 127744)))) ;; no upper case
;; CHAR-DOWNCASE
(test (char= #\a (char-downcase #\a)))
(test (char= #\a (char-downcase #\A)))
(test (char= (code-char 223) (char-downcase (code-char 223)))) ;; already lower case
(test (char= (code-char 127744) (char-downcase (code-char 127744)))) ;; no lower case
;; UPPER-CASE-P, LOWER-CASE-P, BOTH-CASE-P
(test (upper-case-p #\A))
(test (not (upper-case-p #\a)))
(test (both-case-p #\a))
(test (not (both-case-p #\5)))
(test (not (lower-case-p #\5)))
(test (not (upper-case-p #\5)))
(test (not (upper-case-p (code-char 127744))))
;; CODE-CHAR, CHAR-CODE
(test (char= #\A (code-char 65)))
(test (= 65 (char-code #\A)))
(test (= 127744 (char-code (code-char 127744))))
;; CHAR-INT
(test (= (char-int #\A) (char-int #\A))) ;; can be pretty much anything, as long as it's consistent
(test (= 1 (length (string (code-char 127744)))))
;; CHAR-CODE-LIMIT
(test (< 95 char-code-limit 10000000))
;; CHAR-NAME
(test (string= "Space" (char-name #\ )))
;; (test (string= "Space" (char-name #\Space)))
(test (string= "Page" (char-name (code-char 12)))) ;; #\Page
(test (string= "LATIN_SMALL_LETTER_A" (char-name #\a)))
(test (string= "LATIN_CAPITAL_LETTER_A" (char-name #\A)))
;; NAME-CHAR
(test (char= #\ (name-char 'space))) ;; should be: #\Space
(test (char= #\ (name-char "space"))) ;; #\Space
(test (char= #\ (name-char "Space"))) ;; #\Space
(test
(let ((x (char-name #\a)))
(or (not x) (eql (name-char x) #\a))))
;;; EOF
| 4,960 | Common Lisp | .lisp | 139 | 34.510791 | 109 | 0.572917 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 5bb170520ca75c01780a7572cdba1be32a58df7859562f5dc572bf7439649008 | 73 | [
-1
] |
74 | list.lisp | jscl-project_jscl/tests/list.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/list.lisp!")
;;; Tests for list functions
;;; CONS
(test (equal (cons 1 2) '(1 . 2)))
(test (equal (cons 1 nil) '(1)))
(test (equal (cons nil 2) '(NIL . 2)))
(test (equal (cons nil nil) '(NIL)))
(test (equal (cons 1 (cons 2 (cons 3 (cons 4 nil)))) '(1 2 3 4)))
(test (equal (cons 'a 'b) '(A . B)))
(test (equal (cons 'a (cons 'b (cons 'c '()))) '(A B C)))
(test (equal (cons 'a '(b c d)) '(A B C D)))
;;; CONSP
(test (not (consp 'nil)))
(test (not (consp nil)))
(test (not (consp ())))
(test (not (consp '())))
(test (consp (cons 1 2)))
;;; ATOM
(test (atom 'sss))
(test (not (atom (cons 1 2))))
(test (atom nil))
(test (atom '()))
(test (atom 3))
;;; RPLACA
(let ((some-list (list* 'one 'two 'three 'four)))
(test (equal (rplaca some-list 'uno) '(UNO TWO THREE . FOUR)))
(test (equal some-list '(UNO TWO THREE . FOUR))))
;;; RPLACD
(let ((some-list (list* 'one 'two 'three 'four)))
(test (equal (rplacd (last some-list) (list 'IV)) '(THREE IV)))
(test (equal some-list '(ONE TWO THREE IV))))
;;; CAR, CDR and variants
(test (equal (car nil) nil))
(test (equal (cdr '(1 . 2)) 2))
(test (equal (cdr '(1 2)) '(2)))
(test (equal (cadr '(1 2)) 2))
(test (equal (car '(a b c)) 'a))
(test (equal (cdr '(a b c)) '(b c)))
(test (equal (caar '((1 2) 3)) 1))
(test (equal (cadr '(1 2 3)) 2))
(test (equal (cdar '((1 2) 3)) '(2)))
(test (equal (cddr '(1 2 3)) '(3)))
(test (equal (caaar '(((1)))) 1))
(test (equal (caadr '(1 (2))) 2))
(test (equal (cadar '((1 2))) 2))
(test (equal (caddr '(1 2 3)) 3))
(test (equal (cdaar '(((1 2)))) '(2)))
(test (equal (cdadr '(1 (2 3))) '(3)))
(test (equal (cddar '((1 2 3))) '(3)))
(test (equal (cdddr '(1 2 3 4)) '(4)))
(test (equal (caaaar '((((1))))) 1))
(test (equal (caaadr '(1 ((2)))) 2))
(test (equal (caadar '((1 (2)))) 2))
(test (equal (caaddr '(1 2 (3))) 3))
(test (equal (cadaar '(((1 2)))) 2))
(test (equal (cadadr '(1 (2 3))) 3))
(test (equal (caddar '((1 2 3))) 3))
(test (equal (cadddr '(1 2 3 4)) 4))
(test (equal (cdaaar '((((1 2))))) '(2)))
(test (equal (cdaadr '(1 ((2 3)))) '(3)))
(test (equal (cdadar '((1 (2 3)))) '(3)))
(test (equal (cdaddr '(1 2 (3 4))) '(4)))
(test (equal (cddaar '(((1 2 3)))) '(3)))
(test (equal (cddadr '(1 (2 3 4))) '(4)))
(test (equal (cdddar '((1 2 3 4))) '(4)))
(test (equal (cddddr '(1 2 3 4 5)) '(5)))
;;; SETF with CAR, CDR and variants
(test (equal (let ((x '(1 2))) (setf (car x) 0) x) '(0 2)))
(test (equal (let ((x (cons 1 2))) (setf (cdr x) 0) x) '(1 . 0)))
(test (equal (let ((x '(1 2))) (setf (cdr x) '(0)) x) '(1 0)))
(test (equal (let ((x '(1 2))) (setf (cadr x) 0) x) '(1 0)))
(test (equal (let ((x '(a b c))) (setf (car x) 'z) x) '(z b c)))
(test (equal (let ((x '(a b c))) (setf (cdr x) '(y z)) x) '(a y z)))
(test (equal (let ((x '((1 2) 3))) (setf (caar x) 0) x) '((0 2) 3)))
(test (equal (let ((x '(1 2 3))) (setf (cadr x) 0) x) '(1 0 3)))
(test (equal (let ((x '((1 2) 3))) (setf (cdar x) 0) x) '((1 . 0) 3)))
(test (equal (let ((x '(1 2 3))) (setf (cddr x) '(0)) x) '(1 2 0)))
(test (equal (let ((x '(((1))))) (setf (caaar x) 0) x) '(((0)))))
(test (equal (let ((x '(1 (2)))) (setf (caadr x) 0) x) '(1 (0))))
(test (equal (let ((x '((1 2)))) (setf (cadar x) 0) x) '((1 0))))
(test (equal (let ((x '(1 2 3))) (setf (caddr x) 0) x) '(1 2 0)))
(test (equal (let ((x '(((1 2))))) (setf (cdaar x) '(0)) x) '(((1 0)))))
(test (equal (let ((x '(1 (2 3)))) (setf (cdadr x) '(0)) x) '(1 (2 0))))
(test (equal (let ((x '((1 2 3)))) (setf (cddar x) '(0)) x) '((1 2 0))))
(test (equal (let ((x '(1 2 3 4))) (setf (cdddr x) '(0)) x) '(1 2 3 0)))
(test (equal (let ((x '((((1)))))) (setf (caaaar x) 0) x) '((((0))))))
(test (equal (let ((x '(1 ((2))))) (setf (caaadr x) 0) x) '(1 ((0)))))
(test (equal (let ((x '((1 (2))))) (setf (caadar x) 0) x) '((1 (0)))))
(test (equal (let ((x '(1 2 (3)))) (setf (caaddr x) 0) x) '(1 2 (0))))
(test (equal (let ((x '(((1 2))))) (setf (cadaar x) 0) x) '(((1 0)))))
(test (equal (let ((x '(1 (2 3)))) (setf (cadadr x) 0) x) '(1 (2 0))))
(test (equal (let ((x '((1 2 3)))) (setf (caddar x) 0) x) '((1 2 0))))
(test (equal (let ((x '(1 2 3 4))) (setf (cadddr x) 0) x) '(1 2 3 0)))
(test (equal (let ((x '((((1 2)))))) (setf (cdaaar x) '(0)) x) '((((1 0))))))
(test (equal (let ((x '(1 ((2 3))))) (setf (cdaadr x) '(0)) x) '(1 ((2 0)))))
(test (equal (let ((x '((1 (2 3))))) (setf (cdadar x) '(0)) x) '((1 (2 0)))))
(test (equal (let ((x '(1 2 (3 4)))) (setf (cdaddr x) '(0)) x) '(1 2 (3 0))))
(test (equal (let ((x '(((1 2 3))))) (setf (cddaar x) '(0)) x) '(((1 2 0)))))
(test (equal (let ((x '(1 (2 3 4)))) (setf (cddadr x) '(0)) x) '(1 (2 3 0))))
(test (equal (let ((x '((1 2 3 4)))) (setf (cdddar x) '(0)) x) '((1 2 3 0))))
(test (equal (let ((x '(1 2 3 4 5))) (setf (cddddr x) '(0)) x) '(1 2 3 4 0)))
;;; SUBLIS
(test (equal (sublis '((x . 100) (z . zprime))
'(plus x (minus g z x p) 4 . x))
'(PLUS 100 (MINUS G ZPRIME 100 P) 4 . 100)))
(test (equal (sublis '(((+ x y) . (- x y)) ((- x y) . (+ x y)))
'(* (/ (+ x y) (+ x p)) (- x y))
:test #'equal)
'(* (/ (- X Y) (+ X P)) (+ X Y))))
(let ((tree1 '(1 (1 2) ((1 2 3)) (((1 2 3 4))))))
(test (equal (sublis '((3 . "three")) tree1)
'(1 (1 2) ((1 2 "three")) (((1 2 "three" 4))))))
(test (equal (sublis '((t . "string"))
(sublis '((1 . "") (4 . 44)) tree1)
:key #'stringp)
'("string" ("string" 2) (("string" 2 3)) ((("string" 2 3 44))))))
(test (equal tree1 '(1 (1 2) ((1 2 3)) (((1 2 3 4)))))))
(let ((tree2 '("one" ("one" "two") (("one" "Two" "three")))))
(test (equal (sublis '(("two" . 2)) tree2)
'("one" ("one" "two") (("one" "Two" "three")))))
(test (equal tree2 '("one" ("one" "two") (("one" "Two" "three")))))
(test (equal (sublis '(("two" . 2)) tree2 :test 'equal)
'("one" ("one" 2) (("one" "Two" "three"))))))
;;; SUBST
(let ((tree1 '(1 (1 2) (1 2 3) (1 2 3 4))))
(test (equal (subst "two" 2 tree1) '(1 (1 "two") (1 "two" 3) (1 "two" 3 4))))
(test (equal (subst "five" 5 tree1) '(1 (1 2) (1 2 3) (1 2 3 4))))
(test (eq tree1 (subst "five" 5 tree1))) ; Implementation dependent
(test (equal tree1 '(1 (1 2) (1 2 3) (1 2 3 4)))))
(test (equal (subst 'tempest 'hurricane
'(shakespeare wrote (the hurricane)))
'(SHAKESPEARE WROTE (THE TEMPEST))))
(test (equal (subst 'foo 'nil '(shakespeare wrote (twelfth night)))
'(SHAKESPEARE WROTE (TWELFTH NIGHT . FOO) . FOO)))
(test (equal (subst '(a . cons) '(old . pair)
'((old . spice) ((old . shoes) old . pair) (old . pair))
:test #'equal)
'((OLD . SPICE) ((OLD . SHOES) A . CONS) (A . CONS))))
;;; COPY-LIST
(test (eql (copy-list nil) nil))
(test (equal (copy-list (list nil)) (list nil)))
(test (equal (copy-list (list 1 2 3)) (list 1 2 3)))
;;; COPY-TREE
(test (let* ((foo (list '(1 2) '(3 4)))
(bar (copy-tree foo)))
(setf (car (car foo)) 0)
(not (= (car (car foo))
(car (car bar))))))
;;; TREE-EQUAL
(test (tree-equal '(1 2 3) '(1 2 3)))
(test (not (tree-equal '(1 2 3) '(3 2 1))))
(test (tree-equal '(1 (2 (3 4) 5) 6) '(1 (2 (3 4) 5) 6)))
(test (tree-equal (cons 1 2) (cons 2 3) :test (lambda (a b) (not (= a b)))))
(test (tree-equal '(1 . 2) '(2 . 1) :test-not #'eql))
(test (not (tree-equal '(1 . 2) '(1 . 2) :test-not #'eql)))
;;; FIRST to TENTH
(let ((nums '(1 2 3 4 5 6 7 8 9 10)))
(test (= (first nums) 1))
(test (= (second nums) 2))
(test (= (third nums) 3))
(test (= (fourth nums) 4))
(test (= (fifth nums) 5))
(test (= (sixth nums) 6))
(test (= (seventh nums) 7))
(test (= (eighth nums) 8))
(test (= (ninth nums) 9))
(test (= (tenth nums) 10)))
;;; TAILP
(let* ((a (list 1 2 3))
(b (cdr a)))
(test (tailp b a))
(test (tailp a a)))
(test (tailp 'a (cons 'b 'a)))
;;; ACONS
(test (equal '((1 . 2) (3 . 4))
(acons 1 2 '((3 . 4)))))
(test (equal '((1 . 2)) (acons 1 2 ())))
;;; PAIRLIS
(test (equal '((1 . 3) (0 . 2))
(pairlis '(0 1) '(2 3))))
(test (equal '((1 . 2) (a . b))
(pairlis '(1) '(2) '((a . b)))))
;;; COPY-ALIST
(let* ((alist '((1 . 2) (3 . 4)))
(copy (copy-alist alist)))
(test (not (eql alist copy)))
(test (not (eql (car alist) (car copy))))
(test (equal alist copy)))
;;; ASSOC and RASSOC
(let ((alist '((1 . 2) (3 . 4))))
(test (equal (assoc 1 alist) '(1 . 2)))
(test (equal (rassoc 2 alist) '(1 . 2)))
(test (not (assoc 2 alist)))
(test (not (rassoc 1 alist)))
(test (equal (assoc 3 alist :test-not #'=) '(1 . 2)))
(test (equal (rassoc 4 alist :test-not #'=) '(1 . 2)))
(test (equal (assoc 1 alist :key (lambda (x) (/ x 3))) '(3 . 4)))
(test (equal (rassoc 2 alist :key (lambda (x) (/ x 2))) '(3 . 4))))
;;; MEMBER
(test (equal (member 2 '(1 2 3)) '(2 3)))
(test (not (member 4 '(1 2 3))))
(test (equal (member 4 '((1 . 2) (3 . 4)) :key #'cdr) '((3 . 4))))
(test (member '(2) '((1) (2) (3)) :test #'equal))
(test (member 1 '(1 2 3) :test-not #'eql))
;;; ADJOIN
(test (equal (adjoin 1 '(2 3)) '(1 2 3)))
(test (equal (adjoin 1 '(1 2 3)) '(1 2 3)))
(test (equal (adjoin '(1) '((1) (2)) :test #'equal) '((1) (2))))
;;; INTERSECTION
(test (equal (intersection '(1 2) '(2 3)) '(2)))
(test (not (intersection '(1 2 3) '(4 5 6))))
(test (equal (intersection '((1) (2)) '((2) (3)) :test #'equal) '((2))))
(test (equal '((1 . 2))
(intersection '((1 . 2) (2 . 3)) '((9 . 2) (9 . 4))
:test #'equal :key #'cdr)))
;;; POP
(test (let* ((foo '(1 2 3))
(bar (pop foo)))
(and (= bar 1)
(= (car foo) 2))))
;;;; MAPCAR
(test (equal (mapcar #'+ '(1 2) '(3) '(4 5 6)) '(8)))
;;;; MAPLIST
(test (equal '((1 2 3 4 1 2 1 2 3) (2 3 4 2 2 3))
(maplist #'append '(1 2 3 4) '(1 2) '(1 2 3))))
(test (equal '((FOO A B C D) (FOO B C D) (FOO C D) (FOO D))
(maplist #'(lambda (x) (cons 'foo x)) '(a b c d))))
(test (equal '(0 0 1 0 1 1 1)
(maplist #'(lambda (x) (if (member (car x) (cdr x)) 0 1)) '(a b a c d b c))))
;;;; MAPC
(test (equal (mapc #'+ '(1 2) '(3) '(4 5 6)) '(1 2)))
(test (let (foo)
(mapc (lambda (x y z) (push (+ x y z) foo)) '(1 2) '(3) '(4 5 6))
(equal foo '(8))))
;;;; GETF
(test (eq (getf '(a b c d) 'a) 'b))
(test (null (getf '(a b c d) 'e)))
(test (equal (let ((x (list 'a 1))) (setf (getf x 'a) 3) x) '(a 3)))
(test (equal (let ((x (list 'a 1))) (incf (getf x 'a)) x) '(a 2)))
(test (let ((x (list 'a 1 'b 2)))
(setf (getf x 'b) 0)
(setf (getf x 'c) 3)
(and (equal (getf x 'a) 1)
(equal (getf x 'b) 0)
(equal (getf x 'c) 3))))
;;; GET-PROPERTIES
(test (equal (multiple-value-list (get-properties '(a b c d) '(b d e))) '(NIL NIL NIL)))
(test (equal (multiple-value-list (get-properties '(a b c d) '(b a c))) '(a b (a b c d))))
(test (equal (multiple-value-list (get-properties '(a b c d) '(b c a))) '(a b (a b c d))))
;;; BUTLAST
(test (equal (butlast '()) ()))
(test (equal (butlast '(1)) ()))
(test (equal (butlast '(1 2)) '(1)))
(test (equal (butlast '(1 2 3 4 5)) '(1 2 3 4)))
(test (equal '(1 2 3 4) (butlast '(1 2 3 4 5))))
(test (equal (let ((thing '(1 2 3 4 5))) (butlast thing)) '(1 2 3 4)))
(test (equal (let ((thing '(1 2 3 4 5))) (butlast thing) thing) '(1 2 3 4 5)))
(test (equal (let ((thing '(1 2 3 4 5))) (butlast thing 0)) '(1 2 3 4 5)))
(test (equal (let ((thing '(1 2 3 4 5))) (butlast thing 1)) '(1 2 3 4)))
(test (equal (let ((thing '(1 2 3 4 5))) (butlast thing 2)) '(1 2 3)))
(test (equal (let ((thing '())) (butlast thing 2)) '()))
(test (equal (let ((thing '(1 2))) (butlast thing 2)) '()))
(test (equal (let ((thing '())) (butlast thing 0)) '()))
;;; MAKE-LIST
(test (equal (make-list 5) '(nil nil nil nil nil)))
(test (equal (make-list 3 :initial-element 'rah) '(rah rah rah)))
;;; set-difference test
(let ((lst1 (list "A" "b" "C" "d"))
(lst2 (list "a" "B" "C" "d")))
(test (equal
(list
(equal (set-difference lst1 lst2) (list "d" "C" "b" "A"))
(equal (set-difference lst1 lst2 :test 'equal) (list "b" "A"))
(equal (set-difference lst1 lst2 :test #'string=) (list "b" "A")))
(list t t t))))
;;; SORT
#+jscl
(test
(equal (apply 'jscl::concat
(sort (jscl::vector-to-list "cdbaxaybzcd") #'char-lessp))
"aabbccddxyz"))
#+jscl
(test
(let ((sorted (apply 'jscl::concat
(sort (jscl::vector-to-list "cdbaxaybzcd") #'char-lessp))))
(equal (remove-duplicates sorted :test #'char-equal :from-end t) "abcdxyz")))
(test
(equal (sort '((1 2 3) (4 5 6) (7 8 9)) #'> :key #'car)
'((7 8 9) (4 5 6) (1 2 3))))
;;; union
(test
(equal (union '(a b c) '(f a d))
'(C B F A D)))
(test
(equal (union '((x 5) (y 6)) '((z 2) (x 4) (z 2))
:key #'car
:test (lambda (x y) (equal (car x) y)))
'((Y 6) (Z 2) (X 4))))
(test
(let ((lst1 (list 1 2 '(1 2) "a" "b"))
(lst2 (list 2 3 '(2 3) "B" "C")))
(equal (union lst1 lst2)
'("b" "a" (1 2) 1 2 3 (2 3) "B" "C"))))
;;; See https://github.com/jscl-project/jscl/issues/369
(test
(equal
(let ((x (cons 'a 'b))
b)
(rplacd x (progn (setq b 0) 'c)))
'(a . c )))
;;; EOF
| 13,422 | Common Lisp | .lisp | 312 | 39.205128 | 90 | 0.483389 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | e670dcc9586f03da904159a88ea1311a154bd3ede2993ed6558d70ffcb996694 | 74 | [
-1
] |
75 | variables.lisp | jscl-project_jscl/tests/variables.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/variables.lisp!")
(defvar *x*)
(setq *x* 0)
(let* ((*x* (progn
(test (= *x* 0))
(setq *x* 1)
(test (= *x* 1))
2)))
(test (= *x* 2)))
(test (= *x* 1))
(defparameter *special-defparameter* 1)
(flet ((f ()
*special-defparameter*))
(let ((*special-defparameter* 2))
(test (= (f) 2))))
(test (not (fboundp 'abc)))
;;; EOF
| 459 | Common Lisp | .lisp | 18 | 19.833333 | 39 | 0.476744 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | b1cce124b31d708adeda3935a5ecbb3abc0dbcbc9453bc8ca39a304eae9fad56 | 75 | [
-1
] |
76 | defpackage.lisp | jscl-project_jscl/tests/defpackage.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/defpackage.lisp!")
;;; Tests for defpackage
(test (defpackage :test-package)) ; we just define it
(test (eq (defpackage :test-package) (find-package :test-package)))
;; Since we didn't use `:use` before, we expect no exported symbols
(test (eq (find-symbol "CAR" :test-package) nil))
;; We redefine the package
(test (eq (defpackage :test-package (:use cl)) (find-package :test-package)))
;; Now we expect there to be symbols
(test (eq (find-symbol "CAR" :test-package) 'cl::car))
| 549 | Common Lisp | .lisp | 11 | 48.545455 | 77 | 0.696629 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 1eca280d29e120b4eeaaa1de3c3c239c5c392d40de4b1a8296044d4a0288fb61 | 76 | [
-1
] |
77 | iter-macros.lisp | jscl-project_jscl/tests/iter-macros.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/iter-macros.lisp!")
;;; Tests for macros implementing iteration constructs
;;; DOTIMES
(test (let ((total 0))
(dotimes (n 6)
(incf total n))
(= total 15)))
;;; DOLIST
(test (let ((total 0))
(dolist (n '(1 2 3 4 5))
(incf total n))
(= total 15)))
;;; DO
(test (do ((a 0 b)
(b 1 (+ a b))
(n 0 (1+ n)))
((= n 10)
(= a 55))))
(test (= 5
(do (x) (t 5))))
(test (= 5
(do ((x)) (t 5))))
(test (= 5
(do ((x nil)) (t 5))))
(test (= 5
(do ((x nil nil)) (t 5))))
;;; DO*
(test (do* ((a 0 b)
(b 1 (+ a b))
(n 0 (1+ n)))
((= n 10)
(= a 512))))
(test (= 5
(do* (x) (t 5))))
(test (= 5
(do* ((x)) (t 5))))
(test (= 5
(do* ((x nil)) (t 5))))
(test (= 5
(do* ((x nil nil)) (t 5))))
;;; EOF
| 941 | Common Lisp | .lisp | 42 | 16.404762 | 54 | 0.379619 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 08711c87f3f623b9c6271bf0fab89a1849f5bd979bb79855121ae526db763169 | 77 | [
-1
] |
78 | misc.lisp | jscl-project_jscl/tests/misc.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/misc.lisp!")
;;; STEP macro
#+jscl
(test (= 4
(step (progn (setf x 5) (decf x)))))
;;; EOF
| 161 | Common Lisp | .lisp | 7 | 20.285714 | 45 | 0.549669 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 29bc44cf4ddd8fb40aabee73ec75353995bdb0ded157d24e6f3e36fc18349ccf | 78 | [
-1
] |
79 | defstruct.lisp | jscl-project_jscl/tests/defstruct.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/defstruct.lisp!")
(defun sbt-check-fn (sn)
(handler-case
(progn (fdefinition sn)
t)
(error (c) nil)))
(defun eql-vectors (v1 v2)
(and (= (length v1) (length v2))
(every #'identity
(mapcar (lambda (e1 e2) (equal e1 e2))
(jscl::vector-to-list v1)
(jscl::vector-to-list v2)))))
;;;
(defstruct (frob-01-list :named (:type list)
(:conc-name fl01-) (:predicate the-frob-01-list)) a b)
(test
(mv-eql
(let ((fnames (list 'fl01-a 'fl01-b 'make-frob-01-list 'the-frob-01-list 'copy-frob-01-list))
(ip (make-frob-01-list :a 1 :b 2))
(ip2 '(frob-01-list 1 2))
(ip3))
(values
(every #'identity (mapcar 'the-frob-01-list (list ip ip2)))
(every #'identity (mapcar 'sbt-check-fn fnames))
(equal ip ip2)
(equal (copy-frob-01-list ip) ip)
(equal (copy-frob-01-list ip) ip2)
(progn
(setf ip3 (copy-frob-01-list ip)
(fl01-a ip3) 'a)
(and (eql (fl01-a ip) 1) (eql (fl01-a ip3) 'a)))))
t t t t t t))
;;;
(defstruct (frob-01-vector :named (:type vector)
(:conc-name fv01-) (:predicate the-frob-01-vector)) a b)
(test
(mv-eql
(let ((fnames (list 'fv01-a 'fv01-b 'make-frob-01-vector 'the-frob-01-vector 'copy-frob-01-vector))
(ip (make-frob-01-vector :a 1 :b 2))
(ip2 (vector 'frob-01-vector 1 2))
(ip3))
#+nil
(format t "FROB VECTOR ~a"
(LIST
(every #'identity (mapcar 'the-frob-01-vector (list ip ip2)))
(every #'identity (mapcar 'sbt-check-fn fnames))
(eql-vectors ip ip2)
(eql-vectors (copy-frob-01-vector ip) ip)
(eql-vectors (copy-frob-01-vector ip) ip2)
(progn
(setf ip3 (copy-frob-01-vector ip)
(fv01-a ip3) 'a)
(and (eql (fv01-a ip) 1) (eql (fv01-a ip3) 'a)))))
(values
(every #'identity (mapcar 'the-frob-01-vector (list ip ip2)))
(every #'identity (mapcar 'sbt-check-fn fnames))
(eql-vectors ip ip2)
(eql-vectors (copy-frob-01-vector ip) ip)
(eql-vectors (copy-frob-01-vector ip) ip2)
(progn
(setf ip3 (copy-frob-01-vector ip)
(fv01-a ip3) 'a)
(and (eql (fv01-a ip) 1) (eql (fv01-a ip3) 'a)))))
t t t t t t))
;;;
(defstruct (frob-01-clos (:conc-name fc01-) (:predicate the-frob-01-clos)) a b)
(test
(mv-eql
(let* ((fnames (list 'fc01-a 'fc01-b 'make-frob-01-clos 'the-frob-01-clos 'copy-frob-01-clos))
(ip (make-frob-01-clos :a 1 :b 2))
(ip2 (copy-frob-01-clos ip))
(ip3 (copy-frob-01-clos ip2)))
(values
(every #'identity (mapcar 'the-frob-01-clos (list ip ip2 ip3)))
(every #'identity (mapcar 'sbt-check-fn fnames))
(progn
(setf (fc01-a ip3) 'a)
(and (eql (fc01-a ip) 1) (eql (fc01-a ip3) 'a)))))
t t t))
;;; constructors
(defstruct (sbt-01 (:type list)
:named
(:constructor sbt-01-con (&key ((:foo a)))))
a)
(test
(mv-eql
(values
(sbt-01-con)
(sbt-01-con :foo 1234))
(SBT-01 NIL)
(SBT-01 1234)))
;;;
(defstruct (sbt-02 (:type list)
:named
(:constructor sbt-02-con (&key ((:foo a) 32))))
a)
(test
(mv-eql
(values
(mapcar 'fboundp (list 'sbt-02-a 'sbt-02-p 'copy-sbt-02))
(sbt-02-con)
(sbt-02-con :foo 99)
(sbt-02-a (sbt-02-con :foo 1234)))
(t t t)
(SBT-02 32)
(SBT-02 99)
1234))
;;;
(defstruct (sbt-03 (:type list)
:named
(:constructor sbt-03-con
(&key (a 'p a-p)
((:x b) 'q)
(c 'r)
d
((:y e))
((:z f) 's z-p)
&aux (g (list (not a-p)
(not z-p))))))
a b c d e f g)
(defun sbt-check-fn (sn)
(handler-case
(progn (fdefinition sn)
t)
(error (c) nil)))
(test
(mv-eql
(values
(not (remove t
(mapcar 'sbt-check-fn
(list 'sbt-03-p 'copy-sbt-03
'sbt-03-a 'sbt-03-b 'sbt-03-c 'sbt-03-d
'sbt-03-e 'sbt-03-f 'sbt-03-g ))))
(sbt-03-con)
(sbt-03-con :a 'a :x 99)
(sbt-03-con :z 'yes))
t
(SBT-03 P Q R NIL NIL S (T T))
(SBT-03 A 99 R NIL NIL S (NIL T))
(SBT-03 P Q R NIL NIL YES (T NIL))))
;;;
(defstruct (sbt-04 (:type list)
:named
(:constructor sbt-04-con
(&optional (a 'p a-p) (b 'q b-p) (c 'r c-p)
&aux (d (list (not a-p)
(not b-p)
(not c-p))))))
a b c d)
(test
(mv-eql
(values
(sbt-04-con)
(sbt-04-con 1 2 3)
(sbt-04-con 1 2)
(sbt-04-con 1))
(SBT-04 P Q R (T T T))
(SBT-04 1 2 3 (NIL NIL NIL))
(SBT-04 1 2 R (NIL NIL T))
(SBT-04 1 Q R (NIL T T))))
;;;
(defstruct (sbt-05 (:type list)
:named
(:constructor sbt-05-con
(&optional (a 'p a-p) (b 'q b-p) (c 'r c-p))))
a b c d)
(test
(mv-eql
(values
(sbt-05-con)
(sbt-05-con 1 2 3))
(SBT-05 P Q R NIL)
(SBT-05 1 2 3 NIL)))
;;;
(defstruct (sbt-06 (:type list)
:named
(:constructor sbt-06-con (&optional (a 'p) (b 'q) (c 'r))))
(c 1) (b 2) (a 3))
(test
(mv-eql
(values
(sbt-06-con)
(sbt-06-con 'aa)
(sbt-06-con 'aa 'bb 'cc))
(SBT-06 R Q P)
(SBT-06 R Q AA)
(SBT-06 CC BB AA)))
;;;
(defstruct (sbt-07 (:type list)
:named
(:constructor sbt-07-con (a b &optional c)))
(c nil) b (a nil))
(test
(mv-eql
(values
(sbt-07-con 1 2)
(sbt-07-con t t))
(SBT-07 NIL 2 1)
(SBT-07 NIL T T)))
;;;
(defstruct (sbt-08 (:type list)
:named
(:constructor sbt-08-con (a b &optional c)))
c b a)
(test
(mv-eql
(values
(not (ignore-errors (sbt-08-con)))
(sbt-08-con 1 2)
(sbt-08-con 1 2 3))
T
(SBT-08 NIL 2 1)
(SBT-08 3 2 1)))
;;;
(defstruct (sbt-09 (:type list)
:named
(:constructor sbt-09-con-0 (a b c))
(:constructor sbt-09-con-1 (a b))
(:constructor sbt-09-con-2 ()))
(a 'x) (b 'y) (c 'z))
(test
(mv-eql
(values
(sbt-09-con-0 1 2 3)
(sbt-09-con-1 1 2 )
(sbt-09-con-2 ))
(SBT-09 1 2 3)
(SBT-09 1 2 Z)
(SBT-09 X Y Z)))
;;;
(defstruct (sbt-10 (:type list)
:named
(:constructor sbt-10-con (b a c)))
a b c)
(test
(equal (sbt-10-con 'b 'a 'c)
'(SBT-10 A B C)))
;;;
(defstruct (binop (:type list)
:named
(:initial-offset 2))
(operator '? :type symbol)
operand-1
operand-2)
(defstruct (annotated-binop (:type list)
:named
(:initial-offset 3)
(:include binop))
commutative associative identity)
(test
(mv-eql
(let ((p-binop (make-binop ))
(p-anno (make-annotated-binop :operator '*
:operand-1 'x
:operand-2 5
:commutative t
:associative t
:identity 1)))
(values
p-binop
p-anno
(binop-p p-binop)
(binop-p p-anno)
))
(NIL NIL BINOP ? NIL NIL)
(NIL NIL BINOP * X 5 NIL NIL NIL ANNOTATED-BINOP T T 1)
T
T))
;;;
(defstruct (sbt-null-list :named (:type list)))
(defstruct (sbt-null-list-kind :named (:type list) (:initial-offset 3) (:include sbt-null-list)))
(test
(mv-eql
(let ((instance '(sbt-null-list 1 2 3 sbt-null-list-kind)))
(values
(sbt-null-list-p instance)
(sbt-null-list-kind-p instance)))
t
t ))
;;;
(test
(= 6 (let ((e 0))
(dolist (form
'((defstruct (es :conc-name (:conc-name b1-)) x y)
(defstruct (es :copier :copier) x y)
(defstruct (es (:include) (:include)) x y)
(defstruct (es (:initial-offset 2) (:initial-offset nil)) x y)
(defstruct (es (:predicate nil) (:predicate foolp)) x y)
(defstruct (es (:type list) (:type vector)) x y)
(defstruct (es (:type (vector (or (eql s) integer))) :named) x y)
)
e)
(handler-case
(progn (macroexpand form))
(error (ignore) (incf e)))))))
;;;
(defstruct (a-named-struct-vector :named (:type vector)) a b c)
(defstruct (a-kid-struct-vector :named (:type vector) (:include a-named-struct-vector)) n)
;;; todo: bug:
(test
(mv-eql
(let ((par (make-a-named-struct-vector :b 6))
(kid (make-a-kid-struct-vector :n 5)))
(values
(a-named-struct-vector-p par)
(a-named-struct-vector-p kid)
;; bug: must be checked storage length
(not (a-kid-struct-vector-p par))
(a-kid-struct-vector-p kid)))
t t t t))
;;;
(defstruct (a-named-struct-list :named (:type list)) a b c)
(defstruct (a-kid-struct-list :named (:type list) (:include a-named-struct-list)) n)
(test
(mv-eql
(let ((par (make-a-named-struct-list :b 6))
(kid (make-a-kid-struct-list :n 5)))
#+nil(format t "KID-LIST ~a" (list
(a-named-struct-list-p par)
(a-named-struct-list-p kid)
(not (a-kid-struct-list-p par))
(a-kid-struct-list-p kid)))
(values
(a-named-struct-list-p par)
(a-named-struct-list-p kid)
(not (a-kid-struct-list-p par))
(a-kid-struct-list-p kid)))
t t t t))
;;;
(let ((x 0)) (defstruct lexical-default (a (incf x)))
(test (= (lexical-default-a (make-lexical-default))
x
1)))
(test (= (lexical-default-a (make-lexical-default)) 2))
(test (= (let ((x 10))
(lexical-default-a (make-lexical-default))) 3))
;;;
(defstruct defstruct-constant-slot-names t)
(test (= 3 (defstruct-constant-slot-names-t
(make-defstruct-constant-slot-names :t 3))))
;;;
#+nil
(defstruct flopsie a b c)
#+nil
(handler-case
(macroexpand '(defstruct (mopsie (:include flopsie (a 3) (z 9))) q))
(error (c)
(apply #'format nil
(simple-condition-format-control c)
(simple-condition-format-arguments c))))
;;; => "Malformed DEFSTRUCT :include option\n Bad name (Z 9).\n"
#+nil
(test
(let ((pos)(rez))
(setq pos
(search "Bad name (Z 9)"
(handler-case
(eval `(defstruct (mopsie (:include flopsie (a 3) (z 9))) q))
(error (c)
(setq rez
(apply #'format nil
(simple-condition-format-control c)
(simple-condition-format-arguments c)))))))
;; condition: structure flopsie not exists ???
(format t "POS ~a ~a" pos rez)
t))
;;;
(defstruct (boa-supplied-p.1 (:constructor make-boa-supplied-p.1
(&optional (bar t barp))))
bar
barp)
(test
(mv-eql
(let ((b1 (make-boa-supplied-p.1))
(b2 (make-boa-supplied-p.1 t)))
#+nil
(format t "BOA SUPPLIED ~a" (list
(eq t (boa-supplied-p.1-bar b1))
(eq t (boa-supplied-p.1-bar b2))
(eq nil (boa-supplied-p.1-barp b1))
(eq t (boa-supplied-p.1-barp b2))))
(values
(eq t (boa-supplied-p.1-bar b1))
(eq t (boa-supplied-p.1-bar b2))
(eq nil (boa-supplied-p.1-barp b1))
(eq t (boa-supplied-p.1-barp b2))))
t t t NIL))
;;;
(defstruct (boa-supplied-p.2 (:constructor make-boa-supplied-p.2
(&key (bar t barp))))
bar
barp)
(test
(mv-eql
(let ((b1 (make-boa-supplied-p.2))
(b2 (make-boa-supplied-p.2 :bar t)))
#+nil
(format t "BOA SUPPLIED-2 ~a" (list
(eq t (boa-supplied-p.2-bar b1))
(eq t (boa-supplied-p.2-bar b2))
(eq nil (boa-supplied-p.2-barp b1))
(eq t (boa-supplied-p.2-barp b2))))
(values
(eq t (boa-supplied-p.2-bar b1))
(eq t (boa-supplied-p.2-bar b2))
(eq nil (boa-supplied-p.2-barp b1))
;; must be t. nil its bug:
(eq t (boa-supplied-p.2-barp b2))))
t t t NIL))
;;;
(defstruct (list-struct (:type list) :named) a-slot)
(test (list-struct-p (make-list-struct)))
(test (not (list-struct-p nil)))
(test (not (list-struct-p 1)))
(defstruct (offset-list-struct (:type list) :named (:initial-offset 1)) a-slot)
(test (offset-list-struct-p (make-offset-list-struct)))
(test (not (offset-list-struct-p nil)))
(test (not (offset-list-struct-p 1)))
(test (not (offset-list-struct-p '(offset-list-struct))))
;;; error car called on non-list
(test (not (offset-list-struct-p '(offset-list-struct . 3))))
(defstruct (vector-struct (:type vector) :named) a-slot)
(test
(let* ((v (make-vector-struct))
(r (vector-struct-p v)))
#+nil(format t "VECTOR-STRUCT ~a ~a" v r)
r))
(test (vector-struct-p (make-vector-struct)))
(test (not (vector-struct-p nil)))
;;; error out of range
(test (not (vector-struct-p #())))
(defstruct (bug-332a (:type list) (:initial-offset 5) :named))
(defstruct (bug-332b (:type list) (:initial-offset 2) :named (:include bug-332a)))
;;; cons error
(test (not (bug-332b-p (list* nil nil nil nil nil 'foo73 nil 'tail))))
(test (not (bug-332b-p 873257)))
(test (not (bug-332b-p '(1 2 3 4 5 x 1 2 bug-332a))))
(test (bug-332b-p '(1 2 3 4 5 x 1 2 bug-332b)))
(defstruct (bug-332a-aux (:type vector)
(:initial-offset 5) :named))
(defstruct (bug-332b-aux (:type vector)
(:initial-offset 2) :named
(:include bug-332a-aux)))
(test (not (bug-332b-aux-p #(1 2 3 4 5 x 1 premature-end))))
(test (not (bug-332b-aux-p 873257)))
(test (not (bug-332b-aux-p #(1 2 3 4 5 x 1 2 bug-332a-aux))))
(test (bug-332b-aux-p #(1 2 3 4 5 x 1 2 bug-332b-aux)))
;;;
(defstruct (conc-name-syntax :conc-name) a-conc-name-slot)
(test (eq (a-conc-name-slot (make-conc-name-syntax :a-conc-name-slot 'y))
'y))
(defstruct (conc-name-syntax-1 (:conc-name "A-CONC-NAME-")) slot)
(test (eq (a-conc-name-slot (make-conc-name-syntax-1 :slot 'y))
'y))
;;;
(defpackage "DEFSTRUCT-TEST-SCRATCH")
(defstruct (conc-name-nil :conc-name)
defstruct-test-scratch::conc-name-nil-slot)
(test (= (defstruct-test-scratch::conc-name-nil-slot
(make-conc-name-nil :conc-name-nil-slot 1))
1))
(test
(not
(progn
(handler-case
(conc-name-nil-slot (make-conc-name-nil))
(error (c) nil)))))
(defstruct print-struct-test a b c)
(test
;; struct printing with only numbers
(string-equal
(format nil "~S" (make-print-struct-test :a 1 :b 2 :c 3))
"#S(JSCL::PRINT-STRUCT-TEST :A 1 :B 2 :C 3)"))
(test
;; struct printing with some strings in it
(string-equal
(format nil "~S" (make-print-struct-test :a "hello" :b "world" :c 3))
"#S(JSCL::PRINT-STRUCT-TEST :A \"hello\" :B \"world\" :C 3)"))
;;; EOF
| 15,512 | Common Lisp | .lisp | 480 | 24.414583 | 101 | 0.523781 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 3621d935ae2d27867b3e0eab66a458d01231fe5853dec20cc535ae5d4cae9dd3 | 79 | [
-1
] |
80 | validate.lisp | jscl-project_jscl/tests/loop/validate.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/loop/validate-tests.lisp!")
;;;>
;;;> Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute of Technology.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the M.I.T. copyright notice appear in all copies and that
;;;> both that copyright notice and this permission notice appear in
;;;> supporting documentation. The names "M.I.T." and "Massachusetts
;;;> Institute of Technology" may not be used in advertising or publicity
;;;> pertaining to distribution of the software without specific, written
;;;> prior permission. Notice must be given in supporting documentation that
;;;> copying distribution is by permission of M.I.T. M.I.T. makes no
;;;> representations about the suitability of this software for any purpose.
;;;> It is provided "as is" without express or implied warranty.
;;;>
;;;> Massachusetts Institute of Technology
;;;> 77 Massachusetts Avenue
;;;> Cambridge, Massachusetts 02139
;;;> United States of America
;;;> +1-617-253-1000
;;;>
;;;> Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics, Inc.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the Symbolics copyright notice appear in all copies and
;;;> that both that copyright notice and this permission notice appear in
;;;> supporting documentation. The name "Symbolics" may not be used in
;;;> advertising or publicity pertaining to distribution of the software
;;;> without specific, written prior permission. Notice must be given in
;;;> supporting documentation that copying distribution is by permission of
;;;> Symbolics. Symbolics makes no representations about the suitability of
;;;> this software for any purpose. It is provided "as is" without express
;;;> or implied warranty.
;;;>
;;;> Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
;;;> and Zetalisp are registered trademarks of Symbolics, Inc.
;;;>
;;;> Symbolics, Inc.
;;;> 8 New England Executive Park, East
;;;> Burlington, Massachusetts 01803
;;;> United States of America
;;;> +1-617-221-1000
(in-package :jscl/loop)
(defvar *slow-test*
nil)
;; (defvar *loop-lisp-package*
;; (let ((p (car (last (package-use-list (find-package 'jscl/loop))))))
;; (format t "~&assuming the ``lisp'' package used by loop is ~s.~@
;; if not, you must preset jscl/loop::*loop-lisp-package*.~%"
;; p)
;; p))
(defmacro test (short-desc lambda-list form &body params-and-answers)
`(test1 ,short-desc ',form ',lambda-list
#'(lambda ,lambda-list ,form)
',params-and-answers))
(defun test1 (short-desc form lambda-list interpreted params-and-answers)
(declare (ignore short-desc))
(dolist (pair params-and-answers)
(let ((params (first pair)) (answers (rest pair)) yow)
;; fixme:
(jscl::test
(cond
((equal (setq yow (multiple-value-list (apply interpreted params))) answers))
(t
(format t "interpreted loop form gave incorrect answer. ~%
bindings: ~s~%
form: ~s ~%
right: ~s ~%
wrong: ~s ~%"
(and params (mapcar #'list lambda-list params))
form answers yow)
nil))))))
#+nil
(unless (find-package 'extended-loop-test-package)
(let ((p (make-package 'extended-loop-test-package :use (list jscl/loop::*loop-lisp-package*))))
(shadowing-import 'symbolics-loop:loop p)
(use-package (find-package 'symbolics-loop) p)
p))
;;; FIXME: *package* should be bound for the file being compiled.
(in-package :cl)
;;; EOF
| 3,905 | Common Lisp | .lisp | 86 | 42.313953 | 98 | 0.688158 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 16d8ecb5e8b760e5af5c6c828fb98bfd92da52850a9c4cd6cc971c547697f5f8 | 80 | [
-1
] |
81 | extended-tests.lisp | jscl-project_jscl/tests/loop/extended-tests.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/loop/extended-tests.lisp!")
;;;>
;;;> Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute of Technology.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the M.I.T. copyright notice appear in all copies and that
;;;> both that copyright notice and this permission notice appear in
;;;> supporting documentation. The names "M.I.T." and "Massachusetts
;;;> Institute of Technology" may not be used in advertising or publicity
;;;> pertaining to distribution of the software without specific, written
;;;> prior permission. Notice must be given in supporting documentation that
;;;> copying distribution is by permission of M.I.T. M.I.T. makes no
;;;> representations about the suitability of this software for any purpose.
;;;> It is provided "as is" without express or implied warranty.
;;;>
;;;> Massachusetts Institute of Technology
;;;> 77 Massachusetts Avenue
;;;> Cambridge, Massachusetts 02139
;;;> United States of America
;;;> +1-617-253-1000
;;;>
;;;> Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics, Inc.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the Symbolics copyright notice appear in all copies and
;;;> that both that copyright notice and this permission notice appear in
;;;> supporting documentation. The name "Symbolics" may not be used in
;;;> advertising or publicity pertaining to distribution of the software
;;;> without specific, written prior permission. Notice must be given in
;;;> supporting documentation that copying distribution is by permission of
;;;> Symbolics. Symbolics makes no representations about the suitability of
;;;> this software for any purpose. It is provided "as is" without express
;;;> or implied warranty.
;;;>
;;;> Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
;;;> and Zetalisp are registered trademarks of Symbolics, Inc.
;;;>
;;;> Symbolics, Inc.
;;;> 8 New England Executive Park, East
;;;> Burlington, Massachusetts 01803
;;;> United States of America
;;;> +1-617-221-1000
(in-package 'extended-loop-test-package)
(test "simple named"
()
(loop named foo
thereis 'return-this-value
finally (return-from foo 'this-is-not-returned))
(() return-this-value))
(test "named / return clause"
()
(block nil
(1+ (loop named hieronymous
return 5)))
(() 6))
(test "named / return function"
()
(block nil
(1+ (loop named hieronymous
do (return 5))))
(() 6))
(test "named / return-from"
()
(block nil
(1+ (loop named hieronymous
do (return-from hieronymous 5))))
(() 6))
(define-loop-iteration-path cdrs 'loop-cdr-iteration-path
:alternate-names (cdr)
:inclusive-permitted t
:preposition-groups ((:of :in)))
(defun loop-cdr-iteration-path (var type preps &key inclusive)
(assert (and preps (null (cdr preps)) (member (caar preps) '(:in :of))))
(let ((val (second (first preps))))
(if (listp var)
(let ((listv (gensym)))
(if inclusive
`(((,listv ,val) (,var nil ,type))
nil
(atom ,listv) () () (,listv (cdr ,listv) ,var ,listv)
() () () (,var ,listv))
`(((,listv ,val) (,var nil ,type))
nil
(atom ,listv) () () (,listv (cdr ,listv) ,var ,listv))))
`(((,var ,val ,type)) nil
(atom ,var) (,var (cdr ,var)) () ()
,@(and inclusive '(() () () ()))))))
(test "sample iteration path"
(l)
(loop for x being the cdrs in l
collect x)
(((a b c d)) ((b c d) (c d) (d) ()))
((nil) ()))
(test "alternate syntax iteration path"
()
(loop for x being the cdrs of '(a b c d)
collect x)
(() ((b c d) (c d) (d) ())))
(test "inclusive iteration interation path"
(l)
(loop for x being l and its cdrs
collect x)
(((a b c d)) ((a b c d) (b c d) (c d) (d) ()))
((nil) (nil)))
;;; EOF
| 4,192 | Common Lisp | .lisp | 110 | 35.181818 | 90 | 0.661993 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | e7e485390dc360b03d19bbd8135f21e96a480f0c7a9541cfac2becb7455ba9fd | 81 | [
-1
] |
82 | base-tests.lisp | jscl-project_jscl/tests/loop/base-tests.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
(/debug "perform test/loop/base-tests.lisp!")
;;;>
;;;> Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute of Technology.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the M.I.T. copyright notice appear in all copies and that
;;;> both that copyright notice and this permission notice appear in
;;;> supporting documentation. The names "M.I.T." and "Massachusetts
;;;> Institute of Technology" may not be used in advertising or publicity
;;;> pertaining to distribution of the software without specific, written
;;;> prior permission. Notice must be given in supporting documentation that
;;;> copying distribution is by permission of M.I.T. M.I.T. makes no
;;;> representations about the suitability of this software for any purpose.
;;;> It is provided "as is" without express or implied warranty.
;;;>
;;;> Massachusetts Institute of Technology
;;;> 77 Massachusetts Avenue
;;;> Cambridge, Massachusetts 02139
;;;> United States of America
;;;> +1-617-253-1000
;;;>
;;;> Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics, Inc.
;;;> All Rights Reserved.
;;;>
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the Symbolics copyright notice appear in all copies and
;;;> that both that copyright notice and this permission notice appear in
;;;> supporting documentation. The name "Symbolics" may not be used in
;;;> advertising or publicity pertaining to distribution of the software
;;;> without specific, written prior permission. Notice must be given in
;;;> supporting documentation that copying distribution is by permission of
;;;> Symbolics. Symbolics makes no representations about the suitability of
;;;> this software for any purpose. It is provided "as is" without express
;;;> or implied warranty.
;;;>
;;;> Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
;;;> and Zetalisp are registered trademarks of Symbolics, Inc.
;;;>
;;;> Symbolics, Inc.
;;;> 8 New England Executive Park, East
;;;> Burlington, Massachusetts 01803
;;;> United States of America
;;;> +1-617-221-1000
(in-package :jscl/loop)
(test "from/=/collect"
()
(loop for x from 1 to 10
for y = nil then x
collect (list x y))
(() ((1 nil) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9) (10 10))))
(test "from/=/colllect/variable"
(lo hi)
(loop for x from lo to hi
for y = nil then x
collect (list x y))
((1 10) ((1 nil) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9) (10 10))))
(test "exercise loop-body flagvar"
(lo hi)
(loop for x from lo to hi
;; test flagvar stuff in loop-body
as z = (list x x x x x x x x x x x x x x x x x x x x x x x x x)
for y = nil then x
collect (list x y)
do (unless (equal z (list x x x x x x x x x x x x x x x x x x x x x x x x x))
(error "oops")))
((1 10) ((1 nil) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9) (10 10))))
(test "add fixnum dcl"
(lo hi)
(loop for x of-type fixnum from lo to hi
for y = nil then x
collect (list x y))
((1 10) ((1 nil) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9) (10 10))))
(test "add fixnum keyword"
(lo hi)
(loop for x fixnum from lo to hi
for y = nil then x
collect (list x y))
((1 10) ((1 nil) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9) (10 10))))
(test "simple parallel constant arguments"
()
(loop for x from 1 to 10 and y = nil then x
collect (list x y))
(() ((1 nil) (2 1) (3 2) (4 3) (5 4) (6 5) (7 6) (8 7) (9 8) (10 9))))
(test "simple parallel variable arguments"
(lo hi)
(loop for x from lo to hi and y = nil then x
collect (list x y))
((1 10) ((1 nil) (2 1) (3 2) (4 3) (5 4) (6 5) (7 6) (8 7) (9 8) (10 9))))
(test "as constant args"
()
(loop as i from 1 to 3
collect i)
(() (1 2 3)))
(test "as variable args"
(lo hi)
(loop as i from lo to hi
collect i)
((1 3) (1 2 3)))
(test "step downto constant args"
()
(loop for i from 10 downto 1 by 3
collect i)
(() (10 7 4 1)))
(test "step downto variable args constant step"
(hi lo)
(loop for i from hi downto lo by 3
collect i)
((10 1) (10 7 4 1)))
(test "step downto variable args"
(hi lo step)
(loop for i from hi downto lo by step
collect i)
((10 1 3) (10 7 4 1))
((10 2 3) (10 7 4))
((10 3 3) (10 7 4))
((10 4 3) (10 7 4))
((10 5 3) (10 7))
)
(test "step above variable args"
(hi lo step)
(loop for i from hi above lo by step
collect i)
((10 1 3) (10 7 4))
((10 2 3) (10 7 4))
((10 3 3) (10 7 4))
((10 4 3) (10 7))
)
(test "as below constant limit"
()
(loop as i below 3
collect i)
(() (0 1 2)))
(test "as below variable limit"
(limit)
(loop as i below limit
collect i)
((3) (0 1 2)))
(test "in constant list"
()
(loop for item in '(1 2 3)
collect item)
(() (1 2 3)))
(test "in variable list"
(l)
(loop for item in l collect item)
((nil) nil)
(((foo)) (foo)))
(test "in constant list with step"
()
(loop for item in '(1 2 3 4 5) by #'cddr
collect item)
(() (1 3 5)))
(test "in different constant list with step"
()
(loop for item in '(1 2 3 4) by #'cddr
collect item)
(() (1 3)))
(test "in variable list with step"
(l)
(loop for item in l by #'cddr
collect item)
(((1 2 3 4 5)) (1 3 5))
(((1 2 3 4)) (1 3)))
(test "in destructured typedeclared constant list"
()
(loop for (item . x) (t . fixnum) in '((a . 1) (b . 2) (c . 3))
unless (eq item 'b) sum x)
(() 4))
(test "in destructured type-declared variable list"
(l)
(loop for (item . x) (t . fixnum) in l
unless (eq item 'b) sum x)
((((a . 1) (b . 2) (c . 3))) 4))
(test "on constant list"
()
(loop for sublist on '(a b c d)
collect sublist)
(() ((a b c d) (b c d) (c d) (d))))
(test "on variable list"
(l)
(loop for sublist on l
collect sublist)
(((a b c d)) ((a b c d) (b c d) (c d) (d))))
(test "on destructured"
(l)
(loop for (item) on l
collect item)
(((a b c d)) (a b c d)))
(test "ON destructured (item) with step"
(l)
(loop for (item) on l by #'cddr
collect item)
(((a b c d)) (a c)))
(test "ON destructured (x y) with step"
(l)
(loop for (x y) on l by #'cddr
collect (cons x y))
(((a b c d)) ((a . b) (c . d))))
(test "ON destructured (x y . z) with step"
(l)
(loop for (x y . z) on l by #'cddr
collect (list x y z))
(((a b c d)) ((a b (c d)) (c d nil))))
(test "miscellaneous sequential iteration"
()
(loop for item = 1 then (+ item 10)
for iteration from 1 to 5
collect item)
(() (1 11 21 31 41)))
(test "ACROSS constant arg"
()
(loop for char across "foobar" collect char)
(() (#\f #\o #\o #\b #\a #\r)))
(test "ACROSS declared variable arg"
(s)
(loop for char of-type character across (the simple-string s) collect char)
(("foobar") (#\f #\o #\o #\b #\a #\r)))
(test "REPEAT sequencing, constant arg"
(l)
(loop repeat 3
for x in l
collect x)
((nil) nil)
(((1)) (1))
(((1 2)) (1 2))
(((1 2 3)) (1 2 3))
(((1 2 3 4)) (1 2 3)))
(test "REPEAT sequencing 2, constant arg"
(l)
(loop for x in l
repeat 3
collect x)
((nil) nil)
(((1)) (1))
(((1 2)) (1 2))
(((1 2 3)) (1 2 3))
(((1 2 3 4)) (1 2 3)))
(test "REPEAT sequencing, variable arg"
(n l)
(loop repeat n
for x in l
collect x)
((3 nil) nil)
((3 (1)) (1))
((3 (1 2)) (1 2))
((3 (1 2 3)) (1 2 3))
((3 (1 2 3 4)) (1 2 3)))
(test "REPEAT sequencing 2, variable arg"
(n l)
(loop for x in l
repeat n
collect x)
((3 nil) nil)
((3 (1)) (1))
((3 (1 2)) (1 2))
((3 (1 2 3)) (1 2 3))
((3 (1 2 3 4)) (1 2 3)))
(test "WHILE sequencing"
(stack)
(loop while stack
for item = (length stack) then (pop stack)
collect item)
(((a b c d e f)) (6 a b c d e f))
(((a)) (1 a))
((()) ()))
(test "WHILE sequencing 2"
()
(loop for i fixnum from 3
when (oddp i) collect i
while (< i 5))
(() (3 5)))
(test "simple always"
(n)
(loop for i from 0 to n
always (< i 11))
((10) t)
((11) nil))
(test "always runs epilogue"
(n)
(loop for i from 0 to n
always (< i 3)
finally (return 'overriding-value))
((5) nil)
((2) overriding-value))
(test "simple never"
(n)
(loop for i from n to (+ n 3)
never (> i 11))
((8) t)
((9) nil))
(test "never runs epilogue"
(n)
(loop for i from n to (+ n 3)
never (< i 3)
finally (return 'overriding-value))
((0) nil)
((3) overriding-value))
(defun oddsq (x)
(cond ((not (numberp x)) (error "not a number"))
((oddp x) (* x x))
(t nil)))
(test "simple thereis"
(l)
(loop for x in l
thereis (oddsq x))
(((1 2 3)) 1)
(((2 4 6)) nil)
(((2 4 6 7)) 49))
(test "thereis runs epilogue"
(l)
(loop for x in l
thereis (oddsq x)
finally (return 'overriding-value))
(((2 3 4)) 9)
(((2 4 6)) overriding-value))
(test "loop-finish"
()
(loop for i in '(1 2 3 stop-here 4 5 6)
when (symbolp i) do (loop-finish)
count i)
(() 3))
(test "count"
()
(loop for i in '(1 2 3 stop-here 4 5 6)
until (symbolp i)
count i)
(() 3))
(test "multiple collection"
(l)
(loop for x in l
collect x
collecting x
nconc (list x)
nconcing (list x)
append (list x)
appending (list x))
(((a b)) (a a a a a a b b b b b b)))
(test "nconc 1"
(l)
(loop for x in l
nconc (copy-list x))
((((a) (b c) () (d e))) (a b c d e)))
(test "more multiple collection"
()
(loop for name in '(fred sue alice joe june)
for kids in '((bob ken) () () (kris sunshine) ())
collect name
append kids)
(() (fred bob ken sue alice joe kris sunshine june)))
#+nil
(test "multiple collection with INTO"
()
(loop for name in '(fred sue alice joe june)
as age in '(22 26 19 20 10)
append (list name age) into name-and-age-list
counting name into name-count
sum age into total-age
finally (return (values (round total-age name-count)
name-and-age-list)))
(() 19 (fred 22 sue 26 alice 19 joe 20 june 10)))
(test "gratuitous multiple collection"
()
(loop for i in '(bird 3 4 turtle (1 . 4) horse cat)
when (symbolp i) collect i)
(() (bird turtle horse cat)))
(test "collection sequencing"
()
(loop for i from 1 to 10
if (oddp i) collect i)
(() (1 3 5 7 9)))
(test "more collecting into"
()
(loop for i in '(a b c d) by #'cddr
collect i into my-list
finally (return (values 'foo my-list 'bar)))
(() foo (a c) bar))
(test "append 1"
()
(loop for x in '((a) (b) ((c)))
append x)
(() (a b (c))))
(test "nconc 2"
()
(loop for i upfrom 0
as x in '(a b (c))
nconc (if (evenp i) (list x) nil))
(() (a (c))))
(test "count simple variable arg"
()
(loop for i in '(a b nil c nil d e)
count i)
(() 5))
(test "simple sum"
()
(loop for i fixnum in '(1 2 3 4 5)
sum i)
(() 15))
(test "sum fixnum keyword"
()
(loop for i fixnum in '(1 2 3 4 5)
sum i fixnum)
(() 15))
(test "sum fixnum declaration"
()
(loop for i fixnum in '(1 2 3 4 5)
summing i of-type fixnum)
(() 15))
#|| Too dangerous with floating point equality.
(test "sum floating point series"
(series)
(loop for v in series
sum (* 2.0 v))
(((1.2 4.3 5.7)) 22.4))
||#
(test "simple maximize"
()
(loop for i in '(2 1 5 3 4)
maximize i)
(() 5))
(test "simple minimize"
()
(loop for i in '(2 1 5 3 4)
minimize i)
(() 1))
#+nil
(test "maximize fixnum keyword"
(series)
(loop for v in series
maximizing (round v) fixnum)
(((1.2 4.3 5.7)) 6))
#+nil
(test "minimize into fixnum keyword"
(series)
(loop for v float in series
minimizing (round v) into result fixnum
finally (return result))
(((1.2 4.3 5.7)) 1))
#+nil
(test "mimimize declared fixnum"
(series)
(loop for v single-float in series
minimizing (round v) of-type fixnum)
(((1.2 4.3 5.7)) 1))
(test "sequential with"
()
(loop with a = 1
with b = (+ a 2)
with c = (+ b 3)
return (list a b c))
(() (1 3 6)))
(test "parallel with"
()
(loop with a = 1 and b = 2 and c = 3
return (list a b c))
(() (1 2 3)))
(test "parallel with 2"
(a b)
(loop with a = 1 and b = (+ a 2) and c = (+ b 3)
return (list a b c))
((5 10) (1 7 13)))
#+nil
(test "destructuring type-keyworded with"
()
(loop with (a b c d e f) (float integer short-float single-float double-float long-float)
return (list a b c d e f))
(() (0.f0 0 0.0s0 0.0f0 0.0d0 0.0l0)))
(test "single-type-keyword destructured WITH"
()
(loop with (a b c) float
return (list a b c))
(() (0.f0 0.f0 0.f0)))
(test "hairy conditional nesting"
()
(loop with gubbish
for i in '(1 2 3 4 5 6)
when (oddp i)
do (push i gubbish)
and collect i into odd-numbers
and do (push i gubbish)
else
collect i into even-numbers
finally (return (values odd-numbers even-numbers gubbish)))
(() (1 3 5) (2 4 6) (5 5 3 3 1 1)))
(test "collecting IT"
()
(loop for i in '(1 2 3 4 5 6)
when (and (> i 3) i)
collect it)
(() (4 5 6)))
(test "returning IT"
()
(loop for i in '(1 2 3 4 5 6)
when (and (> i 3) i)
return it)
(() 4))
(test "THEREIS 3"
()
(loop for i in '(1 2 3 4 5 6)
thereis (and (> i 3) i))
(() 4))
;; #+nil
;; (test "another multiple collection hairy conditional structure"
;; ()
;; (loop for i in `(,(1+ most-positive-fixnum) 1 2 buckle-my-shoe 3 4 shut-the-door (foo))
;; when (numberp i)
;; when (typep i 'bignum)
;; collect i into big-numbers
;; else
;; collect i into other-numbers
;; else
;; when (symbolp i)
;; collect i into symbol-list
;; else collect i into other-list
;; finally (return (list big-numbers other-numbers symbol-list other-list)))
;; (() ((#.(1+ most-positive-fixnum)) (1 2 3 4) (buckle-my-shoe shut-the-door) ((foo)))))
(test "more conditional structure"
()
(with-output-to-string (s)
(loop for x from 0 to 3
do (format s ":~d " x)
if (zerop (mod x 2))
do (princ " a" s)
and if (zerop (floor x 2))
do (princ " b" s)
end
and do (princ " c" s)))
(() ":0 a b c:1 :2 a c:3 "))
(test "more type-declared destructuring"
()
(loop for (a b c) (integer integer float) in '((1 2 4.0) (5 6 8.3) (8 9 10.4))
collect (list c b a))
(() ((4.0 2 1) (8.3 6 5) (10.4 9 8))))
(test "even more type-declared destructuring"
()
(loop for (a b c) float in '((1.0 2.0 4.0) (5.0 6.0 8.3) (8.0 9.0 10.4))
collect (list c b a))
(() ((4.0 2.0 1.0) (8.3 6.0 5.0) (10.4 9.0 8.0))))
#+nil
(test "hash-keys"
()
(let ((ht (make-hash-table :test #'equal)))
(loop for i from 0 below 10
do (loop for j from 0 below 10
do (setf (gethash (cons i j) ht) (cons (+ i j) (* i j)))))
(loop for (i . j) of-type (fixnum . fixnum) being the hash-keys of ht using (hash-value pair)
as (sum . product) of-type fixnum = pair
always (and (= (+ i j) sum) (= (* i j) product))
count t into count
finally (return (= count 100))))
(() t))
(in-package :cl)
;;; EOF
| 17,230 | Common Lisp | .lisp | 556 | 24.591727 | 101 | 0.524514 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | eb035be7c2e6fe82f9661406b47c1dc4cc6c879f56e10fc5f381b9fbb77d1594 | 82 | [
-1
] |
83 | repl.lisp | jscl-project_jscl/web/repl.lisp | ;;; -*- mode:lisp; coding:utf-8 -*-
;; JSCL is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; JSCL is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
(/debug "loading repl-web/repl.lisp!")
(defun %write-string (string &optional (escape t))
(if #j:jqconsole
(if escape
(#j:jqconsole:Write string "jqconsole-output")
(#j:jqconsole:Write string "jqconsole-output" ""))
(#j:console:log string)))
(defun load-history ()
(let ((raw (#j:localStorage:getItem "jqhist")))
(unless (js-null-p raw)
(#j:jqconsole:SetHistory (#j:JSON:parse raw)))))
(defun save-history ()
(#j:localStorage:setItem "jqhist" (#j:JSON:stringify (#j:jqconsole:GetHistory))))
;;; Decides wheater the input the user has entered is completed or we
;;; should accept one more line.
(defun %sexpr-complete (string)
(let ((i 0)
(stringp nil)
(comments nil)
(s (length string))
(depth 0))
(while (< i s)
(cond
(comments
(case (char string i)
(#\newline
(setq comments nil))))
(stringp
(case (char string i)
(#\\
(incf i))
(#\"
(setq stringp nil)
(decf depth))))
(t
(case (char string i)
(#\;
(setq comments t))
;; skip character literals
(#\\
(incf i))
(#\( (unless comments (incf depth)))
(#\) (unless comments (decf depth)))
(#\"
(incf depth)
(setq stringp t)))))
(incf i))
(if (<= depth 0)
nil
0)))
;;; decode error.msg object from (js-try)
(defun %map-js-object (job)
(mapcar (lambda (k) (list k (oget job k)))
(mapcar (lambda (x) (js-to-lisp x))
(vector-to-list (#j:Object:keys job)))))
(defun %console-terpri()
(#j:jqconsole:Write (string #\newline) "jqconsole-error"))
(defun errmsg-prefix ()
(#j:jqconsole:Write "ERROR: " "jqconsole-error"))
(defparameter +err-css+ "jqconsole-error")
(defgeneric display-condition (c &optional style newline))
(defmethod display-condition (c &optional (style +err-css+) ignore)
(errmsg-prefix)
(#j:jqconsole:Write
(format nil
"Unhandled error condition ~a~%" (class-name (class-of c)))
style))
(defmethod display-condition ((c type-error) &optional (style +err-css+) ignore)
(errmsg-prefix)
(#j:jqconsole:Write
(format nil
"Type error.~% ~a does not designate a ~a~%"
(type-error-datum c)
(type-error-expected-type c))
style))
(defmethod display-condition ((c simple-error) &optional (style +err-css+) (nl t))
(errmsg-prefix)
(#j:jqconsole:Write
(apply #'format nil
(simple-condition-format-control c)
(simple-condition-format-arguments c))
style)
(when nl (%console-terpri)))
(defun toplevel ()
(#j:jqconsole:RegisterMatching "(" ")" "parents")
(let ((prompt (format nil "~a> " (package-name *package*))))
(#j:jqconsole:Write prompt "jqconsole-prompt"))
(flet ((process-input (input)
;; Capture unhandled Javascript exceptions. We evaluate the
;; form and set successp to T. However, if a non-local exit
;; happens, we cancel it, so it is not propagated more.
(%js-try
;; Capture unhandled Lisp conditions.
(handler-case
(when (> (length input) 0)
(let* ((form (read-from-string input))
(results (multiple-value-list (eval-interactive form))))
(dolist (x results)
(#j:jqconsole:Write (format nil "~S~%" x) "jqconsole-return"))))
;; only error condition's
(error (condition) (display-condition condition)))
(catch (js-err)
(#j:console:log js-err)
(let ((message (or (oget js-err "message") (%map-js-object js-err) js-err)))
(#j:jqconsole:Write (format nil "ERROR[!]: ~a~%" message) "jqconsole-error"))))
(save-history)
(toplevel)))
(#j:jqconsole:Prompt t #'process-input #'%sexpr-complete)))
(defun web-init ()
(load-history)
(setq *standard-output*
(make-stream
:write-fn (lambda (string) (%write-string string))))
(welcome-message :html t)
(#j:window:addEventListener "load" (lambda (&rest args) (toplevel))))
(web-init)
;;; EOF
| 5,157 | Common Lisp | .lisp | 130 | 30.846154 | 95 | 0.575794 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 18781a8ad5d9f16495c2e333653301f8b3cd28a92e7e0368c5728184f471d3ca | 83 | [
-1
] |
84 | jscl.html | jscl-project_jscl/jscl.html | <!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<title>JSCL</title>
</head>
<body>
<div id="console"></div>
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
<script
src="jqconsole.min.js"
type="text/javascript"
charset="utf-8"
></script>
<script>
var jqconsole = $("#console").jqconsole("", "");
</script>
<script src="jscl.js" type="text/javascript"></script>
<script src="jscl-web.js" type="text/javascript"></script>
</body>
</html>
| 557 | Common Lisp | .cl | 21 | 22.095238 | 76 | 0.604478 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | efec69202cc9a029b21bb663def82a5e0ce5a0973c100147e1b0abe98e31bf1e | 84 | [
-1
] |
85 | jscl-worker.html | jscl-project_jscl/jscl-worker.html | <!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>JSCL</title>
</head>
<body>
<div id="console"></div>
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="jqconsole.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jscl-worker.js"></script>
</body>
</html>
| 371 | Common Lisp | .cl | 13 | 25.076923 | 83 | 0.642458 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 056d161e6c5864677860871d258db0df4c24fb373922e52755f1c451ba85fda7 | 85 | [
-1
] |
87 | jscl-worker.js | jscl-project_jscl/jscl-worker.js | /* This file, unlike the rest of the project is distributed under a permissive
* license, as it will be included in the generated code. */
/*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
"use strict";
const jqconsole = $("#console").jqconsole("", "");
if (
typeof navigator.serviceWorker !== "undefined" &&
typeof Worker !== "undefined"
) {
initialize().catch(() => {
jqconsole.Write("Could not connect to JSCL worker", "jqconsole-error");
});
} else {
jqconsole.Write("JSCL does not support this browser.", "jqconsole-error");
}
async function initialize() {
await navigator.serviceWorker.register("service-worker.js");
// KLUDGE: When a full-page reload happens (shift-reload),
// navigator.serviceWorker.controller will be null and the
// browser will completely bypass the service-worker, making
// impossible to provide synchronous input for the web
// worker. As a work around, we'll reload the page again to
// ensure the service worker is activated properly.
if (!navigator.serviceWorker.controller) {
window.location.reload(false);
return;
}
const response = await fetch("/__jscl", {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
command: "init"
})
});
const body = await response.json();
const sessionId = body.value;
navigator.serviceWorker.onmessage = event => {
handleServiceWorkerMessage(sessionId, event);
};
loadJSCLWorker(sessionId);
}
function loadJSCLWorker(sessionId) {
const jsclWorker = new Worker("jscl.js");
jsclWorker.onmessage = event => {
const { string, stringclass } = event.data;
jqconsole.Write(string, stringclass);
};
jsclWorker.postMessage({
command: "init",
sessionId
});
prompt();
}
class StreamBuffer {
constructor() {
this.buffer = "";
this.resolve = undefined;
}
push(input) {
this.buffer = this.buffer + input;
if (this.resolve) {
this.resolve();
this.resolve = undefined;
}
}
async read() {
if (this.buffer.length > 0) {
const value = this.buffer;
this.buffer = "";
return value;
} else {
await new Promise(resolve => {
if (this.resolve) {
throw new Error(`Concurrent reads on StreamBuffer are not supported`);
}
this.resolve = resolve;
});
return this.read();
}
}
}
const stdin = new StreamBuffer();
function handleServiceWorkerMessage(sessionId, event) {
const { command } = event.data;
switch (command) {
case "prompt":
{
return stdin.read().then(value => {
navigator.serviceWorker.controller.postMessage({
sessionId,
input: value
});
});
}
break;
}
}
function prompt() {
jqconsole.Prompt(true, input => {
stdin.push(input + "\n");
prompt();
});
}
| 3,934 | Common Lisp | .cl | 125 | 27.416 | 80 | 0.6875 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 7788113444b5d742b3e248b67b743bfc7e77dd2326231ff3f4cdbe6353af64e9 | 87 | [
-1
] |
89 | exclude | jscl-project_jscl/.git/info/exclude | # git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
| 240 | Common Lisp | .cl | 6 | 39 | 65 | 0.713675 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | dde5b661da58300d64b4d8bd8ec4703cb90e0714e2c90a0fa6a50d37e3848417 | 89 | [
-1
] |
94 | style.css | jscl-project_jscl/style.css | /* The console container element */
body { background-color: black; font-size: 16px; font-family: Courier; overflow: hidden; padding: 0 0 0 0;}
#console {
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
background-color:black;
}
.parents {
font-weight: bold;
}
/* The inner console element. */
.jqconsole {
padding: 10px;
}
/* The cursor. */
.jqconsole-cursor {
background-color: gray;
}
/* The cursor color when the console looses focus. */
.jqconsole-blurred .jqconsole-cursor {
background-color: #666;
}
/* The current prompt text color */
.jqconsole-prompt {
color: White;
}
/* The command history */
.jqconsole-old-prompt {
color: White;
font-weight: normal;
}
/* The text color when in input mode. */
.jqconsole-input {
color: White;
}
/* Previously entered input. */
.jqconsole-old-input {
color: White;
font-weight: normal;
}
/* The text color of the output. */
.jqconsole-output {
color: green;
}
.jqconsole-return, .jqconsole-header {
color: gray;
}
.jqconsole-error {
color: red;
}
| 1,090 | Common Lisp | .l | 53 | 18.075472 | 107 | 0.683752 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 6b27fa5983d7234aeb6e34e99728f8cf70191dcf97db0a6e4f98ce75c485dc10 | 94 | [
-1
] |
95 | .mailmap | jscl-project_jscl/.mailmap | David Vázquez <davazp@gmail.com> David Vazquez <davazp@gmail.com>
David Vázquez <davazp@gmail.com> David Vázquez Púa <davazp@gmail.com>
David Vázquez <davazp@gmail.com> David Vazquez Pua <davazp@gmail.com>
David Vázquez <davazp@gmail.com> David <davazp@debian>
David Vázquez <davazp@gmail.com> David Vázquez <davazp@Portatil.(none)>
David Vázquez <davazp@gmail.com> David Vázquez <davidv@eyecarepro.net>
David Vázquez <davazp@gmail.com> David Vazquez <Dvazquezpua@deloitte.nl>
David Vázquez <davazp@gmail.com> David Vazquez Pua <dvazquezpua@deloitte.nl>
Raimon Grau <raimonster@gmail.com> Raimon Grau <raimon@3scale.net>
Owen Rodley <owen.rodley@gmail.com> Strigoides <Strigoides@gmail.com>
Owen Rodley <owen.rodley@gmail.com> Owen Rodley <strigoides@gmail.com>
pnathan <pnathan@vandals.uidaho.edu> pdn <pnathan@vandals.uidaho.edu>
vlad-km <gm5461@gmail.com> <26150554+vlad-km@users.noreply.github.com>
| 916 | Common Lisp | .l | 13 | 68.461538 | 76 | 0.803371 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 47420f03cc1aedeb20fd7a22b3361160673daf0ea743c9b6d42ad1cafd946add | 95 | [
-1
] |
98 | tests.html | jscl-project_jscl/tests.html | <!doctype html>
<html>
<head>
</head>
<body>
<pre id="log"></pre>
<script>
var log = document.getElementById('log');
var console = {
log: function(msg){
log.appendChild ( document.createTextNode(msg + '\n') );
}
};
console.log('Running test suite...');
</script>
<script src="jscl.js" type="text/javascript"></script>
<script src="tests.js" type="text/javascript"></script>
</body>
</html>
| 470 | Common Lisp | .l | 19 | 19.526316 | 67 | 0.572062 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 6f9230ea536df355e1a828996c9cfdc640336e91087dd9f16bdba2a710a1c1a7 | 98 | [
-1
] |
101 | prelude.js | jscl-project_jscl/src/prelude.js | /* This file, unlike the rest of the project is distributed under a permissive
* license, as it will be included in the generated code. */
/*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
// This file is prepended to the result of compile jscl.lisp, and
// contain runtime code that jscl assumes to exist.
var t;
var nil;
var jscl = Object.create(null);
if (typeof module !== 'undefined')
module.exports = jscl;
else if (typeof self !== 'undefined')
self.jscl = jscl;
var internals = jscl.internals = Object.create(null);
internals.globalEval = function(code){
var geval = eval; // Just an indirect eval
var fn = geval('(function(values, internals){ "use strict"; ' + code + '; })');
return fn(internals.mv, internals);
};
internals.pv = function(x) {
return x==undefined? nil: x;
};
internals.mv = function(){
var r = [].slice.call(arguments);
r['multiple-value'] = true;
return r;
};
internals.forcemv = function(x) {
return typeof x == 'object' && x !== null && 'multiple-value' in x? x: internals.mv(x);
};
//
// Workaround the problems with `new` for arbitrary number of
// arguments. Some primitive constructors (like Date) differ if they
// are called as a function or as a constructor.
//
// https://github.com/jscl-project/jscl/pull/242#issuecomment-238923579
//
// Note that primitive constructors, if accessed with oget (e.g:
// #j:Date) will be converted into a Lisp function. We track the
// original function in the jscl_original property as we can't wrap
// the primitive constructor in a Lisp function or it will not work.
internals.newInstance = function(values, ct){
var args = Array.prototype.slice.call(arguments);
var newCt = ct.bind.apply(ct.jscl_original || ct, args.slice(1));
return new newCt();
};
// Workaround the problem with send NULL for async XHR
// BUG: future todo
//var reqXHRsendNull = function(req){
// req.send(null);
//};
// Workaround the problem with operator precedence
// ash
internals.Bitwise_ash_R = function (x, y) { return x >> y;};
internals.Bitwise_ash_L = function (x, y) { return x << y;};
// lognot
internals.Bitwise_not = function (x) {return ~x;};
// logior
internals.Bitwise_ior = function (x, y) {return x | y;};
// logxor
internals.Bitwise_xor = function (x, y) {return x ^ y;};
// logand
internals.Bitwise_and = function (x, y) { return x & y;};
// NOTE: Define VALUES to be MV for toplevel forms. It is because
// `eval' compiles the forms and execute the Javascript code at
// toplevel with `js-eval', so it is necessary to return multiple
// values from the eval function.
var values = internals.mv;
internals.checkArgsAtLeast = function(args, n){
if (args < n) throw 'too few arguments';
};
internals.checkArgsAtMost = function(args, n){
if (args > n) throw 'too many arguments';
};
internals.checkArgs = function(args, n){
internals.checkArgsAtLeast(args, n);
internals.checkArgsAtMost(args, n);
};
// Lists
internals.Cons = function (car, cdr) {
this.car = car;
this.cdr = cdr;
};
internals.car = function(x){
if (x === nil)
return nil;
else if (x instanceof internals.Cons)
return x.car;
else {
console.log(x);
throw new Error('CAR called on non-list argument');
}
};
internals.cdr = function(x){
if (x === nil)
return nil;
else if (x instanceof internals.Cons)
return x.cdr;
else
throw new Error('CDR called on non-list argument');
};
// Improper list constructor (like LIST*)
internals.QIList = function(){
if (arguments.length == 1)
return arguments[0];
else {
var i = arguments.length-1;
var r = arguments[i--];
for (; i>=0; i--){
r = new internals.Cons(arguments[i], r);
}
return r;
}
};
// Arithmetic
internals.handled_division = function (x, y) {
if (y == 0) throw "Division by zero";
return x/y;
};
// Chars and Strings
// Return a new Array of strings, each either length-1, or length-2 (a UTF-16 surrogate pair).
function codepoints (string) {
return string.split(/(?![\udc00-\udfff])/);
};
// Create and return a lisp string for the Javascript string STRING.
internals.make_lisp_string = function (string){
var array = codepoints(string);
array.stringp = 1;
return array;
};
internals.char_to_codepoint = function(ch) {
if (ch.length == 1) {
return ch.charCodeAt(0);
} else {
var xh = ch.charCodeAt(0) - 0xD800;
var xl = ch.charCodeAt(1) - 0xDC00;
return 0x10000 + (xh << 10) + (xl);
}
};
internals.char_from_codepoint = function(x) {
if (x <= 0xFFFF) {
return String.fromCharCode(x);
} else {
x -= 0x10000;
var xh = x >> 10;
var xl = x & 0x3FF;
return String.fromCharCode(0xD800 + xh) + String.fromCharCode(0xDC00 + xl);
}
};
// if a char (JS string) has the same number of codepoints after .toUpperCase(), return that, else the original.
internals.safe_char_upcase = function(x) {
var xu = x.toUpperCase();
if (codepoints(xu).length == 1) {
return xu;
} else {
return x;
}
};
internals.safe_char_downcase = function(x) {
var xl = x.toLowerCase();
if (codepoints(xl).length == 1) {
return xl;
} else {
return x;
}
};
internals.xstring = function(x){
if(typeof x === "number") return x.toString();
const hasFillPointer = typeof x.fillpointer === 'number'
const activechars = hasFillPointer? x.slice(0, x.fillpointer): x
return activechars.join('');
};
internals.lisp_to_js = function (x) {
if (typeof x == 'object' && x !== null && 'length' in x && x.stringp == 1)
return internals.xstring(x);
else if (x === t)
return true;
else if (x === nil)
return false;
else if (typeof x == 'function'){
// Trampoline calling the Lisp function
if("jscl_original" in x) {
return x.jscl_original
} else {
return( function(){
var args = Array.prototype.slice.call(arguments);
for (var i in args)
args[i] = internals.js_to_lisp(args[i]);
return internals.lisp_to_js(x.apply(this, [internals.pv].concat(args)));
});
}
}
else return x;
};
internals.js_to_lisp = function (x) {
if (typeof x == 'string')
return internals.make_lisp_string(x);
else if (x === true)
return t;
else if (x === false)
return nil;
else if (typeof x == 'function'){
// Trampoline calling the JS function
var trampoline = function(values){
var args = Array.prototype.slice.call(arguments, 1);
for (var i in args)
args[i] = internals.lisp_to_js(args[i]);
return values(internals.js_to_lisp(x.apply(this, args)));
};
trampoline.jscl_original = x;
return trampoline;
} else
return x;
};
// Non-local exits
internals.BlockNLX = function (id, values, name){
this.id = id;
this.values = values;
this.name = name;
};
internals.CatchNLX = function (id, values){
this.id = id;
this.values = values;
};
internals.TagNLX = function (id, label){
this.id = id;
this.label = label;
};
internals.isNLX = function(x){
var i = internals;
return x instanceof i.BlockNLX
|| x instanceof i.CatchNLX
|| x instanceof i.TagNLX;
};
// Packages & Symbols
var packages = jscl.packages = Object.create(null);
packages.JSCL = {
packageName: 'JSCL',
symbols: Object.create(null),
exports: Object.create(null),
use: nil
};
packages.CL = {
packageName: 'CL',
symbols: Object.create(null),
exports: Object.create(null),
use: nil
};
packages['COMMON-LISP'] = packages.CL;
packages.KEYWORD = {
packageName: 'KEYWORD',
symbols: Object.create(null),
exports: Object.create(null),
use: nil
};
jscl.CL = packages.CL.exports;
const UNBOUND = Symbol('UnboundFunction')
internals.makeUnboundFunction = function (symbol) {
const fn = ()=>{ throw new Error("Function '" + symbol.name + "' undefined");}
fn[UNBOUND] = true;
return fn;
};
internals.Symbol = function(name, package_name){
this.name = name;
this.package = package_name;
this.value = undefined;
this.fvalue = internals.makeUnboundFunction(this)
this.stack = [];
};
internals.symbolValue = function (symbol){
var value = symbol.value;
if (value === undefined){
throw new Error("Variable " + symbol.name + " is unbound.");
} else {
return value;
}
};
internals.fboundp = function (symbol) {
if (symbol instanceof internals.Symbol){
return !symbol.fvalue[UNBOUND]
} else {
throw new Error(`${symbol} is not a symbol`)
}
}
internals.symbolFunction = function (symbol){
var fn = symbol.fvalue;
if (fn[UNBOUND])
symbol.fvalue();
return fn;
};
internals.bindSpecialBindings = function (symbols, values, callback){
try {
symbols.forEach(function(s, i){
s.stack = s.stack || [];
s.stack.push(s.value);
s.value = values[i];
});
return callback();
} finally {
symbols.forEach(function(s, i){
s.value = s.stack.pop();
});
}
};
internals.intern = function (name, package_name){
package_name = package_name || "JSCL";
var lisp_package = packages[package_name];
if (!lisp_package)
throw "No package " + package_name;
var symbol = lisp_package.symbols[name];
if (!symbol)
symbol = lisp_package.symbols[name] = new internals.Symbol(name, lisp_package);
// Auto-export symbol if it is the KEYWORD package.
if (lisp_package === packages.KEYWORD)
lisp_package.exports[name] = symbol;
return symbol;
};
jscl.evaluateString = function(str) {
return eval_in_lisp(str);
}
/* execute all script tags with type of x-common-lisp */
var eval_in_lisp; // set in FFI.lisp
const commonLispScriptType = "text/x-common-lisp";
if (typeof window !== 'undefined' && window && window.addEventListener) {
window.addEventListener('DOMContentLoaded', function () {
return runCommonLispScripts();
}, false);
}
function runCommonLispScripts() {
var documentScripts = document.getElementsByTagName('script');
var scripts = [];
var script;
var progressivelyRunScripts = function(){
var script, i;
for (i = 0; i < scripts.length; i++) {
script = scripts[i];
if (script.loaded && !script.executed) {
script.executed = true;
eval_in_lisp('(progn ' + script.text + ')');
} else if (!script.loaded && !script.error) {
break;
}
}
}
var loadRemoteDocument = function (url, successCallback, errorCallback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback();
throw new Error('Could not load ' + url);
}
}
};
return xhr.send(null);
}
for(var i = 0; i < documentScripts.length; ++i) {
if(documentScripts[i].type != commonLispScriptType) {
continue;
}
if("src" in documentScripts[i]) {
script = {
executed: false,
error: false,
text: null,
loaded: false,
url: documentScripts[i].src
};
scripts.push(script);
loadRemoteDocument(
documentScripts[i].src,
function successCallback(content) {
script.loaded = true;
script.text = content;
progressivelyRunScripts();
}, function errorCallback(error) {
script.error = true;
progressivelyRunScripts();
});
} else {
scripts.push({
executed: false,
error: false,
text: documentScripts[i].innerHTML,
loaded: true,
url: null
});
}
}
progressivelyRunScripts();
}
// Node Readline
if (typeof module !== 'undefined' &&
typeof global !== 'undefined' &&
typeof phantom === 'undefined')
global.readline = require('readline');
| 13,387 | Common Lisp | .l | 421 | 27.166271 | 112 | 0.648168 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | ea19ef7aa6b95697f9d67612796502587b032934b54b38ccc06afe902ad3b53b | 101 | [
-1
] |
148 | release-latest.yml | jscl-project_jscl/.github/workflows/release-latest.yml | name: Release latest
on:
push:
branches: [master]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: "12.x"
- name: Install SBCL
run: sudo apt-get install sbcl
- name: Build JSCL
run: JSCL_VERSION=$(git rev-parse --short HEAD) ./make.sh
- name: Run tests
run: ./run-tests.sh
- name: Prepare dist directory
run: |
mkdir dist/
cp jscl.html dist/index.html
cp jscl.js jscl-web.js style.css dist/
cp tests.html tests.js dist/
cp jquery.js jqconsole.min.js dist/
- name: Deploy latest version 🚀
uses: JamesIves/github-pages-deploy-action@4.1.1
with:
branch: master
folder: dist
repository-name: jscl-project/jscl-project.github.io
ssh-key: ${{ secrets.DEPLOY_KEY }}
| 908 | Common Lisp | .l | 32 | 21.9375 | 63 | 0.624424 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 02bc7b28f2de156539c32285a9f14394889f3b0c6ac6386d99241f91b146a88e | 148 | [
-1
] |
149 | pull-request.yml | jscl-project_jscl/.github/workflows/pull-request.yml | name: Pipeline CI
on:
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: "12.x"
- name: Install SBCL
run: sudo apt-get install sbcl
- name: Build JSCL
run: ./make.sh
- name: Run tests
run: ./run-tests.sh
| 383 | Common Lisp | .l | 18 | 16.166667 | 36 | 0.612813 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | b5a9a84cd0d37e17f38b28db97d5a813091f70eecfd37fe33121f9cadc3f59b9 | 149 | [
-1
] |
150 | release.yml | jscl-project_jscl/.github/workflows/release.yml | name: Release NPM
on:
push:
tags:
- v*
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: "12.x"
- name: Install SBCL
run: sudo apt-get install sbcl
- name: Build JSCL
run: ./make.sh
- name: Run tests
run: ./run-tests.sh
- name: Prepare dist directory
run: |
mkdir dist/
cp jscl.html dist/index.html
cp jscl.js jscl-web.js style.css dist/
cp tests.html tests.js dist/
cp jquery.js jqconsole.min.js dist/
- uses: JS-DevTools/npm-publish@v1
with:
token: ${{ secrets.NPM_ACCESS_TOKEN }}
| 704 | Common Lisp | .l | 29 | 18.103448 | 46 | 0.596702 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 7240cf1b8bacdf4cd6aabafafb2536a6d6df44b180908a9bf103d1bc056f6bf7 | 150 | [
-1
] |
185 | update.sample | jscl-project_jscl/.git/hooks/update.sample | #!/bin/sh
#
# An example hook script to block unannotated tags from entering.
# Called by "git receive-pack" with arguments: refname sha1-old sha1-new
#
# To enable this hook, rename this file to "update".
#
# Config
# ------
# hooks.allowunannotated
# This boolean sets whether unannotated tags will be allowed into the
# repository. By default they won't be.
# hooks.allowdeletetag
# This boolean sets whether deleting tags will be allowed in the
# repository. By default they won't be.
# hooks.allowmodifytag
# This boolean sets whether a tag may be modified after creation. By default
# it won't be.
# hooks.allowdeletebranch
# This boolean sets whether deleting branches will be allowed in the
# repository. By default they won't be.
# hooks.denycreatebranch
# This boolean sets whether remotely creating branches will be denied
# in the repository. By default this is allowed.
#
# --- Command line
refname="$1"
oldrev="$2"
newrev="$3"
# --- Safety check
if [ -z "$GIT_DIR" ]; then
echo "Don't run this script from the command line." >&2
echo " (if you want, you could supply GIT_DIR then run" >&2
echo " $0 <ref> <oldrev> <newrev>)" >&2
exit 1
fi
if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
echo "usage: $0 <ref> <oldrev> <newrev>" >&2
exit 1
fi
# --- Config
allowunannotated=$(git config --type=bool hooks.allowunannotated)
allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch)
denycreatebranch=$(git config --type=bool hooks.denycreatebranch)
allowdeletetag=$(git config --type=bool hooks.allowdeletetag)
allowmodifytag=$(git config --type=bool hooks.allowmodifytag)
# check for no description
projectdesc=$(sed -e '1q' "$GIT_DIR/description")
case "$projectdesc" in
"Unnamed repository"* | "")
echo "*** Project description file hasn't been set" >&2
exit 1
;;
esac
# --- Check types
# if $newrev is 0000...0000, it's a commit to delete a ref.
zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
if [ "$newrev" = "$zero" ]; then
newrev_type=delete
else
newrev_type=$(git cat-file -t $newrev)
fi
case "$refname","$newrev_type" in
refs/tags/*,commit)
# un-annotated tag
short_refname=${refname##refs/tags/}
if [ "$allowunannotated" != "true" ]; then
echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2
echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2
exit 1
fi
;;
refs/tags/*,delete)
# delete tag
if [ "$allowdeletetag" != "true" ]; then
echo "*** Deleting a tag is not allowed in this repository" >&2
exit 1
fi
;;
refs/tags/*,tag)
# annotated tag
if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1
then
echo "*** Tag '$refname' already exists." >&2
echo "*** Modifying a tag is not allowed in this repository." >&2
exit 1
fi
;;
refs/heads/*,commit)
# branch
if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then
echo "*** Creating a branch is not allowed in this repository" >&2
exit 1
fi
;;
refs/heads/*,delete)
# delete branch
if [ "$allowdeletebranch" != "true" ]; then
echo "*** Deleting a branch is not allowed in this repository" >&2
exit 1
fi
;;
refs/remotes/*,commit)
# tracking branch
;;
refs/remotes/*,delete)
# delete tracking branch
if [ "$allowdeletebranch" != "true" ]; then
echo "*** Deleting a tracking branch is not allowed in this repository" >&2
exit 1
fi
;;
*)
# Anything else (is there anything else?)
echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2
exit 1
;;
esac
# --- Finished
exit 0
| 3,650 | Common Lisp | .l | 120 | 28.308333 | 89 | 0.688813 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 17fc81b270624cc28d3bc5f7c430756ca2dac0f8bb036de196b95b725941484c | 185 | [
-1
] |
186 | pre-receive.sample | jscl-project_jscl/.git/hooks/pre-receive.sample | #!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
echoback=*)
echo "echo from the pre-receive-hook: ${value#*=}" >&2
;;
reject)
exit 1
esac
i=$((i + 1))
done
fi
| 544 | Common Lisp | .l | 23 | 21.521739 | 72 | 0.686538 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | ebdc1c57483511ba783f182c5d4a8d6a1f281fb3cf6ccab53d0c5ab45ee85397 | 186 | [
-1
] |
187 | post-update.sample | jscl-project_jscl/.git/hooks/post-update.sample | #!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-update".
exec git update-server-info
| 189 | Common Lisp | .l | 7 | 25.857143 | 68 | 0.767956 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 7c08b02b17b1b91dab9f7741c1a001fa01a1dcf28ae996a9ce171fb98d6e07e9 | 187 | [
-1
] |
188 | pre-applypatch.sample | jscl-project_jscl/.git/hooks/pre-applypatch.sample | #!/bin/sh
#
# An example hook script to verify what is about to be committed
# by applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-applypatch".
. git-sh-setup
precommit="$(git rev-parse --git-path hooks/pre-commit)"
test -x "$precommit" && exec "$precommit" ${1+"$@"}
:
| 424 | Common Lisp | .l | 13 | 31.538462 | 64 | 0.731707 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | ed897b24eb631f2510727fc18ce3ef9f1d4fca91ec498b545d3c0ec2ebb28b9d | 188 | [
-1
] |
189 | fsmonitor-watchman.sample | jscl-project_jscl/.git/hooks/fsmonitor-watchman.sample | #!/usr/bin/perl
use strict;
use warnings;
use IPC::Open2;
# An example hook script to integrate Watchman
# (https://facebook.github.io/watchman/) with git to speed up detecting
# new and modified files.
#
# The hook is passed a version (currently 2) and last update token
# formatted as a string and outputs to stdout a new update token and
# all files that have been modified since the update token. Paths must
# be relative to the root of the working tree and separated by a single NUL.
#
# To enable this hook, rename this file to "query-watchman" and set
# 'git config core.fsmonitor .git/hooks/query-watchman'
#
my ($version, $last_update_token) = @ARGV;
# Uncomment for debugging
# print STDERR "$0 $version $last_update_token\n";
# Check the hook interface version
if ($version ne 2) {
die "Unsupported query-fsmonitor hook version '$version'.\n" .
"Falling back to scanning...\n";
}
my $git_work_tree = get_working_dir();
my $retry = 1;
my $json_pkg;
eval {
require JSON::XS;
$json_pkg = "JSON::XS";
1;
} or do {
require JSON::PP;
$json_pkg = "JSON::PP";
};
launch_watchman();
sub launch_watchman {
my $o = watchman_query();
if (is_work_tree_watched($o)) {
output_result($o->{clock}, @{$o->{files}});
}
}
sub output_result {
my ($clockid, @files) = @_;
# Uncomment for debugging watchman output
# open (my $fh, ">", ".git/watchman-output.out");
# binmode $fh, ":utf8";
# print $fh "$clockid\n@files\n";
# close $fh;
binmode STDOUT, ":utf8";
print $clockid;
print "\0";
local $, = "\0";
print @files;
}
sub watchman_clock {
my $response = qx/watchman clock "$git_work_tree"/;
die "Failed to get clock id on '$git_work_tree'.\n" .
"Falling back to scanning...\n" if $? != 0;
return $json_pkg->new->utf8->decode($response);
}
sub watchman_query {
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty')
or die "open2() failed: $!\n" .
"Falling back to scanning...\n";
# In the query expression below we're asking for names of files that
# changed since $last_update_token but not from the .git folder.
#
# To accomplish this, we're using the "since" generator to use the
# recency index to select candidate nodes and "fields" to limit the
# output to file names only. Then we're using the "expression" term to
# further constrain the results.
my $last_update_line = "";
if (substr($last_update_token, 0, 1) eq "c") {
$last_update_token = "\"$last_update_token\"";
$last_update_line = qq[\n"since": $last_update_token,];
}
my $query = <<" END";
["query", "$git_work_tree", {$last_update_line
"fields": ["name"],
"expression": ["not", ["dirname", ".git"]]
}]
END
# Uncomment for debugging the watchman query
# open (my $fh, ">", ".git/watchman-query.json");
# print $fh $query;
# close $fh;
print CHLD_IN $query;
close CHLD_IN;
my $response = do {local $/; <CHLD_OUT>};
# Uncomment for debugging the watch response
# open ($fh, ">", ".git/watchman-response.json");
# print $fh $response;
# close $fh;
die "Watchman: command returned no output.\n" .
"Falling back to scanning...\n" if $response eq "";
die "Watchman: command returned invalid output: $response\n" .
"Falling back to scanning...\n" unless $response =~ /^\{/;
return $json_pkg->new->utf8->decode($response);
}
sub is_work_tree_watched {
my ($output) = @_;
my $error = $output->{error};
if ($retry > 0 and $error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) {
$retry--;
my $response = qx/watchman watch "$git_work_tree"/;
die "Failed to make watchman watch '$git_work_tree'.\n" .
"Falling back to scanning...\n" if $? != 0;
$output = $json_pkg->new->utf8->decode($response);
$error = $output->{error};
die "Watchman: $error.\n" .
"Falling back to scanning...\n" if $error;
# Uncomment for debugging watchman output
# open (my $fh, ">", ".git/watchman-output.out");
# close $fh;
# Watchman will always return all files on the first query so
# return the fast "everything is dirty" flag to git and do the
# Watchman query just to get it over with now so we won't pay
# the cost in git to look up each individual file.
my $o = watchman_clock();
$error = $output->{error};
die "Watchman: $error.\n" .
"Falling back to scanning...\n" if $error;
output_result($o->{clock}, ("/"));
$last_update_token = $o->{clock};
eval { launch_watchman() };
return 0;
}
die "Watchman: $error.\n" .
"Falling back to scanning...\n" if $error;
return 1;
}
sub get_working_dir {
my $working_dir;
if ($^O =~ 'msys' || $^O =~ 'cygwin') {
$working_dir = Win32::GetCwd();
$working_dir =~ tr/\\/\//;
} else {
require Cwd;
$working_dir = Cwd::cwd();
}
return $working_dir;
}
| 4,726 | Common Lisp | .l | 143 | 30.804196 | 102 | 0.667838 | jscl-project/jscl | 882 | 108 | 90 | GPL-3.0 | 9/19/2024, 11:24:04 AM (Europe/Amsterdam) | 6dbaa492691af625070903ed16c5dd413bc108883ddf600be8b8350e2ab15ac6 | 189 | [
-1
] |