macros.l 71.9 KB
Newer Older
1
;; macros.l - all the basic macros
rtoy's avatar
rtoy committed
2 3 4 5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;Copyright (c) University of Waikato;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;Hamilton, New Zeland 1992-95 - all rights reserved;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
6
(in-package :f2cl-lib)
rtoy's avatar
rtoy committed
7

8
(defparameter *f2cl-macros-version*
9
  "$Id: macros.l,v 3fe93de3be82 2012/05/06 02:17:14 toy $")
rtoy's avatar
rtoy committed
10

rtoy's avatar
rtoy committed
11 12 13 14
(eval-when
    #+gcl (compile load eval)
    #-gcl (:compile-toplevel :load-toplevel :execute)
    (proclaim '(special *verbose*)))
15
;;----------------------------------------------------------------------------
16 17 18 19
(defvar *check-array-bounds* nil
  "If non-NIL, generated code checks for array bounds.  If NIL, checking
is not included")

20 21 22 23
;;------------------------------------------------------------------------------
;;
;; Define the equivalent types between Fortran and Lisp.  This MUST
;; match the types given in f2cl1.l so keep it in sync!
rtoy's avatar
rtoy committed
24 25 26
(deftype logical ()
  `(member t nil))

rtoy's avatar
rtoy committed
27 28 29 30 31 32 33 34
;; Decide what you want integer*4 to be.  Good choices are fixnum or
;; (signed-byte 32).  The latter is good only if your compiler does a
;; good job with this type.  If you aren't sure, use fixnum.  CMUCL
;; does a good job with (signed-byte 32).
;;
;; If you change this, you may need to change some of the macros
;; below, such as INT and AINT!

rtoy's avatar
rtoy committed
35
#+(or cmu scl sbcl)
rtoy's avatar
rtoy committed
36 37
(deftype integer4 (&optional (low #x-80000000) (high #x7fffffff))
  `(integer ,low ,high))
rtoy's avatar
rtoy committed
38 39 40
#-(or cmu scl sbcl)
(deftype integer4 (&optional low high)
  (declare (ignore low high))
rtoy's avatar
rtoy committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
  'fixnum)

(deftype integer2 ()
  `(signed-byte 16))
(deftype integer1 ()
  `(signed-byte 8))
(deftype real8 ()
  'double-float)
(deftype real4 ()
  'single-float)
(deftype complex8 ()
  `(complex single-float))
(deftype complex16 ()
  `(complex double-float))

56
(deftype array-double-float ()
57
  `(array double-float (*)))
58
(deftype array-integer4 ()
59
  `(array integer4 (*)))
60
(deftype array-single-float ()
61
  `(array single-float (*)))
62 63
(deftype array-strings ()
  `(array string (*)))
64

rtoy's avatar
rtoy committed
65 66
(defconstant %false% nil)
(defconstant %true% t)
67

68
;;------------------------------------------------------------------------------
rtoy's avatar
rtoy committed
69

70
;;-----------------------------------------------------------------------------
rtoy's avatar
rtoy committed
71

72 73 74 75 76 77 78 79 80 81 82 83 84 85
;; Array dimensions are (d1, d2, d3, ...)
;;
;; Then x(n1, n2, n3, ...) means index is
;;
;; n1 + d1*(n2 + d2*(n3 + d3*(n4 + d4*(n5))))

;; Return an expression that computes the column major index given the
;; indices and the bounds on each dimension.  The bounds are a list of
;; the upper and lower bounds for each dimension.
(defun col-major-index (indices dims)
  (flet ((get-offset (n bound)
	   (let ((lo (first bound)))
	     (if (and (numberp lo) (zerop lo))
		 n
86
		 `(the fixnum (- (the fixnum ,n) (the fixnum ,lo))))))
87 88 89 90 91 92 93 94 95 96 97
	 (get-size (bound)
	   (destructuring-bind (lo hi)
	       bound
	     (cond ((numberp lo)
		    (cond ((numberp hi)
			   (1+ (- hi lo)))
			  ((= lo 1)
			   hi)
			  (t
			   `(- ,hi ,(- lo 1)))))
		   (t
98
		    `(the fixnum (- ,hi (the fixnum (- (the fixnum ,lo) 1)))))))))
99 100 101 102 103 104 105
    (let* ((rev-idx (reverse indices))
	   (rev-dim (reverse dims))
	   (idx (get-offset (first rev-idx) (first rev-dim))))
      (do ((d (rest rev-dim) (rest d))
	   (n (rest rev-idx) (rest n)))
	  ((endp d)
	   idx)
106 107
	(setf idx `(the fixnum (+ ,(get-offset (first n) (first d))
				  (the fixnum (* ,(get-size (first d)) ,idx)))))))))
108 109 110 111 112 113

(defun check-array-bounds (indices bounds)
  `(and ,@(mapcar #'(lambda (idx dim)
		     `(<= ,(first dim) ,idx ,(second dim)))
		 indices bounds)))

114
(defmacro fref (arr indices bounds &optional offset)
115 116
  (if *check-array-bounds*
      `(aref ,arr (if ,(check-array-bounds indices bounds)
117
		      (the fixnum (+ (the fixnum ,(or offset 0)) ,(col-major-index indices bounds)))
118 119
		      (error "Out of bounds index for array ~S"
			     ',arr)))
120
      `(aref ,arr (the fixnum (+ (the fixnum ,(or offset 0)) ,(col-major-index indices bounds))))))
121

rtoy's avatar
rtoy committed
122 123 124
(defmacro fset (a b) 
  `(setf (fref ,(second a) ,@(cddr a)) ,b))

rtoy's avatar
rtoy committed
125
(defmacro fref-string (s range)
rtoy's avatar
rtoy committed
126
  `(subseq ,s (1- ,(first range)) ,(second range)))
rtoy's avatar
rtoy committed
127

rtoy's avatar
rtoy committed
128
(defmacro fset-string (a b)
129
  `(setf (fref-string ,(second a) ,(third a)) (string ,b)))
rtoy's avatar
rtoy committed
130

rtoy's avatar
rtoy committed
131
(defmacro f2cl-// (a b)
rtoy's avatar
rtoy committed
132
  `(concatenate 'string ,a ,b))
133

134 135 136 137 138
;; (with-array-data ((data-var offset-var array))
;;   ...
;; )

(defun find-array-data (array)
139
  (declare (type (array * (*)) array))
rtoy's avatar
rtoy committed
140 141 142 143
  (let ((offset 0))
    (declare (type fixnum offset)
	     (optimize (speed 3) (safety 0)))
    (loop
144 145 146 147 148 149
     (multiple-value-bind (displaced-to index-offset)
	 (array-displacement array)
       (when (null displaced-to)
	 (return-from find-array-data (values array offset)))
       (incf offset index-offset)
       (setf array displaced-to)))))
150 151 152 153

(defmacro with-array-data ((data-var offset-var array) &rest body)
  `(multiple-value-bind (,data-var ,offset-var)
    (find-array-data ,array)
154 155 156 157 158 159 160
     ,@body))

(defun multi-array-data-aux (array-info body)
  (let ((results body))
    (dolist (a (reverse array-info))
      (destructuring-bind (array a-type var-name offset-var)
	  a
161 162 163 164 165 166 167 168 169 170
	(let ((atype (if (subtypep a-type 'character)
			 `(simple-string)
			 `(simple-array ,a-type (*)))))
	  (setf results
		`((multiple-value-bind (,var-name ,offset-var)
		      (find-array-data ,array)
		    (declare (ignorable ,offset-var ,var-name)
			     (type f2cl-lib:integer4 ,offset-var)
			     (type ,atype ,var-name))
		    ,@results))))))
171 172 173 174
    (first results)))

