Datasets:

Modalities:
Tabular
Text
Formats:
parquet
DOI:
Libraries:
Datasets
Dask
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 ]
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
43
Edit dataset card