View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Marcus Uneson
    4    E-mail:        marcus.uneson@ling.lu.se
    5    WWW:           http://person.sol.lu.se/MarcusUneson/
    6    Copyright (c)  2011-2015, Marcus Uneson
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(optparse,
   36    [  opt_parse/5,     %+OptsSpec, +CLArgs, -Opts, -PositionalArgs,-ParseOptions
   37       opt_parse/4,     %+OptsSpec, +CLArgs, -Opts, -PositionalArgs,
   38       opt_arguments/3, %+OptsSpec, -Opts, -PositionalArgs
   39       opt_help/2       %+OptsSpec, -Help
   40    ]).   41
   42:- use_module(library(apply)).   43:- use_module(library(lists)).   44:- use_module(library(option)).   45:- use_module(library(error)).   46:- set_prolog_flag(double_quotes, codes).   47%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXPORTS

command line parsing

This module helps in building a command-line interface to an application. In particular, it provides functions that take an option specification and a list of atoms, probably given to the program on the command line, and return a parsed representation (a list of the customary Key(Val) by default; or optionally, a list of Func(Key, Val) terms in the style of current_prolog_flag/2). It can also synthesize a simple help text from the options specification.

The terminology in the following is partly borrowed from python, see http://docs.python.org/library/optparse.html#terminology . Very briefly, arguments is what you provide on the command line and for many prologs show up as a list of atoms Args in current_prolog_flag(argv, Args). For a typical prolog incantation, they can be divided into

Positional arguments are in particular used for mandatory arguments without which your program won't work and for which there are no sensible defaults (e.g,, input file names). Options, by contrast, offer flexibility by letting you change a default setting. Options are optional not only by etymology: this library has no notion of mandatory or required options (see the python docs for other rationales than laziness).

The command-line arguments enter your program as a list of atoms, but the programs perhaps expects booleans, integers, floats or even prolog terms. You tell the parser so by providing an options specification. This is just a list of individual option specifications. One of those, in turn, is a list of ground prolog terms in the customary Name(Value) format. The following terms are recognized (any others raise error).

opt(Key)
Key is what the option later will be accessed by, just like for current_prolog_flag(Key, Value). This term is mandatory (an error is thrown if missing).
shortflags(ListOfFlags)
ListOfFlags denotes any single-dashed, single letter args specifying the current option (-s , -K, etc). Uppercase letters must be quoted. Usually ListOfFlags will be a singleton list, but sometimes aliased flags may be convenient.
longflags(ListOfFlags)
ListOfFlags denotes any double-dashed arguments specifying the current option (--verbose, --no-debug, etc). They are basically a more readable alternative to short flags, except
  1. long flags can be specified as --flag value or --flag=value (but not as --flagvalue); short flags as -f val or -fval (but not -f=val)
  2. boolean long flags can be specified as --bool-flag or --bool-flag=true or --bool-flag true; and they can be negated as --no-bool-flag or --bool-flag=false or --bool-flag false.

    Except that shortflags must be single characters, the distinction between long and short is in calling convention, not in namespaces. Thus, if you have shortflags([v]), you can use it as -v2 or -v 2 or --v=2 or --v 2 (but not -v=2 or --v2).

    Shortflags and longflags both default to []. It can be useful to have flagless options -- see example below.

meta(Meta)
Meta is optional and only relevant for the synthesized usage message and is the name (an atom) of the metasyntactic variable (possibly) appearing in it together with type and default value (e.g, x:integer=3, interest:float=0.11). It may be useful to have named variables (x, interest) in case you wish to mention them again in the help text. If not given the Meta: part is suppressed -- see example below.
type(Type)
Type is one of boolean, atom, integer, float, term. The corresponding argument will be parsed appropriately. This term is optional; if not given, defaults to term.
default(Default)
Default value. This term is optional; if not given, or if given the special value '_', an uninstantiated variable is created (and any type declaration is ignored).
help(Help)
Help is (usually) an atom of text describing the option in the help text. This term is optional (but obviously strongly recommended for all options which have flags).

Long lines are subject to basic word wrapping -- split on white space, reindent, rejoin. However, you can get more control by supplying the line breaking yourself: rather than a single line of text, you can provide a list of lines (as atoms). If you do, they will be joined with the appropriate indent but otherwise left untouched (see the option mode in the example below).

Absence of mandatory option specs or the presence of more than one for a particular option throws an error, as do unknown or incompatible types.

As a concrete example from a fictive application, suppose we want the following options to be read from the command line (long flag(s), short flag(s), meta:type=default, help)

--mode                  -m     atom=SCAN       data gathering mode,
                                               one of
                                                SCAN: do this
                                                READ: do that
                                                MAKE: make numbers
                                                WAIT: do nothing
--rebuild-cache         -r     boolean=true    rebuild cache in
                                               each iteration
--heisenberg-threshold  -t,-h  float=0.1       heisenberg threshold
--depths, --iters       -i,-d  K:integer=3     stop after K
                                               iterations