(defmacro with-multi-array-data (array-info &rest body)
  (multi-array-data-aux array-info body))
175

rtoy's avatar
rtoy committed
176 177 178 179 180 181
;; Create an array slice for the array named VNAME whose elements are
;; of type TYPE.  The slice starts at the indices INDICES and the
;; original array has dimensions given by BOUND.
;;
;; This is done by making a displaced array to VNAME with the
;; appropriate offset.
182
(defmacro array-slice (vname type indices bounds &optional offset)
183 184 185 186 187 188 189 190 191 192
  ;; To figure the size of the sliced array, use ARRAY-TOTAL-SIZE
  ;; instead of the f2cl derived/declared BOUNDS, just in case we
  ;; screwed up or in case we changed the size of the array in some
  ;; other way.  This isn't possible in a function, but the array
  ;; might be in a common block and we could change the dimensions of
  ;; the common block at runtime.  (Some Fortran code like mpfun does
  ;; this, although it's actually illegal.  Neat hack to "dynamically"
  ;; change the dimensions.  Of course, for this to work in Fortran,
  ;; the common block has to contain exactly that one array, or the
  ;; array must be the last element of the common block.)
193 194 195 196 197 198 199 200 201 202 203
  ;;
  ;; Note: In some places in LAPACK, an array slice is taken where the
  ;; slice exceeds the bounds of the array.  However, the array is
  ;; never accessed.  What are we to do?  We could modify the LAPACK
  ;; routines (everywhere!) to check for this, or we can silently make
  ;; array-slice make a 0-element array.  If the array is then
  ;; accessed, we should get an error at the point of access, not the
  ;; point of creation.
  ;;
  ;; This seems somewhat reasonable, so let's do that for array
  ;; slices.
204 205 206 207
  `(make-array (max 0 (- (array-total-size ,vname)
			 (the fixnum
			   (+ ,(col-major-index indices bounds)
			      (or ,offset 0)))))
208 209
    :element-type ',type
    :displaced-to ,vname
210 211 212 213
    :displaced-index-offset (min (array-total-size ,vname)
				 (the fixnum
				   (+ ,(col-major-index indices bounds)
				      (or ,offset 0))))))
rtoy's avatar
rtoy committed
214 215 216 217 218 219 220 221

;; Compute an initializer for make-array given the data in the list
;; DATA.  The array has en element type of TYPE and has dimensions of
;; DIMS.
(defmacro array-initialize (type dims data)
  (let ((data-list (gensym))
	(data-len (length data))
	(total-length (gensym)))
222
    `(let* ((,data-list (list ,@data))
rtoy's avatar
rtoy committed
223 224 225 226 227 228 229 230 231 232 233
	    (,total-length (reduce #'* (list ,@dims))))
       (cond ((< ,data-len ,total-length)
	      ;; Need to append some data.
	      (append ,data-list (make-list (- ,total-length ,data-len)
					    :initial-element (coerce 0 ',type))))
	     ((> ,data-len ,total-length)
	      ;; Need to truncate some data
	      (subseq ,data-list 0 ,total-length))
	     (t
	      ,data-list)))))  

234
;;----------------------------------------------------------------------------
rtoy's avatar
rtoy committed
235 236

#-aclpc (defmacro while (con &rest body)
237 238
	  `(loop (if (not ,con) (return t)) ,@body))
;;------------------------------------------------------------------
rtoy's avatar
rtoy committed
239

rtoy's avatar
rtoy committed
240 241
(defmacro fortran_comment (&rest args)
  (declare (ignore args)))
rtoy's avatar
rtoy committed
242

243 244
;;----------------------------------------------------------------------------
;; fdo has similar syntax as do except there will only be one do_vble
rtoy's avatar
rtoy committed
245 246

(defmacro fdo (do_vble_clause predicate_clause &rest body)
rtoy's avatar
rtoy committed
247
  (let ((step (gensym (symbol-name '#:step-)))
248
	(iteration_count (gensym (symbol-name '#:cnt-)))
249
	(loop-var (first do_vble_clause)))
rtoy's avatar
rtoy committed
250 251
    `(prog* ((,step ,(third (third do_vble_clause)))
	     (,iteration_count 
rtoy's avatar
rtoy committed
252 253 254 255 256 257
	      (max 0 (the integer4
		       (truncate (the integer4
				   (+ (the integer4 (- ,(third (first predicate_clause))
						       ,(second do_vble_clause)))
				      ,step))
				 ,step))
rtoy's avatar
rtoy committed
258
		   )))
rtoy's avatar
rtoy committed
259
      (declare (type integer4 ,step ,iteration_count))
rtoy's avatar
rtoy committed
260
      ;; initialise loop variable
261
      (setq ,loop-var ,(second do_vble_clause))
rtoy's avatar
rtoy committed
262 263 264 265 266
      loop
      (return
	(cond				; all iterations done
	  ((zerop ,iteration_count) nil)
	  ;; execute loop, in/de-crement loop vble and decrement cntr
267 268 269 270 271 272 273 274
	  ,(list 't
		  (append '(tagbody)
			  (append 
			   (append body
				   `(continue
				     (setq ,loop-var (the integer4 ,(third do_vble_clause))
					   ,iteration_count (the integer4 (1- ,iteration_count)))))
			   '((go loop)))))))
275
      exit)))
rtoy's avatar
rtoy committed
276

277
;;----------------------------------------------------------------------------
rtoy's avatar
rtoy committed
278 279
;; macro for division 

rtoy's avatar
rtoy committed
280 281 282 283
(defmacro f2cl/ (x y)
  (let ((top (gensym))
	(bot (gensym)))
    `(let ((,top ,x)
284
	   (,bot ,y))
rtoy's avatar
rtoy committed
285 286
      (if (and (typep ,top 'integer)
	       (typep ,bot 'integer))
287
	  (values (the integer4 (truncate ,top ,bot)))
rtoy's avatar
rtoy committed
288
	  (/ ,top ,bot)))))
rtoy's avatar
rtoy committed
289

rtoy's avatar
rtoy committed
290 291 292 293 294 295 296
(defmacro int-add (arg &rest more-args)
  (if (null more-args)
      arg
      (if (> (length more-args) 1)
	  `(the integer4 (+ ,arg (int-add ,@more-args)))
	  `(the integer4 (+ ,arg ,@more-args)))))

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
(defun convert-int-sub (args)
  (let ((nargs (length args)))
    (case nargs
      (1
       `(the integer4 (- ,(first args))))
      (2
       `(the integer4 (- ,(first args) ,(second args))))
      (t
       (let ((result `(the integer4 (- ,(first args) ,(second args)))))
	 (dolist (arg (rest (rest args)))
	   (setf result `(the integer4 (- ,result ,arg))))
	 result)))))

(defmacro int-sub (&rest args)
  (convert-int-sub args))
  
rtoy's avatar
rtoy committed
313 314 315 316 317 318 319 320
(defmacro int-mul (arg &rest more-args)
  (if (null more-args)
      arg
      (if (> (length more-args) 1)
	  `(the integer4 (* ,arg (int-mul ,@more-args)))
	  `(the integer4 (* ,arg ,@more-args)))))


rtoy's avatar
rtoy committed
321
;; macro for a lisp equivalent of Fortran arithmetic IFs
rtoy's avatar
rtoy committed
322 323 324 325 326 327 328
(defmacro arithmetic-if (pred s1 s2 s3)
  (let ((tst (gensym)))
    `(let ((,tst ,pred))
      (cond ((< ,tst 0) ,s1)
	    ((= ,tst 0) ,s2)
	    (t ,s3)))))

rtoy's avatar
rtoy committed
329
;; macro for a lisp equivalent of Fortran computed GOTOs
rtoy's avatar
rtoy committed
330 331 332 333 334 335 336 337 338 339 340
(defun computed-goto-aux (tags)
  (let ((idx 0)
	(result '()))
    (dolist (tag tags (nreverse result))
      (incf idx)
      (push `(,idx (go ,tag)) result))))

(defmacro computed-goto (tag-lst i)
  `(case ,i
    ,@(computed-goto-aux tag-lst)))

rtoy's avatar
rtoy committed
341
;; macro for a lisp equivalent of Fortran assigned GOTOs
342 343 344
(eval-when
    #+gcl (compile load eval)
    #-gcl (:load-toplevel :compile-toplevel :execute)
rtoy's avatar
rtoy committed
345 346 347
(defun make-label (n) 
  (read-from-string (concatenate 'string (symbol-name :label) (princ-to-string n))))

348

349 350 351
(defun assigned-goto-aux (tag-list)
  (let ((cases nil))
    (dolist (tag tag-list)
352
      (push `(,tag (go ,(f2cl-lib::make-label tag)))
353 354 355
	    cases))
    (push `(t (error "Unknown label for assigned goto")) cases)
    (nreverse cases)))
356 357
)

358

rtoy's avatar
rtoy committed
359
;; macro for a lisp equivalent of Fortran assigned GOTOs
360 361 362 363
(defmacro assigned-goto (var tag-list)
  `(case ,var
     ,@(assigned-goto-aux tag-list)))

364 365 366
;;-----------------------------------------------------------------------------
;;
;; Define the intrinsic functions
rtoy's avatar
rtoy committed
367 368
;;
;; Reference:  The Fortran 77 standard found at www.fortran.com.  Section 15.10
369

rtoy's avatar
rtoy committed
370 371 372
;; INT is the generic name as well as the integer version.  IFIX is
;; the same.  IDINT is the double version.

373 374
(declaim (inline int ifix idfix))

rtoy's avatar
rtoy committed
375
#-(or cmu scl)
376 377 378 379 380 381
(defun int (x)
  ;; We use fixnum here because f2cl thinks Fortran integers are
  ;; fixnums.  If this should change, we need to change the ranges
  ;; here as well.
  (etypecase x
    (integer
382
     (the integer4 x))
383
    (single-float
384 385 386
     (truncate (the (single-float #.(float most-negative-fixnum)
				  #.(float most-positive-fixnum))
		 x)))
387
    (double-float
388 389
     (truncate (the (double-float #.(float most-negative-fixnum 1d0)
				  #.(float most-positive-fixnum 1d0))
390 391 392 393 394 395 396 397 398 399 400
		    x)))
    ((complex single-float)
     (the integer4
       (truncate (the (single-float #.(float (- (ash 1 31)))
				    #.(float (1- (ash 1 31))))
		      (realpart x)))))
    ((complex double-float)
     (the integer4
       (truncate (the (double-float #.(float (- (ash 1 31)) 1d0)
				    #.(float (1- (ash 1 31)) 1d0))
		      (realpart x)))))))
rtoy's avatar
rtoy committed
401

rtoy's avatar
rtoy committed
402
#+(or cmu scl)
403
(defun int (x)
404 405 406 407
  ;; For CMUCL, we support the full 32-bit integer range, so INT can
  ;; return a full 32-bit integer.  Tell CMUCL that this is true so we
  ;; generate fast code.  If this is not true, the original Fortran
  ;; code was wrong.
408 409
  (etypecase x
    (integer
410
     (the integer4 x))
411
    (single-float
rtoy's avatar
rtoy committed
412 413 414 415
     (the integer4
       (truncate (the (single-float #.(float (- (ash 1 31)))
				    #.(float (1- (ash 1 31))))
		   x))))
416
    (double-float
rtoy's avatar
rtoy committed
417 418 419
     (the integer4
       (truncate (the (double-float #.(float (- (ash 1 31)) 1d0)
				    #.(float (1- (ash 1 31)) 1d0))
420 421 422 423 424 425 426 427 428 429 430
		      x))))
    ((complex single-float)
     (the integer4
       (truncate (the (single-float #.(float (- (ash 1 31)))
				    #.(float (1- (ash 1 31))))
		      (realpart x)))))
    ((complex double-float)
     (the integer4
       (truncate (the (double-float #.(float (- (ash 1 31)) 1d0)
				    #.(float (1- (ash 1 31)) 1d0))
		      (realpart x)))))))
431 432


433 434 435 436
(defun ifix (x)
  (int x))
(defun idfix (x)
  (int x))
rtoy's avatar
rtoy committed
437

rtoy's avatar
rtoy committed
438 439 440 441 442 443 444 445 446 447 448
;; AINT is the generic and specific function for real; DINT, for
;; double.  It truncates its arg towards zero and returns the integer
;; as a floating-point number of the same type as its arg.
;;
;; ANINT is the generic and specific function for real; DNINT, for
;; double. It rounds to the nearest integer and returns the result as
;; a float of the same type.
;;
;; NINT is the generic and specific function for real; IDNINT, for
;; double.  Does the same as ANINT, but the result is an integer.

449 450
(declaim (inline aint dint anint dnint nint idnint))

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
;; This is based on the algorithm given by Anton Ertl in
;; comp.arch.arithmetic on Oct. 26, 2002:
;;
;; #define X 9007199254740992. /* 2^53 */
;; double rint(double r)
;; {
;;   if (r<0.0)
;;     return (r+X)-X;
;;   else
;;     return (r-X)+X;
;; }
;;
;; This assumes that we in round-to-nearest mode (the default).
;;
;; These only work if you have IEEE FP arithmetic.  There are 2
466
;; versions given below.  One is for non-x87, which assumes that
467
;; single and double FP numbers are properly rounded after each
468
;; operation.  The version for x87 stores away a value to make sure
469 470 471 472 473 474 475 476 477
;; the rounding happens correctly.
;;
;; Finally, the last version if for platforms where none of this
;; holds and we call ftruncate.
;;
;; With CMUCL pre-18e on sparc, this definition of aint reduces the
;; cost of MPNORM (from MPFUN) from 48.89 sec to 24.88 sec (a factor
;; of 2!) when computing pi to 29593 digits or os.

478
(declaim (inline rint-s rint-d))
479
#+(and cmu (or :sse2 (not x86)))
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
(progn
(defun rint-s (x)
  (declare (single-float x))
  (let ((const (scale-float 1f0 24)))
    (if (>= x 0)
	(+ (- x const) const)
	(- (+ x const) const))))

(defun rint-d (x)
  (declare (double-float x))
  (let ((const (scale-float 1d0 53)))
    (if (>= x 0)
	(+ (- x const) const)
	(- (+ x const) const))))
)

496
#+(and cmu (and x86 x87))
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
(progn
(defun rint-s (x)
  (declare (single-float x))
  (let ((junks (make-array 1 :element-type 'single-float))
	(const (scale-float 1f0 24)))
    (if (>= x 0)
	(progn
	  (setf (aref junks 0) (- x const))
	  (+ (aref junks 0) const))
	(progn
	  (setf (aref junks 0) (+ x const))
	  (- (aref junks 0) const)))))

(defun rint-d (x)
  (declare (double-float x))
  (let ((junkd (make-array 1 :element-type 'double-float))
	(const (scale-float 1d0 53)))
    (if (>= x 0)
	(progn
	  (setf (aref junkd 0) (- x const))
	  (+ (aref junkd 0) const))
	(progn
	  (setf (aref junkd 0) (+ x const))
	  (- (aref junkd 0) const)))))
)

;; Truncate x to an integer.
#+cmu
525
(defun aint (x)
526 527
  ;; rint above is fast.  We use it to round the number, and then
  ;; adjust the result to truncate.
528 529
  (etypecase x
    (single-float
530 531 532 533 534 535
     (let ((r (rint-s x)))
       (if (> (abs r) (abs x))
	   (if (> r 0)
	       (- r 1)
	       (+ r 1))
	   r)))
536
    (double-float
537 538 539 540 541 542 543
     (let ((r (rint-d x)))
       (if (> (abs r) (abs x))
	   (if (> r 0)
	       (- r 1)
	       (+ r 1))
	   r)))))
    
544 545

#-cmu
546
(defun aint (x)
547
  ;; ftruncate is exactly what we want.
548 549
  (etypecase x
    (single-float
550 551 552
     (locally 
       (declare (optimize (space 0) (speed 3)))
       (values (ftruncate (the single-float x)))))
553
    (double-float
554 555 556
     (locally 
       (declare (optimize (space 0) (speed 3)))
       (values (ftruncate (the double-float x)))))))
557 558 559 560 561

(defun dint (x)
  (aint x))

(defun anint (x)
rtoy's avatar
rtoy committed
562
  (values (fround x)))
563 564 565 566 567 568 569
(defun dnint (x)
  (values (fround x)))
(defun nint (x)
  (values (round x)))
(defun idnint (x)
  (values (round x)))

rtoy's avatar
rtoy committed
570 571 572 573 574 575 576
;; Type conversion
;;
;; FREAL is F2CL's version of the Fortran REAL which takes converts
;; its arg to a real.  SNGL is the same.  DBLE returns a double.  They
;; also return the real part of a complex number.  CMPLX takes one or
;; two args and creates a complex number.

rtoy's avatar
rtoy committed
577
(declaim (inline freal sngl dble dfloat cmplx))
rtoy's avatar
rtoy committed
578
(defun freal (x)
579 580 581 582 583 584 585 586
  (coerce (realpart x) 'single-float))

(defun sngl (x)
  (coerce (realpart x) 'single-float))

(defun dble (x)
  (coerce (realpart x) 'double-float))

rtoy's avatar
rtoy committed
587 588 589
(defun dfloat (x)
  (coerce (realpart x) 'double-float))

590 591 592
(defun cmplx (x &optional y)
  (complex x (if y y 0)))

rtoy's avatar
rtoy committed
593 594 595
(defun dcmplx (x &optional y)
  (coerce (complex x (if y y 0)) '(complex double-float)))

596
(defun ichar (c)
597 598 599
  (if (stringp c)
      (char-int (aref c 0))
      (char-int c)))
600
(defun fchar (i)			;intrinsic function char
601
  (code-char i))
rtoy's avatar
rtoy committed
602

rtoy's avatar
rtoy committed
603
(declaim (inline iabs dabs cabs cdabs amod dmod))
rtoy's avatar
rtoy committed
604
#-aclpc
605 606 607 608 609 610 611 612 613
(defun iabs (x)
  (declare (type integer4 x))
  (abs x))
(defun dabs (x)
  (declare (type double-float x))
  (abs x))
(defun cabs (x)
  (declare (type complex x))
  (abs x))
rtoy's avatar
rtoy committed
614 615 616
(defun cdabs (x)
  (declare (type (complex double-float) x))
  (abs x))
617 618 619 620 621 622 623 624 625

(defun amod (x y)
  (declare (type single-float x y))
  (mod x y))
(defun dmod (x y)
  (declare (type double-float x y))
  (mod x y))


rtoy's avatar
rtoy committed
626 627 628 629
;; Transfer of sign.  SIGN is the generic and specific function for
;; real.  ISIGN is for integers; DSIGN for doubles.  Basically
;; computes sign(a2)*|a1|.

630 631
(declaim (inline isign sign dsign))

632 633 634
(defun isign (x y)
  (declare (type integer4 x y))
  (if (>= y 0)
635 636 637
      (the integer4 (abs x))
      (the integer4 (- (the integer4 (abs x))))))

638
;; Fortran 77 says SIGN is a generic!
639
(defun sign (x y)
640 641 642 643 644 645 646 647 648
  (declare (type (or integer4 single-float double-float) x y))
  (etypecase x
    (integer4
     (isign x y))
    (single-float
     (float-sign y x))
    (double-float
     (float-sign y x))))

649 650 651 652
(defun dsign (x y)
  (declare (type double-float x y))
  (float-sign y x))

rtoy's avatar
rtoy committed
653 654 655 656 657
;; Positive difference.  DIM is the generic and specific function for
;; real.  IDIM is for integers; DDIM, doubles.
;;
;; If a1 > a2, returns a1-a2, otherwise 0.  Basically the same as
;; max(0, a1-a2).
658
(declaim (inline idim dim ddim))
659 660
(defun idim (x y)
  (declare (type integer4 x y))
rtoy's avatar
rtoy committed
661 662
  (max 0 (- x y)))

663
(defun dim (x y)
664 665 666
  (declare (type (or integer4 single-float double-float) x y))
  (etypecase x
    (integer4
rtoy's avatar
rtoy committed
667
     (max 0 (- x y)))
668
    (single-float
rtoy's avatar
rtoy committed
669
     (max 0f0 (- x y)))
670
    (double-float
rtoy's avatar
rtoy committed
671
     (max 0d0 (- x y)))))
672

673 674
(defun ddim (x y)
  (declare (type double-float x y))
rtoy's avatar
rtoy committed
675
  (max 0d0 (- x y)))
676

rtoy's avatar
rtoy committed
677 678 679
;; Double-precision product.  How this is done isn't specified, but I
;; suspect the real args are converted to doubles and then the product
;; is computed.
680
(defun dprod (x y)
rtoy's avatar
rtoy committed
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
  (declare (single-float x y))
  (* (float x 1d0) (float y 1d0)))

;; The max and min functions.
;;
;; MAX is the generic. MAX0, AMAX1, and DMAX1 returns the max of the
;; args with the same type as the args.
;;
;; AMAX0 takes integer args and returns the max as a real. MAX1 takes
;; real args and returns the max as a integer.  (How the conversion is
;; done isn't specified.)
;;
;; Should we make these macros that expand directly to the appropriate
;; max?
(defun max0 (x y &rest z)
696
  #-gcl(declare (integer x y))
rtoy's avatar
rtoy committed
697 698
  (apply #'max x y z))
(defun amax1 (x y &rest z)
699
  #-gcl(declare (single-float x y))
rtoy's avatar
rtoy committed
700 701
  (apply #'max x y z))
(defun dmax1 (x y &rest z)
702
  #-gcl(declare (double-float x y))
rtoy's avatar
rtoy committed
703 704
  (apply #'max x y z))
(defun max1 (x y &rest z)
705
  #-gcl(declare (single-float x y))
rtoy's avatar
rtoy committed
706 707
  (int (apply #'max x y z)))
(defun amax0 (x y &rest z)
708
  #-gcl(declare (type integer4 x y))
rtoy's avatar
rtoy committed
709 710 711 712 713 714 715 716 717 718 719 720 721
  (float (apply #'max x y z) 1f0))

(defun min0 (x y &rest z)
  (apply #'min x y z))
(defun amin1 (x y &rest z)
  (apply #'min x y z))
(defun dmin1 (x y &rest z)
  (apply #'min x y z))

(defun amin0 (x y &rest z)
  (float (apply #'min x y z)))
(defun min1 (x y &rest z)
  (nint (apply #'min x y z)))
722 723

;; Define some compile macros for these max/min functions.
rtoy's avatar
rtoy committed
724
#+(or cmu scl)
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
(progn
(define-compiler-macro max0 (&rest args)
  `(max ,@args))
(define-compiler-macro amax1 (&rest args)
  `(max ,@args))
(define-compiler-macro dmax1 (&rest args)
  `(max ,@args))
(define-compiler-macro min0 (&rest args)
  `(min ,@args))
(define-compiler-macro amin1 (&rest args)
  `(min ,@args))
(define-compiler-macro dmin1 (&rest args)
  `(min ,@args))
(define-compiler-macro min1 (&rest args)
  `(nint (min ,@args)))

(define-compiler-macro amax0 (&rest args)
  `(float (max ,@args)))
(define-compiler-macro max1 (&rest args)
  `(nint (max ,@args)))

(define-compiler-macro amin0 (&rest args)
  `(float (min ,@args)))
(define-compiler-macro min1 (&rest args)
  `(nint (min ,@args)))
) ; end progn
751 752 753

(defun len (s)
  (length s))
rtoy's avatar
rtoy committed
754

755 756 757 758 759 760 761 762 763 764 765
;; From http://www.fortran.com/fortran/F77_std/rjcnf0001-sh-15.html#sh-15.10:
;;
;; INDEX(a1 ,a2) returns an integer value indicating the starting
;; position within the character string a1 of a substring identical
;; to string a2 . If a2 occurs more than once in a1 , the starting
;; position of the first occurrence is returned.
;;
;; If a2 does not occur in a1 , the value zero is returned. Note
;; that zero is returned if LEN(a1) < LEN(a2).
;;
;; Thus the arguments are in the opposite order for CL's SEARCH function.
rtoy's avatar
rtoy committed
766
(defun index (s1 s2)
767
  (or (search s2 s1) 0))
rtoy's avatar
rtoy committed
768 769

;; These string operations need some work!
770 771 772 773 774 775 776 777
(defun lge (s1 s2)
  (string>= s1 s2))
(defun lgt (s1 s2)
  (string> s1 s2))
(defun lle (s1 s2)
  (string<= s1 s2))
(defun llt (s1 s2)
  (string< s1 s2))
rtoy's avatar
rtoy committed
778

rtoy's avatar
rtoy committed
779 780 781 782 783 784 785 786 787 788 789 790 791 792
(defun fstring-/= (s1 s2)
  (not (string= s1 s2)))
(defun fstring-= (s1 s2)
  (string= s1 s2))
(defun fstring-> (s1 s2)
  (string> s1 s2))
(defun fstring->= (s1 s2)
  (string>= s1 s2))
(defun fstring-< (s1 s2)
  (string< s1 s2))
(defun fstring-<= (s1 s2)
  (string<= s1 s2))


rtoy's avatar
rtoy committed
793 794
;; AIMAG: imaginary part of a complex number
;; CONJG: conjugate of a complex number
rtoy's avatar
rtoy committed
795
(declaim (inline aimag conjg dconjg dimag))
796 797
(defun aimag (c)
  (imagpart c))
rtoy's avatar
rtoy committed
798
(defun dimag (c)
rtoy's avatar
rtoy committed
799
  (declare (type (complex double-float) c))
rtoy's avatar
rtoy committed
800
  (imagpart c))
801 802
(defun conjg (c)
  (conjugate c))
rtoy's avatar
rtoy committed
803 804 805
(defun dconjg (c)
  (declare (type (complex double-float) c))
  (conjugate c))
rtoy's avatar
rtoy committed
806

807 808 809 810
(declaim (inline fsqrt flog))
(defun fsqrt (x)
  (typecase x
    (single-float
811
     (sqrt (the (or (single-float (0f0)) (member 0f0)) x)))
812
    (double-float
813
     (sqrt (the (or (double-float (0d0)) (member 0d0)) x)))
814 815
    (t
     (sqrt x))))
rtoy's avatar
rtoy committed
816

817 818 819 820 821 822 823 824 825
(defun flog (x)
  (typecase x
    (single-float
     (log (the (or (single-float (0f0)) (member 0f0)) x)))
    (double-float
     (log (the (or (double-float (0d0)) (member 0d0)) x)))
    (t
     (log x))))
  
rtoy's avatar
rtoy committed
826 827 828 829
;; Tell Lisp that the arguments always have the correct range.  If
;; this is not true, the original Fortran code was broken anyway, so
;; GIGO (garbage in, garbage out).

rtoy's avatar
rtoy committed
830
(declaim (inline dsqrt csqrt zsqrt alog dlog clog alog10 dlog10))
831
(defun dsqrt (x)
832 833
  (declare (type (double-float 0d0) x))
  (sqrt  x))
834 835
(defun csqrt (x)
  (sqrt x))
rtoy's avatar
rtoy committed
836 837
(defun zsqrt (x)
  (sqrt x))
838
(defun alog (x)
839 840
  (declare (type (or (single-float (0f0)) (member 0f0)) x))
  (log x))
841
(defun dlog (x)
842 843
  (declare (type (or (double-float (0d0)) (member 0d0)) x))
  (log x))
844 845 846
(defun clog (x)
  (log x))
(defun alog10 (x)
847 848
  (declare (type (or (single-float (0f0)) (member 0f0)) x))
  (log x 10f0))
849
(defun dlog10 (x)
850 851 852 853
  (declare (type (or (double-float (0d0)) (member 0d0)) x))
  (log x 10.0d0))

(declaim (inline log10))
854
(defun log10 (x)
855 856
  (typecase x
    (single-float
857
     (log (the (or (single-float (0.0f0)) (member 0f0)) x) 10f0))
858
    (double-float
859
     (log (the (or (double-float (0.0d0)) (member 0d0)) x) 10d0))
860 861 862 863 864 865 866 867 868
    (t
     (/ (log x)
	(typecase x
	  ((complex double-float)
	   10d0)
	  ((complex single-float)
	   10f0)
	  (t
	   (coerce 10 (type-of (realpart x)))))))))
869

870
(declaim (inline dexp cexp))
871 872 873 874 875 876 877
(defun dexp (x)
  (declare (type double-float x))
  (exp x))
(defun cexp (x)
  (declare (type complex x))
  (exp x))

878
(declaim (inline dsin csin dcos ccos dtan ctan dasin dacos datan atan2 datan2 dsinh dcosh dtanh))
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
(defun dsin (x)
  (declare (type double-float x))
  (sin x))
(defun csin (x)
  (declare (type complex x))
  (sin x))

(defun dcos (x)
  (declare (type double-float x))
  (cos x))
(defun ccos (x)
  (declare (type complex x))
  (cos x))

(defun dtan (x)
  (declare (type double-float x))
  (tan x))
(defun ctan (x)
  (declare (type complex x))
  (tan x))

(defun dasin (x)
  (declare (type double-float x))
  (asin x))
(defun dacos (x)
  (declare (type double-float x))
  (acos x))
(defun datan (x)
  (declare (type double-float x))
  (atan x))
(defun atan2 (x y)
910
  (declare (type single-float x))
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
  (atan x y))
(defun datan2 (x y)
  (declare (type double-float x y))
  (atan x y))

(defun dsinh (x)
  (declare (type double-float x))
  (sinh x))
(defun dcosh (x)
  (declare (type double-float x))
  (cosh x))
(defun dtanh (x)
  (declare (type double-float x))
  (tanh x))

926
(declaim (inline ffloat))
927 928
(defun ffloat (x)
  (coerce x 'single-float))
rtoy's avatar
rtoy committed
929

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
(defun process-implied-do (ido array-bnds var-types init)
  (destructuring-bind (data-vars &rest looping)
      ido
    (labels
	((convert-type (type)
	   (if (eq type 'integer4)
	       `(truncate (pop ,init))
	       `(coerce (pop ,init) ',type)))
	 (map-vars (v)
	   (mapcar #'(lambda (x b vt)
		       `(fset (fref ,(first x) ,(second x) ,b)
			      ,(convert-type vt)))
		   v array-bnds var-types)))
      (let ((body (map-vars data-vars)))
	(dolist (loopvar looping)
	  (destructuring-bind (index-var start end &optional step)
	      loopvar
	    (setf body `((do ((,index-var ,start (+ ,index-var ,(or step 1))))
			    ((> ,index-var ,end))
			  ,@body)))))
	(car body)))))

rtoy's avatar
rtoy committed
952 953

;; Process implied do loops for data statements
954
(defmacro data-implied-do (implied-do array-bnds var-types vals)
rtoy's avatar
rtoy committed
955
  (let ((v (gensym)))
956
    `(let ((,v (list ,@vals)))
957
      ,(process-implied-do implied-do array-bnds var-types v))))
958

rtoy's avatar
rtoy committed
959
;;-----------------------------------------------------------------------------
rtoy's avatar
rtoy committed
960
   
rtoy's avatar
rtoy committed
961 962
;; Map Fortran logical unit numbers to Lisp streams

963
#-gcl
964
(defparameter *lun-hash*
965
  (make-hash-table))
rtoy's avatar
rtoy committed
966

967 968
#+gcl
(defvar *lun-hash*
969
  (make-hash-table))
970

971 972 973 974
(defun lun->stream (lun &optional readp)
  (let ((stream (gethash lun *lun-hash*)))
    (if stream
	stream
975 976 977 978 979 980 981 982 983
	(cond ((eql lun 5)
	       ;; Always standard input
	       (setf (gethash lun *lun-hash*) *standard-input*))
	      ((or (eql lun 6)
		   (eql lun t))
	       ;; Always standard output
	       (setf (gethash lun *lun-hash*) *standard-output*))
	      ((integerp lun)
	       ;; All other cases open a file fort<n>.dat
984 985
	       (setf (gethash lun *lun-hash*)
		     (open (format nil "fort~d.dat" lun)
986
			   :direction :io
987 988 989 990 991
			   :if-exists :rename)))
	      ((stringp lun)
	       (setf (gethash lun *lun-hash*)
		     (if readp
			 (make-string-input-stream lun)
992
			 (make-string-output-stream))))))))
993

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
(defun init-fortran-io ()
  "Initialize the F2CL Fortran I/O subsystem to sensible defaults"
  (clrhash *lun-hash*)
  (setf (gethash 6 *lun-hash*) *standard-output*)
  (setf (gethash 5 *lun-hash*) *standard-input*)
  (setf (gethash t *lun-hash*) *standard-output*))

(defun close-fortran-io ()
  "Close all F2CL Fortran units (except for standard output and input)
causing all pending operations to be flushed"
  (maphash #'(lambda (key val)
	       (when (and (streamp val) (not (member key '(5 6 t))))
		 (format t "Closing unit ~A: ~A~%" key val)
		 (close val)))
rtoy's avatar
rtoy committed
1008
	       *lun-hash*))
1009

1010
(defun %open-file (&key unit file status access form recl blank)
rtoy's avatar
rtoy committed
1011 1012
  (declare (ignore unit))
  ;; We should also check for values of form that we don't support.
1013 1014 1015 1016 1017 1018 1019
  (when recl
    (error "F2CL-LIB does not support record lengths"))
  (when blank
    (error "F2CL-LIB does not support any BLANK mode for files"))
  (when (and access (not (string-equal "sequential"
				       (string-right-trim " " access))))
    (error "F2CL-LIB does not support ACCESS mode ~S" access))
rtoy's avatar
rtoy committed
1020 1021 1022
  (when (and form (not (string-equal "unformatted"
				     (string-right-trim " " form))))
    (error "F2CL-LIB does not support FORM ~S" form))
1023 1024 1025
  (let ((s (and status (string-right-trim " " status))))
    (finish-output)
    (cond ((or (null s) (string-equal s "unknown"))
1026
	   (open file :direction :io :if-exists :supersede
1027
		 :if-does-not-exist :create))
1028
	  ((string-equal s "old")
1029
	   (open file :direction :io :if-does-not-exist nil :if-exists :overwrite))
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
	  ((string-equal s "new")
	   (open file :direction :io :if-exists nil))
	  (t
	   (error "F2CL-LIB does not support this mode for OPEN: ~S~%"
		  s)))))

(defmacro open-file (&key unit iostat err file status access form recl blank)
  (let ((result (gensym)))
    `(prog ((,result (%open-file :unit ,unit :file ,file :status ,status
				 :access ,access :form ,form :recl ,recl :blank ,blank)))
	(when ,result
	  (setf (gethash ,unit *lun-hash*) ,result))
	,(if err `(unless ,result (go ,(f2cl-lib::make-label err))))
	,(if iostat `(setf ,iostat (if ,result 0 1))))))

(defun %rewind (unit)
  (file-position (lun->stream unit) :start))

(defmacro rewind (&key unit iostat err)
  (let ((result (gensym)))
    `(prog ((,result (%rewind ,unit)))
1051
	(declare (ignorable ,result))
1052 1053 1054 1055 1056
	,(if err `(unless ,result (go ,(f2cl-lib::make-label err))))
	,(if iostat `(setf ,iostat (if ,result 0 1))))))
	  

(defun %close (&key unit status)
rtoy's avatar
rtoy committed
1057 1058
  (when status
    (error "F2CL-LIB does not support STATUS"))
1059 1060 1061 1062 1063
  (cl:close (lun->stream unit)))

(defmacro close$ (&key unit iostat err status)
  (let ((result (gensym)))
    `(prog ((,result (%close :unit ,unit  :status ,status)))
1064
	(declare (ignorable ,result))
1065 1066 1067
	,(if err `(unless ,result (go ,(f2cl-lib::make-label err))))
	,(if iostat `(setf ,iostat (if ,result 0 1))))))

1068
#-gcl
rtoy's avatar
rtoy committed
1069 1070
(declaim (ftype (function (t) stream) lun->stream))

1071 1072 1073
(defmacro fformat (dest-lun format-cilist &rest args)
  (let ((stream (gensym)))
    `(let ((,stream (lun->stream ,dest-lun)))
1074 1075 1076 1077
       (execute-format-main ,stream ',format-cilist ,@args)
       ,@(unless (or (eq t dest-lun) (numberp dest-lun))
	  `((when (stringp ,dest-lun)
	     (replace ,dest-lun (get-output-stream-string ,stream))))))))
1078

1079
(defun execute-format (top stream format arg-list)
1080 1081 1082 1083
  (do ((formats format (if (and top (null formats))
			   format
			   (rest formats))))
      ((or (null arg-list)
1084
	   (and (not top)
1085
		(null formats)))
1086 1087 1088 1089
       #+nil
       (progn
	 (format t "~&end formats = ~S~%" formats)
	 (format t "~&end arg-list = ~S~%" arg-list))
1090 1091 1092 1093
       (do ((more formats (rest more)))
	   ((not (stringp (first more))))
	 (format stream (first more)))
       arg-list)
1094

1095
    (when (null formats)
1096
      ;; We're out of formats but not arguments.  I think Fortran says
1097
      ;; we should start over at the last repeat spec.  So we look
1098 1099
      ;; over all the formats until we find the first number.  That
      ;; means it's a repeat spec.
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
      ;;
      ;; This is probably wrong for complicated format statements.
      (do ((f format (cdr f))
	   (last-rep nil))
	  ((null f)
	   (setf formats last-rep))
	(when (or (eq (car f) t)
		  (numberp (car f)))
	  (setf last-rep f)))

1110 1111 1112 1113
      (when (null formats)
	;; Now what?  We couldn't find a repeat spec, so should we
	;; just start over?
	(setf formats format)))
1114 1115
    #+nil
    (let ((*print-circle* t))
rtoy's avatar
rtoy committed
1116
      (format t "~&arg-list = ~S~%" arg-list)
1117 1118 1119
      (format t "~&formats = ~S~%" formats))
    (cond ((listp (first formats))
	   (format stream (caar formats) (pop arg-list)))
1120
	  ((eq (first formats) #\:)
rtoy's avatar
rtoy committed
1121
	   ;; Terminate control if there are no more items
1122 1123
	   (when (null arg-list)
	     (return-from execute-format)))
1124
	  ((numberp (first formats))
1125 1126 1127 1128
	   ;; Repeat a group some fixed number of times
	   (dotimes (k (first formats))
	     ;;(format t "k = ~A, format = ~S~%" k (second formats))
	     (setf arg-list
1129 1130 1131 1132
		   (execute-format nil stream (second formats) arg-list))
	     ;; Gotta exit if we're out of arguments to print!
	     (unless arg-list
	       (return)))
1133
	   (setf formats (rest formats))
rtoy's avatar
rtoy committed
1134 1135
	   ;; Output a newline after the repeat (I think Fortran says this)
	   ;;(format stream "~&")
1136 1137
	   ;;(format t "  cont with format = ~S~%" formats)
	   )
rtoy's avatar
rtoy committed
1138 1139 1140 1141
	  ((eq (first formats) t)
	   ;; Repeat "forever" (until we run out of data)
	   (loop while arg-list do
		(setf arg-list
1142
		      (execute-format nil stream (second formats) arg-list))
rtoy's avatar
rtoy committed
1143 1144
	      ;; Output a newline after the repeat (I think Fortran says this)
		(format stream "~%")))
1145 1146 1147
	  (t
	   (format stream (car formats))))))
	   
rtoy's avatar
rtoy committed
1148 1149 1150 1151 1152 1153 1154 1155 1156
(defun flatten-list (x)
  (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
	     (cond ((null x) r)
		   ((atom x)
		    (cons x r))
		   (t (flatten-helper (car x)
				      (flatten-helper (cdr x) r))))))
    (flatten-helper x nil)))

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
;; Fortran G format, roughly.  We use ~F for numbers "near" 1, and use
;; ~E otherwise.
;;
;; Note that g77 seems to use an exponent marker of E for single and
;; double floats, but Sun Fortran uses E and D.  I think I like E and
;; D to distinguish between them.  Also note that g77 uses just enough
;; digits for the numbers, but Sun Fortran seems to specify the number
;; of printed digits to be 16 or so.  Thus 1.0 is "1.0" with g77, but
;; "1.0000000000000" with Sun Fortran.  I like g77's style better.
(defun fortran-format-g (stream arg colon-p at-p &rest args)
  (declare (ignore colon-p at-p args))
  (let* ((marker (typecase arg
		   (single-float "E")
		   (double-float "D")))
1171
	 (a (abs arg))
1172 1173
	 ;; g77 uses limits 1d-4 and 1d9.  Sun Fortran uses 1 and
	 ;; 1d15.
1174 1175 1176
	 (format-string (if (or (zerop a)
				(and (>= a 1d-4)
				     (< a 1d9)))
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
			    "~F"
			    (concatenate 'string "~,,2,,,,'"
					 marker
					 "E"))))
    (format stream format-string arg)))

;; Output objects in Fortran style, roughly.  This basically means
;; complex numbers are printed as "(<re>, <im>)", floats use
;; FORTRAN-FORMAT-G, integers use ~D, strings are printed as is, and
;; T/NIL become "T" or "F".
(defun fortran-format (stream arg colon-p at-p &rest args)
  (declare (ignore colon-p at-p args))
  (etypecase arg
    (complex
1191
     #-gcl
1192
     (format stream "(~/f2cl-lib::fortran-format-g/, ~/f2cl-lib::fortran-format-g/)"
1193 1194 1195 1196 1197
	     (realpart arg) (imagpart arg))
     #+gcl
     (progn
       (fortran-format-g stream (realpart arg) nil nil)
       (fortran-format-g stream (imagpart arg) nil nil)))
1198
    (float
1199 1200 1201 1202
     #-gcl
     (format stream "  ~/f2cl-lib::fortran-format-g/" arg)
     #+gcl
     (fortran-format-g stream arg nil nil))
1203 1204 1205 1206 1207 1208 1209
    (integer
     (format stream "  ~D" arg))
    (string
     (format stream "~A" arg))
    ((member t nil)
     (format stream (if arg "T " "F ")))))
     
1210
(defun execute-format-main (stream format &rest args)
rtoy's avatar
rtoy committed
1211 1212 1213 1214
  (cond
    ((eq format :list-directed)
     ;; This prints out the args separated by spaces and puts a line
     ;; break after about 80 columns.
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
     (format stream "~& ~{~<~%~1,81:;~?~>~^~}~%"
	     (let (pars)
	       (dolist (v args)
		 ;; Some special cases.  Let FORTRAN-FORMAT handle
		 ;; most cases, except strings, which we just print
		 ;; out ourselves.  Lists (from implied-do loops) and
		 ;; arrays use FORTRAN-FORMAT for each element.
		 (typecase v
		   (string
		    (push "~A"  pars)
		    (push (list v) pars))
		   (cons
		    (dolist (item v)
1228 1229 1230 1231 1232 1233 1234
		      #-gcl
		      (progn
			(push "~/f2cl-lib::fortran-format/" pars)
			(push (list item) pars))
		      (progn
			(push "~A" pars)
			(push (fortran-format nil item nil nil) pars))))
1235 1236
		   (array
		    (dotimes (k (length v))
1237 1238 1239 1240
		      #-gcl
		      (progn
			(push "~/f2cl-lib::fortran-format/" pars)
			(push (list (aref v k)) pars))
1241
		      #+gcl
1242 1243 1244 1245
		      (progn
			(push "~A" pars)
			(push (fortran-format nil (list (aref v k)) nil nil)
			      pars))))
1246
		   (t
1247 1248 1249 1250 1251 1252 1253 1254
		    #-gcl
		    (progn
		      (push "~/f2cl-lib::fortran-format/" pars)
		      (push (list v) pars))
		    #+gcl
		    (progn
		      (push "~A" pars)
		      (push (fortran-format nil (list v) nil nil) pars)))))
1255 1256
	       ;;(format t "~S~%" (reverse pars))
	       (nreverse pars))))
rtoy's avatar
rtoy committed
1257 1258
    (t
     (let ((format-list (copy-tree format))
rtoy's avatar
rtoy committed
1259 1260 1261 1262 1263 1264 1265
	   (arg-list
	    (apply #'append
		   (map 'list #'(lambda (x)
				  (cond ((numberp x)
					 (list x))
					((stringp x)
					 (list x))
rtoy's avatar
rtoy committed
1266
					((member x '(t nil))
rtoy's avatar
rtoy committed
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
					 ;; Convert T and NIL to :T
					 ;; and :F so we print out T
					 ;; and F, respectively.
					 (case x
					   ((t)
					    (list :t))
					   ((nil)
					    (list :f))
					   (t
					    (list x))))
					(t
					 (coerce x 'list))))
			args))))
rtoy's avatar
rtoy committed
1280
       (execute-format t stream format-list arg-list)))))
1281 1282


1283 1284 1285 1286 1287 1288 1289 1290 1291
;; Initialize a multi-dimensional array of character strings. I think
;; we need to do it this way to appease some picky compilers (like
;; CMUCL).  The initial-element is needed to get rid of a warning
;; about the default initial element not being a simple
;; string. However, this initializes all elements of the array to
;; exactly the same string, so we loop over the entire array contents
;; and initialize each element with a string of the appropriate
;; length.  The string is initialized with #\Space because it seems
;; that's what Fortran initializes it to.
1292
(defmacro f2cl-init-string (dims len &optional inits)
rtoy's avatar
rtoy committed
1293 1294
  (let ((init (gensym (symbol-name '#:array-)))
	(k (gensym (symbol-name '#:idx-))))
rtoy's avatar
rtoy committed
1295
    `(let ((,init (make-array (* ,@dims)
1296
			      :element-type `(simple-array character (,',@len))
1297
			      :initial-element (make-string ,@len))))
1298 1299
       (dotimes (,k (array-total-size ,init))
	 (setf (aref ,init ,k)
1300
	       (make-string ,@len :initial-element #\Space)))
1301 1302 1303 1304
       ,@(when inits
	   (let ((k 0)
		 (forms nil))
	     (dolist (val inits)
1305
	       (push `(replace (aref ,init ,k) ,val) forms)