Move more code to sequence.lisp
[jscl.git] / src / boot.lisp
1 ;;; boot.lisp --- First forms to be cross compiled
2
3 ;; Copyright (C) 2012, 2013 David Vazquez
4 ;; Copyright (C) 2012 Raimon Grau
5
6 ;; JSCL is free software: you can redistribute it and/or
7 ;; modify it under the terms of the GNU General Public License as
8 ;; published by the Free Software Foundation, either version 3 of the
9 ;; License, or (at your option) any later version.
10 ;;
11 ;; JSCL is distributed in the hope that it will be useful, but
12 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ;; General Public License for more details.
15 ;;
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with JSCL.  If not, see <http://www.gnu.org/licenses/>.
18
19 ;;; This code is executed when JSCL compiles this file itself. The
20 ;;; compiler provides compilation of some special forms, as well as
21 ;;; funcalls and macroexpansion, but no functions. So, we define the
22 ;;; Lisp world from scratch. This code has to define enough language
23 ;;; to the compiler to be able to run.
24
25 (eval-when-compile
26   (let ((defmacro-macroexpander
27          '#'(lambda (form)
28               (destructuring-bind (name args &body body)
29                   form
30                 (let ((whole (gensym)))
31                   `(eval-when-compile
32                      (%compile-defmacro ',name
33                                         '#'(lambda (,whole)
34                                              (destructuring-bind ,args ,whole
35                                                ,@body)))))))))
36     (%compile-defmacro 'defmacro defmacro-macroexpander)))
37
38 (defmacro declaim (&rest decls)
39   `(eval-when-compile
40      ,@(mapcar (lambda (decl) `(!proclaim ',decl)) decls)))
41
42 (defmacro defconstant (name value &optional docstring)
43   `(progn
44      (declaim (special ,name))
45      (declaim (constant ,name))
46      (setq ,name ,value)
47      ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
48      ',name))
49
50 (defconstant t 't)
51 (defconstant nil 'nil)
52 (%js-vset "nil" nil)
53
54 (defmacro lambda (args &body body)
55   `(function (lambda ,args ,@body)))
56
57 (defmacro when (condition &body body)
58   `(if ,condition (progn ,@body) nil))
59
60 (defmacro unless (condition &body body)
61   `(if ,condition nil (progn ,@body)))
62
63 (defmacro defvar (name &optional (value nil value-p) docstring)
64   `(progn
65      (declaim (special ,name))
66      ,@(when value-p `((unless (boundp ',name) (setq ,name ,value))))
67      ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
68      ',name))
69
70 (defmacro defparameter (name value &optional docstring)
71   `(progn
72      (setq ,name ,value)
73      ,@(when (stringp docstring) `((oset ',name "vardoc" ,docstring)))
74      ',name))
75
76 (defmacro defun (name args &rest body)
77   `(progn
78      (fset ',name #'(named-lambda ,name ,args ,@body))
79      ',name))
80
81 (defmacro return (&optional value)
82   `(return-from nil ,value))
83
84 (defmacro while (condition &body body)
85   `(block nil (%while ,condition ,@body)))
86
87 (defvar *gensym-counter* 0)
88 (defun gensym (&optional (prefix "G"))
89   (setq *gensym-counter* (+ *gensym-counter* 1))
90   (make-symbol (concat-two prefix (integer-to-string *gensym-counter*))))
91
92 (defun boundp (x)
93   (boundp x))
94
95 ;; Basic functions
96 (defun = (x y) (= x y))
97 (defun * (x y) (* x y))
98 (defun / (x y) (/ x y))
99 (defun 1+ (x) (+ x 1))
100 (defun 1- (x) (- x 1))
101 (defun zerop (x) (= x 0))
102
103 (defun truncate (x &optional (y 1))
104   (floor (/ x y)))
105
106 (defun eql (x y) (eq x y))
107
108 (defun not (x) (if x nil t))
109
110 ;; Basic macros
111
112 (defmacro incf (place &optional (delta 1))
113   (multiple-value-bind (dummies vals newval setter getter)
114       (get-setf-expansion place)
115     (let ((d (gensym)))
116       `(let* (,@(mapcar #'list dummies vals)
117               (,d ,delta)
118                 (,(car newval) (+ ,getter ,d))
119                 ,@(cdr newval))
120          ,setter))))
121
122 (defmacro decf (place &optional (delta 1))
123   (multiple-value-bind (dummies vals newval setter getter)
124       (get-setf-expansion place)
125     (let ((d (gensym)))
126       `(let* (,@(mapcar #'list dummies vals)
127               (,d ,delta)
128               (,(car newval) (- ,getter ,d))
129               ,@(cdr newval))
130          ,setter))))
131
132 (defmacro push (x place)
133   (multiple-value-bind (dummies vals newval setter getter)
134       (get-setf-expansion place)
135     (let ((g (gensym)))
136       `(let* ((,g ,x)
137               ,@(mapcar #'list dummies vals)
138               (,(car newval) (cons ,g ,getter))
139               ,@(cdr newval))
140          ,setter))))
141
142 (defmacro dolist ((var list &optional result) &body body)
143   (let ((g!list (gensym)))
144     (unless (symbolp var) (error "`~S' is not a symbol." var))
145     `(block nil
146        (let ((,g!list ,list)
147              (,var nil))
148          (%while ,g!list
149                  (setq ,var (car ,g!list))
150                  (tagbody ,@body)
151                  (setq ,g!list (cdr ,g!list)))
152          ,result))))
153
154 (defmacro dotimes ((var count &optional result) &body body)
155   (let ((g!count (gensym)))
156     (unless (symbolp var) (error "`~S' is not a symbol." var))
157     `(block nil
158        (let ((,var 0)
159              (,g!count ,count))
160          (%while (< ,var ,g!count)
161                  (tagbody ,@body)
162                  (incf ,var))
163          ,result))))
164
165 (defmacro cond (&rest clausules)
166   (unless (null clausules)
167     (destructuring-bind (condition &body body)
168         (first clausules)
169       (cond
170         ((eq condition t)
171          `(progn ,@body))
172         ((null body)
173          (let ((test-symbol (gensym)))
174            `(let ((,test-symbol ,condition))
175               (if ,test-symbol
176                   ,test-symbol
177                   (cond ,@(rest clausules))))))
178         (t
179          `(if ,condition
180               (progn ,@body)
181               (cond ,@(rest clausules))))))))
182
183 (defmacro case (form &rest clausules)
184   (let ((!form (gensym)))
185     `(let ((,!form ,form))
186        (cond
187          ,@(mapcar (lambda (clausule)
188                      (destructuring-bind (keys &body body)
189                          clausule
190                        (if (or (eq keys 't) (eq keys 'otherwise))
191                            `(t nil ,@body)
192                            (let ((keys (if (listp keys) keys (list keys))))
193                              `((or ,@(mapcar (lambda (key) `(eql ,!form ',key)) keys))
194                                nil ,@body)))))
195                    clausules)))))
196
197 (defmacro ecase (form &rest clausules)
198   (let ((g!form (gensym)))
199     `(let ((,g!form ,form))
200        (case ,g!form
201          ,@(append
202             clausules
203             `((t
204                (error "ECASE expression failed for the object `~S'." ,g!form))))))))
205
206 (defmacro and (&rest forms)
207   (cond
208     ((null forms)
209      t)
210     ((null (cdr forms))
211      (car forms))
212     (t
213      `(if ,(car forms)
214           (and ,@(cdr forms))
215           nil))))
216
217 (defmacro or (&rest forms)
218   (cond
219     ((null forms)
220      nil)
221     ((null (cdr forms))
222      (car forms))
223     (t
224      (let ((g (gensym)))
225        `(let ((,g ,(car forms)))
226           (if ,g ,g (or ,@(cdr forms))))))))
227
228 (defmacro prog1 (form &body body)
229   (let ((value (gensym)))
230     `(let ((,value ,form))
231        ,@body
232        ,value)))
233
234 (defmacro prog2 (form1 result &body body)
235   `(prog1 (progn ,form1 ,result) ,@body))
236
237 (defmacro prog (inits &rest body )
238   (multiple-value-bind (forms decls docstring) (parse-body body)
239     `(block nil
240        (let ,inits
241          ,@decls
242          (tagbody ,@forms)))))
243
244
245 ;;; Go on growing the Lisp language in Ecmalisp, with more high level
246 ;;; utilities as well as correct versions of other constructions.
247
248 (defun + (&rest args)
249   (let ((r 0))
250     (dolist (x args r)
251       (incf r x))))
252
253 (defun - (x &rest others)
254   (if (null others)
255       (- x)
256       (let ((r x))
257         (dolist (y others r)
258           (decf r y)))))
259
260 (defun append-two (list1 list2)
261   (if (null list1)
262       list2
263       (cons (car list1)
264             (append (cdr list1) list2))))
265
266 (defun append (&rest lists)
267   (!reduce #'append-two lists nil))
268
269 (defun revappend (list1 list2)
270   (while list1
271     (push (car list1) list2)
272     (setq list1 (cdr list1)))
273   list2)
274
275 (defun reverse (list)
276   (revappend list '()))
277
278 (defmacro psetq (&rest pairs)
279   (let (;; For each pair, we store here a list of the form
280         ;; (VARIABLE GENSYM VALUE).
281         (assignments '()))
282     (while t
283       (cond
284         ((null pairs) (return))
285         ((null (cdr pairs))
286          (error "Odd paris in PSETQ"))
287         (t
288          (let ((variable (car pairs))
289                (value (cadr pairs)))
290            (push `(,variable ,(gensym) ,value)  assignments)
291            (setq pairs (cddr pairs))))))
292     (setq assignments (reverse assignments))
293     ;;
294     `(let ,(mapcar #'cdr assignments)
295        (setq ,@(!reduce #'append (mapcar #'butlast assignments) nil)))))
296
297 (defmacro do (varlist endlist &body body)
298   `(block nil
299      (let ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
300        (while t
301          (when ,(car endlist)
302            (return (progn ,@(cdr endlist))))
303          (tagbody ,@body)
304          (psetq
305           ,@(apply #'append
306                    (mapcar (lambda (v)
307                              (and (consp (cddr v))
308                                   (list (first v) (third v))))
309                            varlist)))))))
310
311 (defmacro do* (varlist endlist &body body)
312   `(block nil
313      (let* ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
314        (while t
315          (when ,(car endlist)
316            (return (progn ,@(cdr endlist))))
317          (tagbody ,@body)
318          (setq
319           ,@(apply #'append
320                    (mapcar (lambda (v)
321                              (and (consp (cddr v))
322                                   (list (first v) (third v))))
323                            varlist)))))))
324
325 (defun list-length (list)
326   (let ((l 0))
327     (while (not (null list))
328       (incf l)
329       (setq list (cdr list)))
330     l))
331
332 (defun length (seq)
333   (cond
334     ((stringp seq)
335      (string-length seq))
336     ((arrayp seq)
337      (oget seq "length"))
338     ((listp seq)
339      (list-length seq))))
340
341 (defun concat-two (s1 s2)
342   (concat-two s1 s2))
343
344 (defmacro with-collect (&body body)
345   (let ((head (gensym))
346         (tail (gensym)))
347     `(let* ((,head (cons 'sentinel nil))
348             (,tail ,head))
349        (flet ((collect (x)
350                 (rplacd ,tail (cons x nil))
351                 (setq ,tail (cdr ,tail))
352                 x))
353          ,@body)
354        (cdr ,head))))
355
356
357 (defmacro loop (&body body)
358   `(while t ,@body))
359
360 (defun identity (x) x)
361
362 (defun constantly (x)
363   (lambda (&rest args)
364     x))
365
366 (defun code-char (x)
367   (code-char x))
368
369 (defun char-code (x)
370   (char-code x))
371
372 (defun char= (x y)
373   (eql x y))
374
375 (defun integerp (x)
376   (and (numberp x) (= (floor x) x)))
377
378 (defun floatp (x)
379   (and (numberp x) (not (integerp x))))
380
381 (defun plusp (x) (< 0 x))
382 (defun minusp (x) (< x 0))
383
384 (defun atom (x)
385   (not (consp x)))
386
387 (defun alpha-char-p (x)
388   (or (<= (char-code #\a) (char-code x) (char-code #\z))
389       (<= (char-code #\Z) (char-code x) (char-code #\Z))))
390
391 (defun digit-char-p (x)
392   (if (and (<= (char-code #\0) (char-code x) (char-code #\9)))
393       (- (char-code x) (char-code #\0))
394       nil))
395
396 (defun digit-char (weight)
397   (and (<= 0 weight 9)
398        (char "0123456789" weight)))
399
400 (defun equal (x y)
401   (cond
402     ((eql x y) t)
403     ((consp x)
404      (and (consp y)
405           (equal (car x) (car y))
406           (equal (cdr x) (cdr y))))
407     ((stringp x)
408      (and (stringp y) (string= x y)))
409     (t nil)))
410
411 (defun fdefinition (x)
412   (cond
413     ((functionp x)
414      x)
415     ((symbolp x)
416      (symbol-function x))
417     (t
418      (error "Invalid function `~S'." x))))
419
420 (defun disassemble (function)
421   (write-line (lambda-code (fdefinition function)))
422   nil)
423
424 (defun documentation (x type)
425   "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
426   (ecase type
427     (function
428      (let ((func (fdefinition x)))
429        (oget func "docstring")))
430     (variable
431      (unless (symbolp x)
432        (error "The type of documentation `~S' is not a symbol." type))
433      (oget x "vardoc"))))
434
435 (defmacro multiple-value-bind (variables value-from &body body)
436   `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
437                           ,@body)
438      ,value-from))
439
440 (defmacro multiple-value-list (value-from)
441   `(multiple-value-call #'list ,value-from))
442
443
444 ;;; Generalized references (SETF)
445
446 (defvar *setf-expanders* nil)
447
448 (defun get-setf-expansion (place)
449   (if (symbolp place)
450       (let ((value (gensym)))
451         (values nil
452                 nil
453                 `(,value)
454                 `(setq ,place ,value)
455                 place))
456       (let ((place (!macroexpand-1 place)))
457         (let* ((access-fn (car place))
458                (expander (cdr (assoc access-fn *setf-expanders*))))
459           (when (null expander)
460             (error "Unknown generalized reference."))
461           (apply expander (cdr place))))))
462
463 (defmacro define-setf-expander (access-fn lambda-list &body body)
464   (unless (symbolp access-fn)
465     (error "ACCESS-FN `~S' must be a symbol." access-fn))
466   `(progn (push (cons ',access-fn (lambda ,lambda-list ,@body))
467                 *setf-expanders*)
468           ',access-fn))
469
470 (defmacro setf (&rest pairs)
471   (cond
472     ((null pairs)
473      nil)
474     ((null (cdr pairs))
475      (error "Odd number of arguments to setf."))
476     ((null (cddr pairs))
477      (let ((place (!macroexpand-1 (first pairs)))
478            (value (second pairs)))
479        (multiple-value-bind (vars vals store-vars writer-form)
480            (get-setf-expansion place)
481          ;; TODO: Optimize the expansion a little bit to avoid let*
482          ;; or multiple-value-bind when unnecesary.
483          `(let* ,(mapcar #'list vars vals)
484             (multiple-value-bind ,store-vars
485                 ,value
486               ,writer-form)))))
487     (t
488      `(progn
489         ,@(do ((pairs pairs (cddr pairs))
490                (result '() (cons `(setf ,(car pairs) ,(cadr pairs)) result)))
491               ((null pairs)
492                (reverse result)))))))
493
494 ;; Incorrect typecase, but used in NCONC.
495 (defmacro typecase (x &rest clausules)
496   (let ((value (gensym)))
497     `(let ((,value ,x))
498        (cond
499          ,@(mapcar (lambda (c)
500                      (if (eq (car c) t)
501                          `((t ,@(rest c)))
502                          `((,(ecase (car c)
503                                     (integer 'integerp)
504                                     (cons 'consp)
505                                     (symbol 'symbolp)
506                                     (array 'arrayp)
507                                     (string 'stringp)
508                                     (atom 'atom)
509                                     (null 'null))
510                              ,value)
511                            ,@(or (rest c)
512                                  (list nil)))))
513                    clausules)))))
514
515 (defmacro etypecase (x &rest clausules)
516   (let ((g!x (gensym)))
517     `(let ((,g!x ,x))
518        (typecase ,g!x
519          ,@clausules
520          (t (error "~X fell through etypeacase expression." ,g!x))))))
521
522 (defun notany (fn seq)
523   (not (some fn seq)))
524
525 (defconstant internal-time-units-per-second 1000) 
526
527 (defun get-internal-real-time ()
528   (get-internal-real-time))
529
530 (defun get-unix-time ()
531   (truncate (/ (get-internal-real-time) 1000)))
532
533 (defun get-universal-time ()
534   (+ (get-unix-time) 2208988800))
535
536 (defun concat (&rest strs)
537   (!reduce #'concat-two strs ""))
538
539 (defun values-list (list)
540   (values-array (list-to-vector list)))
541
542 (defun values (&rest args)
543   (values-list args))
544
545 (defun error (fmt &rest args)
546   (%throw (apply #'format nil fmt args)))
547