--distances                    term=[1,2,3,5]  initial prolog term
--output-file           -o     FILE:atom=_     write output to FILE
--label                 -l     atom=REPORT     report label
--verbosity             -v     V:integer=2     verbosity level,
                                               1 <= V <= 3

We may also have some configuration parameters which we currently think not needs to be controlled from the command line, say path('/some/file/path').

This interface is described by the following options specification (order between the specifications of a particular option is irrelevant).

ExampleOptsSpec =
    [ [opt(mode    ), type(atom), default('SCAN'),
        shortflags([m]),   longflags(['mode'] ),
        help([ 'data gathering mode, one of'
             , '  SCAN: do this'
             , '  READ: do that'
             , '  MAKE: fabricate some numbers'
             , '  WAIT: don''t do anything'])]

    , [opt(cache), type(boolean), default(true),
        shortflags([r]),   longflags(['rebuild-cache']),
        help('rebuild cache in each iteration')]

    , [opt(threshold), type(float), default(0.1),
        shortflags([t,h]),  longflags(['heisenberg-threshold']),
        help('heisenberg threshold')]

    , [opt(depth), meta('K'), type(integer), default(3),
        shortflags([i,d]),longflags([depths,iters]),
        help('stop after K iterations')]

    , [opt(distances), default([1,2,3,5]),
        longflags([distances]),
        help('initial prolog term')]

    , [opt(outfile), meta('FILE'), type(atom),
        shortflags([o]),  longflags(['output-file']),
        help('write output to FILE')]

    , [opt(label), type(atom), default('REPORT'),
        shortflags([l]), longflags([label]),
        help('report label')]

    , [opt(verbose),  meta('V'), type(integer), default(2),
        shortflags([v]),  longflags([verbosity]),
        help('verbosity level, 1 <= V <= 3')]

    , [opt(path), default('/some/file/path/')]
    ].

The help text above was accessed by opt_help(ExamplesOptsSpec, HelpText). The options appear in the same order as in the OptsSpec.

Given ExampleOptsSpec, a command line (somewhat syntactically inconsistent, in order to demonstrate different calling conventions) may look as follows

ExampleArgs = [ '-d5'
              , '--heisenberg-threshold', '0.14'
              , '--distances=[1,1,2,3,5,8]'
              , '--iters', '7'
              , '-ooutput.txt'
              , '--rebuild-cache', 'true'
              , 'input.txt'
              , '--verbosity=2'
              ].

opt_parse(ExampleOptsSpec, ExampleArgs, Opts, PositionalArgs) would then succeed with

Opts =    [ mode('SCAN')
          , label('REPORT')
          , path('/some/file/path')
          , threshold(0.14)
          , distances([1,1,2,3,5,8])
          , depth(7)
          , outfile('output.txt')
          , cache(true)
          , verbose(2)
          ],
PositionalArgs = ['input.txt'].

Note that path('/some/file/path') showing up in Opts has a default value (of the implicit type 'term'), but no corresponding flags in OptsSpec. Thus it can't be set from the command line. The rest of your program doesn't need to know that, of course. This provides an alternative to the common practice of asserting such hard-coded parameters under a single predicate (for instance setting(path, '/some/file/path')), with the advantage that you may seamlessly upgrade them to command-line options, should you one day find this a good idea. Just add an appropriate flag or two and a line of help text. Similarly, suppressing an option in a cluttered interface amounts to commenting out the flags.

opt_parse/5 allows more control through an additional argument list as shown in the example below.

?- opt_parse(ExampleOptsSpec, ExampleArgs,  Opts, PositionalArgs,
             [ output_functor(appl_config)
             ]).

Opts =    [ appl_config(verbose, 2),
          , appl_config(label, 'REPORT')
          ...
          ]

This representation may be preferable with the empty-flag configuration parameter style above (perhaps with asserting appl_config/2).

Notes and tips

author
- Marcus Uneson
version
- 0.20 (2011-04-27)
To be done
- : validation? e.g, numbers; file path existence; one-out-of-a-set-of-atoms */
  337:- predicate_options(opt_parse/5, 5,
  338                     [ allow_empty_flag_spec(boolean),
  339                       duplicated_flags(oneof([keepfirst,keeplast,keepall])),
  340                       output_functor(atom),
  341                       suppress_empty_meta(boolean)
  342                     ]).  343
  344:- multifile
  345    error:has_type/2,
  346    parse_type/3.
 opt_arguments(+OptsSpec, -Opts, -PositionalArgs) is det
Extract commandline options according to a specification. Convenience predicate, assuming that command-line arguments can be accessed by current_prolog_flag/2 (as in swi-prolog). For other access mechanisms and/or more control, get the args and pass them as a list of atoms to opt_parse/4 or opt_parse/5 instead.

