Remove needless #include
[oota-llvm.git] / support / lib / Support / CommandLine.cpp
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 //
3 // This class implements a command line argument processor that is useful when
4 // creating a tool.  It provides a simple, minimalistic interface that is easily
5 // extensible and supports nonlocal (library) command line options.
6 //
7 // Note that rather than trying to figure out what this code does, you could try
8 // reading the library documentation located in docs/CommandLine.html
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "Support/CommandLine.h"
13 #include <algorithm>
14 #include <map>
15 #include <set>
16 #include <iostream>
17
18 using namespace cl;
19 using std::map;
20 using std::pair;
21 using std::vector;
22 using std::string;
23 using std::cerr;
24
25 //===----------------------------------------------------------------------===//
26 // Basic, shared command line option processing machinery...
27 //
28
29 // Return the global command line option vector.  Making it a function scoped
30 // static ensures that it will be initialized correctly before its first use.
31 //
32 static map<string, Option*> &getOpts() {
33   static map<string,Option*> CommandLineOptions;
34   return CommandLineOptions;
35 }
36
37 static vector<Option*> &getPositionalOpts() {
38   static vector<Option*> Positional;
39   return Positional;
40 }
41
42 static void AddArgument(const string &ArgName, Option *Opt) {
43   if (getOpts().find(ArgName) != getOpts().end()) {
44     cerr << "CommandLine Error: Argument '" << ArgName
45          << "' defined more than once!\n";
46   } else {
47     // Add argument to the argument map!
48     getOpts().insert(std::make_pair(ArgName, Opt));
49   }
50 }
51
52 static const char *ProgramName = 0;
53 static const char *ProgramOverview = 0;
54
55 static inline bool ProvideOption(Option *Handler, const char *ArgName,
56                                  const char *Value, int argc, char **argv,
57                                  int &i) {
58   // Enforce value requirements
59   switch (Handler->getValueExpectedFlag()) {
60   case ValueRequired:
61     if (Value == 0 || *Value == 0) {  // No value specified?
62       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
63         Value = argv[++i];
64       } else {
65         return Handler->error(" requires a value!");
66       }
67     }
68     break;
69   case ValueDisallowed:
70     if (*Value != 0)
71       return Handler->error(" does not allow a value! '" + 
72                             string(Value) + "' specified.");
73     break;
74   case ValueOptional: break;
75   default: cerr << "Bad ValueMask flag! CommandLine usage error:" 
76                 << Handler->getValueExpectedFlag() << "\n"; abort();
77   }
78
79   // Run the handler now!
80   return Handler->addOccurance(ArgName, Value);
81 }
82
83 static bool ProvidePositionalOption(Option *Handler, string &Arg) {
84   int Dummy;
85   return ProvideOption(Handler, "", Arg.c_str(), 0, 0, Dummy);
86 }
87
88
89 // Option predicates...
90 static inline bool isGrouping(const Option *O) {
91   return O->getFormattingFlag() == cl::Grouping;
92 }
93 static inline bool isPrefixedOrGrouping(const Option *O) {
94   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
95 }
96
97 // getOptionPred - Check to see if there are any options that satisfy the
98 // specified predicate with names that are the prefixes in Name.  This is
99 // checked by progressively stripping characters off of the name, checking to
100 // see if there options that satisfy the predicate.  If we find one, return it,
101 // otherwise return null.
102 //
103 static Option *getOptionPred(std::string Name, unsigned &Length,
104                              bool (*Pred)(const Option*)) {
105   
106   map<string, Option*>::iterator I = getOpts().find(Name);
107   if (I != getOpts().end() && Pred(I->second)) {
108     Length = Name.length();
109     return I->second;
110   }
111
112   if (Name.size() == 1) return 0;
113   do {
114     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
115     I = getOpts().find(Name);
116
117     // Loop while we haven't found an option and Name still has at least two
118     // characters in it (so that the next iteration will not be the empty
119     // string...
120   } while ((I == getOpts().end() || !Pred(I->second)) && Name.size() > 1);
121
122   if (I != getOpts().end() && Pred(I->second)) {
123     Length = Name.length();
124     return I->second;      // Found one!
125   }
126   return 0;                // No option found!
127 }
128
129 static bool RequiresValue(const Option *O) {
130   return O->getNumOccurancesFlag() == cl::Required ||
131          O->getNumOccurancesFlag() == cl::OneOrMore;
132 }
133
134 static bool EatsUnboundedNumberOfValues(const Option *O) {
135   return O->getNumOccurancesFlag() == cl::ZeroOrMore ||
136          O->getNumOccurancesFlag() == cl::OneOrMore;
137 }
138
139 void cl::ParseCommandLineOptions(int &argc, char **argv,
140                                  const char *Overview) {
141   assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
142          "No options specified, or ParseCommandLineOptions called more"
143          " than once!");
144   ProgramName = argv[0];  // Save this away safe and snug
145   ProgramOverview = Overview;
146   bool ErrorParsing = false;
147
148   map<string, Option*> &Opts = getOpts();
149   vector<Option*> &PositionalOpts = getPositionalOpts();
150
151   // Check out the positional arguments to collect information about them.
152   unsigned NumPositionalRequired = 0;
153   Option *ConsumeAfterOpt = 0;
154   if (!PositionalOpts.empty()) {
155     if (PositionalOpts[0]->getNumOccurancesFlag() == cl::ConsumeAfter) {
156       assert(PositionalOpts.size() > 1 &&
157              "Cannot specify cl::ConsumeAfter without a positional argument!");
158       ConsumeAfterOpt = PositionalOpts[0];
159     }
160
161     // Calculate how many positional values are _required_.
162     bool UnboundedFound = false;
163     for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
164          i != e; ++i) {
165       Option *Opt = PositionalOpts[i];
166       if (RequiresValue(Opt))
167         ++NumPositionalRequired;
168       else if (ConsumeAfterOpt) {
169         // ConsumeAfter cannot be combined with "optional" positional options
170         // unless there is only one positional argument...
171         if (PositionalOpts.size() > 2)
172           ErrorParsing |=
173             Opt->error(" error - this positional option will never be matched, "
174                        "because it does not Require a value, and a "
175                        "cl::ConsumeAfter option is active!");
176       } else if (UnboundedFound) {  // This option does not "require" a value...
177         // Make sure this option is not specified after an option that eats all
178         // extra arguments, or this one will never get any!
179         //
180         ErrorParsing |= Opt->error(" error - option can never match, because "
181                                    "another positional argument will match an "
182                                    "unbounded number of values, and this option"
183                                    " does not require a value!");
184       }
185       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
186     }
187   }
188
189   // PositionalVals - A vector of "positional" arguments we accumulate into to
190   // processes at the end...
191   //
192   vector<string> PositionalVals;
193
194   // Loop over all of the arguments... processing them.
195   bool DashDashFound = false;  // Have we read '--'?
196   for (int i = 1; i < argc; ++i) {
197     Option *Handler = 0;
198     const char *Value = "";
199     const char *ArgName = "";
200
201     // Check to see if this is a positional argument.  This argument is
202     // considered to be positional if it doesn't start with '-', if it is "-"
203     // itself, or if we have see "--" already.
204     //
205     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
206       // Positional argument!
207       if (!PositionalOpts.empty()) {
208         PositionalVals.push_back(argv[i]);
209
210         // All of the positional arguments have been fulfulled, give the rest to
211         // the consume after option... if it's specified...
212         //
213         if (PositionalVals.size() == NumPositionalRequired && 
214             ConsumeAfterOpt != 0) {
215           for (++i; i < argc; ++i)
216             PositionalVals.push_back(argv[i]);
217           break;   // Handle outside of the argument processing loop...
218         }
219
220         // Delay processing positional arguments until the end...
221         continue;
222       }
223     } else {               // We start with a '-', must be an argument...
224       ArgName = argv[i]+1;
225       while (*ArgName == '-') ++ArgName;  // Eat leading dashes
226
227       if (*ArgName == 0 && !DashDashFound) {   // Is this the mythical "--"?
228         DashDashFound = true;  // Yup, take note of that fact...
229         continue;              // Don't try to process it as an argument iself.
230       }
231
232       const char *ArgNameEnd = ArgName;
233       while (*ArgNameEnd && *ArgNameEnd != '=')
234         ++ArgNameEnd; // Scan till end of argument name...
235
236       Value = ArgNameEnd;
237       if (*Value)           // If we have an equals sign...
238         ++Value;            // Advance to value...
239
240       if (*ArgName != 0) {
241         string RealName(ArgName, ArgNameEnd);
242         // Extract arg name part
243         map<string, Option*>::iterator I = Opts.find(RealName);
244
245         if (I == Opts.end() && !*Value && RealName.size() > 1) {
246           // Check to see if this "option" is really a prefixed or grouped
247           // argument...
248           //
249           unsigned Length = 0;
250           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
251
252           // If the option is a prefixed option, then the value is simply the
253           // rest of the name...  so fall through to later processing, by
254           // setting up the argument name flags and value fields.
255           //
256           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
257             ArgNameEnd = ArgName+Length;
258             Value = ArgNameEnd;
259             I = Opts.find(string(ArgName, ArgNameEnd));
260             assert(I->second == PGOpt);
261           } else if (PGOpt) {
262             // This must be a grouped option... handle all of them now...
263             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
264
265             do {
266               // Move current arg name out of RealName into RealArgName...
267               string RealArgName(RealName.begin(), RealName.begin()+Length);
268               RealName.erase(RealName.begin(), RealName.begin()+Length);
269
270               // Because ValueRequired is an invalid flag for grouped arguments,
271               // we don't need to pass argc/argv in...
272               //
273               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
274                      "Option can not be cl::Grouping AND cl::ValueRequired!");
275               int Dummy;
276               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
277                                             0, 0, Dummy);
278
279               // Get the next grouping option...
280               if (!RealName.empty())
281                 PGOpt = getOptionPred(RealName, Length, isGrouping);
282             } while (!RealName.empty() && PGOpt);
283
284             if (RealName.empty())    // Processed all of the options, move on
285               continue;              // to the next argv[] value...
286
287             // If RealName is not empty, that means we did not match one of the
288             // options!  This is an error.
289             //
290             I = Opts.end();
291           }
292         }
293
294         Handler = I != Opts.end() ? I->second : 0;
295       }
296     }
297
298     if (Handler == 0) {
299       cerr << "Unknown command line argument '" << argv[i] << "'.  Try: "
300            << argv[0] << " --help'\n";
301       ErrorParsing = true;
302       continue;
303     }
304
305     ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
306   }
307
308   // Check and handle positional arguments now...
309   if (NumPositionalRequired > PositionalVals.size()) {
310     cerr << "Not enough positional command line arguments specified!\n";
311     cerr << "Must specify at least " << NumPositionalRequired
312          << " positional arguments: See: " << argv[0] << " --help\n";
313     ErrorParsing = true;
314
315
316   } else if (ConsumeAfterOpt == 0) {
317     // Positional args have already been handled if ConsumeAfter is specified...
318     unsigned ValNo = 0, NumVals = PositionalVals.size();
319     for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
320       if (RequiresValue(PositionalOpts[i])) {
321         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
322         --NumPositionalRequired;  // We fulfilled our duty...
323       }
324
325       // If we _can_ give this option more arguments, do so now, as long as we
326       // do not give it values that others need.  'Done' controls whether the
327       // option even _WANTS_ any more.
328       //
329       bool Done = PositionalOpts[i]->getNumOccurancesFlag() == cl::Required;
330       while (NumVals-ValNo > NumPositionalRequired && !Done) {
331         switch (PositionalOpts[i]->getNumOccurancesFlag()) {
332         case cl::Optional:
333           Done = true;          // Optional arguments want _at most_ one value
334           // FALL THROUGH
335         case cl::ZeroOrMore:    // Zero or more will take all they can get...
336         case cl::OneOrMore:     // One or more will take all they can get...
337           ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo++]);
338           break;
339         default:
340           assert(0 && "Internal error, unexpected NumOccurances flag in "
341                  "positional argument processing!");
342         }
343       }
344     }
345   } else {
346     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
347     unsigned ValNo = 0;
348     for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
349       if (RequiresValue(PositionalOpts[j]))
350         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
351                                                 PositionalVals[ValNo++]);
352
353     // Handle the case where there is just one positional option, and it's
354     // optional.  In this case, we want to give JUST THE FIRST option to the
355     // positional option and keep the rest for the consume after.  The above
356     // loop would have assigned no values to positional options in this case.
357     //
358     if (PositionalOpts.size() == 2 && ValNo == 0)
359       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
360                                               PositionalVals[ValNo++]);
361     
362     // Handle over all of the rest of the arguments to the
363     // cl::ConsumeAfter command line option...
364     for (; ValNo != PositionalVals.size(); ++ValNo)
365       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
366                                               PositionalVals[ValNo]);
367   }
368
369   // Loop over args and make sure all required args are specified!
370   for (map<string, Option*>::iterator I = Opts.begin(), 
371          E = Opts.end(); I != E; ++I) {
372     switch (I->second->getNumOccurancesFlag()) {
373     case Required:
374     case OneOrMore:
375       if (I->second->getNumOccurances() == 0) {
376         I->second->error(" must be specified at least once!");
377         ErrorParsing = true;
378       }
379       // Fall through
380     default:
381       break;
382     }
383   }
384
385   // Free all of the memory allocated to the map.  Command line options may only
386   // be processed once!
387   Opts.clear();
388   PositionalOpts.clear();
389
390   // If we had an error processing our arguments, don't let the program execute
391   if (ErrorParsing) exit(1);
392 }
393
394 //===----------------------------------------------------------------------===//
395 // Option Base class implementation
396 //
397
398 bool Option::error(string Message, const char *ArgName) {
399   if (ArgName == 0) ArgName = ArgStr;
400   if (ArgName[0] == 0)
401     cerr << HelpStr;  // Be nice for positional arguments
402   else
403     cerr << "-" << ArgName;
404   cerr << " option" << Message << "\n";
405   return true;
406 }
407
408 bool Option::addOccurance(const char *ArgName, const string &Value) {
409   NumOccurances++;   // Increment the number of times we have been seen
410
411   switch (getNumOccurancesFlag()) {
412   case Optional:
413     if (NumOccurances > 1)
414       return error(": may only occur zero or one times!", ArgName);
415     break;
416   case Required:
417     if (NumOccurances > 1)
418       return error(": must occur exactly one time!", ArgName);
419     // Fall through
420   case OneOrMore:
421   case ZeroOrMore:
422   case ConsumeAfter: break;
423   default: return error(": bad num occurances flag value!");
424   }
425
426   return handleOccurance(ArgName, Value);
427 }
428
429 // addArgument - Tell the system that this Option subclass will handle all
430 // occurances of -ArgStr on the command line.
431 //
432 void Option::addArgument(const char *ArgStr) {
433   if (ArgStr[0])
434     AddArgument(ArgStr, this);
435   else if (getFormattingFlag() == Positional)
436     getPositionalOpts().push_back(this);
437   else if (getNumOccurancesFlag() == ConsumeAfter) {
438     assert((getPositionalOpts().empty() ||
439             getPositionalOpts().front()->getNumOccurancesFlag() != ConsumeAfter)
440            && "Cannot specify more than one option with cl::ConsumeAfter "
441            "specified!");
442     getPositionalOpts().insert(getPositionalOpts().begin(), this);
443   }
444 }
445
446 void Option::removeArgument(const char *ArgStr) {
447   if (ArgStr[0]) {
448     assert(getOpts()[ArgStr] == this && "Arg not in map!");
449     getOpts().erase(ArgStr);
450   } else if (getFormattingFlag() == Positional) {
451     vector<Option*>::iterator I =
452       std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
453     assert(I != getPositionalOpts().end() && "Arg not registered!");
454     getPositionalOpts().erase(I);
455   } else if (getNumOccurancesFlag() == ConsumeAfter) {
456     assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
457            "Arg not registered correctly!");
458     getPositionalOpts().erase(getPositionalOpts().begin());
459   }
460 }
461
462
463 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
464 // has been specified yet.
465 //
466 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
467   if (O.ValueStr[0] == 0) return DefaultMsg;
468   return O.ValueStr;
469 }
470
471 //===----------------------------------------------------------------------===//
472 // cl::alias class implementation
473 //
474
475 // Return the width of the option tag for printing...
476 unsigned alias::getOptionWidth() const {
477   return std::strlen(ArgStr)+6;
478 }
479
480 // Print out the option for the alias...
481 void alias::printOptionInfo(unsigned GlobalWidth) const {
482   unsigned L = std::strlen(ArgStr);
483   cerr << "  -" << ArgStr << string(GlobalWidth-L-6, ' ') << " - "
484        << HelpStr << "\n";
485 }
486
487
488
489 //===----------------------------------------------------------------------===//
490 // Parser Implementation code...
491 //
492
493 // parser<bool> implementation
494 //
495 bool parser<bool>::parseImpl(Option &O, const string &Arg, bool &Value) {
496   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 
497       Arg == "1") {
498     Value = true;
499   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
500     Value = false;
501   } else {
502     return O.error(": '" + Arg +
503                    "' is invalid value for boolean argument! Try 0 or 1");
504   }
505   return false;
506 }
507
508 // Return the width of the option tag for printing...
509 unsigned parser<bool>::getOptionWidth(const Option &O) const {
510   return std::strlen(O.ArgStr)+6;
511 }
512
513 // printOptionInfo - Print out information about this option.  The 
514 // to-be-maintained width is specified.
515 //
516 void parser<bool>::printOptionInfo(const Option &O, unsigned GlobalWidth) const{
517   unsigned L = std::strlen(O.ArgStr);
518   cerr << "  -" << O.ArgStr << string(GlobalWidth-L-6, ' ') << " - "
519        << O.HelpStr << "\n";
520 }
521
522
523
524 // parser<int> implementation
525 //
526 bool parser<int>::parseImpl(Option &O, const string &Arg, int &Value) {
527   const char *ArgStart = Arg.c_str();
528   char *End;
529   Value = (int)strtol(ArgStart, &End, 0);
530   if (*End != 0) 
531     return O.error(": '" + Arg + "' value invalid for integer argument!");
532   return false;
533 }
534
535 // Return the width of the option tag for printing...
536 unsigned parser<int>::getOptionWidth(const Option &O) const {
537   return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "int"))+9;
538 }
539
540 // printOptionInfo - Print out information about this option.  The 
541 // to-be-maintained width is specified.
542 //
543 void parser<int>::printOptionInfo(const Option &O, unsigned GlobalWidth) const{
544   cerr << "  -" << O.ArgStr << "=<" << getValueStr(O, "int") << ">"
545        << string(GlobalWidth-getOptionWidth(O), ' ') << " - "
546        << O.HelpStr << "\n";
547 }
548
549
550 // parser<double> implementation
551 //
552 bool parser<double>::parseImpl(Option &O, const string &Arg, double &Value) {
553   const char *ArgStart = Arg.c_str();
554   char *End;
555   Value = strtod(ArgStart, &End);
556   if (*End != 0) 
557     return O.error(": '" +Arg+ "' value invalid for floating point argument!");
558   return false;
559 }
560
561 // Return the width of the option tag for printing...
562 unsigned parser<double>::getOptionWidth(const Option &O) const {
563   return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "number"))+9;
564 }
565
566 // printOptionInfo - Print out information about this option.  The 
567 // to-be-maintained width is specified.
568 //
569 void parser<double>::printOptionInfo(const Option &O,
570                                      unsigned GlobalWidth) const{
571   cerr << "  -" << O.ArgStr << "=<" << getValueStr(O, "number") << ">"
572        << string(GlobalWidth-getOptionWidth(O), ' ')
573        << " - " << O.HelpStr << "\n";
574 }
575
576
577 // parser<string> implementation
578 //
579
580 // Return the width of the option tag for printing...
581 unsigned parser<string>::getOptionWidth(const Option &O) const {
582   return std::strlen(O.ArgStr)+std::strlen(getValueStr(O, "string"))+9;
583 }
584
585 // printOptionInfo - Print out information about this option.  The 
586 // to-be-maintained width is specified.
587 //
588 void parser<string>::printOptionInfo(const Option &O,
589                                      unsigned GlobalWidth) const{
590   cerr << "  -" << O.ArgStr << " <" << getValueStr(O, "string") << ">"
591        << string(GlobalWidth-getOptionWidth(O), ' ')
592        << " - " << O.HelpStr << "\n";
593 }
594
595 // generic_parser_base implementation
596 //
597
598 // findOption - Return the option number corresponding to the specified
599 // argument string.  If the option is not found, getNumOptions() is returned.
600 //
601 unsigned generic_parser_base::findOption(const char *Name) {
602   unsigned i = 0, e = getNumOptions();
603   string N(Name);
604
605   while (i != e)
606     if (getOption(i) == N)
607       return i;
608     else
609       ++i;
610   return e;
611 }
612
613
614 // Return the width of the option tag for printing...
615 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
616   if (O.hasArgStr()) {
617     unsigned Size = std::strlen(O.ArgStr)+6;
618     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
619       Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
620     return Size;
621   } else {
622     unsigned BaseSize = 0;
623     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
624       BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
625     return BaseSize;
626   }
627 }
628
629 // printOptionInfo - Print out information about this option.  The 
630 // to-be-maintained width is specified.
631 //
632 void generic_parser_base::printOptionInfo(const Option &O,
633                                           unsigned GlobalWidth) const {
634   if (O.hasArgStr()) {
635     unsigned L = std::strlen(O.ArgStr);
636     cerr << "  -" << O.ArgStr << string(GlobalWidth-L-6, ' ')
637          << " - " << O.HelpStr << "\n";
638
639     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
640       unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
641       cerr << "    =" << getOption(i) << string(NumSpaces, ' ') << " - "
642            << getDescription(i) << "\n";
643     }
644   } else {
645     if (O.HelpStr[0])
646       cerr << "  " << O.HelpStr << "\n"; 
647     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
648       unsigned L = std::strlen(getOption(i));
649       cerr << "    -" << getOption(i) << string(GlobalWidth-L-8, ' ') << " - "
650            << getDescription(i) << "\n";
651     }
652   }
653 }
654
655
656 //===----------------------------------------------------------------------===//
657 // --help and --help-hidden option implementation
658 //
659 namespace {
660
661 class HelpPrinter {
662   unsigned MaxArgLen;
663   const Option *EmptyArg;
664   const bool ShowHidden;
665
666   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
667   inline static bool isHidden(pair<string, Option *> &OptPair) {
668     return OptPair.second->getOptionHiddenFlag() >= Hidden;
669   }
670   inline static bool isReallyHidden(pair<string, Option *> &OptPair) {
671     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
672   }
673
674 public:
675   HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
676     EmptyArg = 0;
677   }
678
679   void operator=(bool Value) {
680     if (Value == false) return;
681
682     // Copy Options into a vector so we can sort them as we like...
683     vector<pair<string, Option*> > Options;
684     copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
685
686     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
687     Options.erase(std::remove_if(Options.begin(), Options.end(), 
688                          std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
689                   Options.end());
690
691     // Eliminate duplicate entries in table (from enum flags options, f.e.)
692     {  // Give OptionSet a scope
693       std::set<Option*> OptionSet;
694       for (unsigned i = 0; i != Options.size(); ++i)
695         if (OptionSet.count(Options[i].second) == 0)
696           OptionSet.insert(Options[i].second);   // Add new entry to set
697         else
698           Options.erase(Options.begin()+i--);    // Erase duplicate
699     }
700
701     if (ProgramOverview)
702       cerr << "OVERVIEW:" << ProgramOverview << "\n";
703
704     cerr << "USAGE: " << ProgramName << " [options]";
705
706     // Print out the positional options...
707     vector<Option*> &PosOpts = getPositionalOpts();
708     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
709     if (!PosOpts.empty() && PosOpts[0]->getNumOccurancesFlag() == ConsumeAfter)
710       CAOpt = PosOpts[0];
711
712     for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
713       cerr << " " << PosOpts[i]->HelpStr;
714       switch (PosOpts[i]->getNumOccurancesFlag()) {
715       case Optional:    cerr << "?"; break;
716       case ZeroOrMore:  cerr << "*"; break;
717       case Required:    break;
718       case OneOrMore:   cerr << "+"; break;
719       case ConsumeAfter:
720       default:
721         assert(0 && "Unknown NumOccurances Flag Value!");
722       }
723     }
724
725     // Print the consume after option info if it exists...
726     if (CAOpt) cerr << " " << CAOpt->HelpStr;
727
728     cerr << "\n\n";
729
730     // Compute the maximum argument length...
731     MaxArgLen = 0;
732     for (unsigned i = 0, e = Options.size(); i != e; ++i)
733       MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
734
735     cerr << "OPTIONS:\n";
736     for (unsigned i = 0, e = Options.size(); i != e; ++i)
737       Options[i].second->printOptionInfo(MaxArgLen);
738
739     // Halt the program if help information is printed
740     exit(1);
741   }
742 };
743
744
745
746 // Define the two HelpPrinter instances that are used to print out help, or
747 // help-hidden...
748 //
749 HelpPrinter NormalPrinter(false);
750 HelpPrinter HiddenPrinter(true);
751
752 cl::opt<HelpPrinter, true, parser<bool> > 
753 HOp("help", cl::desc("display available options (--help-hidden for more)"),
754     cl::location(NormalPrinter));
755
756 cl::opt<HelpPrinter, true, parser<bool> >
757 HHOp("help-hidden", cl::desc("display all available options"),
758      cl::location(HiddenPrinter), cl::Hidden);
759
760 } // End anonymous namespace