Arg.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
  2. /******************************************************************************
  3. *
  4. * file: Arg.h
  5. *
  6. * Copyright (c) 2003, Michael E. Smoot .
  7. * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno .
  8. * Copyright (c) 2017 Google Inc.
  9. * All rights reserved.
  10. *
  11. * See the file COPYING in the top directory of this distribution for
  12. * more information.
  13. *
  14. * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. *
  22. *****************************************************************************/
  23. #ifndef TCLAP_ARGUMENT_H
  24. #define TCLAP_ARGUMENT_H
  25. #ifdef HAVE_CONFIG_H
  26. #include <config.h>
  27. #endif
  28. #include <string>
  29. #include <vector>
  30. #include <list>
  31. #include <iostream>
  32. #include <iomanip>
  33. #include <cstdio>
  34. #include <tclap/sstream.h>
  35. #include <tclap/ArgException.h>
  36. #include <tclap/Visitor.h>
  37. #include <tclap/CmdLineInterface.h>
  38. #include <tclap/ArgTraits.h>
  39. #include <tclap/StandardTraits.h>
  40. namespace TCLAP {
  41. /**
  42. * A virtual base class that defines the essential data for all arguments.
  43. * This class, or one of its existing children, must be subclassed to do
  44. * anything.
  45. */
  46. class Arg
  47. {
  48. private:
  49. /**
  50. * Prevent accidental copying.
  51. */
  52. Arg(const Arg& rhs);
  53. /**
  54. * Prevent accidental copying.
  55. */
  56. Arg& operator=(const Arg& rhs);
  57. /**
  58. * Indicates whether the rest of the arguments should be ignored.
  59. */
  60. static bool& ignoreRestRef() { static bool ign = false; return ign; }
  61. /**
  62. * The delimiter that separates an argument flag/name from the
  63. * value.
  64. */
  65. static char& delimiterRef() { static char delim = ' '; return delim; }
  66. protected:
  67. /**
  68. * The single char flag used to identify the argument.
  69. * This value (preceded by a dash {-}), can be used to identify
  70. * an argument on the command line. The _flag can be blank,
  71. * in fact this is how unlabeled args work. Unlabeled args must
  72. * override appropriate functions to get correct handling. Note
  73. * that the _flag does NOT include the dash as part of the flag.
  74. */
  75. std::string _flag;
  76. /**
  77. * A single word namd identifying the argument.
  78. * This value (preceded by two dashed {--}) can also be used
  79. * to identify an argument on the command line. Note that the
  80. * _name does NOT include the two dashes as part of the _name. The
  81. * _name cannot be blank.
  82. */
  83. std::string _name;
  84. /**
  85. * Description of the argument.
  86. */
  87. std::string _description;
  88. /**
  89. * Indicating whether the argument is required.
  90. */
  91. bool _required;
  92. /**
  93. * Label to be used in usage description. Normally set to
  94. * "required", but can be changed when necessary.
  95. */
  96. std::string _requireLabel;
  97. /**
  98. * Indicates whether a value is required for the argument.
  99. * Note that the value may be required but the argument/value
  100. * combination may not be, as specified by _required.
  101. */
  102. bool _valueRequired;
  103. /**
  104. * Indicates whether the argument has been set.
  105. * Indicates that a value on the command line has matched the
  106. * name/flag of this argument and the values have been set accordingly.
  107. */
  108. bool _alreadySet;
  109. /**
  110. * A pointer to a visitor object.
  111. * The visitor allows special handling to occur as soon as the
  112. * argument is matched. This defaults to NULL and should not
  113. * be used unless absolutely necessary.
  114. */
  115. Visitor* _visitor;
  116. /**
  117. * Whether this argument can be ignored, if desired.
  118. */
  119. bool _ignoreable;
  120. /**
  121. * Indicates that the arg was set as part of an XOR and not on the
  122. * command line.
  123. */
  124. bool _xorSet;
  125. bool _acceptsMultipleValues;
  126. /**
  127. * Performs the special handling described by the Visitor.
  128. */
  129. void _checkWithVisitor() const;
  130. /**
  131. * Primary constructor. YOU (yes you) should NEVER construct an Arg
  132. * directly, this is a base class that is extended by various children
  133. * that are meant to be used. Use SwitchArg, ValueArg, MultiArg,
  134. * UnlabeledValueArg, or UnlabeledMultiArg instead.
  135. *
  136. * \param flag - The flag identifying the argument.
  137. * \param name - The name identifying the argument.
  138. * \param desc - The description of the argument, used in the usage.
  139. * \param req - Whether the argument is required.
  140. * \param valreq - Whether the a value is required for the argument.
  141. * \param v - The visitor checked by the argument. Defaults to NULL.
  142. */
  143. Arg( const std::string& flag,
  144. const std::string& name,
  145. const std::string& desc,
  146. bool req,
  147. bool valreq,
  148. Visitor* v = NULL );
  149. public:
  150. /**
  151. * Destructor.
  152. */
  153. virtual ~Arg();
  154. /**
  155. * Adds this to the specified list of Args.
  156. * \param argList - The list to add this to.
  157. */
  158. virtual void addToList( std::list<Arg*>& argList ) const;
  159. /**
  160. * Begin ignoring arguments since the "--" argument was specified.
  161. */
  162. static void beginIgnoring() { ignoreRestRef() = true; }
  163. /**
  164. * Whether to ignore the rest.
  165. */
  166. static bool ignoreRest() { return ignoreRestRef(); }
  167. /**
  168. * The delimiter that separates an argument flag/name from the
  169. * value.
  170. */
  171. static char delimiter() { return delimiterRef(); }
  172. /**
  173. * The char used as a place holder when SwitchArgs are combined.
  174. * Currently set to the bell char (ASCII 7).
  175. */
  176. static char blankChar() { return (char)7; }
  177. /**
  178. * The char that indicates the beginning of a flag. Defaults to '-', but
  179. * clients can define TCLAP_FLAGSTARTCHAR to override.
  180. */
  181. #ifndef TCLAP_FLAGSTARTCHAR
  182. #define TCLAP_FLAGSTARTCHAR '-'
  183. #endif
  184. static char flagStartChar() { return TCLAP_FLAGSTARTCHAR; }
  185. /**
  186. * The sting that indicates the beginning of a flag. Defaults to "-", but
  187. * clients can define TCLAP_FLAGSTARTSTRING to override. Should be the same
  188. * as TCLAP_FLAGSTARTCHAR.
  189. */
  190. #ifndef TCLAP_FLAGSTARTSTRING
  191. #define TCLAP_FLAGSTARTSTRING "-"
  192. #endif
  193. static const std::string flagStartString() { return TCLAP_FLAGSTARTSTRING; }
  194. /**
  195. * The sting that indicates the beginning of a name. Defaults to "--", but
  196. * clients can define TCLAP_NAMESTARTSTRING to override.
  197. */
  198. #ifndef TCLAP_NAMESTARTSTRING
  199. #define TCLAP_NAMESTARTSTRING "--"
  200. #endif
  201. static const std::string nameStartString() { return TCLAP_NAMESTARTSTRING; }
  202. /**
  203. * The name used to identify the ignore rest argument.
  204. */
  205. static const std::string ignoreNameString() { return "ignore_rest"; }
  206. /**
  207. * Sets the delimiter for all arguments.
  208. * \param c - The character that delimits flags/names from values.
  209. */
  210. static void setDelimiter( char c ) { delimiterRef() = c; }
  211. /**
  212. * Pure virtual method meant to handle the parsing and value assignment
  213. * of the string on the command line.
  214. * \param i - Pointer the the current argument in the list.
  215. * \param args - Mutable list of strings. What is
  216. * passed in from main.
  217. */
  218. virtual bool processArg(int *i, std::vector<std::string>& args) = 0;
  219. /**
  220. * Operator ==.
  221. * Equality operator. Must be virtual to handle unlabeled args.
  222. * \param a - The Arg to be compared to this.
  223. */
  224. virtual bool operator==(const Arg& a) const;
  225. /**
  226. * Returns the argument flag.
  227. */
  228. const std::string& getFlag() const;
  229. /**
  230. * Returns the argument name.
  231. */
  232. const std::string& getName() const;
  233. /**
  234. * Returns the argument description.
  235. */
  236. std::string getDescription() const;
  237. /**
  238. * Indicates whether the argument is required.
  239. */
  240. virtual bool isRequired() const;
  241. /**
  242. * Sets _required to true. This is used by the XorHandler.
  243. * You really have no reason to ever use it.
  244. */
  245. void forceRequired();
  246. /**
  247. * Sets the _alreadySet value to true. This is used by the XorHandler.
  248. * You really have no reason to ever use it.
  249. */
  250. void xorSet();
  251. /**
  252. * Indicates whether a value must be specified for argument.
  253. */
  254. bool isValueRequired() const;
  255. /**
  256. * Indicates whether the argument has already been set. Only true
  257. * if the arg has been matched on the command line.
  258. */
  259. bool isSet() const;
  260. /**
  261. * Indicates whether the argument can be ignored, if desired.
  262. */
  263. bool isIgnoreable() const;
  264. /**
  265. * A method that tests whether a string matches this argument.
  266. * This is generally called by the processArg() method. This
  267. * method could be re-implemented by a child to change how
  268. * arguments are specified on the command line.
  269. * \param s - The string to be compared to the flag/name to determine
  270. * whether the arg matches.
  271. */
  272. virtual bool argMatches( const std::string& s ) const;
  273. /**
  274. * Returns a simple string representation of the argument.
  275. * Primarily for debugging.
  276. */
  277. virtual std::string toString() const;
  278. /**
  279. * Returns a short ID for the usage.
  280. * \param valueId - The value used in the id.
  281. */
  282. virtual std::string shortID( const std::string& valueId = "val" ) const;
  283. /**
  284. * Returns a long ID for the usage.
  285. * \param valueId - The value used in the id.
  286. */
  287. virtual std::string longID( const std::string& valueId = "val" ) const;
  288. /**
  289. * Trims a value off of the flag.
  290. * \param flag - The string from which the flag and value will be
  291. * trimmed. Contains the flag once the value has been trimmed.
  292. * \param value - Where the value trimmed from the string will
  293. * be stored.
  294. */
  295. virtual void trimFlag( std::string& flag, std::string& value ) const;
  296. /**
  297. * Checks whether a given string has blank chars, indicating that
  298. * it is a combined SwitchArg. If so, return true, otherwise return
  299. * false.
  300. * \param s - string to be checked.
  301. */
  302. bool _hasBlanks( const std::string& s ) const;
  303. /**
  304. * Sets the requireLabel. Used by XorHandler. You shouldn't ever
  305. * use this.
  306. * \param s - Set the requireLabel to this value.
  307. */
  308. void setRequireLabel( const std::string& s );
  309. /**
  310. * Used for MultiArgs and XorHandler to determine whether args
  311. * can still be set.
  312. */
  313. virtual bool allowMore();
  314. /**
  315. * Use by output classes to determine whether an Arg accepts
  316. * multiple values.
  317. */
  318. virtual bool acceptsMultipleValues();
  319. /**
  320. * Clears the Arg object and allows it to be reused by new
  321. * command lines.
  322. */
  323. virtual void reset();
  324. };
  325. /**
  326. * Typedef of an Arg list iterator.
  327. */
  328. typedef std::list<Arg*>::const_iterator ArgListIterator;
  329. /**
  330. * Typedef of an Arg vector iterator.
  331. */
  332. typedef std::vector<Arg*>::const_iterator ArgVectorIterator;
  333. /**
  334. * Typedef of a Visitor list iterator.
  335. */
  336. typedef std::list<Visitor*>::const_iterator VisitorListIterator;
  337. /*
  338. * Extract a value of type T from it's string representation contained
  339. * in strVal. The ValueLike parameter used to select the correct
  340. * specialization of ExtractValue depending on the value traits of T.
  341. * ValueLike traits use operator>> to assign the value from strVal.
  342. */
  343. template<typename T> void
  344. ExtractValue(T &destVal, const std::string& strVal, ValueLike vl)
  345. {
  346. static_cast<void>(vl); // Avoid warning about unused vl
  347. istringstream is(strVal.c_str());
  348. int valuesRead = 0;
  349. while ( is.good() ) {
  350. if ( is.peek() != EOF )
  351. #ifdef TCLAP_SETBASE_ZERO
  352. is >> std::setbase(0) >> destVal;
  353. #else
  354. is >> destVal;
  355. #endif
  356. else
  357. break;
  358. valuesRead++;
  359. }
  360. if ( is.fail() )
  361. throw( ArgParseException("Couldn't read argument value "
  362. "from string '" + strVal + "'"));
  363. if ( valuesRead > 1 )
  364. throw( ArgParseException("More than one valid value parsed from "
  365. "string '" + strVal + "'"));
  366. }
  367. /*
  368. * Extract a value of type T from it's string representation contained
  369. * in strVal. The ValueLike parameter used to select the correct
  370. * specialization of ExtractValue depending on the value traits of T.
  371. * StringLike uses assignment (operator=) to assign from strVal.
  372. */
  373. template<typename T> void
  374. ExtractValue(T &destVal, const std::string& strVal, StringLike sl)
  375. {
  376. static_cast<void>(sl); // Avoid warning about unused sl
  377. SetString(destVal, strVal);
  378. }
  379. //////////////////////////////////////////////////////////////////////
  380. //BEGIN Arg.cpp
  381. //////////////////////////////////////////////////////////////////////
  382. inline Arg::Arg(const std::string& flag,
  383. const std::string& name,
  384. const std::string& desc,
  385. bool req,
  386. bool valreq,
  387. Visitor* v) :
  388. _flag(flag),
  389. _name(name),
  390. _description(desc),
  391. _required(req),
  392. _requireLabel("required"),
  393. _valueRequired(valreq),
  394. _alreadySet(false),
  395. _visitor( v ),
  396. _ignoreable(true),
  397. _xorSet(false),
  398. _acceptsMultipleValues(false)
  399. {
  400. if ( _flag.length() > 1 )
  401. throw(SpecificationException(
  402. "Argument flag can only be one character long", toString() ) );
  403. if ( _name != ignoreNameString() &&
  404. ( _flag == Arg::flagStartString() ||
  405. _flag == Arg::nameStartString() ||
  406. _flag == " " ) )
  407. throw(SpecificationException("Argument flag cannot be either '" +
  408. Arg::flagStartString() + "' or '" +
  409. Arg::nameStartString() + "' or a space.",
  410. toString() ) );
  411. if ( ( _name.substr( 0, Arg::flagStartString().length() ) == Arg::flagStartString() ) ||
  412. ( _name.substr( 0, Arg::nameStartString().length() ) == Arg::nameStartString() ) ||
  413. ( _name.find( " ", 0 ) != std::string::npos ) )
  414. throw(SpecificationException("Argument name begin with either '" +
  415. Arg::flagStartString() + "' or '" +
  416. Arg::nameStartString() + "' or space.",
  417. toString() ) );
  418. }
  419. inline Arg::~Arg() { }
  420. inline std::string Arg::shortID( const std::string& valueId ) const
  421. {
  422. std::string id = "";
  423. if ( _flag != "" )
  424. id = Arg::flagStartString() + _flag;
  425. else
  426. id = Arg::nameStartString() + _name;
  427. if ( _valueRequired )
  428. id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">";
  429. if ( !_required )
  430. id = "[" + id + "]";
  431. return id;
  432. }
  433. inline std::string Arg::longID( const std::string& valueId ) const
  434. {
  435. std::string id = "";
  436. if ( _flag != "" )
  437. {
  438. id += Arg::flagStartString() + _flag;
  439. if ( _valueRequired )
  440. id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">";
  441. id += ", ";
  442. }
  443. id += Arg::nameStartString() + _name;
  444. if ( _valueRequired )
  445. id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">";
  446. return id;
  447. }
  448. inline bool Arg::operator==(const Arg& a) const
  449. {
  450. if ( ( _flag != "" && _flag == a._flag ) || _name == a._name)
  451. return true;
  452. else
  453. return false;
  454. }
  455. inline std::string Arg::getDescription() const
  456. {
  457. std::string desc = "";
  458. if ( _required )
  459. desc = "(" + _requireLabel + ") ";
  460. // if ( _valueRequired )
  461. // desc += "(value required) ";
  462. desc += _description;
  463. return desc;
  464. }
  465. inline const std::string& Arg::getFlag() const { return _flag; }
  466. inline const std::string& Arg::getName() const { return _name; }
  467. inline bool Arg::isRequired() const { return _required; }
  468. inline bool Arg::isValueRequired() const { return _valueRequired; }
  469. inline bool Arg::isSet() const
  470. {
  471. if ( _alreadySet && !_xorSet )
  472. return true;
  473. else
  474. return false;
  475. }
  476. inline bool Arg::isIgnoreable() const { return _ignoreable; }
  477. inline void Arg::setRequireLabel( const std::string& s)
  478. {
  479. _requireLabel = s;
  480. }
  481. inline bool Arg::argMatches( const std::string& argFlag ) const
  482. {
  483. if ( ( argFlag == Arg::flagStartString() + _flag && _flag != "" ) ||
  484. argFlag == Arg::nameStartString() + _name )
  485. return true;
  486. else
  487. return false;
  488. }
  489. inline std::string Arg::toString() const
  490. {
  491. std::string s = "";
  492. if ( _flag != "" )
  493. s += Arg::flagStartString() + _flag + " ";
  494. s += "(" + Arg::nameStartString() + _name + ")";
  495. return s;
  496. }
  497. inline void Arg::_checkWithVisitor() const
  498. {
  499. if ( _visitor != NULL )
  500. _visitor->visit();
  501. }
  502. /**
  503. * Implementation of trimFlag.
  504. */
  505. inline void Arg::trimFlag(std::string& flag, std::string& value) const
  506. {
  507. int stop = 0;
  508. for ( int i = 0; static_cast<unsigned int>(i) < flag.length(); i++ )
  509. if ( flag[i] == Arg::delimiter() )
  510. {
  511. stop = i;
  512. break;
  513. }
  514. if ( stop > 1 )
  515. {
  516. value = flag.substr(stop+1);
  517. flag = flag.substr(0,stop);
  518. }
  519. }
  520. /**
  521. * Implementation of _hasBlanks.
  522. */
  523. inline bool Arg::_hasBlanks( const std::string& s ) const
  524. {
  525. for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ )
  526. if ( s[i] == Arg::blankChar() )
  527. return true;
  528. return false;
  529. }
  530. inline void Arg::forceRequired()
  531. {
  532. _required = true;
  533. }
  534. inline void Arg::xorSet()
  535. {
  536. _alreadySet = true;
  537. _xorSet = true;
  538. }
  539. /**
  540. * Overridden by Args that need to added to the end of the list.
  541. */
  542. inline void Arg::addToList( std::list<Arg*>& argList ) const
  543. {
  544. argList.push_front( const_cast<Arg*>(this) );
  545. }
  546. inline bool Arg::allowMore()
  547. {
  548. return false;
  549. }
  550. inline bool Arg::acceptsMultipleValues()
  551. {
  552. return _acceptsMultipleValues;
  553. }
  554. inline void Arg::reset()
  555. {
  556. _xorSet = false;
  557. _alreadySet = false;
  558. }
  559. //////////////////////////////////////////////////////////////////////
  560. //END Arg.cpp
  561. //////////////////////////////////////////////////////////////////////
  562. } //namespace TCLAP
  563. #endif