Opts is a list of parsed options in the form Key(Value). Dashed args not in OptsSpec are not permitted and will raise error (see tip on how to pass unknown flags in the module description). PositionalArgs are the remaining non-dashed args after each flag has taken its argument (filling in true or false for booleans). There are no restrictions on non-dashed arguments and they may go anywhere (although it is good practice to put them last). Any leading arguments for the runtime (up to and including '--') are discarded.

  366opt_arguments(OptsSpec, Opts, PositionalArgs) :-
  367    current_prolog_flag(argv, Argv),
  368    opt_parse(OptsSpec, Argv, Opts, PositionalArgs).
 opt_parse(+OptsSpec, +ApplArgs, -Opts, -PositionalArgs) is det
Equivalent to opt_parse(OptsSpec, ApplArgs, Opts, PositionalArgs, []).
  375opt_parse(OptsSpec, ApplArgs, Opts, PositionalArgs) :-
  376    opt_parse(OptsSpec, ApplArgs, Opts, PositionalArgs, []).
 opt_parse(+OptsSpec, +ApplArgs, -Opts, -PositionalArgs, +ParseOptions) is det
Parse the arguments Args (as list of atoms) according to OptsSpec. Any runtime arguments (typically terminated by '--') are assumed to be removed already.

Opts is a list of parsed options in the form Key(Value), or (with the option functor(Func) given) in the form Func(Key, Value). Dashed args not in OptsSpec are not permitted and will raise error (see tip on how to pass unknown flags in the module description). PositionalArgs are the remaining non-dashed args after each flag has taken its argument (filling in true or false for booleans). There are no restrictions on non-dashed arguments and they may go anywhere (although it is good practice to put them last). ParseOptions are

output_functor(Func)
Set the functor Func of the returned options Func(Key,Value). Default is the special value 'OPTION' (upper-case), which makes the returned options have form Key(Value).
duplicated_flags(Keep)
Controls how to handle options given more than once on the commad line. Keep is one of keepfirst, keeplast, keepall with the obvious meaning. Default is keeplast.
allow_empty_flag_spec(Bool)
If true (default), a flag specification is not required (it is allowed that both shortflags and longflags be either [] or absent). Flagless options cannot be manipulated from the command line and will not show up in the generated help. This is useful when you have (also) general configuration parameters in your OptsSpec, especially if you think they one day might need to be controlled externally. See example in the module overview. allow_empty_flag_spec(false) gives the more customary behaviour of raising error on empty flags.
  416opt_parse(OptsSpec, ApplArgs, Opts, PositionalArgs, ParseOptions) :-
  417    opt_parse_(OptsSpec, ApplArgs, Opts, PositionalArgs, ParseOptions).
 opt_help(+OptsSpec, -Help:atom) is det
