bonus.stk 52.3 KB
Newer Older
eg's avatar
eg committed
1
;;;;
2
;;;; bonus.stk  -- Useful primitives not in R5RS
3
;;;;
4
;;;; Copyright © 2000-2018 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
5 6
;;;;
;;;;
eg's avatar
eg committed
7 8 9 10
;;;; This program 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 2 of the License, or
;;;; (at your option) any later version.
11
;;;;
eg's avatar
eg committed
12 13 14 15
;;;; This program 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.
16
;;;;
eg's avatar
eg committed
17 18
;;;; You should have received a copy of the GNU General Public License
;;;; along with this program; if not, write to the Free Software
19
;;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
eg's avatar
eg committed
20
;;;; USA.
21
;;;;
eg's avatar
eg committed
22 23
;;;;           Author: Erick Gallesio [eg@unice.fr]
;;;;    Creation date: 14-Jun-2000 17:24 (eg)
24
;;;; Last file update: 21-Sep-2018 09:47 (eg)
eg's avatar
eg committed
25 26 27
;;;;


28 29 30 31
;;;; Deprecated names
(define read-chars read-bytes)
(define read-chars! read-bytes!)

32

33 34 35 36
;;;; Aliases
(define display-shared display)


eg's avatar
eg committed
37 38 39 40 41
#|
<doc EXT gensym
 * (gensym)
 * (gensym prefix)
 *
42 43 44
 * Creates a new symbol. The print name of the generated symbol
 * consists of a prefix (which defaults to ,(q [G|])) followed by the decimal
 * representation of a number. If |prefix| is specified, it must be
