r3327: *** empty log message ***
[kmrcl.git] / genutils.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          gentils.lisp
6 ;;;; Purpose:       Main general utility functions for KMRCL package
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Apr 2000
9 ;;;;
10 ;;;; $Id: genutils.lisp,v 1.8 2002/11/07 04:07:02 kevin Exp $
11 ;;;;
12 ;;;; This file, part of KMRCL, is Copyright (c) 2002 by Kevin M. Rosenberg
13 ;;;;
14 ;;;; KMRCL users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
18
19
20 (in-package :kmrcl)
21 (declaim (optimize (speed 3) (safety 1) (compilation-speed 0) (debug 3)))
22
23 (defmacro bind-when ((bind-var boundForm) &body body)
24   `(let ((,bind-var ,boundForm))
25       (declare (ignore-if-unused ,bind-var))
26       (when ,bind-var
27         ,@body)))
28   
29 (defmacro bind-if ((bind-var boundForm) yup &optional nope)
30   `(let ((,bind-var ,boundForm))
31       (if ,bind-var
32          ,yup
33          ,nope)))
34
35 ;; Anaphoric macros
36
37 (defmacro aif (test then &optional else)
38   `(let ((it ,test))
39      (if it ,then ,else)))
40
41 (defmacro awhen (test-form &body body)
42   `(aif ,test-form
43         (progn ,@body)))
44
45 (defmacro awhile (expr &body body)
46   `(do ((it ,expr ,expr))
47        ((not it))
48      ,@body))
49
50 (defmacro aand (&rest args)
51   (cond ((null args) t)
52         ((null (cdr args)) (car args))
53         (t `(aif ,(car args) (aand ,@(cdr args))))))
54
55 (defmacro acond (&rest clauses)
56   (if (null clauses)
57       nil
58       (let ((cl1 (car clauses))
59             (sym (gensym)))
60         `(let ((,sym ,(car cl1)))
61            (if ,sym
62                (let ((it ,sym)) ,@(cdr cl1))
63                (acond ,@(cdr clauses)))))))
64
65 (defmacro alambda (parms &body body)
66   `(labels ((self ,parms ,@body))
67      #'self))
68
69
70 (defmacro aif2 (test &optional then else)
71   (let ((win (gensym)))
72     `(multiple-value-bind (it ,win) ,test
73        (if (or it ,win) ,then ,else))))
74
75 (defmacro awhen2 (test &body body)
76   `(aif2 ,test
77          (progn ,@body)))
78
79 (defmacro awhile2 (test &body body)
80   (let ((flag (gensym)))
81     `(let ((,flag t))
82        (while ,flag
83          (aif2 ,test
84                (progn ,@body)
85                (setq ,flag nil))))))
86
87 (defmacro acond2 (&rest clauses)
88   (if (null clauses)
89       nil
90       (let ((cl1 (car clauses))
91             (val (gensym))
92             (win (gensym)))
93         `(multiple-value-bind (,val ,win) ,(car cl1)
94            (if (or ,val ,win)
95                (let ((it ,val)) ,@(cdr cl1))
96                (acond2 ,@(cdr clauses)))))))
97
98
99 ;; Debugging 
100
101 (defmacro mac (expr)
102 "Expand a macro"
103   `(pprint (macroexpand-1 ',expr)))
104
105 (defmacro print-form-and-results (form)
106   `(format t "~&~A --> ~S~%" (write-to-string ',form) ,form))
107
108 (defun show (&optional (what :variables) (package *package*))
109   (ecase what
110     (:variables (show-variables package))
111     (:functions (show-functions package))))
112
113 (defun show-variables (package)
114   (do-symbols (s package)
115     (multiple-value-bind (sym status)
116         (find-symbol (symbol-name s) package)
117       (when (and (or (eq status :external)
118                      (eq status :internal))
119                  (boundp sym))
120         (format t "~&Symbol ~S~T -> ~S~%"
121                 sym
122                 (symbol-value sym))))))
123
124 (defun show-functions (package)
125   (do-symbols (s package)
126     (multiple-value-bind (sym status)
127         (find-symbol (symbol-name s) package)
128       (when (and (or (eq status :external)
129                      (eq status :internal))
130                  (fboundp sym))
131         (format t "~&Function ~S~T -> ~S~%"
132                 sym
133                 (symbol-function sym))))))
134
135 #+allegro
136 (ff:def-foreign-call (memory-status-dump "memory_status_dump")
137     ()
138   :strings-convert t)
139
140
141 ;; Ensure functions
142
143 (defmacro ensure-integer (obj)
144   "Ensure object is an integer. If it is a string, then parse it"
145   `(if (stringp ,obj)
146       (parse-integer ,obj)
147     ,obj))
148
149 ;; Lists
150
151 (defun mklist (obj)
152   "Make into list if atom"
153   (if (listp obj) obj (list obj)))
154
155 (defun filter (fn lst)
156   "Filter a list by function, eliminate elements where fn returns nil"
157   (let ((acc nil))
158     (dolist (x lst)
159       (let ((val (funcall fn x)))
160         (if val (push val acc))))
161     (nreverse acc)))
162
163
164 ;; Functions
165
166 (defun memo-proc (fn)
167   "Memoize results of call to fn, returns a closure with hash-table"
168   (let ((cache (make-hash-table :test #'equal)))
169     #'(lambda (&rest args)
170         (multiple-value-bind (val foundp) (gethash args cache)
171           (if foundp
172               val
173               (setf (gethash args cache) 
174                     (apply fn args)))))))
175
176 (defun memoize (fn-name)
177   (setf (fdefinition fn-name) (memo-proc (fdefinition fn-name))))
178
179 (defmacro defun-memo (fn args &body body)
180   "Define a memoized function"
181   `(memoize (defun ,fn ,args . ,body)))
182
183 (defmacro _f (op place &rest args)
184   (multiple-value-bind (vars forms var set access) 
185                        (get-setf-expansion place)
186     `(let* (,@(mapcar #'list vars forms)
187             (,(car var) (,op ,access ,@args)))
188        ,set)))
189
190 (defun compose (&rest fns)
191   (if fns
192       (let ((fn1 (car (last fns)))
193             (fns (butlast fns)))
194         #'(lambda (&rest args)
195             (reduce #'funcall fns 
196                     :from-end t
197                     :initial-value (apply fn1 args))))
198       #'identity))
199
200 ;;; Loop macros
201
202 (defmacro until (test &body body)
203   `(do ()
204        (,test)
205      ,@body))
206
207 (defmacro while (test &body body)
208   `(do ()
209        ((not ,test))
210      ,@body))
211
212 (defmacro for ((var start stop) &body body)
213   (let ((gstop (gensym)))
214     `(do ((,var ,start (1+ ,var))
215           (,gstop ,stop))
216          ((> ,var ,gstop))
217        ,@body)))
218
219 (defmacro with-each-stream-line ((var stream) &body body)
220   (let ((eof (gensym))
221         (strm (gensym)))
222     `(let ((,strm ,stream))
223        (do ((,var (read-line stream nil ,eof) (read-line stream nil ,eof)))
224            (eq ,var ,eof)
225          ,@body))))
226
227 (defmacro with-each-file-line ((var file) &body body)
228   (let ((stream (gensym)))
229     `(with-open-file (,stream file :direction :input)
230          (with-each-stream-line (,var ,stream)
231             ,@body))))
232
233                 
234 ;;; Keyword functions
235
236 (defun remove-keyword (key arglist)
237   (loop for sublist = arglist then rest until (null sublist)
238         for (elt arg . rest) = sublist
239         unless (eq key elt) append (list elt arg)))
240
241 (defun remove-keywords (key-names args)
242   (loop for ( name val ) on args by #'cddr
243         unless (member (symbol-name name) key-names 
244                        :key #'symbol-name :test 'equal)
245         append (list name val)))
246
247 (defmacro in (obj &rest choices)
248   (let ((insym (gensym)))
249     `(let ((,insym ,obj))
250        (or ,@(mapcar #'(lambda (c) `(eql ,insym ,c))
251                      choices)))))
252
253 (defmacro mean (&rest args)
254   `(/ (+ ,@args) ,(length args)))
255
256 (defmacro with-gensyms (syms &body body)
257   `(let ,(mapcar #'(lambda (s) `(,s (gensym)))
258           syms)
259      ,@body))
260
261
262 ;;; Mapping
263
264 (defun mapappend (fn list)
265   (apply #'append (mapcar fn list)))
266
267
268 (defun mapcar-append-string-nontailrec (func v)
269   "Concatenate results of mapcar lambda calls"  
270   (aif (car v)
271        (concatenate 'string (funcall func it)
272                     (mapcar-append-string-nontailrec func (cdr v)))
273        ""))
274
275
276 (defun mapcar-append-string (func v &optional (accum ""))
277   "Concatenate results of mapcar lambda calls"  
278   (aif (car v)
279        (mapcar-append-string 
280         func 
281         (cdr v) 
282         (concatenate 'string accum (funcall func it)))
283        accum))
284
285 (defun mapcar2-append-string-nontailrec (func la lb)
286   "Concatenate results of mapcar lambda call's over two lists"  
287   (let ((a (car la))
288         (b (car lb)))
289     (if (and a b)
290       (concatenate 'string (funcall func a b)
291                    (mapcar2-append-string-nontailrec func (cdr la) (cdr lb)))
292       "")))
293   
294 (defun mapcar2-append-string (func la lb &optional (accum ""))
295   "Concatenate results of mapcar lambda call's over two lists"  
296   (let ((a (car la))
297         (b (car lb)))
298     (if (and a b)
299         (mapcar2-append-string 
300          func 
301          (cdr la) 
302          (cdr lb)
303          (concatenate 'string accum (funcall func a b)))
304       accum)))
305   
306
307 ;;; Output
308
309 (defun indent-spaces (n &optional (stream *standard-output*))
310   "Indent n*2 spaces to output stream"
311   (when (numberp n)
312     (let ((fmt (format nil "~~~DT" (+ n n))))
313       (format stream fmt))))
314
315 (defun print-list (l &optional (output *standard-output*))
316   "Print a list to a stream"
317   (if (consp l)
318     (progn
319       (mapcar (lambda (x) (princ x output) (princ #\newline output)) l)
320       t)
321     nil))
322
323 (defun print-rows (rows &optional (ostrm *standard-output*))
324   "Print a list of list rows to a stream"  
325   (dolist (r rows)
326     (mapcar (lambda (a) (princ a ostrm) (princ #\space ostrm)) r)
327     (terpri ostrm)))
328
329
330 ;;; Symbol functions
331
332 (defmacro concat-symbol (&rest args)
333   `(intern (concatenate 'string ,@args)))
334
335 (defmacro concat-symbol-pkg (pkg &rest args)
336   `(intern (concatenate 'string ,@args) ,pkg))
337
338
339 ;;; IO
340
341
342 (defstruct buf
343   vec (start -1) (used -1) (new -1) (end -1))
344
345 (defun bref (buf n)
346   (svref (buf-vec buf)
347          (mod n (length (buf-vec buf)))))
348
349 (defun (setf bref) (val buf n)
350   (setf (svref (buf-vec buf)
351                (mod n (length (buf-vec buf))))
352         val))
353
354 (defun new-buf (len)
355   (make-buf :vec (make-array len)))
356
357 (defun buf-insert (x b)
358   (setf (bref b (incf (buf-end b))) x))
359
360 (defun buf-pop (b)
361   (prog1 
362     (bref b (incf (buf-start b)))
363     (setf (buf-used b) (buf-start b)
364           (buf-new  b) (buf-end   b))))
365
366 (defun buf-next (b)
367   (when (< (buf-used b) (buf-new b))
368     (bref b (incf (buf-used b)))))
369
370 (defun buf-reset (b)
371   (setf (buf-used b) (buf-start b)
372         (buf-new  b) (buf-end   b)))
373
374 (defun buf-clear (b)
375   (setf (buf-start b) -1 (buf-used  b) -1
376         (buf-new   b) -1 (buf-end   b) -1))
377
378 (defun buf-flush (b str)
379   (do ((i (1+ (buf-used b)) (1+ i)))
380       ((> i (buf-end b)))
381     (princ (bref b i) str)))
382
383
384 (defun file-subst (old new file1 file2)
385   (with-open-file (in file1 :direction :input)
386      (with-open-file (out file2 :direction :output
387                                 :if-exists :supersede)
388        (stream-subst old new in out))))
389
390 (defun stream-subst (old new in out)
391   (declare (string old new))
392   (let* ((pos 0)
393          (len (length old))
394          (buf (new-buf len))
395          (from-buf nil))
396     (declare (fixnum pos len))
397     (do ((c (read-char in nil :eof)
398             (or (setf from-buf (buf-next buf))
399                 (read-char in nil :eof))))
400         ((eql c :eof))
401       (declare (character c))
402       (cond ((char= c (char old pos))
403              (incf pos)
404              (cond ((= pos len)            ; 3
405                     (princ new out)
406                     (setf pos 0)
407                     (buf-clear buf))
408                    ((not from-buf)         ; 2
409                     (buf-insert c buf))))
410             ((zerop pos)                   ; 1
411              (princ c out)
412              (when from-buf
413                (buf-pop buf)
414                (buf-reset buf)))
415             (t                             ; 4
416              (unless from-buf
417                (buf-insert c buf))
418              (princ (buf-pop buf) out)
419              (buf-reset buf)
420              (setf pos 0))))
421     (buf-flush buf out)))
422
423
424 ;;; Tree Functions
425
426 (defun remove-tree-if (pred tree)
427   "Strip from tree of atoms that satistify predicate"
428   (if (atom tree)
429       (unless (funcall pred tree)
430         tree)
431     (let ((car-strip (remove-tree-if pred (car tree)))
432           (cdr-strip (remove-tree-if pred (cdr tree))))
433       (cond
434        ((and car-strip (atom (cadr tree)) (null cdr-strip))
435         (list car-strip))
436        ((and car-strip cdr-strip)
437         (cons car-strip cdr-strip))
438        (car-strip
439         car-strip)
440        (cdr-strip
441         cdr-strip)))))
442
443 (defun find-tree (sym tree)
444   "Finds an atom as a car in tree and returns cdr tree at that positions"
445   (if (or (null tree) (atom tree))
446       nil
447     (if (eql sym (car tree))
448         (cdr tree)
449       (aif (find-tree sym (car tree))
450           it
451         (aif (find-tree sym (cdr tree))
452             it
453           nil)))))
454
455 ;;; Files
456
457 (defun print-file-contents (file &optional (strm *standard-output*))
458   "Opens a reads a file. Returns the contents as a single string"
459   (when (probe-file file)
460     (with-open-file (in file :direction :input)
461       (let ((eof (gensym)))                 
462         (do ((line (read-line in nil eof) 
463                    (read-line in nil eof)))
464             ((eq line eof))
465           (format strm "~A~%" line))))))
466
467 (defun read-file-to-string (file)
468   "Opens a reads a file. Returns the contents as a single string"
469   (with-output-to-string (out)
470     (with-open-file (in file :direction :input)
471       (let ((eof (gensym)))                 
472         (do ((line (read-line in nil eof) 
473                    (read-line in nil eof)))
474             ((eq line eof))
475           (format out "~A~%" line))))))
476
477 (defun read-file-to-strings (file)
478   "Opens a reads a file. Returns the contents as a list of strings"
479   (let ((lines '()))
480     (with-open-file (in file :direction :input)
481       (let ((eof (gensym)))                 
482         (do ((line (read-line in nil eof) 
483                    (read-line in nil eof)))
484             ((eq line eof))
485           (push line lines)))
486       (nreverse lines))))
487
488
489 ;;; Formatting functions
490
491 (defun pretty-date (year month day &optional (hour 12) (m 0) (s 0))
492   (multiple-value-bind (sec min hr dy mn yr wkday)
493     (decode-universal-time
494      (encode-universal-time s m hour day month year))
495     (values (elt '("Monday" "Tuesday" "Wednesday" "Thursday"
496                    "Friday" "Saturday" "Sunday")
497                  wkday)
498             (elt '("January" "February" "March" "April" "May" "June"
499                    "July" "August" "September" "October" "November"
500                    "December")
501                  (1- mn))
502             (format nil "~A" dy) (format nil "~A" yr)
503             (format nil "~2,'0D:~2,'0D:~2,'0D" hr min sec))))
504
505
506 (defun date-string (ut)
507   (if (typep ut 'integer)
508       (multiple-value-bind (sec min hr day mon year dow daylight-p zone)
509           (decode-universal-time ut)
510         (declare (ignore daylight-p zone))
511         (format nil "~[Mon~;Tue~;Wed~;Thu~;Fri~;Sat~;Sun~], ~d ~[Jan~;Feb~;Mar~;Apr~;May~;Jun~;Jul~;Aug~;Sep~;Oct~;Nov~;Dec~] ~d ~2,'0d:~2,'0d:~2,'0d" 
512                 dow
513                 day
514                 (1- mon)
515                 year
516                 hr min sec))))
517