True when Help is a help string synthesized from OptsSpec.
  424opt_help(OptsSpec, Help) :-
  425    opt_help(OptsSpec, Help, []).
  426
  427% semi-arbitrary default format settings go here;
  428% if someone needs more control one day, opt_help/3 could be exported
  429opt_help(OptsSpec, Help, HelpOptions0) :-
  430    Defaults = [ line_width(80)
  431               , min_help_width(40)
  432               , break_long_flags(false)
  433               , suppress_empty_meta(true)
  434               ],
  435    merge_options(HelpOptions0, Defaults, HelpOptions),
  436    opt_help_(OptsSpec, Help, HelpOptions).
  437
  438
  439%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OPT_PARSE
  440
  441opt_parse_(OptsSpec0, Args0, Opts, PositionalArgs, ParseOptions) :-
  442    must_be(list(atom), Args0),
  443
  444    check_opts_spec(OptsSpec0, ParseOptions, OptsSpec),
  445
  446    maplist(atom_codes, Args0, Args1),
  447    parse_options(OptsSpec, Args1, Args2, PositionalArgs),
  448    add_default_opts(OptsSpec, Args2, Args3),
  449
  450    option(duplicated_flags(Keep), ParseOptions, keeplast),
  451    remove_duplicates(Keep, Args3, Args4),
  452
  453    option(output_functor(Func), ParseOptions, 'OPTION'),
  454    refunctor_opts(Func, Args4, Opts). %}}}
  455
  456
  457
  458%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MAKE HELP
  459opt_help_(OptsSpec0, Help, HelpOptions) :-
  460    check_opts_spec(OptsSpec0, HelpOptions, OptsSpec1),
  461    include_in_help(OptsSpec1, OptsSpec2),
  462    format_help_fields(OptsSpec2, OptsSpec3),
  463    col_widths(OptsSpec3, [shortflags, metatypedef], CWs),
  464    long_flag_col_width(OptsSpec3, LongestFlagWidth),
  465    maplist(format_opt(LongestFlagWidth, CWs, HelpOptions), OptsSpec3, Lines),
  466    atomic_list_concat(Lines, Help).
  467
  468include_in_help([], []).
  469include_in_help([OptSpec|OptsSpec], Result) :-
  470    (  flags(OptSpec, [_|_])
  471    -> Result = [OptSpec|Rest]
  472    ;  Result = Rest
  473    ),
  474    include_in_help(OptsSpec, Rest).
  475
  476format_help_fields(OptsSpec0, OptsSpec) :-
  477    maplist(embellish_flag(short), OptsSpec0, OptsSpec1),
  478    maplist(embellish_flag(long), OptsSpec1, OptsSpec2),
  479    maplist(merge_meta_type_def, OptsSpec2, OptsSpec).
  480
  481merge_meta_type_def(OptSpecIn, [metatypedef(MTD)|OptSpecIn]) :-
  482    memberchk(meta(Meta), OptSpecIn),
  483    memberchk(type(Type), OptSpecIn),
  484    memberchk(default(Def), OptSpecIn),
  485    atom_length(Meta, N),
  486    (  N > 0
  487    -> format(atom(MTD), '~w:~w=~w', [Meta, Type, Def])
  488    ;  format(atom(MTD), '~w=~w', [Type, Def])
  489    ).
  490embellish_flag(short, OptSpecIn, OptSpecOut) :-
  491    memberchk(shortflags(FlagsIn), OptSpecIn),
  492    maplist(atom_concat('-'), FlagsIn, FlagsOut0),
  493    atomic_list_concat(FlagsOut0, ',',  FlagsOut),
  494    merge_options([shortflags(FlagsOut)], OptSpecIn, OptSpecOut).
  495embellish_flag(long, OptSpecIn, OptSpecOut) :-
  496    memberchk(longflags(FlagsIn), OptSpecIn),
  497    maplist(atom_concat('--'), FlagsIn, FlagsOut),
  498    merge_options([longflags(FlagsOut)], OptSpecIn, OptSpecOut).
  499
  500col_widths(OptsSpec, Functors, ColWidths) :-
  501    maplist(col_width(OptsSpec), Functors, ColWidths).
  502col_width(OptsSpec, Functor, ColWidth) :-
  503    findall(N,
  504            ( member(OptSpec, OptsSpec),
  505              M =.. [Functor, Arg],
  506              member(M, OptSpec),
  507              format(atom(Atom), '~w', [Arg]),
  508              atom_length(Atom, N0),
  509              N is N0 + 2     %separate cols with two spaces
  510            ),
  511            Ns),
  512    max_list([0|Ns], ColWidth).
  513
  514long_flag_col_width(OptsSpec, ColWidth) :-
  515    findall(FlagLength,
  516           ( member(OptSpec, OptsSpec),
  517             memberchk(longflags(LFlags), OptSpec),
  518             member(LFlag, LFlags),
  519             atom_length(LFlag, FlagLength)
  520             ),
  521            FlagLengths),
  522    max_list([0|FlagLengths], ColWidth).
  523
  524
  525format_opt(LongestFlagWidth, [SFlagsCW, MTDCW], HelpOptions, Opt, Line) :-
  526    memberchk(shortflags(SFlags), Opt),
  527
  528    memberchk(longflags(LFlags0), Opt),
  529    group_length(LongestFlagWidth, LFlags0, LFlags1),
  530    LFlagsCW is LongestFlagWidth + 2, %separate with comma and space
  531    option(break_long_flags(BLF), HelpOptions, true),
  532    (  BLF
  533    -> maplist(atomic_list_concat_(',\n'), LFlags1, LFlags2)
  534    ;  maplist(atomic_list_concat_(', '), LFlags1, LFlags2)
  535    ),
  536    atomic_list_concat(LFlags2, ',\n', LFlags),
  537
  538    memberchk(metatypedef(MetaTypeDef), Opt),
  539
  540    memberchk(help(Help), Opt),
  541    HelpIndent is LFlagsCW + SFlagsCW + MTDCW + 2,
  542    option(line_width(LW), HelpOptions, 80),
  543    option(min_help_width(MHW), HelpOptions, 40),
  544    HelpWidth is max(MHW, LW - HelpIndent),
  545    (  atom(Help)
  546    -> line_breaks(Help, HelpWidth, HelpIndent, BrokenHelp)
  547    ;  assertion(is_list_of_atoms(Help))
  548    -> indent_lines(Help, HelpIndent, BrokenHelp)
  549    ),
  550    format(atom(Line), '~w~t~*+~w~t~*+~w~t~*+~w~n',
  551      [LFlags, LFlagsCW, SFlags, SFlagsCW, MetaTypeDef, MTDCW, BrokenHelp]).
  552
  553
  554line_breaks(TextLine, LineLength, Indent, TextLines) :-
  555    atomic_list_concat(Words, ' ', TextLine),
  556    group_length(LineLength, Words, Groups0),
  557    maplist(atomic_list_concat_(' '), Groups0, Groups),
  558    indent_lines(Groups, Indent, TextLines).
  559
  560indent_lines(Lines, Indent, TextLines) :-
  561    format(atom(Separator), '~n~*|', [Indent]),
  562    atomic_list_concat(Lines, Separator, TextLines).
  563
  564atomic_list_concat_(Separator, List, Atom) :-
  565    atomic_list_concat(List, Separator, Atom).
  566
  567%group_length(10,
  568%             [here, are, some, words, you, see],
  569%             [[here are], [some words], [you see]]) %each group >= 10F
  570group_length(LineLength, Words, Groups) :-
  571    group_length_(Words, LineLength, LineLength, [], [], Groups).
  572
  573group_length_([], _, _, ThisLine, GroupsAcc, Groups) :-
  574    maplist(reverse, [ThisLine|GroupsAcc], GroupsAcc1),
  575    reverse(GroupsAcc1, Groups).
  576group_length_([Word|Words], LineLength, Remains, ThisLine, Groups, GroupsAcc) :-
  577    atom_length(Word, K),
  578    (  (Remains >= K; ThisLine = [])  %Word fits on ThisLine, or too long too fit
  579    -> Remains1 is Remains - K - 1,  %even on a new line
  580     group_length_(Words, LineLength, Remains1, [Word|ThisLine], Groups, GroupsAcc)
  581
  582                                     %Word doesn't fit on ThisLine (non-empty)
  583    ;  group_length_([Word|Words], LineLength, LineLength, [], [ThisLine|Groups], GroupsAcc)
  584    ).
  585
  586
  587%}}}
  588
  589
  590%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OPTSSPEC DEFAULTS
  591
  592
  593add_default_defaults(OptsSpec0, OptsSpec, Options) :-
  594    option(suppress_empty_meta(SEM), Options, true),
  595    maplist(default_defaults(SEM), OptsSpec0, OptsSpec).
  596
  597default_defaults(SuppressEmptyMeta, OptSpec0, OptSpec) :-
  598    (  SuppressEmptyMeta
  599    -> Meta = ''
  600    ;  memberchk(type(Type), OptSpec0)
  601    -> meta_placeholder(Type, Meta)
  602    ;  Meta = 'T'
  603    ),
  604
  605    Defaults = [ help('')
  606             , type(term)
  607             , shortflags([])
  608             , longflags([])
  609             , default('_')
  610             , meta(Meta)
  611             ],
  612    merge_options(OptSpec0, Defaults, OptSpec).
  613    %merge_options(+New, +Old, -Merged)
  614
  615
  616meta_placeholder(boolean, 'B').
  617meta_placeholder(atom, 'A').
  618meta_placeholder(float, 'F').
  619meta_placeholder(integer, 'I').
  620meta_placeholder(term, 'T').
  621
  622
  623
  624%}}}
  625
  626
  627%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OPTSSPEC VALIDATION
  628
  629%this is a bit paranoid, but OTOH efficiency is no issue
  630check_opts_spec(OptsSpec0, Options, OptsSpec) :-
  631    validate_opts_spec(OptsSpec0, Options),
  632    add_default_defaults(OptsSpec0, OptsSpec, Options),
  633    validate_opts_spec(OptsSpec, Options).
  634
  635validate_opts_spec(OptsSpec, ParseOptions) :-
  636    \+ invalidate_opts_spec(OptsSpec, ParseOptions).
  637
  638invalidate_opts_spec(OptsSpec, _ParseOptions) :-
  639    %invalid if not ground -- must go first for \+ to be sound
  640    ( \+ ground(OptsSpec)
  641    -> throw(error(instantiation_error,
  642                   context(validate_opts_spec/1, 'option spec must be ground')))
  643
  644    %invalid if conflicting flags
  645    ; ( member(O1, OptsSpec), flags(O1, Flags1), member(F, Flags1),
  646        member(O2, OptsSpec), flags(O2, Flags2), member(F, Flags2),
  647        O1 \= O2)
  648    -> throw(error(domain_error(unique_atom, F),
  649                   context(validate_opts_spec/1, 'ambiguous flag')))
  650
  651    %invalid if unknown opt spec
  652    ; ( member(OptSpec, OptsSpec),
  653        member(Spec, OptSpec),
  654        functor(Spec, F, _),
  655        \+ member(F, [opt, shortflags, longflags, type, help, default, meta]) )
  656    ->  throw(error(domain_error(opt_spec, F),
  657                   context(validate_opts_spec/1, 'unknown opt spec')))
  658
  659    %invalid if mandatory option spec opt(ID) is not unique in the entire Spec
  660    ; ( member(O1, OptsSpec), member(opt(Name), O1),
  661        member(O2, OptsSpec), member(opt(Name), O2),
  662        O1 \= O2)
  663    -> throw(error(domain_error(unique_atom, Name),
  664                   context(validate_opts_spec/1, 'ambiguous id')))
  665    ).
  666
  667invalidate_opts_spec(OptsSpec, _ParseOptions) :-
  668    member(OptSpec, OptsSpec),
  669    \+ member(opt(_Name), OptSpec),
  670    %invalid if mandatory option spec opt(ID) is absent
  671    throw(error(domain_error(unique_atom, OptSpec),
  672                context(validate_opts_spec/1, 'opt(id) missing'))).
  673
  674invalidate_opts_spec(OptsSpec, ParseOptions) :-
  675    member(OptSpec, OptsSpec), %if we got here, OptSpec has a single unique Name
  676    member(opt(Name), OptSpec),
  677
  678    option(allow_empty_flag_spec(AllowEmpty), ParseOptions, true),
  679
  680    %invalid if allow_empty_flag_spec(false) and no flag is given
  681    ( (\+ AllowEmpty, \+ flags(OptSpec, [_|_]))
  682    -> format(atom(Msg), 'no flag specified for option ''~w''', [Name]),
  683       throw(error(domain_error(unique_atom, _),
  684                context(validate_opts_spec/1, Msg)))
  685
  686    %invalid if any short flag is not actually single-letter
  687    ; ( memberchk(shortflags(Flags), OptSpec),
  688        member(F, Flags),
  689        atom_length(F, L),
  690        L > 1)
  691    ->  format(atom(Msg), 'option ''~w'': flag too long to be short', [Name]),
  692        throw(error(domain_error(short_flag, F),
  693                context(validate_opts_spec/1, Msg)))
  694
  695    %invalid if any option spec is given more than once
  696    ; duplicate_optspec(OptSpec,
  697      [type,opt,default,help,shortflags,longflags,meta])
  698    ->  format(atom(Msg), 'duplicate spec in option ''~w''', [Name]),
  699        throw(error(domain_error(unique_functor, _),
  700                context(validate_opts_spec/1, Msg)))
  701
  702    %invalid if unknown type
  703    ;   (   memberchk(type(Type), OptSpec),
  704            Type \== term,
  705            \+ clause(error:has_type(Type,_), _)
  706        )
  707    ->  format(atom(Msg), 'unknown type ''~w'' in option ''~w''', [Type, Name]),
  708        throw(error(type_error(flag_value, Type),
  709              context(validate_opts_spec/1, Msg)))
  710
  711    %invalid if type does not match default
  712    %note1: reverse logic: we are trying to _in_validate OptSpec
  713
  714    %note2: 'term' approves of any syntactically valid prolog term, since
  715    %if syntactically invalid, OptsSpec wouldn't have parsed
  716
  717    %note3: the special placeholder '_' creates a new variable, so no typecheck
  718    ;    (memberchk(type(Type), OptSpec),
  719          Type \= term,
  720          memberchk(default(Default), OptSpec),
  721          Default \= '_'
  722    ->   \+ must_be(Type, Default))
  723
  724    %invalidation failed, i.e., optspec is OK
  725    ; fail
  726    ).
  727
  728duplicate_optspec(_, []) :- !, fail.
  729duplicate_optspec(OptSpec, [Func|Funcs]) :-
  730    functor(F, Func, 1),
  731    findall(F, member(F, OptSpec), Xs),
  732    (Xs = [_,_|_]
  733    -> true
  734    ; duplicate_optspec(OptSpec, Funcs)
  735    ).
  736
  737
  738%}}}
  739
  740
  741%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PARSE OPTIONS
  742% NOTE:
  743% -sbar could be interpreted in two ways: as short for -s bar, and
  744% as short ('clustered') for -s -b -a -r. Here, the former interpretation
  745% is chosen.
  746% Cf http://perldoc.perl.org/Getopt/Long.html (no clustering by default)
  747
  748
  749parse_options(OptsSpec, Args0, Options, PosArgs) :-
  750    append(Args0, [""], Args1),
  751    parse_args_(Args1, OptsSpec, Args2),
  752    partition_args_(Args2, Options, PosArgs).
  753
  754%{{{ PARSE ARGS
  755
  756
  757%if arg is boolean flag given as --no-my-arg, expand to my-arg, false, re-call
  758parse_args_([Arg,Arg2|Args], OptsSpec, [opt(KID, false)|Result]) :-
  759    flag_name_long_neg(Dashed, NonDashed, Arg, []),
  760    flag_id_type(OptsSpec, NonDashed, KID, boolean),
  761    !,
  762    parse_args_([Dashed, "false", Arg2|Args], OptsSpec, Result).
  763
  764%if arg is ordinary boolean flag, fill in implicit true if arg absent; re-call
  765parse_args_([Arg,Arg2|Args], OptsSpec, Result) :-
  766    flag_name(K, Arg, []),
  767    flag_id_type(OptsSpec, K, _KID, boolean),
  768    \+ member(Arg2, ["true", "false"]),
  769    !,
  770    parse_args_([Arg, "true", Arg2 | Args], OptsSpec, Result).
  771
  772% separate short or long flag run together with its value and parse
  773parse_args_([Arg|Args], OptsSpec, [opt(KID, Val)|Result]) :-
  774    flag_name_value(Arg1, Arg2, Arg, []),
  775    \+ short_flag_w_equals(Arg1, Arg2),
  776    flag_name(K, Arg1, []),
  777    !,
  778    parse_option(OptsSpec, K, Arg2, opt(KID, Val)),
  779    parse_args_(Args, OptsSpec, Result).
  780
  781%from here, unparsed args have form
  782%  PosArg1,Flag1,Val1,PosArg2,PosArg3,Flag2,Val2, PosArg4...
  783%i.e., positional args may go anywhere except between FlagN and ValueN
  784%(of course, good programming style says they should go last, but it is poor
  785%programming style to assume that)
  786
  787parse_args_([Arg1,Arg2|Args], OptsSpec, [opt(KID, Val)|Result]) :-
  788    flag_name(K, Arg1, []),
  789    !,
  790    parse_option(OptsSpec, K, Arg2, opt(KID, Val)),
  791    parse_args_(Args, OptsSpec, Result).
  792
  793parse_args_([Arg1,Arg2|Args], OptsSpec, [pos(At)|Result]) :-
  794    \+ flag_name(_, Arg1, []),
  795    !,
  796    atom_codes(At, Arg1),
  797    parse_args_([Arg2|Args], OptsSpec, Result).
  798
  799parse_args_([""], _, []) :- !.   %placeholder, but useful for error messages
  800parse_args_([], _, []) :- !.
  801
  802short_flag_w_equals([0'-,_C], [0'=|_]) :-
  803    throw(error(syntax_error('disallowed: <shortflag>=<value>'),_)).
  804
  805
  806
  807flag_id_type(OptsSpec, FlagCodes, ID, Type) :-
  808    atom_codes(Flag, FlagCodes),
  809    member(OptSpec, OptsSpec),
  810    flags(OptSpec, Flags),
  811    member(Flag, Flags),
  812    member(type(Type), OptSpec),
  813    member(opt(ID), OptSpec).
  814
  815%{{{ FLAG DCG
  816
  817%DCG non-terminals:
  818%  flag_name(NonDashed)                  %c, flag-name, x
  819%  flag_name_short(Dashed, NonDashed)    %c, x
  820%  flag_name_long(Dashed, NonDashed)     %flag-name
  821%  flag_name_long_neg(Dashed, NonDashed) %no-flag-name
  822%  flag_value(Val)                       %non-empty string
  823%  flag_value0(Val)                      %any string, also empty
  824%  flag_name_value(Dashed, Val)          %pair of flag_name, flag_value
  825
  826
  827flag_name(NonDashed) --> flag_name_long(_, NonDashed).
  828flag_name(NonDashed) --> flag_name_short(_, NonDashed).
  829flag_name(NonDashed) --> flag_name_long_neg(_, NonDashed).
  830
  831flag_name_long_neg([0'-,0'-|Cs], Cs) --> "--no-", name_long(Cs).
  832flag_name_long([0'-,0'-|Cs], Cs) --> "--", name_long(Cs).
  833flag_name_short([0'-|C], C) --> "-", name_1st(C).
  834
  835flag_value([C|Cs]) --> [C], flag_value0(Cs).
  836flag_value0([]) --> [].
  837flag_value0([C|Cs]) --> [C], flag_value0(Cs).
  838flag_name_value(Dashed, Val) --> flag_name_long(Dashed, _), "=", flag_value0(Val).
  839flag_name_value(Dashed, Val) --> flag_name_short(Dashed, _), flag_value(Val).
  840
  841name_long([C|Cs]) --> name_1st([C]), name_rest(Cs).
  842name_1st([C]) --> [C], {name_1st(C)}.
  843name_rest([]) --> [].
  844name_rest([C|Cs]) --> [C], {name_char(C)}, name_rest(Cs).
  845name_1st(C) :- char_type(C, alpha).
  846name_char(C) :- char_type(C, alpha).
  847name_char( 0'_ ).
  848name_char( 0'- ). %}}}
  849
  850
  851%{{{ PARSE OPTION
  852parse_option(OptsSpec, Arg1, Arg2, opt(KID, Val)) :-
  853    (  flag_id_type(OptsSpec, Arg1, KID, Type)
  854    -> parse_val(Arg1, Type, Arg2, Val)
  855    ;  format(atom(Msg), '~s', [Arg1]),
  856     opt_help(OptsSpec, Help),        %unknown flag: dump usage on stderr
  857     nl(user_error),
  858     write(user_error, Help),
  859     throw(error(domain_error(flag_value, Msg),context(_, 'unknown flag')))
  860    ).
  861
  862
  863parse_val(Opt, Type, Cs, Val) :-
  864    catch(
  865    parse_loc(Type, Cs, Val),
  866    E,
  867    ( format('~nERROR: flag ''~s'': expected atom parsable as ~w, found ''~s'' ~n',
  868                             [Opt,                           Type,        Cs]),
  869      throw(E))
  870    ).
  871
  872%parse_loc(+Type, +ListOfCodes, -Result).
  873parse_loc(Type, _LOC, _) :-
  874    var(Type), !, throw(error(instantiation_error, _)).
  875parse_loc(_Type, LOC, _) :-
  876    var(LOC), !, throw(error(instantiation_error, _)).
  877parse_loc(boolean, Cs, true) :- atom_codes(true, Cs), !.
  878parse_loc(boolean, Cs, false) :- atom_codes(false, Cs), !.
  879parse_loc(atom, Cs, Result) :- atom_codes(Result, Cs), !.
  880parse_loc(integer, Cs, Result) :-
  881    number_codes(Result, Cs),
  882    integer(Result),
  883
  884    !.
  885parse_loc(float, Cs, Result)   :-
  886    number_codes(Result, Cs),
  887    float(Result),
  888
  889    !.
  890parse_loc(term, Cs, Result) :-
  891    atom_codes(A, Cs),
  892    term_to_atom(Result, A),
  893
  894    !.
  895parse_loc(Type, Cs, Result) :-
  896    parse_type(Type, Cs, Result),
  897    !.
  898parse_loc(Type, _Cs, _) :- %could not parse Cs as Type
  899    throw(error(type_error(flag_value, Type), _)),
  900    !. %}}}
  901%}}}
 parse_type(+Type, +Codes:list(code), -Result) is semidet
Hook to parse option text Codes to an object of type Type.
  907partition_args_([], [], []).
  908partition_args_([opt(K,V)|Rest], [opt(K,V)|RestOpts], RestPos) :-
  909    !,
  910    partition_args_(Rest, RestOpts, RestPos).
  911partition_args_([pos(Arg)|Rest], RestOpts, [Arg|RestPos]) :-
  912    !,
  913    partition_args_(Rest, RestOpts, RestPos).
  914
  915
  916
  917
  918%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ADD DEFAULTS
  919
  920add_default_opts([], Opts, Opts).
  921add_default_opts([OptSpec|OptsSpec], OptsIn, Result) :-
  922    memberchk(opt(OptName), OptSpec),
  923    (  memberchk(opt(OptName, _Val), OptsIn)
  924    -> Result = OptsOut                      %value given on cl, ignore default
  925
  926    ;                                        %value not given on cl:
  927       memberchk(default('_'), OptSpec)      % no default in OptsSpec (or 'VAR'):
  928    -> Result = [opt(OptName, _) | OptsOut]  % create uninstantiated variable
  929    ;
  930       memberchk(default(Def), OptSpec),     % default given in OptsSpec
  931%       memberchk(type(Type), OptSpec),      % already typechecked
  932%       assertion(must_be(Type, Def)),
  933       Result = [opt(OptName, Def) | OptsOut]
  934    ),
  935    add_default_opts(OptsSpec, OptsIn, OptsOut).
  936
  937
  938
  939%}}}
  940
  941
  942%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% REMOVE DUPLICATES
  943remove_duplicates(_, [], []) :- !.
  944remove_duplicates(keeplast, [opt(OptName, Val) | Opts], Result) :-
  945    !,
  946    (  memberchk(opt(OptName, _), Opts)
  947    -> Result = RestOpts
  948    ;  Result = [opt(OptName, Val) | RestOpts]
  949    ),
  950    remove_duplicates(keeplast, Opts, RestOpts).
  951
  952remove_duplicates(keepfirst, OptsIn, OptsOut) :-
  953    !,
  954    reverse(OptsIn, OptsInRev),
  955    remove_duplicates(keeplast, OptsInRev, OptsOutRev),
  956    reverse(OptsOutRev, OptsOut).
  957
  958remove_duplicates(keepall, OptsIn, OptsIn) :- !.
  959remove_duplicates(K, [_|_], _) :-
  960    !,
  961    throw(error(domain_error(keep_flag, K), _)). %}}}
  962
  963
  964%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% REFUNCTOR
  965refunctor_opts(Fnct, OptsIn, OptsOut) :-
  966    maplist(refunctor_opt(Fnct), OptsIn, OptsOut).
  967
  968refunctor_opt('OPTION', opt(OptName, OptVal), Result) :-
  969    !,
  970    Result =.. [OptName, OptVal].
  971
  972refunctor_opt(F, opt(OptName, OptVal), Result) :-
  973    Result =.. [F, OptName, OptVal]. %}}}
  974
  975
  976%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ACCESSORS
  977
  978flags(OptSpec, Flags) :- memberchk(shortflags(Flags), OptSpec).
  979flags(OptSpec, Flags) :- memberchk(longflags(Flags), OptSpec). %}}}
  980
  981%{{{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UTILS
  982is_list_of_atoms([]).
  983is_list_of_atoms([X|Xs]) :- atom(X), is_list_of_atoms(Xs).
  984%}}}