Merge pull request #108 from abeaumont/master
[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 (defun fboundp (x)
96   (fboundp x))
97
98 (defun eq (x y) (eq x y))
99 (defun eql (x y) (eq x y))
100
101 (defun not (x) (if x nil t))
102
103 ;; Basic macros
104 (defmacro incf (place &optional (delta 1))
105   (multiple-value-bind (dummies vals newval setter getter)
106       (get-setf-expansion place)
107     (let ((d (gensym)))
108       `(let* (,@(mapcar #'list dummies vals)
109               (,d ,delta)
110                 (,(car newval) (+ ,getter ,d))
111                 ,@(cdr newval))
112          ,setter))))
113
114 (defmacro decf (place &optional (delta 1))
115   (multiple-value-bind (dummies vals newval setter getter)
116       (get-setf-expansion place)
117     (let ((d (gensym)))
118       `(let* (,@(mapcar #'list dummies vals)
119               (,d ,delta)
120               (,(car newval) (- ,getter ,d))
121               ,@(cdr newval))
122          ,setter))))
123
124 (defmacro push (x place)
125   (multiple-value-bind (dummies vals newval setter getter)
126       (get-setf-expansion place)
127     (let ((g (gensym)))
128       `(let* ((,g ,x)
129               ,@(mapcar #'list dummies vals)
130               (,(car newval) (cons ,g ,getter))
131               ,@(cdr newval))
132          ,setter))))
133
134 (defmacro pushnew (x place &rest keys &key key test test-not)
135   (declare (ignore key test test-not))
136   (multiple-value-bind (dummies vals newval setter getter)
137       (get-setf-expansion place)
138     (let ((g (gensym))
139           (v (gensym)))
140       `(let* ((,g ,x)
141               ,@(mapcar #'list dummies vals)
142               ,@(cdr newval)
143               (,v ,getter))
144          (if (member ,g ,v ,@keys)
145              ,v
146              (let ((,(car newval) (cons ,g ,getter)))
147                ,setter))))))
148
149 (defmacro dolist ((var list &optional result) &body body)
150   (let ((g!list (gensym)))
151     (unless (symbolp var) (error "`~S' is not a symbol." var))
152     `(block nil
153        (let ((,g!list ,list)
154              (,var nil))
155          (%while ,g!list
156                  (setq ,var (car ,g!list))
157                  (tagbody ,@body)
158                  (setq ,g!list (cdr ,g!list)))
159          ,result))))
160
161 (defmacro dotimes ((var count &optional result) &body body)
162   (let ((g!count (gensym)))
163     (unless (symbolp var) (error "`~S' is not a symbol." var))
164     `(block nil
165        (let ((,var 0)
166              (,g!count ,count))
167          (%while (< ,var ,g!count)
168                  (tagbody ,@body)
169                  (incf ,var))
170          ,result))))
171
172 (defmacro cond (&rest clausules)
173   (unless (null clausules)
174     (destructuring-bind (condition &body body)
175         (first clausules)
176       (cond
177         ((eq condition t)
178          `(progn ,@body))
179         ((null body)
180          (let ((test-symbol (gensym)))
181            `(let ((,test-symbol ,condition))
182               (if ,test-symbol
183                   ,test-symbol
184                   (cond ,@(rest clausules))))))
185         (t
186          `(if ,condition
187               (progn ,@body)
188               (cond ,@(rest clausules))))))))
189
190 (defmacro case (form &rest clausules)
191   (let ((!form (gensym)))
192     `(let ((,!form ,form))
193        (cond
194          ,@(mapcar (lambda (clausule)
195                      (destructuring-bind (keys &body body)
196                          clausule
197                        (if (or (eq keys 't) (eq keys 'otherwise))
198                            `(t nil ,@body)
199                            (let ((keys (if (listp keys) keys (list keys))))
200                              `((or ,@(mapcar (lambda (key) `(eql ,!form ',key)) keys))
201                                nil ,@body)))))
202                    clausules)))))
203
204 (defmacro ecase (form &rest clausules)
205   (let ((g!form (gensym)))
206     `(let ((,g!form ,form))
207        (case ,g!form
208          ,@(append
209             clausules
210             `((t
211                (error "ECASE expression failed for the object `~S'." ,g!form))))))))
212
213 (defmacro and (&rest forms)
214   (cond
215     ((null forms)
216      t)
217     ((null (cdr forms))
218      (car forms))
219     (t
220      `(if ,(car forms)
221           (and ,@(cdr forms))
222           nil))))
223
224 (defmacro or (&rest forms)
225   (cond
226     ((null forms)
227      nil)
228     ((null (cdr forms))
229      (car forms))
230     (t
231      (let ((g (gensym)))
232        `(let ((,g ,(car forms)))
233           (if ,g ,g (or ,@(cdr forms))))))))
234
235 (defmacro prog1 (form &body body)
236   (let ((value (gensym)))
237     `(let ((,value ,form))
238        ,@body
239        ,value)))
240
241 (defmacro prog2 (form1 result &body body)
242   `(prog1 (progn ,form1 ,result) ,@body))
243
244 (defmacro prog (inits &rest body )
245   (multiple-value-bind (forms decls docstring) (parse-body body)
246     `(block nil
247        (let ,inits
248          ,@decls
249          (tagbody ,@forms)))))
250
251
252 ;;; Go on growing the Lisp language in Ecmalisp, with more high level
253 ;;; utilities as well as correct versions of other constructions.
254
255 (defun append-two (list1 list2)
256   (if (null list1)
257       list2
258       (cons (car list1)
259             (append (cdr list1) list2))))
260
261 (defun append (&rest lists)
262   (!reduce #'append-two lists nil))
263
264 (defun revappend (list1 list2)
265   (while list1
266     (push (car list1) list2)
267     (setq list1 (cdr list1)))
268   list2)
269
270 (defun reverse (list)
271   (revappend list '()))
272
273 (defmacro psetq (&rest pairs)
274   (let (;; For each pair, we store here a list of the form
275         ;; (VARIABLE GENSYM VALUE).
276         (assignments '()))
277     (while t
278       (cond
279         ((null pairs) (return))
280         ((null (cdr pairs))
281          (error "Odd paris in PSETQ"))
282         (t
283          (let ((variable (car pairs))
284                (value (cadr pairs)))
285            (push `(,variable ,(gensym) ,value)  assignments)
286            (setq pairs (cddr pairs))))))
287     (setq assignments (reverse assignments))
288     ;;
289     `(let ,(mapcar #'cdr assignments)
290        (setq ,@(!reduce #'append (mapcar #'butlast assignments) nil)))))
291
292 (defmacro do (varlist endlist &body body)
293   `(block nil
294      (let ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
295        (while t
296          (when ,(car endlist)
297            (return (progn ,@(cdr endlist))))
298          (tagbody ,@body)
299          (psetq
300           ,@(apply #'append
301                    (mapcar (lambda (v)
302                              (and (consp (cddr v))
303                                   (list (first v) (third v))))
304                            varlist)))))))
305
306 (defmacro do* (varlist endlist &body body)
307   `(block nil
308      (let* ,(mapcar (lambda (x) (list (first x) (second x))) varlist)
309        (while t
310          (when ,(car endlist)
311            (return (progn ,@(cdr endlist))))
312          (tagbody ,@body)
313          (setq
314           ,@(apply #'append
315                    (mapcar (lambda (v)
316                              (and (consp (cddr v))
317                                   (list (first v) (third v))))
318                            varlist)))))))
319
320 (defun list-length (list)
321   (let ((l 0))
322     (while (not (null list))
323       (incf l)
324       (setq list (cdr list)))
325     l))
326
327 (defun length (seq)
328   (cond
329     ((stringp seq)
330      (string-length seq))
331     ((arrayp seq)
332      (oget seq "length"))
333     ((listp seq)
334      (list-length seq))))
335
336 (defun concat-two (s1 s2)
337   (concat-two s1 s2))
338
339 (defmacro with-collect (&body body)
340   (let ((head (gensym))
341         (tail (gensym)))
342     `(let* ((,head (cons 'sentinel nil))
343             (,tail ,head))
344        (flet ((collect (x)
345                 (rplacd ,tail (cons x nil))
346                 (setq ,tail (cdr ,tail))
347                 x))
348          ,@body)
349        (cdr ,head))))
350
351
352 (defmacro loop (&body body)
353   `(while t ,@body))
354
355 (defun identity (x) x)
356
357 (defun complement (x)
358   (lambda (&rest args)
359     (not (apply x args))))
360
361 (defun constantly (x)
362   (lambda (&rest args)
363     x))
364
365 (defun code-char (x)
366   (code-char x))
367
368 (defun char-code (x)
369   (char-code x))
370
371 (defun char= (x y)
372   (eql x y))
373
374 (defun char< (x y)
375   (< (char-code x) (char-code y)))
376
377 (defun atom (x)
378   (not (consp x)))
379
380 (defun alpha-char-p (x)
381   (or (<= (char-code #\a) (char-code x) (char-code #\z))
382       (<= (char-code #\A) (char-code x) (char-code #\Z))))
383
384 (defun digit-char-p (x)
385   (if (and (<= (char-code #\0) (char-code x) (char-code #\9)))
386       (- (char-code x) (char-code #\0))
387       nil))
388
389 (defun digit-char (weight)
390   (and (<= 0 weight 9)
391        (char "0123456789" weight)))
392
393 (defun equal (x y)
394   (cond
395     ((eql x y) t)
396     ((consp x)
397      (and (consp y)
398           (equal (car x) (car y))
399           (equal (cdr x) (cdr y))))
400     ((stringp x)
401      (and (stringp y) (string= x y)))
402     (t nil)))
403
404 (defun fdefinition (x)
405   (cond
406     ((functionp x)
407      x)
408     ((symbolp x)
409      (symbol-function x))
410     (t
411      (error "Invalid function `~S'." x))))
412
413 (defun disassemble (function)
414   (write-line (lambda-code (fdefinition function)))
415   nil)
416
417 (defun documentation (x type)
418   "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
419   (ecase type
420     (function
421      (let ((func (fdefinition x)))
422        (oget func "docstring")))
423     (variable
424      (unless (symbolp x)
425        (error "The type of documentation `~S' is not a symbol." type))
426      (oget x "vardoc"))))
427
428 (defmacro multiple-value-bind (variables value-from &body body)
429   `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
430                           ,@body)
431      ,value-from))
432
433 (defmacro multiple-value-list (value-from)
434   `(multiple-value-call #'list ,value-from))
435
436
437 ;;; Generalized references (SETF)
438
439 (defvar *setf-expanders* nil)
440
441 (defun get-setf-expansion (place)
442   (if (symbolp place)
443       (let ((value (gensym)))
444         (values nil
445                 nil
446                 `(,value)
447                 `(setq ,place ,value)
448                 place))
449       (let ((place (!macroexpand-1 place)))
450         (let* ((access-fn (car place))
451                (expander (cdr (assoc access-fn *setf-expanders*))))
452           (when (null expander)
453             (error "Unknown generalized reference."))
454           (apply expander (cdr place))))))
455
456 (defmacro define-setf-expander (access-fn lambda-list &body body)
457   (unless (symbolp access-fn)
458     (error "ACCESS-FN `~S' must be a symbol." access-fn))
459   `(progn (push (cons ',access-fn (lambda ,lambda-list ,@body))
460                 *setf-expanders*)
461           ',access-fn))
462
463 (defmacro setf (&rest pairs)
464   (cond
465     ((null pairs)
466      nil)
467     ((null (cdr pairs))
468      (error "Odd number of arguments to setf."))
469     ((null (cddr pairs))
470      (let ((place (!macroexpand-1 (first pairs)))
471            (value (second pairs)))
472        (multiple-value-bind (vars vals store-vars writer-form)
473            (get-setf-expansion place)
474          ;; TODO: Optimize the expansion a little bit to avoid let*
475          ;; or multiple-value-bind when unnecesary.
476          `(let* ,(mapcar #'list vars vals)
477             (multiple-value-bind ,store-vars
478                 ,value
479               ,writer-form)))))
480     (t
481      `(progn
482         ,@(do ((pairs pairs (cddr pairs))
483                (result '() (cons `(setf ,(car pairs) ,(cadr pairs)) result)))
484               ((null pairs)
485                (reverse result)))))))
486
487 ;; Incorrect typecase, but used in NCONC.
488 (defmacro typecase (x &rest clausules)
489   (let ((value (gensym)))
490     `(let ((,value ,x))
491        (cond
492          ,@(mapcar (lambda (c)
493                      (if (eq (car c) t)
494                          `((t ,@(rest c)))
495                          `((,(ecase (car c)
496                                     (integer 'integerp)
497                                     (cons 'consp)
498                                     (symbol 'symbolp)
499                                     (array 'arrayp)
500                                     (string 'stringp)
501                                     (atom 'atom)
502                                     (null 'null))
503                              ,value)
504                            ,@(or (rest c)
505                                  (list nil)))))
506                    clausules)))))
507
508 (defmacro etypecase (x &rest clausules)
509   (let ((g!x (gensym)))
510     `(let ((,g!x ,x))
511        (typecase ,g!x
512          ,@clausules
513          (t (error "~X fell through etypeacase expression." ,g!x))))))
514
515 (defun notany (fn seq)
516   (not (some fn seq)))
517
518 (defconstant internal-time-units-per-second 1000) 
519
520 (defun get-internal-real-time ()
521   (get-internal-real-time))
522
523 (defun get-unix-time ()
524   (truncate (/ (get-internal-real-time) 1000)))
525
526 (defun get-universal-time ()
527   (+ (get-unix-time) 2208988800))
528
529 (defun concat (&rest strs)
530   (!reduce #'concat-two strs ""))
531
532 (defun values-list (list)
533   (values-array (list-to-vector list)))
534
535 (defun values (&rest args)
536   (values-list args))
537
538 (defun error (fmt &rest args)
539   (%throw (apply #'format nil fmt args)))