optparse: Make enum opthandler take an evaluated list.
[lisp] / optparse.lisp
CommitLineData
861345b4 1;;; -*-lisp-*-
2;;;
3;;; $Id$
4;;;
5;;; Option parser, standard issue
6;;;
7;;; (c) 2005 Straylight/Edgeware
8;;;
9
10;;;----- Licensing notice ---------------------------------------------------
11;;;
12;;; This program is free software; you can redistribute it and/or modify
13;;; it under the terms of the GNU General Public License as published by
14;;; the Free Software Foundation; either version 2 of the License, or
15;;; (at your option) any later version.
16;;;
17;;; This program is distributed in the hope that it will be useful,
18;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;;; GNU General Public License for more details.
21;;;
22;;; You should have received a copy of the GNU General Public License
23;;; along with this program; if not, write to the Free Software Foundation,
24;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
02866e07
MW
26;;;--------------------------------------------------------------------------
27;;; Packages.
28
0b3651e5 29(defpackage #:optparse
861345b4 30 (:use #:common-lisp #:mdw.base #:mdw.sys-base #:mdw.str)
31 (:export #:exit #:*program-name* #:*command-line-strings*
32 #:moan #:die
33 #:option #:optionp #:make-option
34 #:opt-short-name #:opt-long-name #:opt-tag #:opt-negated-tag
35 #:opt-arg-name #:opt-arg-optional-p #:opt-documentation
36 #:option-parser #:make-option-parser #:option-parser-p
37 #:op-options #:op-non-option #:op-long-only-p #:op-numeric-p
38 #:op-negated-numeric-p #:op-negated-p
39 #:option-parse-error
40 #:option-parse-remainder #:option-parse-next #:option-parse-try
b3bc3745 41 #:with-unix-error-reporting #:option-parse-return
861345b4 42 #:defopthandler #:invoke-option-handler
43 #:set #:clear #:inc #:dec #:read #:int #:string
44 #:keyword #:list
45 #:parse-option-form #:options
46 #:simple-usage #:show-usage #:show-version #:show-help
5fa07b7a
MW
47 #:sanity-check-option-list
48 #:*help* #:*version* #:*usage* #:*options*
b3bc3745
MW
49 #:do-options #:help-options
50 #:define-program #:do-usage #:die-usage))
861345b4 51
0b3651e5 52(in-package #:optparse)
861345b4 53
02866e07 54;;;--------------------------------------------------------------------------
861345b4 55;;; Standard error-reporting functions.
56
57(defun moan (msg &rest args)
58 "Report an error message in the usual way."
59 (format *error-output* "~&~A: ~?~%" *program-name* msg args))
5fa07b7a 60
861345b4 61(defun die (&rest args)
62 "Report an error message and exit."
63 (apply #'moan args)
64 (exit 1))
65
02866e07 66;;;--------------------------------------------------------------------------
861345b4 67;;; The main option parser.
68
b3bc3745 69(defvar *options* nil)
5fa07b7a 70
861345b4 71(defstruct (option (:predicate optionp)
72 (:conc-name opt-)
73 (:print-function
74 (lambda (o s k)
75 (declare (ignore k))
76 (format s
77 "#<option~@[ -~C,~]~@[ --~A~]~:[~2*~;~:[=~A~;[=~A]~]~]~@[ ~S~]>"
78 (opt-short-name o)
79 (opt-long-name o)
80 (opt-arg-name o)
81 (opt-arg-optional-p o)
82 (opt-arg-name o)
83 (opt-documentation o))))
84 (:constructor %make-option)
85 (:constructor make-option
86 (long-name
87 short-name
88 &optional
89 arg-name
90 &key
91 (tag (intern (string-upcase long-name)
92 :keyword))
93 negated-tag
94 arg-optional-p
95 doc
96 (documentation doc))))
97 "Describes a command-line option. Slots:
98
0ff9df03
MW
99 LONG-NAME The option's long name. If this is null, the `option' is
100 just a banner to be printed in the program's help text.
861345b4 101
0ff9df03
MW
102 TAG The value to be returned if this option is encountered. If
103 this is a function, instead, the function is called with the
104 option's argument or nil.
861345b4 105
0ff9df03
MW
106 NEGATED-TAG As for TAG, but used if the negated form of the option is
107 found. If this is nil (the default), the option cannot be
108 negated.
861345b4 109
0ff9df03
MW
110 SHORT-NAME The option's short name. This must be a single character, or
111 nil if the option has no short name.
861345b4 112
0ff9df03
MW
113 ARG-NAME The name of the option's argument, a string. If this is nil,
114 the option doesn't accept an argument. The name is shown in
115 the help text.
861345b4 116
0ff9df03
MW
117 ARG-OPTIONAL-P
118 If non-nil, the option's argument is optional. This is
119 ignored unless ARG-NAME is non-null.
861345b4 120
0ff9df03
MW
121 DOCUMENTATION
122 The help text for this option. It is automatically line-
123 wrapped. If nil, the option is omitted from the help
124 text.
861345b4 125
0ff9df03 126 Usually, one won't use make-option, but use the option macro instead."
861345b4 127 (long-name nil :type (or null string))
128 (tag nil :type t)
129 (negated-tag nil :type t)
130 (short-name nil :type (or null character))
131 (arg-name nil :type (or null string))
132 (arg-optional-p nil :type t)
133 (documentation nil :type (or null string)))
134
135(defstruct (option-parser (:conc-name op-)
136 (:constructor make-option-parser
5fa07b7a
MW
137 (&key
138 ((:args argstmp)
139 (cdr *command-line-strings*))
140 (options *options*)
861345b4 141 (non-option :skip)
142 ((:numericp numeric-p))
143 negated-numeric-p
144 long-only-p
145 &aux
146 (args (cons nil argstmp))
147 (next args)
148 (negated-p (or negated-numeric-p
149 (some
150 #'opt-negated-tag
151 options))))))
152 "An option parser object. Slots:
153
0ff9df03
MW
154 ARGS The arguments to be parsed. Usually this will be
155 *command-line-strings*.
861345b4 156
0ff9df03 157 OPTIONS List of option structures describing the acceptable options.
861345b4 158
0ff9df03
MW
159 NON-OPTION Behaviour when encountering a non-option argument. The
160 default is :skip. Allowable values are:
161 :skip -- pretend that it appeared after the option
162 arguments; this is the default behaviour of GNU getopt
163 :stop -- stop parsing options, leaving the remaining
164 command line unparsed
165 :return -- return :non-option and the argument word
861345b4 166
0ff9df03
MW
167 NUMERIC-P Non-nil tag (as for options) if numeric options (e.g., -43)
168 are to be allowed. The default is nil. (Anomaly: the
169 keyword for this argument is :numericp.)
861345b4 170
0ff9df03
MW
171 NEGATED-NUMERIC-P
172 Non-nil tag (as for options) if numeric options (e.g., -43)
173 can be negated. This is not the same thing as a negative
174 numeric option!
861345b4 175
0ff9df03
MW
176 LONG-ONLY-P A misnomer inherited from GNU getopt. Whether to allow
177 long options to begin with a single dash. Short options are
178 still allowed, and may be cuddled as usual. The default is
179 nil."
861345b4 180 (args nil :type list)
181 (options nil :type list)
182 (non-option :skip :type (or function (member :skip :stop :return)))
183 (next nil :type list)
184 (short-opt nil :type (or null string))
185 (short-opt-index 0 :type fixnum)
186 (short-opt-neg-p nil :type t)
187 (long-only-p nil :type t)
188 (numeric-p nil :type t)
189 (negated-numeric-p nil :type t)
190 (negated-p nil :type t))
191
192(define-condition option-parse-error (error simple-condition)
193 ()
0ff9df03
MW
194 (:documentation
195 "Indicates an error found while parsing options. Probably not that
196 useful."))
861345b4 197
198(defun option-parse-error (msg &rest args)
199 "Signal an option-parse-error with the given message and arguments."
200 (error (make-condition 'option-parse-error
201 :format-control msg
202 :format-arguments args)))
203
204(defun option-parse-remainder (op)
205 "Returns the unparsed remainder of the command line."
206 (cdr (op-args op)))
207
b3bc3745
MW
208(defun option-parse-return (tag &optional argument)
209 "Should be called from an option handler: forces a return from the
210 immediately enclosing `option-parse-next' with the given TAG and
211 ARGUMENT."
212 (throw 'option-parse-return (values tag argument)))
213
861345b4 214(defun option-parse-next (op)
215 "The main option-parsing function. OP is an option-parser object,
0ff9df03
MW
216 initialized appropriately. Returns two values, OPT and ARG: OPT is the
217 tag of the next option read, and ARG is the argument attached to it, or
218 nil if there was no argument. If there are no more options, returns nil
219 twice. Options whose TAG is a function aren't returned; instead, the tag
220 function is called, with the option argument (or nil) as the only
221 argument. It is safe for tag functions to throw out of option-parse-next,
222 if they desparately need to. (This is the only way to actually get
223 option-parse-next to return a function value, should that be what you
b3bc3745 224 want. See `option-parse-return' for a way of doing this.)
0ff9df03
MW
225
226 While option-parse-next is running, there is a restart `skip-option' which
227 moves on to the next option. Error handlers should use this to resume
228 after parsing errors."
b3bc3745
MW
229 (labels ((ret (opt &optional arg)
230 (return-from option-parse-next (values opt arg)))
231 (finished ()
232 (setf (op-next op) nil)
233 (ret nil nil))
234 (peek-arg ()
235 (cadr (op-next op)))
236 (more-args-p ()
237 (and (op-next op)
238 (cdr (op-next op))))
239 (skip-arg ()
240 (setf (op-next op) (cdr (op-next op))))
241 (eat-arg ()
242 (setf (cdr (op-next op)) (cddr (op-next op))))
243 (get-arg ()
244 (prog1 (peek-arg) (eat-arg)))
245 (process-option (o name negp &key arg argfunc)
246 (cond ((not (opt-arg-name o))
247 (when arg
248 (option-parse-error
249 "Option `~A' does not accept arguments"
250 name)))
251 (arg)
252 (argfunc
253 (setf arg (funcall argfunc)))
254 ((opt-arg-optional-p o))
255 ((more-args-p)
256 (setf arg (get-arg)))
257 (t
258 (option-parse-error "Option `~A' requires an argument"
259 name)))
260 (let ((how (if negp (opt-negated-tag o) (opt-tag o))))
261 (if (functionp how)
262 (funcall how arg)
263 (ret how arg))))
264 (process-long-option (arg start negp)
265 (when (and (not negp)
266 (op-negated-p op)
267 (> (length arg) (+ start 3))
268 (string= arg "no-"
269 :start1 start :end1 (+ start 3)))
270 (incf start 3)
271 (setf negp t))
272 (let* ((matches nil)
273 (eqpos (position #\= arg :start start))
274 (len (or eqpos (length arg)))
275 (optname (subseq arg 0 len))
276 (len-2 (- len start)))
277 (dolist (o (op-options op))
278 (cond ((or (not (stringp (opt-long-name o)))
279 (and negp (not (opt-negated-tag o)))
280 (< (length (opt-long-name o)) len-2)
281 (string/= optname (opt-long-name o)
282 :start1 start :end2 len-2)))
283 ((= (length (opt-long-name o)) len-2)
284 (setf matches (list o))
285 (return))
286 (t
287 (push o matches))))
288 (cond ((null matches)
289 (option-parse-error "Unknown option `~A'" optname))
290 ((cdr matches)
291 (option-parse-error
292 "~
861345b4 293Ambiguous long option `~A' -- could be any of:~{~% --~A~}"
b3bc3745
MW
294 optname
295 (mapcar #'opt-long-name matches))))
296 (process-option (car matches)
297 optname
298 negp
299 :arg (and eqpos
300 (subseq arg (1+ eqpos)))))))
301 (catch 'option-parse-return
302 (loop
303 (with-simple-restart (skip-option "Skip this bogus option.")
304 (cond
305 ;;
306 ;; We're embroiled in short options: handle them.
307 ((op-short-opt op)
308 (if (>= (op-short-opt-index op) (length (op-short-opt op)))
309 (setf (op-short-opt op) nil)
310 (let* ((str (op-short-opt op))
311 (i (op-short-opt-index op))
312 (ch (char str i))
313 (negp (op-short-opt-neg-p op))
314 (name (format nil "~C~A" (if negp #\+ #\-) ch))
315 (o (find ch (op-options op) :key #'opt-short-name)))
316 (incf i)
317 (setf (op-short-opt-index op) i)
318 (when (or (not o)
319 (and negp (not (opt-negated-tag o))))
320 (option-parse-error "Unknown option `~A'" name))
321 (process-option o
322 name
323 negp
324 :argfunc
325 (and (< i (length str))
326 (lambda ()
327 (prog1
328 (subseq str i)
329 (setf (op-short-opt op)
330 nil))))))))
331 ;;
332 ;; End of the list. Say we've finished.
333 ((not (more-args-p))
334 (finished))
335 ;;
336 ;; Process the next option.
337 (t
338 (let ((arg (peek-arg)))
339 (cond
340 ;;
341 ;; Non-option. Decide what to do.
342 ((or (<= (length arg) 1)
343 (and (char/= (char arg 0) #\-)
344 (or (char/= (char arg 0) #\+)
345 (not (op-negated-p op)))))
346 (case (op-non-option op)
347 (:skip (skip-arg))
348 (:stop (finished))
349 (:return (eat-arg)
350 (ret :non-option arg))
351 (t (eat-arg)
352 (funcall (op-non-option op) arg))))
353 ;;
354 ;; Double-hyphen. Stop right now.
355 ((string= arg "--")
356 (eat-arg)
357 (finished))
358 ;;
359 ;; Numbers. Check these before long options, since `--43'
360 ;; is not a long option.
361 ((and (op-numeric-p op)
362 (or (char= (char arg 0) #\-)
363 (op-negated-numeric-p op))
364 (or (and (digit-char-p (char arg 1))
365 (every #'digit-char-p (subseq arg 2)))
366 (and (or (char= (char arg 1) #\-)
367 (char= (char arg 1) #\+))
368 (>= (length arg) 3)
369 (digit-char-p (char arg 2))
370 (every #'digit-char-p (subseq arg 3)))))
371 (eat-arg)
372 (let ((negp (char= (char arg 0) #\+))
373 (num (parse-integer arg :start 1)))
374 (when (and negp (eq (op-negated-numeric-p op) :-))
375 (setf num (- num))
376 (setf negp nil))
377 (let ((how (if negp
378 (op-negated-numeric-p op)
379 (op-numeric-p op))))
380 (if (functionp how)
381 (funcall how num)
382 (ret (if negp :negated-numeric :numeric) num)))))
383 ;;
384 ;; Long option. Find the matching option-spec and process
385 ;; it.
386 ((and (char= (char arg 0) #\-)
387 (char= (char arg 1) #\-))
388 (eat-arg)
389 (process-long-option arg 2 nil))
390 ;;
391 ;; Short options. All that's left.
392 (t
393 (eat-arg)
394 (let ((negp (char= (char arg 0) #\+))
395 (ch (char arg 1)))
396 (cond ((and (op-long-only-p op)
397 (not (member ch (op-options op)
398 :key #'opt-short-name)))
399 (process-long-option arg 1 negp))
400 (t
401 (setf (op-short-opt op) arg
402 (op-short-opt-index op) 1
403 (op-short-opt-neg-p op) negp))))))))))))))
861345b4 404
405(defmacro option-parse-try (&body body)
406 "Report errors encountered while parsing options, and continue struggling
0ff9df03
MW
407 along. Also establishes a restart `stop-parsing'. Returns t if parsing
408 completed successfully, or nil if errors occurred."
861345b4 409 (with-gensyms (retcode)
410 `(let ((,retcode t))
411 (restart-case
412 (handler-bind
413 ((option-parse-error
414 (lambda (cond)
415 (setf ,retcode nil)
416 (moan "~A" cond)
417 (dolist (rn '(skip-option stop-parsing))
418 (let ((r (find-restart rn)))
419 (when r (invoke-restart r)))))))
420 ,@body)
421 (stop-parsing ()
422 :report "Give up parsing options."
423 (setf ,retcode nil)))
424 ,retcode)))
425
426(defmacro with-unix-error-reporting ((&key) &body body)
427 "Evaluate BODY with errors reported in the standard Unix fashion."
428 (with-gensyms (cond)
429 `(handler-case
430 (progn ,@body)
431 (simple-condition (,cond)
5fa07b7a
MW
432 (apply #'die
433 (simple-condition-format-control ,cond)
434 (simple-condition-format-arguments ,cond)))
861345b4 435 (error (,cond)
436 (die "~A" ,cond)))))
437
02866e07 438;;;--------------------------------------------------------------------------
861345b4 439;;; Standard option handlers.
440
441(defmacro defopthandler (name (var &optional (arg (gensym)))
442 (&rest args)
443 &body body)
444 "Define an option handler function NAME. Option handlers update a
0ff9df03
MW
445 generalized variable, which may be referred to as VAR in the BODY, based
446 on some parameters (the ARGS) and the value of an option-argument named
447 ARG."
861345b4 448 (let ((func (intern (format nil "OPTHANDLER/~:@(~A~)" name))))
449 `(progn
450 (setf (get ',name 'opthandler) ',func)
451 (defun ,func (,var ,arg ,@args)
452 (with-locatives ,var
453 (declare (ignorable ,arg))
454 ,@body))
5fa07b7a 455 ',name)))
861345b4 456
457(defun parse-c-integer (string &key radix (start 0) end)
458 "Parse STRING, or at least the parts of it between START and END, according
0ff9df03
MW
459 to the standard C rules. Well, almost: the 0 and 0x prefixes are
460 accepted, but so too are 0o (Haskell) and 0b (original); also RADIX_DIGITS
461 is accepted, for any radix between 2 and 36. Prefixes are only accepted
462 if RADIX is nil. Returns two values: the integer parsed (or nil if there
463 wasn't enough for a sensible parse), and the index following the
464 characters of the integer."
861345b4 465 (unless end (setf end (length string)))
202c91a3
MW
466 (labels ((simple (i r goodp sgn)
467 (multiple-value-bind
468 (a i)
469 (if (and (< i end)
470 (digit-char-p (char string i) r))
471 (parse-integer string
472 :start i :end end
473 :radix r
474 :junk-allowed t)
475 (values nil i))
476 (values (if a (* sgn a) (and goodp 0)) i)))
861345b4 477 (get-radix (i r sgn)
202c91a3 478 (cond (r (simple i r nil sgn))
861345b4 479 ((>= i end) (values nil i))
480 ((and (char= (char string i) #\0)
481 (>= (- end i) 2))
482 (case (char string (1+ i))
202c91a3
MW
483 (#\x (simple (+ i 2) 16 nil sgn))
484 (#\o (simple (+ i 2) 8 nil sgn))
485 (#\b (simple (+ i 2) 2 nil sgn))
486 (t (simple (1+ i) 8 t sgn))))
861345b4 487 (t
488 (multiple-value-bind
202c91a3
MW
489 (r i)
490 (simple i 10 nil +1)
861345b4 491 (cond ((not r) (values nil i))
492 ((and (< i end)
493 (char= (char string i) #\_)
494 (<= 2 r 36))
202c91a3 495 (simple (1+ i) r nil sgn))
861345b4 496 (t
497 (values (* r sgn) i))))))))
498 (cond ((>= start end) (values nil start))
499 ((char= (char string start) #\-)
500 (get-radix (1+ start) radix -1))
501 ((char= (char string start) #\+)
502 (get-radix (1+ start) radix +1))
503 (t
504 (get-radix start radix +1)))))
505
506(defun invoke-option-handler (handler loc arg args)
507 "Call the HANDLER function, giving it LOC to update, the option-argument
0ff9df03 508 ARG, and the remaining ARGS."
861345b4 509 (apply (if (functionp handler) handler
510 (fdefinition (get handler 'opthandler)))
511 loc
512 arg
513 args))
514
5fa07b7a
MW
515;;;--------------------------------------------------------------------------
516;;; Built-in option handlers.
517
861345b4 518(defopthandler set (var) (&optional (value t))
519 "Sets VAR to VALUE; defaults to t."
520 (setf var value))
5fa07b7a 521
861345b4 522(defopthandler clear (var) (&optional (value nil))
523 "Sets VAR to VALUE; defaults to nil."
524 (setf var value))
5fa07b7a 525
861345b4 526(defopthandler inc (var) (&optional max (step 1))
527 "Increments VAR by STEP (defaults to 1), but not greater than MAX (default
0ff9df03 528 nil for no maximum). No errors are signalled."
861345b4 529 (incf var step)
530 (when (>= var max)
531 (setf var max)))
5fa07b7a 532
861345b4 533(defopthandler dec (var) (&optional min (step 1))
534 "Decrements VAR by STEP (defaults to 1), but not less than MIN (default nil
0ff9df03 535 for no maximum). No errors are signalled."
861345b4 536 (decf var step)
537 (when (<= var min)
538 (setf var min)))
5fa07b7a 539
861345b4 540(defopthandler read (var arg) ()
541 "Stores in VAR the Lisp object found by reading the ARG. Evaluation is
0ff9df03
MW
542 forbidden while reading ARG. If there is an error during reading, an
543 error of type option-parse-error is signalled."
861345b4 544 (handler-case
545 (let ((*read-eval* nil))
546 (multiple-value-bind (x end) (read-from-string arg t)
547 (unless (>= end (length arg))
548 (option-parse-error "Junk at end of argument `~A'" arg))
549 (setf var x)))
550 (error (cond)
551 (option-parse-error (format nil "~A" cond)))))
5fa07b7a 552
861345b4 553(defopthandler int (var arg) (&key radix min max)
554 "Stores in VAR the integer read from the ARG. Integers are parsed
0ff9df03
MW
555 according to C rules, which is normal in Unix; the RADIX may be nil to
556 allow radix prefixes, or an integer between 2 and 36. An
557 option-parse-error is signalled if the ARG is not a valid integer, or if
558 it is not between MIN and MAX (either of which may be nil if no lower
559 resp. upper bound is wanted)."
861345b4 560 (multiple-value-bind (v end) (parse-c-integer arg :radix radix)
561 (unless (and v (>= end (length arg)))
562 (option-parse-error "Bad integer `~A'" arg))
563 (when (or (and min (< v min))
564 (and max (> v max)))
565 (option-parse-error
566 "Integer ~A out of range (must have ~@[~D <= ~]x~@[ <= ~D~])"
567 arg min max))
568 (setf var v)))
5fa07b7a 569
861345b4 570(defopthandler string (var arg) ()
571 "Stores ARG in VAR, just as it is."
572 (setf var arg))
5fa07b7a 573
a8bbb2e7
MW
574(defopthandler keyword (var arg) (&optional (valid t))
575 "Converts ARG into a keyword. If VALID is t, then any ARG string is
576 acceptable: the argument is uppercased and interned in the keyword
577 package. If VALID is a list, then we ensure that ARG matches one of the
578 elements of the list; unambigious abbreviations are allowed."
579 (etypecase valid
580 ((member t)
581 (setf var (intern (string-upcase arg) :keyword)))
582 (list
583 (let ((matches nil)
584 (guess (string-upcase arg))
585 (len (length arg)))
586 (dolist (k valid)
587 (let* ((kn (symbol-name k))
588 (klen (length kn)))
589 (cond ((string= kn guess)
590 (setf matches (list k))
591 (return))
592 ((and (< len klen)
593 (string= guess kn :end2 len))
594 (push k matches)))))
595 (cond
596 ((null matches)
597 (option-parse-error "Argument `~A' invalid: must be one of:~
598 ~{~%~8T~(~A~)~}"
599 arg valid))
600 ((null (cdr matches))
601 (setf var (car matches)))
602 (t
603 (option-parse-error "Argument `~A' ambiguous: may be any of:~
604 ~{~%~8T~(~A~)~}"
605 arg matches)))))))
5fa07b7a 606
861345b4 607(defopthandler list (var arg) (&optional handler &rest handler-args)
608 "Collect ARGs in a list at VAR. ARGs are translated by the HANDLER first,
0ff9df03 609 if specified. If not, it's as if you asked for `string'."
861345b4 610 (when handler
611 (invoke-option-handler handler (locf arg) arg handler-args))
612 (setf var (nconc var (list arg))))
613
5fa07b7a
MW
614;;;--------------------------------------------------------------------------
615;;; Option descriptions.
616
617(defmacro defoptmacro (name args &body body)
618 "Defines an option macro NAME. Option macros should produce a list of
0ff9df03 619 expressions producing one option structure each."
5fa07b7a
MW
620 `(progn
621 (setf (get ',name 'optmacro) (lambda ,args ,@body))
622 ',name))
623
861345b4 624(compile-time-defun parse-option-form (form)
625 "Does the heavy lifting for parsing an option form. See the docstring for
0ff9df03 626 the `option' macro for details of the syntax."
861345b4 627 (flet ((doc (form)
628 (cond ((stringp form) form)
629 ((null (cdr form)) (car form))
630 (t `(format nil ,@form))))
631 (docp (form)
632 (or (stringp form)
633 (and (consp form)
634 (stringp (car form))))))
5fa07b7a
MW
635 (cond ((stringp form)
636 `(%make-option :documentation ,form))
637 ((not (listp form))
638 (error "option form must be string or list"))
639 ((and (docp (car form)) (null (cdr form)))
640 `(%make-option :documentation ,(doc (car form))))
641 (t
642 (let (long-name short-name
643 arg-name arg-optional-p
644 tag negated-tag
645 doc)
646 (dolist (f form)
647 (cond ((and (or (not tag) (not negated-tag))
648 (or (keywordp f)
649 (and (consp f)
650 (member (car f) '(lambda function)))))
651 (if tag
652 (setf negated-tag f)
653 (setf tag f)))
654 ((and (not long-name)
655 (or (rationalp f)
656 (symbolp f)
657 (stringp f)))
658 (setf long-name (if (stringp f) f
659 (format nil "~(~A~)" f))))
660 ((and (not short-name)
661 (characterp f))
662 (setf short-name f))
663 ((and (not doc)
664 (docp f))
665 (setf doc (doc f)))
666 ((and (consp f) (symbolp (car f)))
667 (case (car f)
b3bc3745
MW
668 (:short-name (setf short-name (cadr f)))
669 (:long-name (setf long-name (cadr f)))
670 (:tag (setf tag (cadr f)))
671 (:negated-tag (setf negated-tag (cadr f)))
5fa07b7a
MW
672 (:arg (setf arg-name (cadr f)))
673 (:opt-arg (setf arg-name (cadr f))
674 (setf arg-optional-p t))
675 (:doc (setf doc (doc (cdr f))))
676 (t (let ((handler (get (car f) 'opthandler)))
677 (unless handler
678 (error "No handler `~S' defined." (car f)))
679 (let* ((var (cadr f))
680 (arg (gensym))
681 (thunk `#'(lambda (,arg)
682 (,handler (locf ,var)
683 ,arg
684 ,@(cddr f)))))
685 (if tag
686 (setf negated-tag thunk)
687 (setf tag thunk)))))))
688 (t
689 (error "Unexpected thing ~S in option form." f))))
690 `(make-option ,long-name ,short-name ,arg-name
691 ,@(and arg-optional-p `(:arg-optional-p t))
692 ,@(and tag `(:tag ,tag))
693 ,@(and negated-tag `(:negated-tag ,negated-tag))
694 ,@(and doc `(:documentation ,doc))))))))
861345b4 695
696(defmacro options (&rest optlist)
697 "More convenient way of initializing options. The OPTLIST is a list of
0ff9df03 698 OPTFORMS. Each OPTFORM is one of the following:
5fa07b7a 699
0ff9df03 700 STRING A banner to print.
5fa07b7a 701
0ff9df03
MW
702 SYMBOL or (SYMBOL STUFF...)
703 If SYMBOL is an optform macro, the result of invoking it.
5fa07b7a 704
0ff9df03 705 (...) A full option-form. See below.
5fa07b7a 706
b3bc3745
MW
707 Full option-forms are a list of the following kinds of items.
708
709 (:short-name CHAR)
710 (:long-name STRING)
711 (:arg STRING)
712 (:tag TAG)
713 (:negated-tag TAG)
714 (:doc STRING)
715 Set the appropriate slot of the option to the given value.
716 The argument is evaluated.
861345b4 717
b3bc3745
MW
718 (:doc FORMAT-CONTROL ARGUMENTS...)
719 As for (:doc (format nil FORMAT-CONTROL ARGUMENTS...)).
720
721 KEYWORD, (function ...), (lambda ...)
0ff9df03
MW
722 If no TAG is set yet, then as a TAG; otherwise as the
723 NEGATED-TAG.
861345b4 724
0ff9df03
MW
725 STRING (or SYMBOL or RATIONAL)
726 If no LONG-NAME seen yet, then the LONG-NAME. For symbols
727 and rationals, the item is converted to a string and squashed
728 to lower-case.
861345b4 729
b3bc3745 730 CHARACTER If no SHORT-NAME, then the SHORT-NAME.
861345b4 731
0ff9df03
MW
732 STRING or (STRING STUFF...)
733 If no DOCUMENTATION set yet, then the DOCUMENTATION string,
b3bc3745 734 as for (:doc STRING STUFF...)
861345b4 735
b3bc3745 736 (:opt-arg NAME)
0ff9df03 737 Set the ARG-NAME, and also set ARG-OPTIONAL-P.
861345b4 738
0ff9df03
MW
739 (HANDLER VAR ARGS...)
740 If no TAG is set yet, attach the HANDLER to this option,
741 giving it ARGS. Otherwise, set the NEGATED-TAG."
b3bc3745 742
5fa07b7a
MW
743 `(list ,@(mapcan (lambda (form)
744 (multiple-value-bind
745 (sym args)
746 (cond ((symbolp form) (values form nil))
747 ((and (consp form) (symbolp (car form)))
748 (values (car form) (cdr form)))
749 (t (values nil nil)))
750 (let ((macro (and sym (get sym 'optmacro))))
751 (if macro
752 (apply macro args)
753 (list (parse-option-form form))))))
861345b4 754 optlist)))
755
02866e07 756;;;--------------------------------------------------------------------------
5fa07b7a 757;;; Support stuff for help and usage messages.
861345b4 758
759(defun print-text (string
760 &optional
761 (stream *standard-output*)
762 &key
763 (start 0)
764 (end nil))
765 "Prints STRING to a pretty-printed STREAM, breaking it at whitespace and
0ff9df03
MW
766 newlines in the obvious way. Stuff between square brackets is not broken:
767 this makes usage messages work better."
861345b4 768 (let ((i start)
769 (nest 0)
770 (splitp nil))
771 (flet ((emit ()
772 (write-string string stream :start start :end i)
773 (setf start i)))
774 (unless end
775 (setf end (length string)))
776 (loop
777 (unless (< i end)
778 (emit)
779 (return))
780 (let ((ch (char string i)))
781 (cond ((char= ch #\newline)
782 (emit)
783 (incf start)
784 (pprint-newline :mandatory stream))
785 ((whitespace-char-p ch)
786 (when (zerop nest)
787 (setf splitp t)))
788 (t
789 (when splitp
790 (emit)
791 (pprint-newline :fill stream))
792 (setf splitp nil)
793 (case ch
794 (#\[ (incf nest))
795 (#\] (when (plusp nest) (decf nest))))))
796 (incf i))))))
797
798(defun simple-usage (opts &optional mandatory-args)
799 "Build a simple usage list from a list of options, and (optionally)
0ff9df03 800 mandatory argument names."
861345b4 801 (let (short-simple long-simple short-arg long-arg)
802 (dolist (o opts)
803 (cond ((not (and (opt-documentation o)
804 (opt-long-name o))))
805 ((and (opt-short-name o) (opt-arg-name o))
806 (push o short-arg))
807 ((opt-short-name o)
808 (push o short-simple))
809 ((opt-arg-name o)
810 (push o long-arg))
811 (t
812 (push o long-simple))))
813 (list
814 (nconc (and short-simple
815 (list (format nil "[-~{~C~}]"
816 (sort (mapcar #'opt-short-name short-simple)
817 #'char<))))
818 (and long-simple
819 (mapcar (lambda (o)
820 (format nil "[--~A]" (opt-long-name o)))
821 (sort long-simple #'string< :key #'opt-long-name)))
822 (and short-arg
823 (mapcar (lambda (o)
824 (format nil "~:[[-~C ~A]~;[-~C[~A]]~]"
825 (opt-arg-optional-p o)
826 (opt-short-name o)
827 (opt-arg-name o)))
828 (sort short-arg #'char-lessp
829 :key #'opt-short-name)))
830 (and long-arg
831 (mapcar (lambda (o)
832 (format nil "~:[[--~A ~A]~;[--~A[=~A]]~]"
833 (opt-arg-optional-p o)
834 (opt-long-name o)
835 (opt-arg-name o)))
836 (sort long-arg #'string-lessp
837 :key #'opt-long-name)))
838 (listify mandatory-args)))))
839
840(defun show-usage (prog usage &optional (stream *standard-output*))
5fa07b7a 841 "Basic usage-showing function. PROG is the program name, probably from
0ff9df03
MW
842 *command-line-strings*. USAGE is a list of possible usages of the
843 program, each of which is a list of items to be supplied by the user. In
844 simple cases, a single string is sufficient."
861345b4 845 (pprint-logical-block (stream nil :prefix "Usage: ")
846 (dolist (u (listify usage))
847 (pprint-logical-block (stream nil :prefix (format nil "~A " prog))
848 (format stream "~{~A ~:_~}" (listify u)))
849 (pprint-newline :mandatory stream))))
850
851(defun show-help (prog ver usage opts &optional (stream *standard-output*))
852 "Basic help-showing function. PROG is the program name, probably from
0ff9df03
MW
853 *command-line-strings*. VER is the program's version number. USAGE is a
854 list of the possible usages of the program, each of which may be a list of
855 items to be supplied. OPTS is the list of supported options, as provided
856 to the options parser. STREAM is the stream to write on."
861345b4 857 (format stream "~A, version ~A~2%" prog ver)
858 (show-usage prog usage stream)
859 (terpri stream)
860 (let (newlinep)
861 (dolist (o opts)
862 (let ((doc (opt-documentation o)))
863 (cond ((not o))
864 ((not (opt-long-name o))
865 (when newlinep
866 (terpri stream)
867 (setf newlinep nil))
868 (pprint-logical-block (stream nil)
869 (print-text doc stream))
870 (terpri stream))
871 (t
872 (setf newlinep t)
873 (pprint-logical-block (stream nil :prefix " ")
874 (pprint-indent :block 30 stream)
875 (format stream "~:[ ~;-~:*~C,~] --~A"
876 (opt-short-name o)
877 (opt-long-name o))
878 (when (opt-arg-name o)
879 (format stream "~:[=~A~;[=~A]~]"
880 (opt-arg-optional-p o)
881 (opt-arg-name o)))
882 (write-string " " stream)
883 (pprint-tab :line 30 1 stream)
884 (print-text doc stream))
885 (terpri stream)))))))
886
887(defun sanity-check-option-list (opts)
888 "Check the option list OPTS for basic sanity. Reused short and long option
0ff9df03
MW
889 names are diagnosed. Maybe other problems will be reported later.
890 Returns a list of warning strings."
861345b4 891 (let ((problems nil)
892 (longs (make-hash-table :test #'equal))
893 (shorts (make-hash-table)))
894 (flet ((problem (msg &rest args)
895 (push (apply #'format nil msg args) problems)))
896 (dolist (o opts)
897 (push o (gethash (opt-long-name o) longs))
898 (push o (gethash (opt-short-name o) shorts)))
899 (maphash (lambda (k v)
900 (when (and k (cdr v))
901 (problem "Long name `--~A' reused in ~S" k v)))
902 longs)
903 (maphash (lambda (k v)
904 (when (and k (cdr v))
905 (problem "Short name `-~C' reused in ~S" k v)))
906 shorts)
907 problems)))
908
5fa07b7a
MW
909;;;--------------------------------------------------------------------------
910;;; Full program descriptions.
911
b3bc3745
MW
912(defvar *help* nil)
913(defvar *version* "<unreleased>")
914(defvar *usage* nil)
915
916(defun do-usage (&optional (stream *standard-output*))
917 (show-usage *program-name* *usage* stream))
918
919(defun die-usage ()
920 (do-usage *error-output*)
921 (exit 1))
5fa07b7a
MW
922
923(defun opt-help (arg)
924 (declare (ignore arg))
925 (show-help *program-name* *version* *usage* *options*)
926 (typecase *help*
927 (string (terpri) (write-string *help*))
928 ((or function symbol) (terpri) (funcall *help*)))
929 (format t "~&")
930 (exit 0))
5fa07b7a
MW
931(defun opt-version (arg)
932 (declare (ignore arg))
933 (format t "~A, version ~A~%" *program-name* *version*)
934 (exit 0))
5fa07b7a
MW
935(defun opt-usage (arg)
936 (declare (ignore arg))
937 (do-usage)
938 (exit 0))
939
b3bc3745
MW
940(defoptmacro help-options (&key (short-help #\h)
941 (short-version #\v)
942 (short-usage #\u))
943 "Inserts a standard help options collection in an options list."
944 (flet ((shortform (char)
945 (and char (list char))))
946 (mapcar
947 #'parse-option-form
948 `("Help options"
949 (,@(shortform short-help) "help" #'opt-help
950 "Show this help message.")
951 (,@(shortform short-version) "version" #'opt-version
952 ("Show ~A's version number." *program-name*))
953 (,@(shortform short-usage) "usage" #'opt-usage
954 ("Show a very brief usage summary for ~A." *program-name*))))))
5fa07b7a
MW
955
956(defun define-program (&key
b3bc3745
MW
957 (program-name nil progp)
958 (help nil helpp)
959 (version nil versionp)
960 (usage nil usagep)
961 (full-usage nil fullp)
962 (options nil optsp))
5fa07b7a 963 "Sets up all the required things a program needs to have to parse options
0ff9df03 964 and respond to them properly."
b3bc3745
MW
965 (when progp (setf *program-name* program-name))
966 (when helpp (setf *help* help))
967 (when versionp (setf *version* version))
968 (when optsp (setf *options* options))
969 (cond ((and usagep fullp) (error "conflicting options"))
970 (usagep (setf *usage* (simple-usage *options* usage)))
971 (fullp (setf *usage* full-usage))))
972
973(defmacro do-options ((&key (parser '(make-option-parser)))
974 &body clauses)
0ff9df03
MW
975 "Handy all-in-one options parser macro. PARSER defaults to a new options
976 parser using the preset default options structure. The CLAUSES are
977 `case2'-like clauses to match options, and must be exhaustive. If there
978 is a clause (nil (REST) FORMS...) then the FORMS are evaluated after
979 parsing is done with REST bound to the remaining command-line arguments."
b3bc3745
MW
980 (let*/gensyms (parser)
981 `(progn
560e1186
MW
982 (loop
983 (,(if (find t clauses :key #'car) 'case2 'ecase2)
b3bc3745 984 (option-parse-next ,parser)
560e1186
MW
985 ((nil) () (return))
986 ,@(remove-if #'null clauses :key #'car)))
987 ,@(let ((tail (find nil clauses :key #'car)))
988 (and tail
989 (destructuring-bind ((&optional arg) &rest forms) (cdr tail)
990 (if arg
b3bc3745
MW
991 (list `(let ((,arg (option-parse-remainder ,parser)))
992 ,@forms))
560e1186 993 forms)))))))
5fa07b7a 994
861345b4 995;;;----- That's all, folks --------------------------------------------------