lemon/arg_parser.h
author Alpar Juttner <alpar@cs.elte.hu>
Sun, 28 Feb 2010 20:52:08 +0100
changeset 849 1b8db382910c
parent 440 88ed40ad0d4f
child 877 141f9c0db4a3
permissions -rw-r--r--
Merge #342
alpar@209
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
alpar@85
     2
 *
alpar@209
     3
 * This file is a part of LEMON, a generic C++ optimization library.
alpar@85
     4
 *
alpar@440
     5
 * Copyright (C) 2003-2009
alpar@85
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@85
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@85
     8
 *
alpar@85
     9
 * Permission to use, modify and distribute this software is granted
alpar@85
    10
 * provided that this copyright notice appears in all copies. For
alpar@85
    11
 * precise terms see the accompanying LICENSE file.
alpar@85
    12
 *
alpar@85
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@85
    14
 * express or implied, and with no claim as to its suitability for any
alpar@85
    15
 * purpose.
alpar@85
    16
 *
alpar@85
    17
 */
alpar@85
    18
alpar@261
    19
#ifndef LEMON_ARG_PARSER_H
alpar@261
    20
#define LEMON_ARG_PARSER_H
alpar@85
    21
alpar@85
    22
#include <vector>
alpar@85
    23
#include <map>
alpar@85
    24
#include <list>
alpar@85
    25
#include <string>
alpar@85
    26
#include <iostream>
alpar@85
    27
#include <sstream>
alpar@85
    28
#include <algorithm>
deba@108
    29
#include <lemon/assert.h>
alpar@85
    30
alpar@85
    31
///\ingroup misc
alpar@85
    32
///\file
kpeter@88
    33
///\brief A tool to parse command line arguments.
alpar@85
    34
alpar@85
    35