eg's avatar
eg committed
45 46 47 48 49 50 51 52 53 54 55 56
 * either a string or a symbol.
 * @lisp
 * (gensym)        => @pipeG100@pipe
 * (gensym "foo-") => foo-101
 * (gensym 'foo-)  => foo-102
 * @end lisp
doc>
|#
(define gensym
  (let ((counter 0))
    (lambda (:optional (prefix "G"))
      (when (symbol? prefix)
57 58 59
        (set! prefix (symbol->string prefix))
        (unless (string? prefix)
          (error 'gensym "bad gensym prefix ~S" prefix)))
eg's avatar
eg committed
60 61
      (set! counter (+ counter 1))
      (string->uninterned-symbol (string-append prefix
62
                                                (number->string counter))))))
eg's avatar
eg committed
63 64 65 66 67 68


#|
<doc EXT remove remove!
 * (remove pred list)
 *
69 70
 * |Remove| returns |list| without the elements that satisfy predicate |pred|:
 * @l
eg's avatar
eg committed
71 72
 * The list is not disordered -- elements that appear in the result list occur
 * in the same order as they occur in the argument list. |Remove!| does the
73
 * same job than |remove| by physically modifying its |list| argument
eg's avatar
eg committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
 * @lisp
 * (remove even? '(0 7 8 8 43 -4)) => (7 43)
 * @end lisp
doc>
|#
(define (remove  pred l) (filter  (lambda (x) (not (pred x))) l))
(define (remove! pred l) (filter! (lambda (x) (not (pred x))) l))


#|
<doc EXT delete delete!
 * (delete  x list [=])
 * (delete! x list [=])
 *
 * |Delete| uses the comparison procedure |=|, which defaults to
 * |equal?|, to find all elements of |list| that are equal to |x|, and
 * deletes them from |list|. The dynamic order in which the various
 * applications of |=| are made is not specified.
92
 * @l
eg's avatar
eg committed
93 94
 * The list is not disordered -- elements that appear in the result
 * list occur in the same order as they occur in the argument list.
95
 * @l
eg's avatar
eg committed
96 97 98 99 100 101 102
 * The comparison procedure is used in this way: |(= x ei)|. That is,
 * |x| is always the first argument, and a list element is always the
 * second argument. The comparison procedure will be used to compare
 * each element of list exactly once; the order in which it is applied
 * to the various |ei| is not specified. Thus, one can reliably remove
 * all the numbers greater than five from a list with
 * @lisp
103
 * (delete 5 list <)
eg's avatar
eg committed
104
 * @end lisp
105 106 107 108
 *
 * |delete!| is the linear-update variant of |delete|. It is allowed,
 * but not required, to alter the cons cells in its argument |list| to
 * construct the result.
eg's avatar
eg committed
109 110
doc>
|#
111
(define (delete  x l :optional (comp equal?))
eg's avatar
eg committed
112 113
  (filter  (lambda (y) (not (comp x y))) l))

114
(define (delete! x l :optional (comp equal?))
eg's avatar
eg committed
115 116 117 118 119 120 121 122 123
  (filter! (lambda (y) (not (comp x y))) l))


#|
<doc EXT every
 * (every pred list1 list2 ...)
 *
 * |every| applies the predicate |pred| across the lists, returning true if
 * the predicate returns true on every application.
124
 * @l
eg's avatar
eg committed
125
 * If there are n list arguments |list1| ... |listn|, then |pred| must be
126 127
 * a procedure taking n arguments and returning a boolean result.
 * @l
eg's avatar
eg committed
128
 * |every| applies pred to the first elements of the |listi| parameters. If
129
 * this application returns false, every immediately returns |%f|.
eg's avatar
eg committed
130 131
 * Otherwise, it iterates, applying |pred| to the second elements of the |listi|
 * parameters, then the third, and so forth. The iteration stops when a
132
 * false value is produced or one of the lists runs out of values.
eg's avatar
eg committed
133
 * In the latter case, |every| returns the true value produced by its final
134 135 136 137 138
 * application of pred. The application of pred to the last element of the
 * lists is a tail call.
 * @l
 * If one of the |listi| has no elements, |every| simply returns |%t|.
 * @l
eg's avatar
eg committed
139
 * Like |any|, every's name does not end with a question mark -- this is to
140 141
 * indicate that it does not return a simple boolean (|%t| or |%f|), but a
 * general value.
eg's avatar
eg committed
142 143
doc>
|#
144
(define (every pred l . others)         ;; compatible with SRFI-1
eg's avatar
eg committed
145 146 147
  (if (null? others)
      ;; EVERY called with mono argument predicate
      (letrec ((every (lambda (l)
148 149 150 151
                        (if (null? l)
                            #t
                            (and (pred (car l)) (every (cdr l)))))))
        (every l))
eg's avatar
eg committed
152 153
      ;; General case
      (letrec ((every (lambda (l)
154 155 156 157 158
                        (if (memq '() l)
                            #t
                            (and (apply pred (map car l))
                                 (every (map cdr l)))))))
        (every (cons l others)))))
eg's avatar
eg committed
159 160 161 162 163 164

#|
<doc EXT any
 * (any pred list1 list2 ...)
 *
 * |any| applies the predicate across the lists, returning true if the
165 166
 * predicate returns true on any application.
 * @l
eg's avatar
eg committed
167
 * If there are n list arguments |list1| ... |listn|, then |pred| must be
168 169
 * a procedure taking n arguments.
 * @l
eg's avatar
eg committed
170 171 172 173
 * |any| applies |pred| to the first elements of the |listi| parameters. If
 * this application returns a true value, |any| immediately returns that value.
 * Otherwise, it iterates, applying |pred| to the second elements of the |listi|
 * parameters, then the third, and so forth. The iteration stops when a true
174 175 176 177 178 179 180
 * value is produced or one of the lists runs out of values; in the latter case,
 * any returns |%f|. The application of |pred| to the last element of the
 * lists is a tail call.
 * @l
 * Like every, |any|'s name does not end with a question mark -- this is
 * to indicate that it does not return a simple boolean (|%t| or |%f|), but
 * a general value.
eg's avatar
eg committed
181 182 183 184 185 186 187 188 189
 *
 * @lisp
 * (any integer? '(a 3 b 2.7))   => #t
 * (any integer? '(a 3.1 b 2.7)) => #f
 * (any < '(3 1 4 1 5)
 *        '(2 7 1 8 2))          => #t
 * @end lisp
doc>
|#
190
(define (any pred l . others)           ;; compatible with SRFI-1
eg's avatar
eg committed
191 192 193
  (if (null? others)
      ;; ANY called with mono argument predicate
      (letrec ((any (lambda (l)
194 195 196 197
                        (if (null? l)
                            #f
                            (or (pred (car l)) (any (cdr l)))))))
        (any l))
eg's avatar
eg committed
198 199
      ;; General case
      (letrec ((any (lambda (l)
200 201 202 203 204
                        (if (memq '() l)
                            #f
                            (or (apply pred (map car l))
                                 (any (map cdr l)))))))
        (any (cons l others)))))
205

eg's avatar
eg committed
206 207

;;;
208
;;; String Port functions
eg's avatar
eg committed
209 210 211 212 213 214 215 216
;;;
#|
<doc EXT call-with-input-string
 * (call-with-input-string string proc)
 *
 * behaves as |call-with-input-file| except that the port passed to |proc|
 * is the sting port obtained from |port|.
 * @lisp
217
 * (call-with-input-string "123 456"
eg's avatar
eg committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231
 *   (lambda (x)
 *      (let* ((n1 (read x))
 *             (n2 (read x)))
 *         (cons n1 n2))))          => (123 . 456)
 * @end lisp
doc>
|#

(define call-with-input-string (%call-with open-input-string))

#|
<doc EXT call-with-output-string
 * (call-with-output-string proc)
 *
232 233
 * |Proc| should be a procedure of one argument. |Call-with-output-string|
 * calls |proc| with a freshly opened output string port. The result of
eg's avatar
eg committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
 * this procedure is a string containing all the text that has been written
 * on the string port.
 * @lisp
 * (call-with-output-string
 *   (lambda (x) (write 123 x) (display "Hello" x))) => "123Hello"
 * @end lisp
doc>
|#
(define (call-with-output-string proc)
  (let ((port (open-output-string)))
    (proc port)
    (close-port port)
    (get-output-string port)))

;;;
249
;;; Virtual Port functions
eg's avatar
eg committed
250 251
;;;
(define (open-input-virtual :key (read-char #f) (ready? #f) (eof? #f) (close #f))
Erick Gallesio's avatar
Erick Gallesio committed
252
  (%open-input-virtual (vector read-char ready? eof? close)))
eg's avatar
eg committed
253 254 255


(define (open-output-virtual :key (write-char #f) (write-string #f)
256
                             (flush #f) (close #f))
eg's avatar
eg committed
257 258 259 260 261 262 263 264 265
  (%open-output-virtual (vector write-char write-string flush close)))



;;;;
;;;; String functions
;;;;

#|
266
<doc EXT read-from-string
eg's avatar
eg committed
267 268 269 270 271 272 273 274 275 276 277 278 279
 * (read-from-string str)
 *
 * Performs a read from the given |str|. If |str| is the empty string,
 * an end of file object is returned.
 *
 * @lisp
 * (read-from-string "123 456") => 123
 * (read-from-string "")        => an eof object
 * @end lisp
doc>
|#
(define (read-from-string s)
  (let* ((p    (open-input-string s))
280
         (expr (read p)))
eg's avatar
eg committed
281 282 283 284 285 286 287 288 289
    (close-port p)
    expr))

#|
<doc EXT eval-from-string
 * (eval-from-string str)
 * (eval-from-string str module)
 *
 * Read an expression from |str| and evaluates it with |eval|. If a |module|
290 291
 * is passed, the evaluation takes place in the environment of this module.
 * Otherwise, the evaluation takes place in the environment returned by
eg's avatar
eg committed
292 293 294 295 296 297 298 299 300 301 302
 * |current-module|.
 * @lisp
 * (define x 10)
 * (define-module M
 *   (define x 100))
 * (eval-from-string "(+ x x)")                   => 20
 * (eval-from-string "(+ x x)" (find-module 'M))  => 200
 * @end lisp
doc>
|#
(define (eval-from-string str :optional env)
303
  (eval (read-from-string str)
304
        env))
305 306


eg's avatar
eg committed
307 308 309 310 311 312 313


;;;;
;;;; System functions
;;;;

#|
314
<doc EXT argv
eg's avatar
eg committed
315 316
 * (argv)
 *
317
 * Returns a list of the arguments given on the shell command line. The
eg's avatar
eg committed
318 319 320
 * interpreter options are no included in the result
doc>
|#
321
(define (argv)
eg's avatar
eg committed
322 323 324 325 326 327 328 329 330 331 332 333
  (key-get *%program-args* :argv '()))

#|
<doc EXT program-name
 * (program-name)
 *
 * Returns the invocation name of the current program as a string.
doc>
|#
(define (program-name)
  (key-get *%program-args* :program-name))

334 335 336 337 338 339 340 341 342 343 344 345
#|
<doc R7RS command-line
 * (command-line)
 *
 * Returns the command line passed to the process as a list
 * of strings. The first string corresponds to the command
 * name.
doc>
|#
(define (command-line)
  (cons (key-get *%program-args* :program-name)
        (key-get *%program-args* :argv '())))
Erick Gallesio's avatar
.  
Erick Gallesio committed
346 347 348 349 350

#|
<doc EXT make-directories
 * (make-directories str)
 *
351 352
 * Create a directory with name |dir|. No error is signaled if |dir| already exists,
 * Parent directories of |dir| are created as needed.
Erick Gallesio's avatar
.  
Erick Gallesio committed
353 354 355 356 357 358 359 360
doc>
|#
(define (make-directories path)
  (let ((dir (dirname path)))
    (unless (file-is-directory? dir)
      (make-directories dir))
    (make-directory path)))

361 362 363 364 365

#|
<doc EXT ensure-directories-exist
 * (ensure-directories-exist path)
 *
366 367
 * Create a directory with name |dir| (and its parent directories if needed), if it
 * does not exist yet.
368 369 370 371 372 373
doc>
|#
(define (ensure-directories-exist path)
  (unless (file-is-directory? path)
    (make-directories path)))

eg's avatar
eg committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
;;;;
;;;; Hash-tables functions
;;;;

#|
<doc EXT make-hash-table
 * (make-hash-table)
 * (make-hash-table comparison)
 * (make-hash-table comparison hash)
 *
 * |Make-hash-table| admits three different forms.  The most general form
 * admit two arguments. The first argument is a comparison function which
 * determines how keys are compared; the second argument is a function which
 * computes a hash code for an object and returns the hash code as a non
 * negative integer. Objets with the same hash code are stored in an A-list
 * registered in the bucket corresponding to the key.
390 391
 * @l
 * If omitted,
eg's avatar
eg committed
392 393 394 395 396
 * ,(itemize
 * (item [|hash| defaults to the |hash-table-hash| procedure (see
 * ,(ref :mark "hash-table-hash")).])
 * (item [|comparison| defaults to the |eq?| procedure (see ,(ref :mark "eq?")).])
 * )
397
 * Consequently,
eg's avatar
eg committed
398 399 400 401 402 403 404
 * @lisp
 * (define h (make-hash-table))
 * @end lisp
 * is equivalent to
 * @lisp
 * (define h (make-hash-table eq? hash-table-hash))
 * @end lisp
405 406
 *
 * An interesting example is
eg's avatar
eg committed
407 408 409 410
 * @lisp
 * (define h (make-hash-table string-ci=? string-length))
 * @end lisp
 * which defines a new hash table which uses |string-ci=?| for
411 412
 * comparing keys. Here, we use the string-length as a (very simple)
 * hashing function. Of course, a function which gives a key depending
eg's avatar
eg committed
413 414 415 416 417
 * of the characters composing the string gives a better repartition
 * and should probably enhance performances. For instance, the following
 * call to |make-hash-table| should return a more efficient, even if
 * not perfect, hash table:
 * @lisp
418 419
 * (make-hash-table
 *    string-ci=?
eg's avatar
eg committed
420 421 422 423 424
 *    (lambda (s)
 *      (let ((len (string-length s)))
 *        (do ((h 0)  (i 0 (+ i 1)))
 *            ((= i len) h)
 *          (set! h
425
 *                (+ h (char->integer
eg's avatar
eg committed
426 427
 *                       (char-downcase (string-ref s i)))))))))
 * @end lisp
428
 *
eg's avatar
eg committed
429 430 431 432 433 434 435 436 437 438 439 440 441
 * ,(bold "Note:") Hash tables with a comparison function equal to |eq?| or
 * |string=?| are handled in an more efficient way (in fact, they don't use
 * the |hash-table-hash| function to speed up hash table retrievals).
doc>
|#
(define (make-hash-table :optional (comparison eq?) (hash-func hash-table-hash))
  (%make-hash-table comparison hash-func))


#|
<doc EXT hash-table->alist
 * (hash-table->alist hash)
 *
442
 * Returns an ``association list'' built from the entries in |hash|.
eg's avatar
eg committed
443 444
 * Each entry in |hash| will be represented as a pair whose |car| is the
 * entry's key and whose |cdr| is its value.
445
 * @l
eg's avatar
eg committed
446
 * ,(bold "Note:") the order of pairs in the resulting list is unspecified.
447
 * @lisp
eg's avatar
eg committed
448
 * (let ((h (make-hash-table)))
449
 *   (dotimes (i 5)
eg's avatar
eg committed
450
 *     (hash-table-set! h i (number->string i)))
451
 *   (hash-table->alist h))
eg's avatar
eg committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
 *        => ((3 . "3") (4 . "4") (0 . "0")
 *            (1 . "1") (2 . "2"))
 * @end lisp
doc>
|#
(define (hash-table->alist h)
  (hash-table-map h cons))

#|
<doc EXT alist->hash-table
 * (alist->hash-table alist)
 * (alist->hash-table alist comparison)
 * (alist->hash-table alist comparison hash)
 *
 * Returns hash-table built from the ``association list''
 * |alist|. This function maps the |car| of every element in |alist|
 * to the |cdr| of corresponding elements in |alist|. the |comparison| and
 * |hash| functions are interpreted as in |make-hash-table|. If some key
 * occurs multiple times in |alist|, the value in the first
471
 * association will take precedence over later ones.
eg's avatar
eg committed
472 473 474 475 476 477
 *
doc>
|#
(define (alist->hash-table lst :optional (comp eq?) (hash hash-table-hash))
  (let ((ht (make-hash-table comp hash)))
    (for-each (lambda (x)
478 479 480
                (if (not (hash-table-exists? ht (car x)))
                    (hash-table-set! ht (car x) (cdr x))))
              lst)
eg's avatar
eg committed
481 482 483 484
    ht))


#|
485
<doc EXT  hash-table-update!/default hash-table-update!
eg's avatar
eg committed
486 487 488 489 490 491 492
 * (hash-table-update! hash key update-fun thunk)
 * (hash-table-update!/default hash key update-fun default)
 *
 * Update the value associated to |key| in table |hash| if key is already in
 * table with the value |(update-fun current-value)|. If no value is
 * associated to |key|, a new entry in the table is first inserted
 * before updating it (this new entry being the result of calling |thunk|).
493
 * @l
eg's avatar
eg committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
 * Note that the expression
 * @lisp
 * (hash-table-update!/default hash key update-fun default)
 * @end lisp
 * is equivalent to
 * @lisp
 * (hash-table-update! hash key update-fun (lambda () default))
 * @end lisp
 *
 * @lisp
 * (let ((h   (make-hash-table))
 *       (1+  (lambda (n) (+ n 1))))
 *   (hash-table-update!/default h 'test 1+ 100)
 *   (hash-table-update!/default h 'test 1+)
 *   (hash-table-ref h 'test))             => 102
 * @end lisp
doc>
|#
(define (hash-table-update! hash key func :optional (thunk #f thunk?))
  (let ((value (if thunk?
514 515
                   (hash-table-ref hash key thunk)
                   (hash-table-ref hash key))))
eg's avatar
eg committed
516 517 518 519 520 521 522 523
    (hash-table-set! hash key (func value))))

(define (hash-table-update!/default hash key func default)
  (let ((value (hash-table-ref/default hash key default)))
    (hash-table-set! hash key (func value))))


#|
524
<doc EXT hash-table-values hash-table-keys
eg's avatar
eg committed
525 526 527
 * (hash-table-keys hash)
 * (hash-table-values hash)
 *
528
 * Returns the keys or the values of |hash|.
eg's avatar
eg committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
doc>
|#
(define (hash-table-keys ht)
  (hash-table-map ht (lambda (x y) x)))

(define (hash-table-values ht)
  (hash-table-map ht (lambda (x y) y)))

#|
<doc EXT hash-table-fold
 * (hash-table-fold hash func init-value)
 *
 * This procedure calls |func| for every association in |hash|
 * with three arguments: the key of the association key, the value
 * of the association value, and an accumulated value, |val|. |Val| is
 * init-value for the first invocation of |func|, and for subsequent
 * invocations of |func|, the return value of the previous invocation of
 * |func|. The value |final-value| returned by |hash-table-fold| is the
 * return value of the last invocation of |func|. The order in which |func| is
 * called for different associations is unspecified.
549
 * @l
eg's avatar
eg committed
550 551 552 553 554 555 556 557
 * For instance, the following expression
 * @lisp
 * (hash-table-fold ht (lambda (k v acc) (+ acc 1)) 0)
 * @end lisp
 * computes the number of associations present in the |ht| hash table.
doc>
|#
(define (hash-table-fold ht func val)
558
  (hash-table-for-each ht
559 560
                       (lambda (key value)
                         (set! val (func key value val))))
eg's avatar
eg committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
  val)

#|
<doc EXT hash-table-merge!
 * (hash-table-merge! hash1 hash2)
 *
 * Adds all mappings in |hash2| into |hash1| and returns the resulting
 * hash table. This function may modify |hash1| destructively.
doc>
|#
(define (hash-table-merge! ht1 ht2)
  (hash-table-for-each ht2 (lambda (key val) (hash-table-set! ht1 key val)))
  ht1)


#|
<doc EXT hash-table-copy
 * (hash-table-copy hash)
 *
 * Returns a copy of |hash|.
doc>
|#
(define (hash-table-copy ht)
  (let ((new (make-hash-table (hash-table-equivalence-function ht)
585
                              (hash-table-hash-function ht))))
eg's avatar
eg committed
586 587 588 589 590 591 592 593 594 595 596 597
    (hash-table-merge! new ht)))

;; ======================================================================



#|
<doc EXT-SYNTAX fluid-let
 * (fluid-let <bindings> <body>)
 *
 * The |<bindings>| are evaluated in the current environment, in some
 * unspecified order, the current values of the variables present in
598
 * |<bindings>| are saved, and the new evaluated values are assigned to the
eg's avatar
eg committed
599 600 601
 * |<bindings>| variables. Once this is done, the expressions of |<body>|
 * are evaluated sequentially in the current environment; the value of the
 * last expression is the result of |fluid-let|. Upon exit, the stored
602
 * variables values are restored. An error is signalled if any of the
eg's avatar
eg committed
603 604 605 606
 * |<bindings>| variable is unbound.
 * @lisp
 * (let* ((a 'out)
 *        (f (lambda () a)))
607
 *   (list (f)
eg's avatar
eg committed
608 609 610
 *         (fluid-let ((a 'in)) (f))
 *         (f))) => (out in out)
 * @end lisp
611
 *
eg's avatar
eg committed
612
 * When the body of a |fluid-let| is exited by invoking a continuation,
613
 * the new variable values are saved, and the variables are set to their old
eg's avatar
eg committed
614 615 616
 * values. Then, if the body is reentered by invoking a continuation, the old
 * values are saved and new values are restored. The following example illustrates
 * this behavior
617
 *
eg's avatar
eg committed
618 619 620 621 622 623 624 625 626
 * @lisp
 * (let ((cont #f)
 *       (l    '())
 *       (a    'out))
 *   (set! l (cons a l))
 *   (fluid-let ((a 'in))
 *     (set! cont (call-with-current-continuation (lambda (k) k)))
 *     (set! l (cons a l)))
 *   (set! l (cons a l))
627
 *
eg's avatar
eg committed
628 629 630 631 632 633
 *   (if cont (cont #f) l)) =>  (out in out in out)
 * @end lisp
doc>
|#
(define-macro (fluid-let bindings . body)
  (let* ((vars (map car bindings))
634 635
         (vals (map cadr bindings))
         (tmps (map (lambda (x) (gensym)) vars)))
eg's avatar
eg committed
636 637
    `(let ,(map list tmps vars)
       (dynamic-wind
638 639 640
          (lambda () ,@(map (lambda (x y) `(set! ,x ,y)) vars vals))
          (lambda () ,@body)
          (lambda () ,@(map (lambda (x y) `(set! ,x ,y)) vars tmps))))))
eg's avatar
eg committed
641 642 643 644 645 646 647 648 649 650 651

;;;;
;;;; SETTERS
;;;;
#|
<doc setter
 * (setter proc)
 *
 * Returns the setter associated to a |proc|. Setters are defined in the
 * ,(link-srfi 17) document. A setter proc, can be used in a generalized
 * assignment, as described in |set!|.
652
 * @l
eg's avatar
eg committed
653 654 655 656 657 658 659 660
 * To associate |s| to the procedure |p|, use the following form:
 * @lisp
 * (set! (setter p) s)
 * @end lisp
 * For instance, we can write
 * @lisp
 * (set! (setter car) set-car!)
 * @end lisp
661 662
 *
 * The following standard procedures have pre-defined setters:
eg's avatar
eg committed
663 664 665 666
 * @lisp
 * (set! (car x) v)              == (set-car! x v)
 * (set! (cdr x) v)              == (set-cdr! x v)
 * (set! (string-ref x i) v)     == (string-set! x i v)
667
 * (set! (vector-ref x i) v)     == (vector-set! x i v)!
eg's avatar
eg committed
668
 * (set! (slot-ref x 'name) v)   == (slot-set! x 'name v)
669
 * (set! (struct-ref x 'name) v) == (struct-set! x 'name v)
eg's avatar
eg committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683
 * @end lisp
 * Furhermore, ,(ref :section "Parameter Objects" :text "parameters objects")
 * are their own setter:
 * @lisp
 * (real-precision)              => 15
 * (set! (real-precision) 12)
 * (real-precision)              => 12
 * @end lisp
doc>
|#
(define (setter proc)
  (if (or (generic? proc) (parameter? proc))
      proc
      (or (key-get (%procedure-plist proc) :setter #f)
684
          (error 'setter "no setter defined for ~S" proc))))
eg's avatar
eg committed
685 686 687


;; Initialize the setter of setter !!
688 689
(%set-procedure-plist!
         setter
690 691 692 693 694 695
         (list :setter
               (lambda (proc setter)
                 (%set-procedure-plist! proc
                                        (key-set! (%procedure-plist proc)
                                                  :setter
                                                  setter)))))
eg's avatar
eg committed
696 697

;; And now set some setter for primitive functions
698 699 700 701 702 703
(set! (setter car)              set-car!)
(set! (setter cdr)              set-cdr!)
(set! (setter vector-ref)       vector-set!)
(set! (setter string-ref)       string-set!)
(set! (setter slot-ref)         slot-set!)
(set! (setter struct-ref)       struct-set!)
eg's avatar
eg committed
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719


;=============================================================================

#|
<doc EXT-SYNTAX time
 * (time expr1 expr2 ...)
 *
 * Evaluates the expressions |expr1|, |expr2|, ... and returns the
 * result of the last expression. This form prints also the time spent
 * for this evaluation on the current error port.
doc>
|#
(define-macro time
  (lambda args
    (let ((tmp1 (gensym))
720
          (tmp2 (gensym)))
eg's avatar
eg committed
721
      `(let* ((,tmp1 (clock))
722 723 724
              (,tmp2 (begin ,@args)))
         (format (current-error-port) "Elapsed time: ~S ms\n" (- (clock) ,tmp1))
         ,tmp2))))
eg's avatar
eg committed
725 726 727 728 729




#|
730
<doc EXT-SYNTAX dotimes
eg's avatar
eg committed
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
 * (dotimes [var count] <expression1> <expression2> ... )
 * (dotimes [var count result] <expression1> <expression2> ... )
 *
 * Evaluates the |count| expression, which must return an
 * integer and then evaluates the |<expression>|s once for each
 * integer from zero (inclusive) to |count| (exclusive), in order,
 * with the symbol |var| bound to the integer; if the value of
 * |count| is zero or negative, then the |<expression>|s are not
 * evaluated. When the loop completes, |result| is evaluated and its
 * value is returned as the value of the |dotimes| construction. If
 * |result| is omitted, |dotimes| result is ,(emph "void").
 * @lisp
 * (let ((l '()))
 *   (dotimes (i 4 l)
 *      (set! l (cons i l)))) => (3 2 1 0)
 * @end lisp
doc>
|#
(define-macro (dotimes bindings . body)
  (apply (lambda (var count . result)
751 752 753 754 755 756 757
           (let ((limit  (gensym))
                 (result (if (null? result) (list '(void)) result)))
             `(let ((,limit ,count))
                (do ((,var 0 (+ ,var 1)))
                    ((>= ,var ,limit) ,@result)
                  ,@body))))
         bindings))
eg's avatar
eg committed
758 759

#|
760
<doc EXT-SYNTAX while
eg's avatar
eg committed
761 762 763 764 765 766 767 768 769
 * (while <test> <expression1> <expression2> ...)
 *
 * |While| evaluates the |<expression>|s until |<test>| returns a false
 * value. The value returned by this form is ,(emph "void").
doc>
|#
(define-macro (while test . body)
  (let ((lab (gensym)))
    `(let ,lab ()
770
          (when ,test ,@body (,lab)))))
eg's avatar
eg committed
771 772

#|
773
<doc EXT-SYNTAX until
eg's avatar
eg committed
774 775 776 777 778 779 780 781 782
 * (until <test> <expression1> <expression2> ...)
 *
 * |Until| evaluates the |<expression>|s until |<while>| returns a false
 * value. The value returned by this form is ,(emph "void").
doc>
|#
(define-macro (until test . body)
  (let ((lab (gensym)))
    `(let ,lab ()
783
          (unless ,test ,@body (,lab)))))
eg's avatar
eg committed
784 785 786 787 788 789 790 791 792



#|
<doc EXT call/ec
 * (call/ec proc)
 *
 * |call/ec| is an short name for |call-with-escape-continuation|. |call/ec|
 * calls |proc| with one parameter, which is the current escape continuation
793
 * (a continuation which can only be used to abort a computation and hence
eg's avatar
eg committed
794
 * cannot be "re-enterered".
795
 *
eg's avatar
eg committed
796 797 798 799 800
 * @lisp
 * (list 1
 *       (call/ec (lambda (return) (list 'a (return 'b) 'c)))
 *       3)        => (1 b 3)
 * @end lisp
Erick Gallesio's avatar
Erick Gallesio committed
801
 * |call/ec| is cheaper than the full call/cc. It is particularily useful
802
 * when all the power of |call/cc| is not needded.
eg's avatar
eg committed
803 804 805 806 807 808
doc>
|#
(define (call/ec proc)
  (let ((tag   (gensym "call/ec")))
    (with-handler
        (lambda (c)
809 810 811 812
          (if (and (pair? c) (eq? (car c) tag))
              (apply values (cdr c))
              (raise c)))
        (proc (lambda l (raise (cons tag l)))))))
eg's avatar
eg committed
813 814


815
;; ======================================================================
816
;;      base64 ...
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
;; ======================================================================
#|
<doc EXT base64-encode-string
 * (base64-encode-string str)
 *
 * Return a string contening the contents of |str| converted to Base64
 * encoded format
doc>

<doc EXT base64-decode-string
 * (base64-encode-string str)
 *
 * Decode the contents of |str| expressed in Base64.
doc>
|#
(define base64-encode-string #f)
(define base64-decode-string #f)
(let ((encode/decode (lambda (op)
835 836 837 838 839
                       (lambda (str)
                         (let ((in  (open-input-string str))
                               (out (open-output-string)))
                           (op in out)
                           (get-output-string out))))))
840 841 842 843

  (set! base64-encode-string (encode/decode base64-encode))
  (set! base64-decode-string (encode/decode base64-decode)))

Erick Gallesio's avatar
Erick Gallesio committed
844
;; ======================================================================
845
;;      md5sum ...
Erick Gallesio's avatar
Erick Gallesio committed
846 847 848 849 850 851 852 853 854 855 856
;; ======================================================================
#|
<doc EXT md5sum-file
 * (md5sum-file str)
 *
 * Return a string contening the md5 dum of the file whose name is |str|.
doc>
|#
(define (md5sum-file path)
  (let ((port (open-file path "r")))
    (if port
857 858 859 860
        (let ((res (md5sum port)))
          (close-input-port port)
          res)
        (error "cannot read file ~s" path))))
861

eg's avatar
eg committed
862
;; ======================================================================
863
;;      ansi-color  & ansi-color-protect...
eg's avatar
eg committed
864
;; ======================================================================
865
(define ansi-color         #f)
866 867 868 869 870 871
(define ansi-color-protect #f)

(let ((ansi-color-start   "\e[")
      (ansi-color-stop    "m"))

  (define (code c)
872 873 874 875 876 877 878 879 880 881 882 883 884 885
    (let ((alist '((normal      . "0")
                   (bold        . "1")  (no-bold        . "21")
                   (italic      . "2")  (no-italic      . "22")
                   (underline   . "4")  (no-undeline    . "24")
                   (blink       . "5")  (no-blink       . "25")
                   (reverse     . "7")  (no-reverse     . "27")
                   (black       . "30") (bg-black       . "40")
                   (red         . "31") (bg-red         . "41")
                   (green       . "32") (bg-green       . "42")
                   (yellow      . "33") (bg-yellow      . "43")
                   (blue        . "34") (bg-blue        . "44")
                   (magenta     . "35") (bg-magenta     . "45")
                   (cyan        . "36") (bg-cyan        . "46")
                   (white       . "37") (bg-white       . "47"))))
886
      (let ((v (assoc c alist)))
887
        (if v (cdr v) ""))))
888 889 890 891 892 893 894 895 896 897 898

  ;; ansi-color-protect ...
  (set! ansi-color-protect
    (lambda (start stop)
      (set! ansi-color-start (string-append start "\e["))
      (set! ansi-color-stop  (string-append "m" stop))))

  ;; ansi-color ...
  (set! ansi-color
    (lambda  args
      (let Loop ((args        args)
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
                 (str-prev?  #t)
                 (res         ""))
        (cond
          ((null? args)
             (if str-prev?
                 res
                 (string-append res ansi-color-stop)))
          ((string? (car args))
             (Loop (cdr args)
                   #t
                   (string-append res
                                  (if str-prev? "" ansi-color-stop)
                                  (car args))))
          ((symbol? (car args))
             (Loop (cdr args)
                   #f
                   (string-append res
                                  (if  str-prev? ansi-color-start ";")
                                  (code (car args)))))
          (else (error 'ansi-color "bad command ~S" args)))))))
eg's avatar
eg committed
919

920
(define do-color
921 922
  (let ((term (getenv "TERM")))
    (if (and (not (key-get *%program-args* :interactive #f))
923 924 925 926 927 928 929 930 931
             (any (lambda(x) (regexp-match x term))
                  '("rxvt" "xterm" "xterm-color" "linux" "cygwin" "cons25")))
        ;; Terminal accepts color
        ansi-color
        ;; Provide a procedure which ignore color indications
        (lambda args
          (apply string-append
                 (map (lambda (x) (if (string? x) x ""))
                      args))))))
932

eg's avatar
eg committed
933 934 935 936 937 938 939 940 941 942
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; Port conversions
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

#|
<doc EXT port->string  port->sexp-list port->string-list
 * (port->string port)
 * (port->sexp-list port)
943 944
 * (port->string-list port)
 *
eg's avatar
eg committed
945
 * All these procedure take a port opened for reading. |Port->string| reads
946 947
 * |port| until the it reads an end of file object and returns all the
 * characters read as a string. |Port->sexp-list)| and |port->string-list|
eg's avatar
eg committed
948
 * do the same things except that they return a list of S-expressions and
949 950
 * a list of strings respectively. For the following example we suppose that
 * file |"foo"| is formed of two lines which contains respectively the number
eg's avatar
eg committed
951 952 953 954
 * |100| and the string |"bar"|.
 * @lisp
 * (port->sexp-list (open-input-file "foo"))   => (100 "bar")
 * (port->string-list (open-input-file "foo")) => ("100" "\"bar\"")
955
 * @end lisp
eg's avatar
eg committed
956 957 958
doc>
|#
(define (%port->list reader p)
959
  (unless (input-port? p) (error 'port->list "bad port ~S" p))
eg's avatar
eg committed
960 961
  ;; Read all the lines of port and put them in a list
  (let loop ((res '()) (sexp (reader p)))
962
    (if (eof-object? sexp)
963 964
        (values (reverse res))
        (loop (cons sexp res) (reader p)))))
965

eg's avatar
eg committed
966
(define (port->string p)
967 968 969
  (unless (input-port? p) (error "bad port ~S" p))
  (with-output-to-string
    (lambda () (copy-port p (current-output-port)))))
eg's avatar
eg committed
970

971
(define (port->sexp-list p)
eg's avatar
eg committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
  (%port->list read p))

(define (port->string-list p)
  (%port->list read-line p))


#|
<doc EXT print printerr
 * (print obj ...)
 * (printerr obj ...)
 *
 * These procedures display all their arguments followed by a newline. The
 * procedure |print| uses the standard output port, whereas |printerr| uses the
 * current error port
doc>
|#
(define (print . l)
  (for-each display l)
  (newline))

(define (printerr . l)
  (let ((p (current-error-port)))
    (for-each (lambda (x) (display x p)) l)
    (newline p)))

997 998 999 1000 1001 1002 1003

#|
<doc EXT printf fprintf eprintf
 * (printf fmt obj ...)
 * (fprintf port fmt obj ...)
 * (eprintf fmt obj ...)
 *
1004
 * These procedures are specialized version of |,(ref :mark "format" "format")|.
1005 1006 1007
 * In these procedures, |fmt| is a string using the |format| conventions.
 * |printf| outputs go on the current output port.
 * |fprintf| outputs go on the specified |port|.
Erick Gallesio's avatar
Erick Gallesio committed
1008 1009
 * |eprintf| outputs go on the current error port (note that eprintf always
 * flushes the characters printed).
1010 1011 1012
doc>
|#
(define (eprintf fmt . args)
Erick's avatar
Erick committed
1013
  (display (apply format fmt args) (current-error-port))
Erick Gallesio's avatar
Erick Gallesio committed
1014
  (flush-output-port (current-error-port)))
1015 1016

(define (printf fmt . args)
Erick's avatar
Erick committed
1017
  (display (apply format fmt args)))
1018 1019

(define (fprintf port fmt . args)
Erick's avatar
Erick committed
1020
  (display (apply format fmt args) port))
1021 1022


1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
#|
<doc EXT-SYNTAX declare-new-error
 * (declare-new-error name)
 *
 * TODO
 *
doc>
|#
(define-macro (declare-new-error name)
  (let ((cond-name (string->symbol (format "&~a" name)))
1033 1034
        (predicate (string->symbol (format "&~a?" name)))
        (args      (gensym)))
1035 1036 1037
    `(begin
       (define-condition-type ,cond-name &error-message ,predicate)
       (define (,name . ,args)
1038 1039 1040 1041
         (if (and (not (null? ,args))
                  (symbol? (car ,args)))
             (apply signal-error ,cond-name ,args)
             (apply signal-error ,cond-name ',name ,args))))))
1042

eg's avatar
eg committed
1043 1044 1045 1046
#|
<doc EXT  exec exec-list
 * (exec str)
 * (exec-list str)
1047 1048 1049
 *
 * These procedures execute the command given in |str|. The command given
 * in |str| is passed to |/bin/sh|. |Exec| returns a strings which contains
eg's avatar
eg committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
 * all the characters that the command |str| has printed on it's standard
 * output, whereas |exec-list| returns a list of the lines which constitute
 * the output of |str|.
 * @lisp
 * (exec "echo A; echo B")                => "A\\nB\\n"
 * (exec-list "echo A; echo B")           => ("A" "B")
 * @end lisp
doc>
|#
(define (exec command)
  (call-with-input-file (string-append "| " command) port->string))

(define (exec-list command)
  (call-with-input-file (string-append "| " command) port->string-list))


#|
<doc EXT argc
 * (argc)
 *
 * Returns the number of argument present on the command line
doc>
|#
(define argc (lambda () (length (argv))))


#|
<doc EXT apropos
 * (apropos obj)
 * (apropos obj module)
 *
 * |Apropos| returns a list of symbols whose print name contains the
 * characters of |obj| as a substring . The given |obj| can be a string or
 * symbol. This function returns the list of matched symbols which can
 * be accessed from the given |module| (defaults to the current module if not
 * provided).
 *
doc>
|#
(define (apropos str :optional (module (current-module)))
1090 1091 1092 1093 1094 1095

  (define (list->set lst res)
    (cond
      ((null? lst) res)
      ((memq (car lst) res) (list->set (cdr lst) res))
      (else (list->set (cdr lst) (cons (car lst) res)))))
1096

1097 1098 1099
  (define (symbol<? s1 s2)
    (string<? (symbol->string s1) (symbol->string s2)))

eg's avatar
eg committed
1100 1101 1102 1103 1104 1105
  ;; Sanity check
  (unless (module? module)
    (error 'apropos "bad module ~S" module))

  ;; Here we go
  (let ((s        (if (symbol? str) (symbol->string str) str))
1106 1107
        (external (apply append (map module-exports (module-imports module))))
        (internal (module-symbols module)))
1108
    (let Loop ((symbs (list->set (append internal external) '()))
1109
               (res   '()))
eg's avatar
eg committed
1110
      (cond
1111 1112 1113 1114 1115 1116
        ((null? symbs)
           (and (not (null? res)) (sort res symbol<?)))
        ((string-find? s (symbol->string (car symbs)))
           (Loop (cdr symbs) (cons (car symbs) res)))
        (else
           (Loop (cdr symbs) res))))))
eg's avatar
eg committed
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

#|
<doc EXT die
 * (die message)
 * (die message status)
 *
 * |Die| prints the given |message| on the current error port and exits
 * the program with the |status| value. If |status| is omitted, it
 * defaults to 1.
doc>
|#
(define (die message :optional (status 1))
  (format (current-error-port) "**** ~A\n**** EXIT\n" message)
  (exit status))


#|
1134
<doc EXT decompose-file-name
eg's avatar
eg committed
1135
 * (decompose-file-name string)
1136
 *
eg's avatar
eg committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
 * Returns an ``exploded'' list of the path name components given in
 * |string|.
 * The first element in the list denotes if the given |string| is an
 * absolute path or a relative one, being "/" or "." respectively.
 * Each component of this list is a string.
 * @lisp
 * (decompose-file-name "/a/b/c.stk") => ("/" "a" "b" "c.stk")
 * (decompose-file-name "a/b/c.stk")  => ("." "a" "b" "c.stk")
 * @end lisp
doc>

<doc EXT dirname
 * (dirname str)
 *
 * Returns a string containing all but the last component of the path
 * name given in |str|.
 * @lisp
 * (dirname "/a/b/c.stk") => "/a/b"
 * @end lisp
doc>

<doc EXT basename
 * (basename str)
 *
 * Returns a string containing the last component of the path name
 * given in |str|.
 * @lisp
 * (basename "/a/b/c.stk") => "c.stk"
 * @end lisp
doc>
|#
(if (eq? (running-os) 'cygwin-windows)
    [begin
      (define (decompose-file-name str)
1171 1172 1173 1174 1175 1176
        (let ((str (posixify-file-name str)))
          (cons (if (and (> (string-length str) 0)
                         (char=? (string-ref str 0) #\/))
                    "/"
                    ".")
                (string-split str "/"))))
eg's avatar
eg committed
1177 1178

      (define (dirname str)
1179 1180 1181 1182 1183 1184
        (let ((str (posixify-file-name str)))
          (let ((res (regexp-replace "^(.*)/(.+)$" str "\\1")))
            (cond
              ((string=? res "")   "/")
              ((string=? res str)  ".")
              (else              res)))))
eg's avatar
eg committed
1185 1186

      (define (basename str)
1187 1188
        (let ((str (posixify-file-name str)))
          (regexp-replace "^(.*)/(.*)$" str "\\2")))
eg's avatar
eg committed
1189 1190 1191
    ]
    [begin
      (define (decompose-file-name str)
1192 1193 1194 1195 1196
        (cons (if (and (> (string-length str) 0)
                       (char=? (string-ref str 0) #\/))
                  "/"
                  ".")
              (string-split str "/")))
eg's avatar
eg committed
1197 1198

      (define (dirname str)
1199 1200 1201 1202 1203
        (let ((res (regexp-replace "^(.*)/(.+)$" str "\\1")))
          (cond
            ((string=? res "")   "/")
            ((string=? res str)  ".")
            (else                res))))
1204

eg's avatar
eg committed
1205
      (define (basename str)
1206
        (regexp-replace "^(.*)/(.*)$" str "\\2"))
eg's avatar
eg committed
1207 1208 1209 1210 1211 1212
      ])

#|
<doc EXT file-separator
 * (file-separator)
 *
1213
 * Retuns the operating system file separator as a character. This is typically
eg's avatar
eg committed
1214 1215 1216 1217 1218
 * #\\/ on Unix (or Cygwin) systems and #\\\\ on Windows.
doc>
|#
(define (file-separator)
  (case (running-os)
1219
    ((unix cygwin-windows)    #\/)
1220 1221
    ((windows)                #\\)
    (else                     #\?)))
eg's avatar
eg committed
1222 1223 1224

#|
<doc EXT make-path
1225
 * (make-path dirname .  names)
eg's avatar
eg committed
1226
 *
1227 1228 1229 1230
 * Builds a file name from the directory |dirname| and |names|. For instance,
 * on a Unix system:
 * @lisp
 * (make-path "a" "b" "c")   => "a/b/c"
eg's avatar
eg committed
1231
 * @end lisp
eg's avatar
eg committed
1232 1233
doc>
|#
1234 1235 1236 1237
(define (make-path dirname . names)
  (if (null? names)
      dirname
      (apply make-path
1238 1239
             (format "~A~A~A" dirname (file-separator) (car names))
             (cdr names))))
eg's avatar
eg committed
1240

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

#|
<doc EXT file-suffix
 * (file-suffix pathname)
 *
 * Returns the suffix of given |pathname|. If no suffix is found, |file-suffix|
 * returns an empty string.
 * @lisp
 * (file-suffix "./foo.tar.gz") => "gz"
 * (file-suffix "./a.b/c")      => ""
 * @end lisp
Erick Gallesio's avatar
Erick Gallesio committed
1252
doc>
1253 1254 1255 1256 1257 1258 1259 1260
|#
(define (file-suffix pathname)
  (let ((end (string-length pathname)))
    (let loop ((i (- end 1)))
      (if (< i 0)
          ""
          (let ((c (string-ref pathname i)))
            (cond
1261 1262 1263 1264 1265 1266
              ((char=? c #\.)
               (substring pathname (+ i 1) end))
              ((char=? c (file-separator))
               "")
              (else
               (loop (- i 1)))))))))
1267

1268 1269 1270 1271
#|
<doc EXT file-prefix
 * (file-prefix pathname)
 *
1272
 * Returns the suffix of given |pathname|.
1273 1274 1275 1276
 * @lisp
 * (file-prefix "./foo.tar.gz") => "./foo.tar"
 * (file-prefix "./a.b/c")      => "./a.b/c"
 * @end lisp
Erick Gallesio's avatar
Erick Gallesio committed
1277
doc>
1278 1279 1280 1281 1282 1283 1284 1285
|#
(define (file-prefix pathname)
  (let ((end (string-length pathname)))
    (let loop ((i (- end 1)))
      (if (< i 0)
          pathname
          (let ((c (string-ref pathname i)))
            (cond
1286 1287 1288 1289 1290 1291
              ((char=? c #\.)
               (substring pathname 0 i))
              ((char=? c (file-separator))
               pathname)
              (else
               (loop (- i 1)))))))))
1292 1293


eg's avatar
eg committed
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
#|
<doc  EXT port-idle-register! port-idle-unregister! port-idle-reset!
 * (port-idle-register! port thunk)
 * (port-idle-unregister! port thunk)
 * (port-idle-reset! port)
 *
 * |port-idle-register!| allows to register |thunk| as an idle handler
 * when reading on port. That means that |thunk| will be called continuously
 * while waiting  an input on |port| (and only while using a reading
 * primitive on this port). |port-idle-unregister!| can be used to
 * unregister a handler previously set by |port-idle-register!|. The
 * primitive |port-idle-reset!| unregisters all the handlers set on
 * |port|.
 *
 * Hereafter is a (not too realistic) example: a message will be displayed
 * repeatedly until a ,(emph "sexpr") is read on the current input port.
1310
 *
eg's avatar
eg committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
 * @lisp
 * (let ((idle (lambda () (display "Nothing to read!\\n"))))
 *   (port-idle-register! (current-input-port) idle)
 *   (let ((result (read)))
 *     (port-idle-unregister! (current-input-port) idle)
 *     result))
 * @end lisp
doc>
|#

(define (port-idle-register! port proc)
  (unless (procedure? proc) (error 'port-idle-register! "bad procedure ~S" proc))
  (let ((idle (%port-idle port)))
    (%port-idle port (cons proc idle))))

(define (port-idle-unregister! port proc)
  (unless (procedure? proc) (error 'port-idle-unregister! "bad procedure ~S" proc))
  (let ((idle (%port-idle port)))
    (%port-idle port (delete! proc idle))))

(define (port-idle-reset! port)
  (%port-idle port '()))



#|
<doc EXT chmod
 * (chmod str)
 * (chmod str option1 ...)
 *
1341 1342
 * Change the access mode of the file whose path name is given in |string|.
 * The options must be composed of either an integer or one of the
eg's avatar
eg committed
1343
 * following symbols |read|, |write| or |execute|. Giving no option to |chmod|
1344 1345
 * is equivalent to pass it the integer |0|. If the operation succeeds,
 * |chmod| returns |%t|; otherwise it returns |%f|.
eg's avatar
eg committed
1346 1347 1348 1349 1350 1351 1352 1353 1354
 *
 * @lisp
 * (chmod "~/.stklos/stklosrc" 'read 'execute)
 * (chmod "~/.stklos/stklosrc" #o644)
 * @end lisp
doc>
|#
(define (chmod file . opt)
  (let ((file (if (string? file) (expand-file-name file) file))
1355
        (mode 0))
eg's avatar
eg committed
1356 1357
    (let Loop ((opt opt))
      (cond
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
        ((null? opt)
           (%chmod file mode))
        ((symbol? (car opt))
           (case (car opt)
             ((read)    (set! mode (bit-or mode #o400)))
             ((write)   (set! mode (bit-or mode #o200)))
             ((execute) (set! mode (bit-or mode #o100)))
             (else      (error 'chmod "bad option ~S" (car opt))))
           (Loop (cdr opt)))
        ((integer? (car opt))
         (%chmod file (car opt)))
        (else
           (error 'chmod "bad option ~S" (car opt)))))))
eg's avatar
eg committed
1371

Erick Gallesio's avatar
Erick Gallesio committed
1372 1373 1374 1375 1376 1377 1378 1379 1380
#|
<doc EXT with-mutex
 * (with-mutex mtx <body>)
 *
doc>
|#
(define (with-mutex mtx  proc)
  (dynamic-wind
      (lambda () (mutex-lock! mtx))
Erick's avatar
Erick committed
1381
      (proc)
Erick Gallesio's avatar
Erick Gallesio committed
1382 1383
      (lambda () (mutex-unlock! mtx))))

eg's avatar
eg committed
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408

;;;; ======================================================================
;;;;
;;;; SRFIs support
;;;;
;;;; ======================================================================

;;;
;;; SRFI-8
;;;


#|
<doc EXT-SYNTAX receive
 * (receive <formals> <expression> <body>)
 *
 * This form is defined in ,(link-srfi 8). It simplifies
 * the usage of multiple values. Specifically, |<formals>| can have any
 * of three forms:
 * ,(itemize
 * (item [(|<variable1>| ... |<variablen>|):
 * ,(linebreak)
 * The environment in which the
 * receive-expression is evaluated is extended by binding |<variable1>|, ...,
 * |<variablen>| to fresh locations.
1409
 * @l
eg's avatar
eg committed
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
 * The |<expression>| is evaluated, and its
 * values are stored into those locations. (It is an error if |<expression>|
 * does not have exactly n values.)
 * ])
 * (item [|<variable>|:
 * ,(linebreak)
 * The environment in which the receive-expression is
 * evaluated is extended by binding |<variable>| to a fresh location.
 * The |<expression>| is evaluated, its values are converted into a newly
 * allocated list, and the list is stored in the location bound to |<variable>|.
 * ])
 * (item [(|<variable1>| ... |<variablen>| . |<variablen + 1>|):
 * ,(linebreak)
 * The environment
 * in which the receive-expression is evaluated is extended by binding
 * |<variable1>|, ..., |<variablen + 1>| to fresh locations.
 * The |<expression>| is evaluated. Its first n values are stored into the
 * locations bound to |<variable1>| ... |<variablen>|. Any remaining values
 * are converted into a newly allocated list, which is stored into the location
 * bound to |<variablen + 1>|. (It is an error if |<expression>| does not have
 * at least n values.)])
 * )
1432
 *
eg's avatar
eg committed
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
 * In any case, the expressions in |<body>| are evaluated sequentially in
 * the extended environment. The results of the last expression in the body
 * are the values of the receive-expression.
 * @lisp
 * (let ((n 123))
 *   (receive (q r)
 *      (values (quotient n 10) (modulo n 10))
 *      (cons q r)))
 *               => (12 . 3)
 * @end lisp
doc>
|#
(define-macro (receive vars producer . body)
  `(call-with-values (lambda () ,producer)
1447
                     (lambda ,vars ,@body)))
eg's avatar
eg committed
1448 1449 1450 1451 1452 1453 1454 1455

;;
;; SRFI-16: "Syntax for procedures of variable arity"
;;
#|
<doc EXT-SYNTAX case-lambda
 * (case-lambda <clause> ...)
 *
1456
 * Each |<clause>| should have the form |(<formals> <body>)|, where
eg's avatar
eg committed
1457 1458
 * |<formals>| is a formal arguments list as for |lambda|.
 * Each |<body>| is a |<tail-body>|, as defined in R5RS.
1459
 * @l
eg's avatar
eg committed
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
 * A |case-lambda| expression evaluates to a procedure that
 * accepts a variable number of arguments and is lexically scoped in
 * the same manner as procedures resulting from |lambda|
 * expressions. When the procedure is called with some arguments
 * |v1 ... vk|, then the first |<clause>| for which the arguments agree
 * with |<formals>| is selected, where agreement is specified as for the
 * |<formals>| of a |lambda| expression. The variables of |<formals>|
 * are bound to fresh locations, the values |v1 ... vk| are stored in those
 * locations, the |<body>| is evaluated in the extended environment,
 * and the results of |<body>| are returned as the results of the
 * procedure call.
1471
 * @l
eg's avatar
eg committed
1472 1473
 * It is an error for the arguments not to agree with the |<formals>|
 * of any |<clause>|.
1474
 * @l
eg's avatar
eg committed
1475 1476 1477 1478
 * This form is defined in ,(link-srfi 16).
 *
 * @lisp
 *  (define plus
1479
 *    (case-lambda
eg's avatar
eg committed
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
 *     (() 0)
 *     ((x) x)
 *     ((x y) (+ x y))
 *     ((x y z) (+ (+ x y) z))
 *     (args (apply + args))))
 *
 *  (plus)                     => 0
 *  (plus 1)                   => 1
 *  (plus 1 2 3)               => 6
 *
1490
 *  ((case-lambda
eg's avatar
eg committed
1491 1492 1493 1494 1495 1496 1497 1498
 *    ((a) a)
 *    ((a b) (* a b)))
 *   1 2 3)                    => error
 * @end lisp
doc>
|#
(define-macro (case-lambda . clauses)
  (let ((len  (gensym))
1499 1500
        (args (gensym))
        (compute-arity (in-module STKLOS-COMPILER compute-arity)))
eg's avatar
eg committed
1501 1502
    `(lambda ,args
       (let ((,len (length ,args)))
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
         (cond
           ,@(map (lambda (x)
                    (unless (>= (length x) 2)
                      (error 'case-lambda "bad clause ~S" x))
                    (let* ((formals (car x))
                           (body    (cdr x))
                           (arity   (compute-arity formals)))
                      (cond
                        ((positive? arity)
                            `((= ,len ,arity)
                              (apply (lambda ,formals ,@body) ,args)))
                        ((zero? arity)
                            `((= ,len ,arity)
                              ,@body))
                        (else
                            `((>= ,len ,(- (- arity) 1))
                                (apply (lambda ,formals ,@body) ,args))))))
                  clauses)
           (else (error 'case-lambda "no matching clause in list ~S for ~S"
                        ',(map car clauses) ,args)))))))
eg's avatar
eg committed
1523 1524 1525 1526 1527 1528 1529

;;
;; SRFI-38: "External Representation for Data With Shared Structure"
;;
(define read-with-shared-structure read)

(define (write-with-shared-structure obj :optional (port (current-output-port))
1530
                                                   (optarg #f))
eg's avatar
eg committed
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
  ;; optarg is unspecified in SRFI-38, it is a hook for implementation
  ;; We don't use it
  (write* obj port))

(define read/ss read-with-shared-structure)
(define write/ss write-with-shared-structure)

;;
;; Macro used by SRFI-35 & SRFI-36 implementations
;;
(define-macro (%define-condition-type-accessors name supertype predicate . slots)
  (let ((obj (gensym)))
    `(begin
       ;; define the predicate
       (define (,predicate ,obj)
1546
         (and (condition? ,obj) (condition-has-type? ,obj ,name)))
1547
       ;; define the accessors
eg's avatar
eg committed
1548
       ,@(map (lambda(x)
1549 1550 1551 1552 1553
                `(define (,(cadr x) ,obj)
                   (unless (,predicate ,obj)
                     (error ',(cadr x) "bad type for condition ~S" ,obj))
                   (condition-ref ,obj ',(car x))))
              slots))))
eg's avatar
eg committed
1554 1555 1556 1557 1558 1559

;;
;; SRFI-39: "Parameter Objects"
;;

#|
1560
<doc EXT-SYNTAX parameterize
eg's avatar
eg committed
1561
 * (parameterize ((expr1 expr2) ...) <body>)
1562
 *
eg's avatar
eg committed
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
 * The expressions |expr1| and |expr2| are evaluated in an unspecified order.
 * The value of the |expr1| expressions must be parameter objects.
 * For each |expr1| expression and in an unspecified order, the local
 * dynamic environment is extended with a binding of the parameter object
 * |expr1| to a new cell whose content is the result of the call
 * |(converter val)|, where |val| is the value of |expr2| and converter
 * is the conversion procedure of the parameter object. The resulting
 * dynamic environment is then used for the evaluation of |<body>|
 * (which refers to the R5RS grammar nonterminal of that name).
 * The result(s) of the parameterize form are the result(s) of
 * the |<body>|.
 *
 * @lisp
 * (radix)                                              =>  2
 * (parameterize ((radix 16)) (radix))                  =>  16
 * (radix)                                              =>  2
1579
 *
eg's avatar
eg committed
1580
 * (define (f n) (number->string n (radix)))
1581
 *
eg's avatar
eg committed
1582 1583 1584 1585 1586 1587 1588
 * (f 10)                                               =>  "1010"
 * (parameterize ((radix 8)) (f 10))                    =>  "12"
 * (parameterize ((radix 8) (prompt (f 10))) (prompt))  =>  "1010"
 * @end lisp
doc>
|#
(define-macro (parameterize bindings . body)
1589 1590
  (let ((tmp (map (lambda (_) (gensym)) bindings)))
    `(let ,(map (lambda (x y) (list y (cadr x)))
1591
                 bindings tmp)
1592
       (dynamic-wind
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
           (lambda ()
             ;; First push all the current parameter values
             ,@(map (lambda (x) `(%parameter-dynenv-push! ,(car x)))
                    bindings)
             ;; Change all parameters values
             ,@(map (lambda (x y) `(,(car x) ,y))
                    bindings tmp))
           (lambda ()
             ,@body)
           (lambda ()
             ,@(map (lambda (x) `(%parameter-dynenv-pop! ,(car x)))
                   bindings))))))
1605

eg's avatar
eg committed
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
;;
;; SRFI-55: "require-extension"
;;
#|
<doc EXT-SYNTAX require-extension
 * (require-extension <clause> ...)
 *
 * The syntax of require-extension is as follows:
 * @lisp
 * (require-extension <clause> ...)
 * @end lisp
 * A clause has the form:
 * @lisp
 *  (srfi <extension-argument> ...)
 * @end lisp
 * where |<extension-argument>|s may be any Scheme-values.
1622
 * @l
eg's avatar
eg committed
1623 1624 1625
 * If an |<extension-argument>| is a nonnegative integer, the functionality
 * of the indicated SRFIs is made available in the context in
 * which the require-extension form appears. For instance,
1626
 * @lisp
eg's avatar
eg committed
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
 * (require-extension (srfi 1 2))
 *                ; Make the SRFI 1 and 2 available
 * @end lisp
 * This form is compatible with ,(link-srfi 55). However, STklos
 * accepts also some symbolic names for requiring some extensions.
 * For instance,
 * @lisp
 * (require-extension (srfi lists and-let*))
 * @end lisp
 * is equivalent to the previous |require-extension|. A list of available
 *  symbols as  |<extension-argument>| is given in chapter
 * ,(ref :chapter "SRFIs").
doc>
|#
(define-macro (require-extension . clauses)
  (when (null? clauses)
    (error 'require-extension "requires at least one clause"))
1644
  `(let ((%has-feature? (in-module SRFI-0 %has-feature?)))
eg's avatar
eg committed
1645
     ,@(map (lambda (x)
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
              `(cond
                ((and (pair? ',x) (eq? (car ',x) 'srfi) (not (null? (cdr ',x))))
                 (let ((ok? (lambda (x)
                              (let ((x (if (integer? x)
                                           (string->symbol (format "srfi-~a" x))
                                           x)))
                                (or (%has-feature? x)
                                    (error 'require-extension
                                           "extension ~S is absent" x))))))
                   (and ,@(map (lambda (x) `(ok? ',x))
                               (cdr x))
                        (void))))
                (else (error 'require-extension "bad clause ~S" ',x))))
            clauses)))
eg's avatar
eg committed
1660

1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
;;
;; SRFI-88: "keyword objects"
;;
#|
<doc EXT string->keyword
 * (string->keyword str)
 *
 * This function function has been added to be compatibe with SRFI-88.
 * It is equivalent to make-keyword, except that the parameter cannot be
 * a symbol.
doc>
|#
(define (string->keyword str)
  (unless (string? str)
    (error "bad string ~S" str))
  (make-keyword str))
eg's avatar
eg committed
1677

Erick's avatar
Erick committed
1678 1679 1680 1681
;;
;; SRFI-98: "An interface to access environment variables"
;;

1682
#| <doc R7RS get-environment-variable
Erick's avatar
Erick committed
1683 1684 1685
 * (get-environment-variable name)
 *
 * Returns the value of the named environment variable as a string, or
1686
 * |%f| if the named environment variable is not found. The name argument
Erick's avatar
Erick committed
1687 1688 1689 1690 1691 1692
 * is expected to be a string. This function is similar to the |getenv|. It
 * has been added to be  support ,(link-srfi 98).
|#
(define (get-environment-variable name)
  (getenv name))

1693
#| <doc R7RS get-environment-variables
Erick's avatar
Erick committed
1694 1695 1696 1697 1698 1699 1700 1701
 * (get-environment-variables)
 *
 * Returns names and values of all the environment variables as an a-list.
 * This function is defined by ,(link-srfi 98)
|#
(define (get-environment-variables)
  (getenv))

eg's avatar
eg committed
1702 1703

;; LocalWords:  doc dotimes R5RS str SRFI optarg