Move sequence functions 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 subseq (seq a &optional b)
401   (if b
402       (slice seq a b)
403       (slice seq a)))
404
405 (defmacro do-sequence (iteration &body body)
406   (let ((seq (gensym))
407         (index (gensym)))
408     `(let ((,seq ,(second iteration)))
409        (cond
410          ;; Strings
411          ((stringp ,seq)
412           (let ((,index 0))
413             (dotimes (,index (length ,seq))
414               (let ((,(first iteration)
415                      (char ,seq ,index)))
416                 ,@body))))
417          ;; Lists
418          ((listp ,seq)
419           (dolist (,(first iteration) ,seq)
420             ,@body))
421          (t
422           (error "type-error!"))))))
423
424 (defun equal (x y)
425   (cond
426     ((eql x y) t)
427     ((consp x)
428      (and (consp y)
429           (equal (car x) (car y))
430           (equal (cdr x) (cdr y))))
431     ((stringp x)
432      (and (stringp y) (string= x y)))
433     (t nil)))
434
435 (defun fdefinition (x)
436   (cond
437     ((functionp x)
438      x)
439     ((symbolp x)
440      (symbol-function x))
441     (t
442      (error "Invalid function `~S'." x))))
443
444 (defun disassemble (function)
445   (write-line (lambda-code (fdefinition function)))
446   nil)
447
448 (defun documentation (x type)
449   "Return the documentation of X. TYPE must be the symbol VARIABLE or FUNCTION."
450   (ecase type
451     (function
452      (let ((func (fdefinition x)))
453        (oget func "docstring")))
454     (variable
455      (unless (symbolp x)
456        (error "The type of documentation `~S' is not a symbol." type))
457      (oget x "vardoc"))))
458
459 (defmacro multiple-value-bind (variables value-from &body body)
460   `(multiple-value-call (lambda (&optional ,@variables &rest ,(gensym))
461                           ,@body)
462      ,value-from))
463
464 (defmacro multiple-value-list (value-from)
465   `(multiple-value-call #'list ,value-from))
466
467
468 ;;; Generalized references (SETF)
469
470 (defvar *setf-expanders* nil)
471
472 (defun get-setf-expansion (place)
473   (if (symbolp place)
474       (let ((value (gensym)))
475         (values nil
476                 nil
477                 `(,value)
478                 `(setq ,place ,value)
479                 place))
480       (let ((place (!macroexpand-1 place)))
481         (let* ((access-fn (car place))
482                (expander (cdr (assoc access-fn *setf-expanders*))))
483           (when (null expander)
484             (error "Unknown generalized reference."))
485           (apply expander (cdr place))))))
486
487 (defmacro define-setf-expander (access-fn lambda-list &body body)
488   (unless (symbolp access-fn)
489     (error "ACCESS-FN `~S' must be a symbol." access-fn))
490   `(progn (push (cons ',access-fn (lambda ,lambda-list ,@body))
491                 *setf-expanders*)
492           ',access-fn))
493
494 (defmacro setf (&rest pairs)
495   (cond
496     ((null pairs)
497      nil)
498     ((null (cdr pairs))
499      (error "Odd number of arguments to setf."))
500     ((null (cddr pairs))
501      (let ((place (!macroexpand-1 (first pairs)))
502            (value (second pairs)))
503        (multiple-value-bind (vars vals store-vars writer-form)
504            (get-setf-expansion place)
505          ;; TODO: Optimize the expansion a little bit to avoid let*
506          ;; or multiple-value-bind when unnecesary.
507          `(let* ,(mapcar #'list vars vals)
508             (multiple-value-bind ,store-vars
509                 ,value
510               ,writer-form)))))
511     (t
512      `(progn
513         ,@(do ((pairs pairs (cddr pairs))
514                (result '() (cons `(setf ,(car pairs) ,(cadr pairs)) result)))
515               ((null pairs)
516                (reverse result)))))))
517
518 ;; Incorrect typecase, but used in NCONC.
519 (defmacro typecase (x &rest clausules)
520   (let ((value (gensym)))
521     `(let ((,value ,x))
522        (cond
523          ,@(mapcar (lambda (c)
524                      (if (eq (car c) t)
525                          `((t ,@(rest c)))
526                          `((,(ecase (car c)
527                                     (integer 'integerp)
528                                     (cons 'consp)
529                                     (symbol 'symbolp)
530                                     (array 'arrayp)
531                                     (string 'stringp)
532                                     (atom 'atom)
533                                     (null 'null))
534                              ,value)
535                            ,@(or (rest c)
536                                  (list nil)))))
537                    clausules)))))
538
539 (defmacro etypecase (x &rest clausules)
540   (let ((g!x (gensym)))
541     `(let ((,g!x ,x))
542        (typecase ,g!x
543          ,@clausules
544          (t (error "~X fell through etypeacase expression." ,g!x))))))
545
546 (defun notany (fn seq)
547   (not (some fn seq)))
548
549 (defconstant internal-time-units-per-second 1000) 
550
551 (defun get-internal-real-time ()
552   (get-internal-real-time))
553
554 (defun get-unix-time ()
555   (truncate (/ (get-internal-real-time) 1000)))
556
557 (defun get-universal-time ()
558   (+ (get-unix-time) 2208988800))
559
560 (defun concat (&rest strs)
561   (!reduce #'concat-two strs ""))
562
563 (defun values-list (list)
564   (values-array (list-to-vector list)))
565
566 (defun values (&rest args)
567   (values-list args))
568
569 (defun error (fmt &rest args)
570   (%throw (apply #'format nil fmt args)))
571