namespace lemon {
alpar@85
    36
alpar@842
    37
  ///Exception used by ArgParser
alpar@842
    38
  class ArgParserException : public Exception {
alpar@842
    39
  public:
alpar@842
    40
    enum Reason {
alpar@842
    41
      HELP,         /// <tt>--help</tt> option was given
alpar@842
    42
      UNKNOWN_OPT,  /// Unknown option was given
alpar@842
    43
      INVALID_OPT   /// Invalid combination of options
alpar@842
    44
    };
alpar@842
    45
    
alpar@842
    46
  private:
alpar@842
    47
    Reason _reason;
alpar@842
    48
    
alpar@842
    49
  public:
alpar@842
    50
    ///Constructor
alpar@842
    51
    ArgParserException(Reason r) throw() : _reason(r) {}
alpar@842
    52
    ///Virtual destructor
alpar@842
    53
    virtual ~ArgParserException() throw() {}
alpar@842
    54
    ///A short description of the exception
alpar@842
    55
    virtual const char* what() const throw() {
alpar@842
    56
      switch(_reason)
alpar@842
    57
        {
alpar@842
    58
        case HELP:
alpar@842
    59
          return "lemon::ArgParseException: ask for help";
alpar@842
    60
          break;
alpar@842
    61
        case UNKNOWN_OPT:
alpar@842
    62
          return "lemon::ArgParseException: unknown option";
alpar@842
    63
          break;
alpar@842
    64
        case INVALID_OPT:
alpar@842
    65
          return "lemon::ArgParseException: invalid combination of options";
alpar@842
    66
          break;
alpar@842
    67
        }
alpar@842
    68
      return "";
alpar@842
    69
    }
alpar@842
    70
    ///Return the reason for the failure
alpar@842
    71
    Reason reason() const {return _reason; }
alpar@842
    72
  };
alpar@842
    73
alpar@842
    74
alpar@85
    75
  ///Command line arguments parser
alpar@85
    76
alpar@85
    77
  ///\ingroup misc
kpeter@88
    78
  ///Command line arguments parser.
alpar@85
    79
  ///
kpeter@88
    80
  ///For a complete example see the \ref arg_parser_demo.cc demo file.
alpar@85
    81
  class ArgParser {
alpar@209
    82
alpar@85
    83
    static void _showHelp(void *p);
alpar@85
    84
  protected:
alpar@209
    85
alpar@85
    86
    int _argc;
ladanyi@311
    87
    const char * const *_argv;
alpar@209
    88
alpar@85
    89
    enum OptType { UNKNOWN=0, BOOL=1, STRING=2, DOUBLE=3, INTEGER=4, FUNC=5 };
alpar@209
    90
alpar@85
    91
    class ParData {
alpar@85
    92
    public:
alpar@85
    93
      union {
alpar@209
    94
        bool *bool_p;
alpar@209
    95
        int *int_p;
alpar@209
    96
        double *double_p;
alpar@209
    97
        std::string *string_p;
alpar@209
    98
        struct {
alpar@209
    99
          void (*p)(void *);
alpar@209
   100
          void *data;
alpar@209
   101
        } func_p;
alpar@209
   102
alpar@85
   103
      };
alpar@85
   104
      std::string help;
alpar@85
   105
      bool mandatory;
alpar@85
   106
      OptType type;
alpar@85
   107
      bool set;
alpar@85
   108
      bool ingroup;
alpar@85
   109
      bool has_syn;
alpar@85
   110
      bool syn;
alpar@85
   111
      bool self_delete;
alpar@85
   112
      ParData() : mandatory(false), type(UNKNOWN), set(false), ingroup(false),
alpar@209
   113
                  has_syn(false), syn(false), self_delete(false) {}
alpar@85
   114
    };
alpar@85
   115
alpar@85
   116
    typedef std::map<std::string,ParData> Opts;
alpar@85
   117
    Opts _opts;
alpar@85
   118
alpar@209
   119
    class GroupData
alpar@85
   120
    {
alpar@85
   121
    public:
alpar@85
   122
      typedef std::list<std::string> Opts;
alpar@85
   123
      Opts opts;
alpar@85
   124
      bool only_one;
alpar@85
   125
      bool mandatory;
alpar@85
   126
      GroupData() :only_one(false), mandatory(false) {}
alpar@85
   127
    };
alpar@209
   128
alpar@85
   129
    typedef std::map<std::string,GroupData> Groups;
alpar@85
   130
    Groups _groups;
alpar@85
   131
alpar@85
   132
    struct OtherArg
alpar@85
   133
    {
alpar@85
   134
      std::string name;
alpar@85
   135
      std::string help;
alpar@85
   136
      OtherArg(std::string n, std::string h) :name(n), help(h) {}
alpar@85
   137
alpar@85
   138
    };
alpar@209
   139
alpar@85
   140
    std::vector<OtherArg> _others_help;
alpar@85
   141
    std::vector<std::string> _file_args;
alpar@85
   142
    std::string _command_name;
alpar@87
   143
alpar@842
   144
    
alpar@87
   145
  private:
alpar@87
   146
    //Bind a function to an option.
alpar@87
   147
alpar@87
   148
    //\param name The name of the option. The leading '-' must be omitted.
alpar@87
   149
    //\param help A help string.
alpar@87
   150
    //\retval func The function to be called when the option is given. It
alpar@87
   151
    //  must be of type "void f(void *)"
alpar@87
   152
    //\param data Data to be passed to \c func
alpar@87
   153
    ArgParser &funcOption(const std::string &name,
alpar@209
   154
                    const std::string &help,
alpar@209
   155
                    void (*func)(void *),void *data);
alpar@209
   156
alpar@842
   157
    bool _exit_on_problems;
alpar@842
   158
    
alpar@842
   159
    void _terminate(ArgParserException::Reason reason) const;
alpar@842
   160
alpar@85
   161
  public:
alpar@85
   162
kpeter@204
   163
    ///Constructor
ladanyi@311
   164
    ArgParser(int argc, const char * const *argv);
alpar@85
   165
alpar@85
   166
    ~ArgParser();
alpar@85
   167
kpeter@204
   168
    ///\name Options
kpeter@204
   169
    ///
kpeter@204
   170
kpeter@204
   171
    ///@{
kpeter@204
   172
alpar@85
   173
    ///Add a new integer type option
alpar@85
   174
kpeter@204
   175
    ///Add a new integer type option.
alpar@85
   176
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   177
    ///\param help A help string.
kpeter@95
   178
    ///\param value A default value for the option.
alpar@85
   179
    ///\param obl Indicate if the option is mandatory.
alpar@85
   180
    ArgParser &intOption(const std::string &name,
alpar@209
   181
                    const std::string &help,
alpar@209
   182
                    int value=0, bool obl=false);
alpar@85
   183
alpar@86
   184
    ///Add a new floating point type option
alpar@85
   185
kpeter@204
   186
    ///Add a new floating point type option.
alpar@85
   187
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   188
    ///\param help A help string.
kpeter@95
   189
    ///\param value A default value for the option.
alpar@85
   190
    ///\param obl Indicate if the option is mandatory.
alpar@85
   191
    ArgParser &doubleOption(const std::string &name,
alpar@209
   192
                      const std::string &help,
alpar@209
   193
                      double value=0, bool obl=false);
alpar@85
   194
alpar@85
   195
    ///Add a new bool type option
alpar@85
   196
kpeter@204
   197
    ///Add a new bool type option.
alpar@85
   198
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   199
    ///\param help A help string.
kpeter@95
   200
    ///\param value A default value for the option.
alpar@85
   201
    ///\param obl Indicate if the option is mandatory.
kpeter@95
   202
    ///\note A mandatory bool obtion is of very little use.
alpar@85
   203
    ArgParser &boolOption(const std::string &name,
alpar@209
   204
                      const std::string &help,
alpar@209
   205
                      bool value=false, bool obl=false);
alpar@85
   206
alpar@85
   207
    ///Add a new string type option
alpar@85
   208
kpeter@204
   209
    ///Add a new string type option.
alpar@85
   210
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   211
    ///\param help A help string.
kpeter@95
   212
    ///\param value A default value for the option.
alpar@85
   213
    ///\param obl Indicate if the option is mandatory.
alpar@85
   214
    ArgParser &stringOption(const std::string &name,
alpar@209
   215
                      const std::string &help,
alpar@209
   216
                      std::string value="", bool obl=false);
alpar@85
   217
kpeter@204
   218
    ///Give help string for non-parsed arguments.
kpeter@204
   219
kpeter@204
   220
    ///With this function you can give help string for non-parsed arguments.
kpeter@204
   221
    ///The parameter \c name will be printed in the short usage line, while
kpeter@204
   222
    ///\c help gives a more detailed description.
kpeter@204
   223
    ArgParser &other(const std::string &name,
alpar@209
   224
                     const std::string &help="");
alpar@209
   225
kpeter@204
   226
    ///@}
kpeter@204
   227
kpeter@204
   228
    ///\name Options with External Storage
alpar@85
   229
    ///Using this functions, the value of the option will be directly written
alpar@85
   230
    ///into a variable once the option appears in the command line.
alpar@85
   231
alpar@85
   232
    ///@{
alpar@85
   233
alpar@85
   234
    ///Add a new integer type option with a storage reference
alpar@85
   235
kpeter@204
   236
    ///Add a new integer type option with a storage reference.
alpar@85
   237
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   238
    ///\param help A help string.
alpar@90
   239
    ///\param obl Indicate if the option is mandatory.
alpar@85
   240
    ///\retval ref The value of the argument will be written to this variable.
alpar@85
   241
    ArgParser &refOption(const std::string &name,
alpar@209
   242
                    const std::string &help,
alpar@209
   243
                    int &ref, bool obl=false);
alpar@85
   244
alpar@85
   245
    ///Add a new floating type option with a storage reference
alpar@85
   246
kpeter@204
   247
    ///Add a new floating type option with a storage reference.
alpar@85
   248
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   249
    ///\param help A help string.
alpar@90
   250
    ///\param obl Indicate if the option is mandatory.
alpar@85
   251
    ///\retval ref The value of the argument will be written to this variable.
alpar@85
   252
    ArgParser &refOption(const std::string &name,
alpar@209
   253
                      const std::string &help,
alpar@209
   254
                      double &ref, bool obl=false);
alpar@85
   255
alpar@85
   256
    ///Add a new bool type option with a storage reference
alpar@85
   257
kpeter@204
   258
    ///Add a new bool type option with a storage reference.
alpar@85
   259
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   260
    ///\param help A help string.
alpar@90
   261
    ///\param obl Indicate if the option is mandatory.
alpar@85
   262
    ///\retval ref The value of the argument will be written to this variable.
kpeter@95
   263
    ///\note A mandatory bool obtion is of very little use.
alpar@85
   264
    ArgParser &refOption(const std::string &name,
alpar@209
   265
                      const std::string &help,
alpar@209
   266
                      bool &ref, bool obl=false);
alpar@85
   267
alpar@85
   268
    ///Add a new string type option with a storage reference
alpar@85
   269
kpeter@204
   270
    ///Add a new string type option with a storage reference.
alpar@85
   271
    ///\param name The name of the option. The leading '-' must be omitted.
alpar@85
   272
    ///\param help A help string.
kpeter@95
   273
    ///\param obl Indicate if the option is mandatory.
alpar@85
   274
    ///\retval ref The value of the argument will be written to this variable.
alpar@85
   275
    ArgParser &refOption(const std::string &name,
alpar@209
   276
                      const std::string &help,
alpar@209
   277
                      std::string &ref, bool obl=false);
alpar@209
   278
alpar@85
   279
    ///@}
alpar@85
   280
alpar@85
   281
    ///\name Option Groups and Synonyms
alpar@85
   282
    ///
alpar@209
   283
alpar@85
   284
    ///@{
alpar@85
   285
kpeter@204
   286
    ///Bundle some options into a group
alpar@85
   287
alpar@85
   288
    /// You can group some option by calling this function repeatedly for each
kpeter@88
   289
    /// option to be grouped with the same groupname.
kpeter@88
   290
    ///\param group The group name.
kpeter@88
   291
    ///\param opt The option name.
alpar@85
   292
    ArgParser &optionGroup(const std::string &group,
alpar@209
   293
                           const std::string &opt);
alpar@85
   294
alpar@85
   295
    ///Make the members of a group exclusive
alpar@85
   296
alpar@85
   297
    ///If you call this function for a group, than at most one of them can be
kpeter@204
   298
    ///given at the same time.
alpar@85
   299
    ArgParser &onlyOneGroup(const std::string &group);
alpar@209
   300
alpar@85
   301
    ///Make a group mandatory
alpar@85
   302
alpar@85
   303
    ///Using this function, at least one of the members of \c group
alpar@85
   304
    ///must be given.
alpar@85
   305
    ArgParser &mandatoryGroup(const std::string &group);
alpar@209
   306
alpar@85
   307
    ///Create synonym to an option
alpar@85
   308
kpeter@88
   309
    ///With this function you can create a synonym \c syn of the
alpar@85
   310
    ///option \c opt.
alpar@85
   311
    ArgParser &synonym(const std::string &syn,
alpar@209
   312
                           const std::string &opt);
alpar@209
   313
alpar@85
   314
    ///@}
alpar@85
   315
alpar@214
   316
  private:
alpar@214
   317
    void show(std::ostream &os,Opts::const_iterator i) const;
alpar@214
   318
    void show(std::ostream &os,Groups::const_iterator i) const;
alpar@214
   319
    void showHelp(Opts::const_iterator i) const;
alpar@214
   320
    void showHelp(std::vector<OtherArg>::const_iterator i) const;
alpar@85
   321
alpar@214
   322
    void unknownOpt(std::string arg) const;
alpar@85
   323
alpar@214
   324
    void requiresValue(std::string arg, OptType t) const;
alpar@214
   325
    void checkMandatories() const;
alpar@214
   326
alpar@214
   327
    void shortHelp() const;
alpar@214
   328
    void showHelp() const;
alpar@214
   329
  public:
alpar@209
   330
alpar@85
   331
    ///Start the parsing process
alpar@85
   332
    ArgParser &parse();
alpar@85
   333
alpar@85
   334
    /// Synonym for parse()
alpar@209
   335
    ArgParser &run()
alpar@85
   336
    {
alpar@85
   337
      return parse();
alpar@85
   338
    }
alpar@209
   339
kpeter@204
   340
    ///Give back the command name (the 0th argument)
alpar@214
   341
    const std::string &commandName() const { return _command_name; }
kpeter@204
   342
alpar@85
   343
    ///Check if an opion has been given to the command.
alpar@214
   344
    bool given(std::string op) const
alpar@85
   345
    {
alpar@214
   346
      Opts::const_iterator i = _opts.find(op);
alpar@85
   347
      return i!=_opts.end()?i->second.set:false;
alpar@85
   348
    }
alpar@85
   349
alpar@85
   350
alpar@85
   351
    ///Magic type for operator[]
alpar@209
   352
alpar@85
   353
    ///This is the type of the return value of ArgParser::operator[]().
kpeter@88
   354
    ///It automatically converts to \c int, \c double, \c bool or
deba@290
   355
    ///\c std::string if the type of the option matches, which is checked
deba@290
   356
    ///with an \ref LEMON_ASSERT "assertion" (i.e. it performs runtime
deba@290
   357
    ///type checking).
alpar@209
   358
    class RefType
alpar@85
   359
    {
alpar@214
   360
      const ArgParser &_parser;
alpar@85
   361
      std::string _name;
alpar@85
   362
    public:
alpar@85
   363
      ///\e
alpar@214
   364
      RefType(const ArgParser &p,const std::string &n) :_parser(p),_name(n) {}
alpar@85
   365
      ///\e
alpar@209
   366
      operator bool()
alpar@85
   367
      {
alpar@214
   368
        Opts::const_iterator i = _parser._opts.find(_name);
alpar@209
   369
        LEMON_ASSERT(i!=_parser._opts.end(),
alpar@209
   370
                     std::string()+"Unkown option: '"+_name+"'");
alpar@209
   371
        LEMON_ASSERT(i->second.type==ArgParser::BOOL,
alpar@209
   372
                     std::string()+"'"+_name+"' is a bool option");
alpar@209
   373
        return *(i->second.bool_p);
alpar@85
   374
      }
alpar@85
   375
      ///\e
alpar@85
   376
      operator std::string()
alpar@85
   377
      {
alpar@214
   378
        Opts::const_iterator i = _parser._opts.find(_name);
alpar@209
   379
        LEMON_ASSERT(i!=_parser._opts.end(),
alpar@209
   380
                     std::string()+"Unkown option: '"+_name+"'");
alpar@209
   381
        LEMON_ASSERT(i->second.type==ArgParser::STRING,
alpar@209
   382
                     std::string()+"'"+_name+"' is a string option");
alpar@209
   383
        return *(i->second.string_p);
alpar@85
   384
      }
alpar@85
   385
      ///\e
alpar@209
   386
      operator double()
alpar@85
   387
      {
alpar@214
   388
        Opts::const_iterator i = _parser._opts.find(_name);
alpar@209
   389
        LEMON_ASSERT(i!=_parser._opts.end(),
alpar@209
   390
                     std::string()+"Unkown option: '"+_name+"'");
alpar@209
   391
        LEMON_ASSERT(i->second.type==ArgParser::DOUBLE ||
alpar@209
   392
                     i->second.type==ArgParser::INTEGER,
alpar@209
   393
                     std::string()+"'"+_name+"' is a floating point option");
alpar@209
   394
        return i->second.type==ArgParser::DOUBLE ?
alpar@209
   395
          *(i->second.double_p) : *(i->second.int_p);
alpar@85
   396
      }
alpar@85
   397
      ///\e
alpar@209
   398
      operator int()
alpar@85
   399
      {
alpar@214
   400
        Opts::const_iterator i = _parser._opts.find(_name);
alpar@209
   401
        LEMON_ASSERT(i!=_parser._opts.end(),
alpar@209
   402
                     std::string()+"Unkown option: '"+_name+"'");
alpar@209
   403
        LEMON_ASSERT(i->second.type==ArgParser::INTEGER,
alpar@209
   404
                     std::string()+"'"+_name+"' is an integer option");
alpar@209
   405
        return *(i->second.int_p);
alpar@85
   406
      }
alpar@85
   407
alpar@85
   408
    };
alpar@85
   409
alpar@85
   410
    ///Give back the value of an option
alpar@209
   411
kpeter@88
   412
    ///Give back the value of an option.
alpar@85
   413
    ///\sa RefType
alpar@214
   414
    RefType operator[](const std::string &n) const
alpar@85
   415
    {
alpar@85
   416
      return RefType(*this, n);
alpar@209
   417
    }
kpeter@204
   418
kpeter@204
   419
    ///Give back the non-option type arguments.
kpeter@204
   420
kpeter@204
   421
    ///Give back a reference to a vector consisting of the program arguments
kpeter@204
   422
    ///not starting with a '-' character.
alpar@214
   423
    const std::vector<std::string> &files() const { return _file_args; }
alpar@209
   424
alpar@842
   425
    ///Throw instead of exit in case of problems
alpar@842
   426
    void throwOnProblems() 
alpar@842
   427
    {
alpar@842
   428
      _exit_on_problems=false;
alpar@842
   429
    }
alpar@85
   430
  };
alpar@85
   431
}
alpar@85
   432
alpar@261
   433
#endif // LEMON_ARG_PARSER_H