3 ;;; Option parser, standard issue
5 ;;; (c) 2005 Straylight/Edgeware
8 ;;;----- Licensing notice ---------------------------------------------------
10 ;;; This file is part of the Sensible Object Design, an object system for C.
12 ;;; SOD 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.
17 ;;; SOD 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.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 (eval-when (:compile-toplevel :load-toplevel :execute)
27 (handler-bind ((warning #'muffle-warning))
28 (cl:defpackage #:optparse
29 (:use #:common-lisp #:sod-utilities))))
31 (cl:in-package #:optparse)
33 ;;;--------------------------------------------------------------------------
34 ;;; Program environment things.
36 (export '(*program-name* *command-line*))
37 (defvar *program-name* "<unknown>"
38 "Program name, as retrieved from the command line.")
39 (defvar *command-line* nil
40 "A list of command-line arguments, including the program name.")
42 (export 'set-command-line-arguments)
43 (defun set-command-line-arguments ()
44 "Retrieve command-line arguments.
46 Set `*command-line*' and `*program-name*'."
47 (setf *command-line* (cons (uiop:argv0) uiop:*command-line-arguments*)
48 *program-name* (pathname-name (car *command-line*))))
50 ;;;--------------------------------------------------------------------------
51 ;;; Fancy conditionals.
53 (eval-when (:compile-toplevel :load-toplevel :execute)
54 (defun do-case2-like (kind vform clauses)
55 "Helper function for `case2' and `ecase2'."
56 (with-gensyms (scrutinee argument)
57 `(multiple-value-bind (,scrutinee ,argument) ,vform
58 (declare (ignorable ,argument))
60 ,@(mapcar (lambda (clause)
62 (cases (&optional varx vary) &rest forms)
66 (list `(let ((,(or vary varx) ,argument)
68 `((,varx ,scrutinee))))
73 (defmacro case2 (vform &body clauses)
74 "Switch based on the first value of a form, capturing the second value.
76 VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
77 The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
78 standard `case' clause has the form (CASES FORMS...). The `case2' form
79 evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
80 order, just like `case'. If there is a match, then the corresponding
81 FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
82 the SCRUTINEE (where specified). Note the bizarre defaulting behaviour:
83 ARGVAR is less optional than SCRUVAR."
84 (do-case2-like 'case vform clauses))
86 (defmacro ecase2 (vform &body clauses)
87 "Like `case2', but signals an error if no clause matches the SCRUTINEE."
88 (do-case2-like 'ecase vform clauses))
90 ;;;--------------------------------------------------------------------------
91 ;;; Standard error-reporting functions.
94 (defun moan (msg &rest args)
95 "Report an error message in the usual way."
96 (format *error-output* "~&~A: ~?~%" *program-name* msg args))
99 (defun die (&rest args)
100 "Report an error message and exit."
104 ;;;--------------------------------------------------------------------------
105 ;;; The main option parser.
108 (defvar *options* nil
109 "The default list of command-line options.")
111 (export '(option optionp make-option
112 opt-short-name opt-long-name opt-tag opt-negated-tag
113 opt-arg-name opt-arg-optional-p opt-documentation))
114 (locally (declare #+sbcl (sb-ext:muffle-conditions style-warning))
121 (print-unreadable-object (o s :type t)
122 (format s "~*~:[~2:*~:[~3*~@[~S~]~
125 ~2*~@[~:*~:[ ~A~;[~A]~]~]~
129 ~*~@[~:*~:[=~A~;[=~A]~]~]~
133 (opt-arg-optional-p o)
135 (opt-%documentation o)))))
136 (:constructor %make-option
137 (&key long-name tag negated-tag short-name
138 arg-name arg-optional-p documentation
139 &aux (%documentation documentation)))
140 (:constructor make-option
141 (long-name short-name
143 &key (tag (intern (string-upcase
148 doc (documentation doc)
151 "Describes a command-line option. Slots:
153 LONG-NAME The option's long name. If this is null, the `option' is
154 just a banner to be printed in the program's help text.
156 TAG The value to be returned if this option is encountered. If
157 this is a function, instead, the function is called with the
158 option's argument or `nil'.
160 NEGATED-TAG As for TAG, but used if the negated form of the option is
161 found. If this is `nil' (the default), the option cannot be
164 SHORT-NAME The option's short name. This must be a single character, or
165 nil if the option has no short name.
167 ARG-NAME The name of the option's argument, a string. If this is
168 `nil', the option doesn't accept an argument. The name is
169 shown in the help text.
172 If non-nil, the option's argument is optional. This is
173 ignored unless ARG-NAME is non-null.
176 The help text for this option. It is automatically line-
177 wrapped. If `nil', the option is omitted from the help
180 Usually, one won't use `make-option', but use the `option' macro instead."
181 (long-name nil :type (or null string))
183 (negated-tag nil :type t)
184 (short-name nil :type (or null character))
185 (arg-name nil :type (or null string))
186 (arg-optional-p nil :type t)
187 (%documentation nil :type (or null string))))
188 (define-access-wrapper opt-documentation opt-%documentation)
190 (export '(option-parser option-parser-p make-option-parser
191 op-options op-non-option op-long-only-p
192 op-numeric-p op-negated-numeric-p op-negated-p))
193 (defstruct (option-parser
195 (:constructor make-option-parser
196 (&key ((:args argstmp) (cdr *command-line*))
198 (non-option (if (uiop:getenv "POSIXLY_CORRECT") :stop
200 ((:numericp numeric-p))
203 &aux (args (cons nil argstmp))
206 (negated-p (or negated-numeric-p
207 (some #'opt-negated-tag
209 "An option parser object. Slots:
211 ARGS The arguments to be parsed. Usually this will be
214 OPTIONS List of option structures describing the acceptable options.
216 NON-OPTION Behaviour when encountering a non-option argument. The
217 default is :skip. Allowable values are:
218 `:skip' -- pretend that it appeared after the option
219 arguments; this is the default behaviour of GNU getopt
220 `:stop' -- stop parsing options, leaving the remaining
221 command line unparsed
222 `:return' -- return :non-option and the argument word
224 NUMERIC-P Non-nil tag (as for options) if numeric options (e.g., -43)
225 are to be allowed. The default is `nil'. (Anomaly: the
226 keyword for this argument is `:numericp'.)
229 Non-nil tag (as for options) if numeric options (e.g., -43)
230 can be negated. This is not the same thing as a negative
233 LONG-ONLY-P A misnomer inherited from GNU `getopt'. Whether to allow
234 long options to begin with a single dash. Short options are
235 still allowed, and may be cuddled as usual. The default is
237 (args nil :type list)
238 (%options nil :type list)
239 (non-option :skip :type (or function (member :skip :stop :return)))
240 (next nil :type list)
241 (short-opt nil :type (or null string))
242 (short-opt-index 0 :type fixnum)
243 (short-opt-neg-p nil :type t)
244 (long-only-p nil :type t)
245 (numeric-p nil :type t)
246 (negated-numeric-p nil :type t)
247 (negated-p nil :type t))
248 (define-access-wrapper op-options op-%options)
250 (export 'option-parse-error)
251 (define-condition option-parse-error (error simple-condition)
254 "Indicates an error found while parsing options.
256 Probably not that useful."))
258 (defun option-parse-error (msg &rest args)
259 "Signal an `option-parse-error' with the given message and arguments."
260 (error (make-condition 'option-parse-error
262 :format-arguments args)))
264 (export 'option-parse-remainder)
265 (defun option-parse-remainder (op)
266 "Returns the unparsed remainder of the command line."
269 (export 'option-parse-return)
270 (defun option-parse-return (tag &optional argument)
271 "Force a return from `option-parse-next' with TAG and ARGUMENT.
273 This should only be called from an option handler."
274 (throw 'option-parse-return (values tag argument)))
276 (export 'option-parse-next)
277 (defun option-parse-next (op)
278 "Parse and handle the next option from the command-line.
280 This is the main option-parsing function. OP is an option-parser object,
281 initialized appropriately. Returns two values, OPT and ARG: OPT is the
282 tag of the next option read, and ARG is the argument attached to it, or
283 `nil' if there was no argument. If there are no more options, returns
284 `nil' twice. Options whose TAG is a function aren't returned; instead,
285 the tag function is called, with the option argument (or `nil') as the
286 only argument. It is safe for tag functions to throw out of
287 `option-parse-next', if they desparately need to. (This is the only way
288 to actually get `option-parse-next' to return a function value, should
289 that be what you want. See `option-parse-return' for a way of doing
292 While `option-parse-next' is running, there is a restart `skip-option'
293 which moves on to the next option. Error handlers should use this to
294 resume after parsing errors."
295 (labels ((ret (opt &optional arg)
296 (return-from option-parse-next (values opt arg)))
298 (setf (op-next op) nil)
306 (setf (op-next op) (cdr (op-next op))))
308 (setf (cdr (op-next op)) (cddr (op-next op))))
310 (prog1 (peek-arg) (eat-arg)))
312 (process-option (o name negp &key arg argfunc)
313 (cond ((not (opt-arg-name o))
316 "Option `~A' does not accept arguments"
320 (setf arg (funcall argfunc)))
321 ((opt-arg-optional-p o))
323 (setf arg (get-arg)))
325 (option-parse-error "Option `~A' requires an argument"
327 (let ((how (if negp (opt-negated-tag o) (opt-tag o))))
332 (process-long-option (arg start negp)
333 (when (and (not negp)
335 (> (length arg) (+ start 3))
337 :start1 start :end1 (+ start 3)))
341 (eqpos (position #\= arg :start start))
342 (len (or eqpos (length arg)))
343 (optname (subseq arg 0 len))
344 (len-2 (- len start)))
345 (dolist (o (op-options op))
346 (cond ((or (not (stringp (opt-long-name o)))
347 (and negp (not (opt-negated-tag o)))
348 (< (length (opt-long-name o)) len-2)
349 (string/= optname (opt-long-name o)
350 :start1 start :end2 len-2)))
351 ((= (length (opt-long-name o)) len-2)
352 (setf matches (list o))
356 (cond ((null matches)
357 (option-parse-error "Unknown option `~A'" optname))
360 #.(concatenate 'string
361 "Ambiguous long option `~A' -- "
365 (mapcar #'opt-long-name matches))))
366 (process-option (car matches)
370 (subseq arg (1+ eqpos)))))))
372 (catch 'option-parse-return
374 (with-simple-restart (skip-option "Skip this bogus option.")
377 ;; We're embroiled in short options: handle them.
379 (if (>= (op-short-opt-index op) (length (op-short-opt op)))
380 (setf (op-short-opt op) nil)
381 (let* ((str (op-short-opt op))
382 (i (op-short-opt-index op))
384 (negp (op-short-opt-neg-p op))
385 (name (format nil "~C~A" (if negp #\+ #\-) ch))
386 (o (find ch (op-options op) :key #'opt-short-name)))
388 (setf (op-short-opt-index op) i)
390 (and negp (not (opt-negated-tag o))))
391 (option-parse-error "Unknown option `~A'" name))
396 (and (< i (length str))
400 (setf (op-short-opt op)
403 ;; End of the list. Say we've finished.
407 ;; Process the next option.
409 (let ((arg (peek-arg)))
412 ;; Non-option. Decide what to do.
413 ((or (<= (length arg) 1)
414 (and (char/= (char arg 0) #\-)
415 (or (char/= (char arg 0) #\+)
416 (not (op-negated-p op)))))
417 (case (op-non-option op)
421 (ret :non-option arg))
423 (funcall (op-non-option op) arg))))
425 ;; Double-hyphen. Stop right now.
430 ;; Numbers. Check these before long options, since `--43'
431 ;; is not a long option.
432 ((and (op-numeric-p op)
433 (or (char= (char arg 0) #\-)
434 (op-negated-numeric-p op))
435 (or (and (digit-char-p (char arg 1))
436 (every #'digit-char-p (subseq arg 2)))
437 (and (or (char= (char arg 1) #\-)
438 (char= (char arg 1) #\+))
440 (digit-char-p (char arg 2))
441 (every #'digit-char-p (subseq arg 3)))))
443 (let ((negp (char= (char arg 0) #\+))
444 (num (parse-integer arg :start 1)))
445 (when (and negp (eq (op-negated-numeric-p op) :-))
449 (op-negated-numeric-p op)
453 (ret (if negp :negated-numeric :numeric) num)))))
455 ;; Long option. Find the matching option-spec and process
457 ((and (char= (char arg 0) #\-)
458 (char= (char arg 1) #\-))
460 (process-long-option arg 2 nil))
462 ;; Short options. All that's left.
465 (let ((negp (char= (char arg 0) #\+))
467 (cond ((and (op-long-only-p op)
468 (not (member ch (op-options op)
469 :key #'opt-short-name)))
470 (process-long-option arg 1 negp))
472 (setf (op-short-opt op) arg
473 (op-short-opt-index op) 1
474 (op-short-opt-neg-p op) negp))))))))))))))
476 (export 'option-parse-try)
477 (defmacro option-parse-try (&body body)
478 "Report errors encountered while parsing options, and try to continue.
480 Also establishes a restart `stop-parsing'. Returns `t' if parsing
481 completed successfully, or `nil' if errors occurred."
482 (with-gensyms (retcode)
490 (dolist (rn '(skip-option stop-parsing))
491 (let ((r (find-restart rn)))
492 (when r (invoke-restart r)))))))
495 :report "Give up parsing options."
496 (setf ,retcode nil)))
499 (export 'with-unix-error-reporting)
500 (defmacro with-unix-error-reporting ((&key) &body body)
501 "Evaluate BODY with errors reported in the standard Unix fashion."
505 (simple-condition (,cond)
507 (simple-condition-format-control ,cond)
508 (simple-condition-format-arguments ,cond)))
512 ;;;--------------------------------------------------------------------------
513 ;;; Standard option handlers.
515 (export 'defopthandler)
516 (defmacro defopthandler (name (var &optional (arg (gensym)))
519 "Define an option handler function NAME.
521 Option handlers update a generalized variable, which may be referred to as
522 VAR in the BODY, based on some parameters (the ARGS) and the value of an
523 option-argument named ARG."
524 (let ((func (intern (format nil "OPTHANDLER/~:@(~A~)" name))))
525 (multiple-value-bind (docs decls body) (parse-body body)
527 (setf (get ',name 'opthandler-function) ',func)
528 (defun ,func (,var ,arg ,@args)
530 (declare (ignorable ,arg))
532 (block ,name ,@body)))
536 (defmethod documentation ((symbol symbol) (doc-type (eql 'opthandler)))
537 (let ((func (get symbol 'opthandler-function)))
538 (and func (documentation func 'function))))
539 (defmethod (setf documentation)
540 (string (symbol symbol) (doc-type (eql 'opthandler)))
541 (let ((func (get symbol 'optmacro-function)))
542 (unless func (error "No option handler defined with name `~S'." symbol))
543 (setf (documentation func 'function) string)))
545 (defun parse-c-integer (string &key radix (start 0) end)
546 "Parse (a substring of) STRING according to the standard C rules.
548 Well, almost: the `0' and `0x' prefixes are accepted, but so too are
549 `0o' (Haskell) and `0b' (original); also `RADIX_DIGITS' is accepted, for
550 any radix between 2 and 36. Prefixes are only accepted if RADIX is `nil'.
551 Returns two values: the integer parsed (or `nil' if there wasn't enough
552 for a sensible parse), and the index following the characters of the
554 (unless end (setf end (length string)))
555 (labels ((simple (i r goodp sgn)
559 (digit-char-p (char string i) r))
560 (parse-integer string
565 (values (if a (* sgn a) (and goodp 0)) i)))
568 (cond (r (simple i r nil sgn))
569 ((>= i end) (values nil i))
570 ((and (char= (char string i) #\0)
572 (case (char string (1+ i))
573 (#\x (simple (+ i 2) 16 nil sgn))
574 (#\o (simple (+ i 2) 8 nil sgn))
575 (#\b (simple (+ i 2) 2 nil sgn))
576 (t (simple (1+ i) 8 t sgn))))
581 (cond ((not r) (values nil i))
583 (char= (char string i) #\_)
585 (simple (1+ i) r nil sgn))
587 (values (* r sgn) i))))))))
589 (cond ((>= start end) (values nil start))
590 ((char= (char string start) #\-)
591 (get-radix (1+ start) radix -1))
592 ((char= (char string start) #\+)
593 (get-radix (1+ start) radix +1))
595 (get-radix start radix +1)))))
597 (export 'invoke-option-handler)
598 (defun invoke-option-handler (handler loc arg args)
599 "Call an option HANDLER.
601 The handler is invoked to update the locative LOC, given an
602 option-argument ARG, and the remaining ARGS."
603 (apply (if (functionp handler) handler
604 (fdefinition (get handler 'opthandler-function)))
607 ;;;--------------------------------------------------------------------------
608 ;;; Built-in option handlers.
611 (defopthandler set (var) (&optional (value t))
612 "Sets VAR to VALUE; defaults to `t'."
616 (defopthandler clear (var) (&optional (value nil))
617 "Sets VAR to VALUE; defaults to `nil'."
621 (defopthandler inc (var) (&optional max (step 1))
622 "Increments VAR by STEP (defaults to 1).
624 If MAX is not `nil' then VAR will not be made larger than MAX. No errors
627 (when (and max (>= var max))
631 (defopthandler dec (var) (&optional min (step 1))
632 "Decrements VAR by STEP (defaults to 1).
634 If MIN is not `nil', then VAR will not be made smaller than MIN. No
635 errors are signalled."
637 (when (and min (<= var min))
641 (defopthandler read (var arg) ()
642 "Stores in VAR the Lisp object found by reading the ARG.
644 Evaluation is forbidden while reading ARG. If there is an error during
645 reading, an error of type `option-parse-error' is signalled."
647 (let ((*read-eval* nil))
648 (multiple-value-bind (x end) (read-from-string arg t)
649 (unless (>= end (length arg))
650 (option-parse-error "Junk at end of argument `~A'" arg))
653 (option-parse-error (format nil "~A" cond)))))
656 (defopthandler int (var arg) (&key radix min max)
657 "Stores in VAR the integer read from the ARG.
659 Integers are parsed according to C rules, which is normal in Unix; the
660 RADIX may be `nil' to allow radix prefixes, or an integer between 2 and
661 36. An `option-parse-error' is signalled if the ARG is not a valid
662 integer, or if it is not between MIN and MAX (either of which may be `nil'
663 if no lower or upper bound is wanted)."
664 (multiple-value-bind (v end) (parse-c-integer arg :radix radix)
665 (unless (and v (>= end (length arg)))
666 (option-parse-error "Bad integer `~A'" arg))
667 (when (or (and min (< v min))
670 #.(concatenate 'string
671 "Integer ~A out of range "
672 "(must have ~@[~D <= ~]x~@[ <= ~D~])")
677 (defopthandler string (var arg) ()
678 "Stores ARG in VAR, just as it is."
682 (defopthandler keyword (var arg) (&optional (valid t))
683 "Converts ARG into a keyword.
685 If VALID is `t', then any ARG string is acceptable: the argument is
686 uppercased and interned in the keyword package. If VALID is a list, then
687 we ensure that ARG matches one of the elements of the list; unambigious
688 abbreviations are allowed."
691 (setf var (intern (string-upcase arg) :keyword)))
694 (guess (string-upcase arg))
697 (let* ((kn (symbol-name k))
699 (cond ((string= kn guess)
700 (setf matches (list k))
703 (string= guess kn :end2 len))
707 (option-parse-error #.(concatenate 'string
708 "Argument `~A' invalid: "
712 ((null (cdr matches))
713 (setf var (car matches)))
715 (option-parse-error #.(concatenate 'string
716 "Argument `~A' ambiguous: "
722 (defopthandler list (var arg) (&optional handler &rest handler-args)
723 "Collect ARGs in a list at VAR.
725 ARGs are translated by the HANDLER first, if specified. If not, it's as
726 if you asked for `string'."
728 (invoke-option-handler handler (locf arg) arg handler-args))
729 (setf var (nconc var (list arg))))
731 ;;;--------------------------------------------------------------------------
732 ;;; Option descriptions.
734 (export 'defoptmacro)
735 (defmacro defoptmacro (name args &body body)
736 "Defines an option macro NAME.
738 Option macros should produce a list of expressions producing one `option'
740 (multiple-value-bind (docs decls body) (parse-body body)
742 (setf (get ',name 'optmacro-function)
745 (block ,name ,@body)))
749 (defmethod documentation ((symbol symbol) (doc-type (eql 'optmacro)))
750 (let ((func (get symbol 'optmacro-function)))
751 (and func (documentation func t))))
752 (defmethod (setf documentation)
753 (string (symbol symbol) (doc-type (eql 'optmacro)))
754 (let ((func (get symbol 'optmacro-function)))
755 (unless func (error "No option macro defined with name `~S'." symbol))
756 (setf (documentation func t) string)))
758 (export 'parse-option-form)
759 (eval-when (:compile-toplevel :load-toplevel :execute)
760 (defun parse-option-form (form)
761 "Does the heavy lifting for parsing an option form.
763 See the docstring for the `option' macro for details of the syntax."
765 (cond ((stringp form) form)
766 ((null (cdr form)) (car form))
767 (t `(format nil ,@form))))
771 (stringp (car form))))))
772 (cond ((stringp form)
773 `(%make-option :documentation ,form))
775 (error "option form must be string or list"))
776 ((and (docp (car form)) (null (cdr form)))
777 `(%make-option :documentation ,(doc (car form))))
779 (let (long-name short-name
780 arg-name arg-optional-p
784 (cond ((and (or (not tag) (not negated-tag))
787 (member (car f) '(lambda function)))))
791 ((and (not long-name)
795 (setf long-name (if (stringp f) f
796 (format nil "~(~A~)" f))))
797 ((and (not short-name)
803 ((and (consp f) (symbolp (car f)))
805 (:short-name (setf short-name (cadr f)))
806 (:long-name (setf long-name (cadr f)))
807 (:tag (setf tag (cadr f)))
808 (:negated-tag (setf negated-tag (cadr f)))
809 (:arg (setf arg-name (cadr f)))
810 (:opt-arg (setf arg-name (cadr f))
811 (setf arg-optional-p t))
812 (:doc (setf doc (doc (cdr f))))
813 (t (let ((handler (get (car f)
814 'opthandler-function)))
816 (error "No handler `~S' defined." (car f)))
817 (let* ((var (cadr f))
819 (thunk `#'(lambda (,arg)
820 (,handler (locf ,var)
824 (setf negated-tag thunk)
825 (setf tag thunk)))))))
827 (error "Unexpected thing ~S in option form." f))))
828 `(make-option ,long-name ,short-name ,arg-name
829 ,@(and arg-optional-p `(:arg-optional-p t))
830 ,@(and tag `(:tag ,tag))
831 ,@(and negated-tag `(:negated-tag ,negated-tag))
832 ,@(and doc `(:documentation ,doc)))))))))
835 (defmacro options (&rest optlist)
836 "A more convenient way of initializing options.
838 The OPTLIST is a list of OPTFORMS. Each OPTFORM is one of the following:
840 STRING A banner to print.
842 SYMBOL or (SYMBOL STUFF...)
843 If SYMBOL is an optform macro, the result of invoking it.
845 (...) A full option-form. See below.
847 Full option-forms are a list of the following kinds of items.
855 Set the appropriate slot of the option to the given value.
856 The argument is evaluated.
858 (:doc FORMAT-CONTROL ARGUMENTS...)
859 As for (:doc (format nil FORMAT-CONTROL ARGUMENTS...)).
861 KEYWORD, (function ...), (lambda ...)
862 If no TAG is set yet, then as a TAG; otherwise as the
865 STRING (or SYMBOL or RATIONAL)
866 If no LONG-NAME seen yet, then the LONG-NAME. For symbols
867 and rationals, the item is converted to a string and squashed
870 CHARACTER If no SHORT-NAME, then the SHORT-NAME.
872 STRING or (STRING STUFF...)
873 If no DOCUMENTATION set yet, then the DOCUMENTATION string,
874 as for (:doc STRING STUFF...)
877 Set the ARG-NAME, and also set ARG-OPTIONAL-P.
879 (HANDLER VAR ARGS...)
880 If no TAG is set yet, attach the HANDLER to this option,
881 giving it ARGS. Otherwise, set the NEGATED-TAG."
883 `(list ,@(mapcan (lambda (form)
886 (cond ((symbolp form) (values form nil))
887 ((and (consp form) (symbolp (car form)))
888 (values (car form) (cdr form)))
889 (t (values nil nil)))
890 (let ((macro (and sym (get sym 'optmacro-function))))
893 (list (parse-option-form form))))))
896 ;;;--------------------------------------------------------------------------
897 ;;; Support stuff for help and usage messages.
899 (locally (declare #+sbcl (sb-ext:muffle-conditions style-warning))
900 (defun print-text (string
901 &optional (stream *standard-output*)
902 &key (start 0) (end nil))
903 "Print and line-break STRING to a pretty-printed STREAM.
905 The string is broken at whitespace and newlines in the obvious way.
906 Stuff between square brackets is not broken: this makes usage messages
912 (write-string string stream :start start :end i)
914 (unless end (setf end (length string)))
919 (let ((ch (char string i)))
920 (cond ((char= ch #\newline)
923 (pprint-newline :mandatory stream))
924 ((whitespace-char-p ch)
930 (pprint-newline :fill stream))
934 (#\] (when (plusp nest) (decf nest))))))
937 (export 'simple-usage)
938 (defun simple-usage (opts &optional mandatory-args)
939 "Build a simple usage list.
941 The usage list is constructed from a list OPTS of `option' values, and
942 a list MANDATORY-ARGS of mandatory argument names; the latter defaults to
944 (let (short-simple long-simple short-arg long-arg)
946 (cond ((not (and (opt-documentation o)
948 ((and (opt-short-name o) (opt-arg-name o))
951 (push o short-simple))
955 (push o long-simple))))
957 (nconc (and short-simple
958 (list (format nil "[-~{~C~}]"
959 (sort (mapcar #'opt-short-name short-simple)
963 (format nil "[--~A]" (opt-long-name o)))
964 (sort long-simple #'string< :key #'opt-long-name)))
967 (format nil "~:[[-~C ~A]~;[-~C[~A]]~]"
968 (opt-arg-optional-p o)
971 (sort short-arg #'char-lessp
972 :key #'opt-short-name)))
975 (format nil "~:[[--~A ~A]~;[--~A[=~A]]~]"
976 (opt-arg-optional-p o)
979 (sort long-arg #'string-lessp
980 :key #'opt-long-name)))
981 (if (listp mandatory-args)
983 (list mandatory-args))))))
986 (defun show-usage (prog usage &optional (stream *standard-output*))
987 "Basic usage-showing function.
989 PROG is the program name, probably from `*program-name*'. USAGE is a list
990 of possible usages of the program, each of which is a list of items to be
991 supplied by the user. In simple cases, a single string is sufficient."
992 (pprint-logical-block (stream nil :prefix "Usage: ")
993 (dolist (u (if (listp usage) usage (list usage)))
994 (pprint-logical-block (stream nil
995 :prefix (concatenate 'string prog " "))
996 (format stream "~{~A~^ ~:_~}" (if (listp u) u (list u))))))
999 (defun show-options-help (opts &optional (stream *standard-output*))
1000 "Write help for OPTS to the STREAM.
1002 This is the core of the `show-help' function."
1005 (let ((doc (opt-documentation o)))
1007 ((not (or (opt-short-name o)
1011 (setf newlinep nil))
1012 (pprint-logical-block (stream nil)
1013 (print-text doc stream))
1017 (pprint-logical-block (stream nil :prefix " ")
1018 (format stream "~:[ ~;-~:*~C~:[~;,~]~:*~]~@[ --~A~]"
1021 (when (opt-arg-name o)
1023 "~:[~;[~]~:[~0@*~:[ ~;~]~*~;=~]~A~0@*~:[~;]~]"
1024 (opt-arg-optional-p o)
1027 (write-string " " stream)
1028 (pprint-tab :line 30 1 stream)
1029 (pprint-indent :block 30 stream)
1030 (print-text doc stream))
1031 (terpri stream)))))))
1034 (defun show-help (prog ver usage opts &optional (stream *standard-output*))
1035 "Basic help-showing function.
1037 PROG is the program name, probably from `*program-name*'. VER is the
1038 program's version number. USAGE is a list of the possible usages of the
1039 program, each of which may be a list of items to be supplied. OPTS is the
1040 list of supported options, as provided to the options parser. STREAM is
1041 the stream to write on."
1042 (format stream "~A, version ~A~2%" prog ver)
1043 (show-usage prog usage stream)
1045 (show-options-help opts stream))
1047 (export 'sanity-check-option-list)
1048 (defun sanity-check-option-list (opts)
1049 "Check the option list OPTS for basic sanity.
1051 Reused short and long option names are diagnosed. Maybe other problems
1052 will be reported later. Returns a list of warning strings."
1053 (let ((problems nil)
1054 (longs (make-hash-table :test #'equal))
1055 (shorts (make-hash-table)))
1056 (flet ((problem (msg &rest args)
1057 (push (apply #'format nil msg args) problems)))
1059 (push o (gethash (opt-long-name o) longs))
1060 (push o (gethash (opt-short-name o) shorts)))
1061 (maphash (lambda (k v)
1062 (when (and k (cdr v))
1063 (problem "Long name `--~A' reused in ~S" k v)))
1065 (maphash (lambda (k v)
1066 (when (and k (cdr v))
1067 (problem "Short name `-~C' reused in ~S" k v)))
1071 ;;;--------------------------------------------------------------------------
1072 ;;; Full program descriptions.
1074 (export '(*help* *version* *usage*))
1075 (defvar *help* nil "Help text describing the program.")
1076 (defvar *version* "<unreleased>" "The program's version number.")
1077 (defvar *usage* nil "A usage summary string")
1080 (defun do-usage (&optional (stream *standard-output*))
1081 (show-usage *program-name* *usage* stream))
1085 (do-usage *error-output*)
1088 (defun opt-help (arg)
1089 (declare (ignore arg))
1090 (show-help *program-name* *version* *usage* *options*)
1092 (string (terpri) (write-string *help*))
1094 ((or function symbol) (terpri) (funcall *help*)))
1097 (defun opt-version (arg)
1098 (declare (ignore arg))
1099 (format t "~A, version ~A~%" *program-name* *version*)
1101 (defun opt-usage (arg)
1102 (declare (ignore arg))
1106 (export 'help-options)
1107 (defoptmacro help-options (&key (short-help #\h)
1110 "Inserts a standard help options collection in an options list."
1111 (flet ((shortform (char)
1112 (and char (list char))))
1116 (,@(shortform short-help) "help" #'opt-help
1117 "Show this help message.")
1118 (,@(shortform short-version) "version" #'opt-version
1119 ("Show ~A's version number." *program-name*))
1120 (,@(shortform short-usage) "usage" #'opt-usage
1121 ("Show a very brief usage summary for ~A." *program-name*))))))
1123 (export 'define-program)
1124 (defun define-program (&key
1125 (program-name nil progp)
1127 (version nil versionp)
1129 (full-usage nil fullp)
1130 (options nil optsp))
1131 "Sets up all the required things a program needs to have to parse options.
1133 This is a simple shorthand for setting `*program-name*', `*help*',
1134 `*version*', `*options*', and `*usage*' from the corresponding arguments.
1135 If an argument is not given then the corresponding variable is left alone.
1137 The USAGE argument should be a list of mandatory argument names to pass to
1138 `simple-usage'; FULL-USAGE should be a complete usage-token list. An
1139 error will be signalled if both USAGE and FULL-USAGE are provided."
1140 (when progp (setf *program-name* program-name))
1141 (when helpp (setf *help* help))
1142 (when versionp (setf *version* version))
1143 (when optsp (setf *options* options))
1144 (cond ((and usagep fullp) (error "conflicting options"))
1145 (usagep (setf *usage* (simple-usage *options* usage)))
1146 (fullp (setf *usage* full-usage))))
1148 (export 'do-options)
1149 (defmacro do-options ((&key (parser '(make-option-parser)))
1151 "Handy all-in-one options parser macro.
1153 PARSER defaults to a new options parser using the preset default options
1154 structure. The CLAUSES are `case2'-like clauses to match options, and
1155 must be exhaustive. If there is a clause (nil (REST) FORMS...) then the
1156 FORMS are evaluated after parsing is done with REST bound to the remaining
1157 command-line arguments."
1161 (,(if (find t clauses :key #'car) 'case2 'ecase2)
1162 (option-parse-next ,parser)
1164 ,@(remove-if #'null clauses :key #'car)))
1165 ,@(let ((tail (find nil clauses :key #'car)))
1167 (destructuring-bind ((&optional arg) &rest forms) (cdr tail)
1169 (list `(let ((,arg (option-parse-remainder ,parser)))
1173 ;;;----- That's all, folks --------------------------------------------------