Make the ProgramName variable a std::string so we can eliminate the path
[oota-llvm.git] / lib / Support / CommandLine.cpp
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class implements a command line argument processor that is useful when
11 // creating a tool.  It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
13 //
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/System/Path.h"
22 #include <algorithm>
23 #include <functional>
24 #include <map>
25 #include <set>
26 #include <iostream>
27 #include <cstdlib>
28 #include <cerrno>
29 #include <cstring>
30 using namespace llvm;
31
32 using namespace cl;
33
34 // Globals for name and overview of program
35 static std::string ProgramName ( "<premain>" );
36 static const char *ProgramOverview = 0;
37
38 // This collects additional help to be printed.
39 static std::vector<const char*> &MoreHelp() {
40   static std::vector<const char*> moreHelp;
41   return moreHelp;
42 }
43
44 extrahelp::extrahelp(const char* Help)
45   : morehelp(Help) {
46   MoreHelp().push_back(Help);
47 }
48
49 //===----------------------------------------------------------------------===//
50 // Basic, shared command line option processing machinery...
51 //
52
53 // Return the global command line option vector.  Making it a function scoped
54 // static ensures that it will be initialized correctly before its first use.
55 //
56 static std::map<std::string, Option*> &getOpts() {
57   static std::map<std::string, Option*> CommandLineOptions;
58   return CommandLineOptions;
59 }
60
61 static Option *getOption(const std::string &Str) {
62   std::map<std::string,Option*>::iterator I = getOpts().find(Str);
63   return I != getOpts().end() ? I->second : 0;
64 }
65
66 static std::vector<Option*> &getPositionalOpts() {
67   static std::vector<Option*> Positional;
68   return Positional;
69 }
70
71 static void AddArgument(const char *ArgName, Option *Opt) {
72   if (getOption(ArgName)) {
73     std::cerr << ProgramName << ": CommandLine Error: Argument '"
74               << ArgName << "' defined more than once!\n";
75   } else {
76     // Add argument to the argument map!
77     getOpts()[ArgName] = Opt;
78   }
79 }
80
81 // RemoveArgument - It's possible that the argument is no longer in the map if
82 // options have already been processed and the map has been deleted!
83 //
84 static void RemoveArgument(const char *ArgName, Option *Opt) {
85   if(getOpts().empty()) return;
86
87 #ifndef NDEBUG
88   // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
89   // If we pass ArgName directly into getOption here.
90   std::string Tmp = ArgName;
91   assert(getOption(Tmp) == Opt && "Arg not in map!");
92 #endif
93   getOpts().erase(ArgName);
94 }
95
96 static inline bool ProvideOption(Option *Handler, const char *ArgName,
97                                  const char *Value, int argc, char **argv,
98                                  int &i) {
99   // Enforce value requirements
100   switch (Handler->getValueExpectedFlag()) {
101   case ValueRequired:
102     if (Value == 0) {       // No value specified?
103       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
104         Value = argv[++i];
105       } else {
106         return Handler->error(" requires a value!");
107       }
108     }
109     break;
110   case ValueDisallowed:
111     if (Value)
112       return Handler->error(" does not allow a value! '" +
113                             std::string(Value) + "' specified.");
114     break;
115   case ValueOptional:
116     break;
117   default:
118     std::cerr << ProgramName
119               << ": Bad ValueMask flag! CommandLine usage error:"
120               << Handler->getValueExpectedFlag() << "\n";
121     abort();
122     break;
123   }
124
125   // Run the handler now!
126   return Handler->addOccurrence(i, ArgName, Value ? Value : "");
127 }
128
129 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
130                                     int i) {
131   int Dummy = i;
132   return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
133 }
134
135
136 // Option predicates...
137 static inline bool isGrouping(const Option *O) {
138   return O->getFormattingFlag() == cl::Grouping;
139 }
140 static inline bool isPrefixedOrGrouping(const Option *O) {
141   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
142 }
143
144 // getOptionPred - Check to see if there are any options that satisfy the
145 // specified predicate with names that are the prefixes in Name.  This is
146 // checked by progressively stripping characters off of the name, checking to
147 // see if there options that satisfy the predicate.  If we find one, return it,
148 // otherwise return null.
149 //
150 static Option *getOptionPred(std::string Name, unsigned &Length,
151                              bool (*Pred)(const Option*)) {
152
153   Option *Op = getOption(Name);
154   if (Op && Pred(Op)) {
155     Length = Name.length();
156     return Op;
157   }
158
159   if (Name.size() == 1) return 0;
160   do {
161     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
162     Op = getOption(Name);
163
164     // Loop while we haven't found an option and Name still has at least two
165     // characters in it (so that the next iteration will not be the empty
166     // string...
167   } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
168
169   if (Op && Pred(Op)) {
170     Length = Name.length();
171     return Op;             // Found one!
172   }
173   return 0;                // No option found!
174 }
175
176 static bool RequiresValue(const Option *O) {
177   return O->getNumOccurrencesFlag() == cl::Required ||
178          O->getNumOccurrencesFlag() == cl::OneOrMore;
179 }
180
181 static bool EatsUnboundedNumberOfValues(const Option *O) {
182   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
183          O->getNumOccurrencesFlag() == cl::OneOrMore;
184 }
185
186 /// ParseCStringVector - Break INPUT up wherever one or more
187 /// whitespace characters are found, and store the resulting tokens in
188 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
189 /// using strdup (), so it is the caller's responsibility to free ()
190 /// them later.
191 ///
192 static void ParseCStringVector (std::vector<char *> &output,
193                                 const char *input) {
194   // Characters which will be treated as token separators:
195   static const char *delims = " \v\f\t\r\n";
196
197   std::string work (input);
198   // Skip past any delims at head of input string.
199   size_t pos = work.find_first_not_of (delims);
200   // If the string consists entirely of delims, then exit early.
201   if (pos == std::string::npos) return;
202   // Otherwise, jump forward to beginning of first word.
203   work = work.substr (pos);
204   // Find position of first delimiter.
205   pos = work.find_first_of (delims);
206
207   while (!work.empty() && pos != std::string::npos) {
208     // Everything from 0 to POS is the next word to copy.
209     output.push_back (strdup (work.substr (0,pos).c_str ()));
210     // Is there another word in the string?
211     size_t nextpos = work.find_first_not_of (delims, pos + 1);
212     if (nextpos != std::string::npos) {
213       // Yes? Then remove delims from beginning ...
214       work = work.substr (work.find_first_not_of (delims, pos + 1));
215       // and find the end of the word.
216       pos = work.find_first_of (delims);
217     } else {
218       // No? (Remainder of string is delims.) End the loop.
219       work = "";
220       pos = std::string::npos;
221     }
222   }
223
224   // If `input' ended with non-delim char, then we'll get here with
225   // the last word of `input' in `work'; copy it now.
226   if (!work.empty ()) {
227     output.push_back (strdup (work.c_str ()));
228   }
229 }
230
231 /// ParseEnvironmentOptions - An alternative entry point to the
232 /// CommandLine library, which allows you to read the program's name
233 /// from the caller (as PROGNAME) and its command-line arguments from
234 /// an environment variable (whose name is given in ENVVAR).
235 ///
236 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
237                                  const char *Overview) {
238   // Check args.
239   assert(progName && "Program name not specified");
240   assert(envVar && "Environment variable name missing");
241
242   // Get the environment variable they want us to parse options out of.
243   const char *envValue = getenv (envVar);
244   if (!envValue)
245     return;
246
247   // Get program's "name", which we wouldn't know without the caller
248   // telling us.
249   std::vector<char *> newArgv;
250   newArgv.push_back (strdup (progName));
251
252   // Parse the value of the environment variable into a "command line"
253   // and hand it off to ParseCommandLineOptions().
254   ParseCStringVector (newArgv, envValue);
255   int newArgc = newArgv.size ();
256   ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
257
258   // Free all the strdup()ed strings.
259   for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
260        i != e; ++i) {
261     free (*i);
262   }
263 }
264
265 /// LookupOption - Lookup the option specified by the specified option on the
266 /// command line.  If there is a value specified (after an equal sign) return
267 /// that as well.
268 static Option *LookupOption(const char *&Arg, const char *&Value) {
269   while (*Arg == '-') ++Arg;  // Eat leading dashes
270
271   const char *ArgEnd = Arg;
272   while (*ArgEnd && *ArgEnd != '=')
273     ++ArgEnd; // Scan till end of argument name.
274
275   if (*ArgEnd == '=')  // If we have an equals sign...
276     Value = ArgEnd+1;  // Get the value, not the equals
277
278
279   if (*Arg == 0) return 0;
280
281   // Look up the option.
282   std::map<std::string, Option*> &Opts = getOpts();
283   std::map<std::string, Option*>::iterator I =
284     Opts.find(std::string(Arg, ArgEnd));
285   return (I != Opts.end()) ? I->second : 0;
286 }
287
288 void cl::ParseCommandLineOptions(int &argc, char **argv,
289                                  const char *Overview) {
290   assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
291          "No options specified, or ParseCommandLineOptions called more"
292          " than once!");
293   sys::Path progname(argv[0]);
294   ProgramName = sys::Path(argv[0]).getLast();
295   ProgramOverview = Overview;
296   bool ErrorParsing = false;
297
298   std::map<std::string, Option*> &Opts = getOpts();
299   std::vector<Option*> &PositionalOpts = getPositionalOpts();
300
301   // Check out the positional arguments to collect information about them.
302   unsigned NumPositionalRequired = 0;
303   
304   // Determine whether or not there are an unlimited number of positionals
305   bool HasUnlimitedPositionals = false;
306   
307   Option *ConsumeAfterOpt = 0;
308   if (!PositionalOpts.empty()) {
309     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
310       assert(PositionalOpts.size() > 1 &&
311              "Cannot specify cl::ConsumeAfter without a positional argument!");
312       ConsumeAfterOpt = PositionalOpts[0];
313     }
314
315     // Calculate how many positional values are _required_.
316     bool UnboundedFound = false;
317     for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
318          i != e; ++i) {
319       Option *Opt = PositionalOpts[i];
320       if (RequiresValue(Opt))
321         ++NumPositionalRequired;
322       else if (ConsumeAfterOpt) {
323         // ConsumeAfter cannot be combined with "optional" positional options
324         // unless there is only one positional argument...
325         if (PositionalOpts.size() > 2)
326           ErrorParsing |=
327             Opt->error(" error - this positional option will never be matched, "
328                        "because it does not Require a value, and a "
329                        "cl::ConsumeAfter option is active!");
330       } else if (UnboundedFound && !Opt->ArgStr[0]) {
331         // This option does not "require" a value...  Make sure this option is
332         // not specified after an option that eats all extra arguments, or this
333         // one will never get any!
334         //
335         ErrorParsing |= Opt->error(" error - option can never match, because "
336                                    "another positional argument will match an "
337                                    "unbounded number of values, and this option"
338                                    " does not require a value!");
339       }
340       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
341     }
342     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
343   }
344
345   // PositionalVals - A vector of "positional" arguments we accumulate into
346   // the process at the end...
347   //
348   std::vector<std::pair<std::string,unsigned> > PositionalVals;
349
350   // If the program has named positional arguments, and the name has been run
351   // across, keep track of which positional argument was named.  Otherwise put
352   // the positional args into the PositionalVals list...
353   Option *ActivePositionalArg = 0;
354
355   // Loop over all of the arguments... processing them.
356   bool DashDashFound = false;  // Have we read '--'?
357   for (int i = 1; i < argc; ++i) {
358     Option *Handler = 0;
359     const char *Value = 0;
360     const char *ArgName = "";
361
362     // Check to see if this is a positional argument.  This argument is
363     // considered to be positional if it doesn't start with '-', if it is "-"
364     // itself, or if we have seen "--" already.
365     //
366     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
367       // Positional argument!
368       if (ActivePositionalArg) {
369         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
370         continue;  // We are done!
371       } else if (!PositionalOpts.empty()) {
372         PositionalVals.push_back(std::make_pair(argv[i],i));
373
374         // All of the positional arguments have been fulfulled, give the rest to
375         // the consume after option... if it's specified...
376         //
377         if (PositionalVals.size() >= NumPositionalRequired &&
378             ConsumeAfterOpt != 0) {
379           for (++i; i < argc; ++i)
380             PositionalVals.push_back(std::make_pair(argv[i],i));
381           break;   // Handle outside of the argument processing loop...
382         }
383
384         // Delay processing positional arguments until the end...
385         continue;
386       }
387     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
388                !DashDashFound) {
389       DashDashFound = true;  // This is the mythical "--"?
390       continue;              // Don't try to process it as an argument itself.
391     } else if (ActivePositionalArg &&
392                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
393       // If there is a positional argument eating options, check to see if this
394       // option is another positional argument.  If so, treat it as an argument,
395       // otherwise feed it to the eating positional.
396       ArgName = argv[i]+1;
397       Handler = LookupOption(ArgName, Value);
398       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
399         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
400         continue;  // We are done!
401       }
402
403     } else {     // We start with a '-', must be an argument...
404       ArgName = argv[i]+1;
405       Handler = LookupOption(ArgName, Value);
406
407       // Check to see if this "option" is really a prefixed or grouped argument.
408       if (Handler == 0) {
409         std::string RealName(ArgName);
410         if (RealName.size() > 1) {
411           unsigned Length = 0;
412           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
413
414           // If the option is a prefixed option, then the value is simply the
415           // rest of the name...  so fall through to later processing, by
416           // setting up the argument name flags and value fields.
417           //
418           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
419             Value = ArgName+Length;
420             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
421                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
422             Handler = PGOpt;
423           } else if (PGOpt) {
424             // This must be a grouped option... handle them now.
425             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
426
427             do {
428               // Move current arg name out of RealName into RealArgName...
429               std::string RealArgName(RealName.begin(),
430                                       RealName.begin() + Length);
431               RealName.erase(RealName.begin(), RealName.begin() + Length);
432
433               // Because ValueRequired is an invalid flag for grouped arguments,
434               // we don't need to pass argc/argv in...
435               //
436               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
437                      "Option can not be cl::Grouping AND cl::ValueRequired!");
438               int Dummy;
439               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
440                                             0, 0, 0, Dummy);
441
442               // Get the next grouping option...
443               PGOpt = getOptionPred(RealName, Length, isGrouping);
444             } while (PGOpt && Length != RealName.size());
445
446             Handler = PGOpt; // Ate all of the options.
447           }
448         }
449       }
450     }
451
452     if (Handler == 0) {
453       std::cerr << ProgramName << ": Unknown command line argument '"
454                   << argv[i] << "'.  Try: '" << argv[0] << " --help'\n";
455       ErrorParsing = true;
456       continue;
457     }
458
459     // Check to see if this option accepts a comma separated list of values.  If
460     // it does, we have to split up the value into multiple values...
461     if (Value && Handler->getMiscFlags() & CommaSeparated) {
462       std::string Val(Value);
463       std::string::size_type Pos = Val.find(',');
464
465       while (Pos != std::string::npos) {
466         // Process the portion before the comma...
467         ErrorParsing |= ProvideOption(Handler, ArgName,
468                                       std::string(Val.begin(),
469                                                   Val.begin()+Pos).c_str(),
470                                       argc, argv, i);
471         // Erase the portion before the comma, AND the comma...
472         Val.erase(Val.begin(), Val.begin()+Pos+1);
473         Value += Pos+1;  // Increment the original value pointer as well...
474
475         // Check for another comma...
476         Pos = Val.find(',');
477       }
478     }
479
480     // If this is a named positional argument, just remember that it is the
481     // active one...
482     if (Handler->getFormattingFlag() == cl::Positional)
483       ActivePositionalArg = Handler;
484     else
485       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
486   }
487
488   // Check and handle positional arguments now...
489   if (NumPositionalRequired > PositionalVals.size()) {
490     std::cerr << ProgramName
491               << ": Not enough positional command line arguments specified!\n"
492               << "Must specify at least " << NumPositionalRequired
493               << " positional arguments: See: " << argv[0] << " --help\n";
494     
495     ErrorParsing = true;
496   } else if (!HasUnlimitedPositionals
497              && PositionalVals.size() > PositionalOpts.size()) {
498     std::cerr << ProgramName
499               << ": Too many positional arguments specified!\n"
500               << "Can specify at most " << PositionalOpts.size()
501               << " positional arguments: See: " << argv[0] << " --help\n";
502     ErrorParsing = true;
503
504   } else if (ConsumeAfterOpt == 0) {
505     // Positional args have already been handled if ConsumeAfter is specified...
506     unsigned ValNo = 0, NumVals = PositionalVals.size();
507     for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
508       if (RequiresValue(PositionalOpts[i])) {
509         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
510                                 PositionalVals[ValNo].second);
511         ValNo++;
512         --NumPositionalRequired;  // We fulfilled our duty...
513       }
514
515       // If we _can_ give this option more arguments, do so now, as long as we
516       // do not give it values that others need.  'Done' controls whether the
517       // option even _WANTS_ any more.
518       //
519       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
520       while (NumVals-ValNo > NumPositionalRequired && !Done) {
521         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
522         case cl::Optional:
523           Done = true;          // Optional arguments want _at most_ one value
524           // FALL THROUGH
525         case cl::ZeroOrMore:    // Zero or more will take all they can get...
526         case cl::OneOrMore:     // One or more will take all they can get...
527           ProvidePositionalOption(PositionalOpts[i],
528                                   PositionalVals[ValNo].first,
529                                   PositionalVals[ValNo].second);
530           ValNo++;
531           break;
532         default:
533           assert(0 && "Internal error, unexpected NumOccurrences flag in "
534                  "positional argument processing!");
535         }
536       }
537     }
538   } else {
539     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
540     unsigned ValNo = 0;
541     for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
542       if (RequiresValue(PositionalOpts[j])) {
543         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
544                                                 PositionalVals[ValNo].first,
545                                                 PositionalVals[ValNo].second);
546         ValNo++;
547       }
548
549     // Handle the case where there is just one positional option, and it's
550     // optional.  In this case, we want to give JUST THE FIRST option to the
551     // positional option and keep the rest for the consume after.  The above
552     // loop would have assigned no values to positional options in this case.
553     //
554     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
555       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
556                                               PositionalVals[ValNo].first,
557                                               PositionalVals[ValNo].second);
558       ValNo++;
559     }
560
561     // Handle over all of the rest of the arguments to the
562     // cl::ConsumeAfter command line option...
563     for (; ValNo != PositionalVals.size(); ++ValNo)
564       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
565                                               PositionalVals[ValNo].first,
566                                               PositionalVals[ValNo].second);
567   }
568
569   // Loop over args and make sure all required args are specified!
570   for (std::map<std::string, Option*>::iterator I = Opts.begin(),
571          E = Opts.end(); I != E; ++I) {
572     switch (I->second->getNumOccurrencesFlag()) {
573     case Required:
574     case OneOrMore:
575       if (I->second->getNumOccurrences() == 0) {
576         I->second->error(" must be specified at least once!");
577         ErrorParsing = true;
578       }
579       // Fall through
580     default:
581       break;
582     }
583   }
584
585   // Free all of the memory allocated to the map.  Command line options may only
586   // be processed once!
587   getOpts().clear();
588   PositionalOpts.clear();
589   MoreHelp().clear();
590
591   // If we had an error processing our arguments, don't let the program execute
592   if (ErrorParsing) exit(1);
593 }
594
595 //===----------------------------------------------------------------------===//
596 // Option Base class implementation
597 //
598
599 // Out of line virtual function to provide home for the class.
600 void Option::anchor() {
601 }
602
603 bool Option::error(std::string Message, const char *ArgName) {
604   if (ArgName == 0) ArgName = ArgStr;
605   if (ArgName[0] == 0)
606     std::cerr << HelpStr;  // Be nice for positional arguments
607   else
608     std::cerr << ProgramName << ": for the -" << ArgName;
609   
610   std::cerr << " option: " << Message << "\n";
611   return true;
612 }
613
614 bool Option::addOccurrence(unsigned pos, const char *ArgName,
615                            const std::string &Value) {
616   NumOccurrences++;   // Increment the number of times we have been seen
617
618   switch (getNumOccurrencesFlag()) {
619   case Optional:
620     if (NumOccurrences > 1)
621       return error(": may only occur zero or one times!", ArgName);
622     break;
623   case Required:
624     if (NumOccurrences > 1)
625       return error(": must occur exactly one time!", ArgName);
626     // Fall through
627   case OneOrMore:
628   case ZeroOrMore:
629   case ConsumeAfter: break;
630   default: return error(": bad num occurrences flag value!");
631   }
632
633   return handleOccurrence(pos, ArgName, Value);
634 }
635
636 // addArgument - Tell the system that this Option subclass will handle all
637 // occurrences of -ArgStr on the command line.
638 //
639 void Option::addArgument(const char *ArgStr) {
640   if (ArgStr[0])
641     AddArgument(ArgStr, this);
642
643   if (getFormattingFlag() == Positional)
644     getPositionalOpts().push_back(this);
645   else if (getNumOccurrencesFlag() == ConsumeAfter) {
646     if (!getPositionalOpts().empty() &&
647         getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
648       error("Cannot specify more than one option with cl::ConsumeAfter!");
649     getPositionalOpts().insert(getPositionalOpts().begin(), this);
650   }
651 }
652
653 void Option::removeArgument(const char *ArgStr) {
654   if (ArgStr[0])
655     RemoveArgument(ArgStr, this);
656
657   if (getFormattingFlag() == Positional) {
658     std::vector<Option*>::iterator I =
659       std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
660     assert(I != getPositionalOpts().end() && "Arg not registered!");
661     getPositionalOpts().erase(I);
662   } else if (getNumOccurrencesFlag() == ConsumeAfter) {
663     assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
664            "Arg not registered correctly!");
665     getPositionalOpts().erase(getPositionalOpts().begin());
666   }
667 }
668
669
670 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
671 // has been specified yet.
672 //
673 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
674   if (O.ValueStr[0] == 0) return DefaultMsg;
675   return O.ValueStr;
676 }
677
678 //===----------------------------------------------------------------------===//
679 // cl::alias class implementation
680 //
681
682 // Return the width of the option tag for printing...
683 unsigned alias::getOptionWidth() const {
684   return std::strlen(ArgStr)+6;
685 }
686
687 // Print out the option for the alias.
688 void alias::printOptionInfo(unsigned GlobalWidth) const {
689   unsigned L = std::strlen(ArgStr);
690   std::cout << "  -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
691             << HelpStr << "\n";
692 }
693
694
695
696 //===----------------------------------------------------------------------===//
697 // Parser Implementation code...
698 //
699
700 // basic_parser implementation
701 //
702
703 // Return the width of the option tag for printing...
704 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
705   unsigned Len = std::strlen(O.ArgStr);
706   if (const char *ValName = getValueName())
707     Len += std::strlen(getValueStr(O, ValName))+3;
708
709   return Len + 6;
710 }
711
712 // printOptionInfo - Print out information about this option.  The
713 // to-be-maintained width is specified.
714 //
715 void basic_parser_impl::printOptionInfo(const Option &O,
716                                         unsigned GlobalWidth) const {
717   std::cout << "  -" << O.ArgStr;
718
719   if (const char *ValName = getValueName())
720     std::cout << "=<" << getValueStr(O, ValName) << ">";
721
722   std::cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
723             << O.HelpStr << "\n";
724 }
725
726
727
728
729 // parser<bool> implementation
730 //
731 bool parser<bool>::parse(Option &O, const char *ArgName,
732                          const std::string &Arg, bool &Value) {
733   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
734       Arg == "1") {
735     Value = true;
736   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
737     Value = false;
738   } else {
739     return O.error(": '" + Arg +
740                    "' is invalid value for boolean argument! Try 0 or 1");
741   }
742   return false;
743 }
744
745 // parser<int> implementation
746 //
747 bool parser<int>::parse(Option &O, const char *ArgName,
748                         const std::string &Arg, int &Value) {
749   char *End;
750   Value = (int)strtol(Arg.c_str(), &End, 0);
751   if (*End != 0)
752     return O.error(": '" + Arg + "' value invalid for integer argument!");
753   return false;
754 }
755
756 // parser<unsigned> implementation
757 //
758 bool parser<unsigned>::parse(Option &O, const char *ArgName,
759                              const std::string &Arg, unsigned &Value) {
760   char *End;
761   errno = 0;
762   unsigned long V = strtoul(Arg.c_str(), &End, 0);
763   Value = (unsigned)V;
764   if (((V == ULONG_MAX) && (errno == ERANGE))
765       || (*End != 0)
766       || (Value != V))
767     return O.error(": '" + Arg + "' value invalid for uint argument!");
768   return false;
769 }
770
771 // parser<double>/parser<float> implementation
772 //
773 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
774   const char *ArgStart = Arg.c_str();
775   char *End;
776   Value = strtod(ArgStart, &End);
777   if (*End != 0)
778     return O.error(": '" +Arg+ "' value invalid for floating point argument!");
779   return false;
780 }
781
782 bool parser<double>::parse(Option &O, const char *AN,
783                            const std::string &Arg, double &Val) {
784   return parseDouble(O, Arg, Val);
785 }
786
787 bool parser<float>::parse(Option &O, const char *AN,
788                           const std::string &Arg, float &Val) {
789   double dVal;
790   if (parseDouble(O, Arg, dVal))
791     return true;
792   Val = (float)dVal;
793   return false;
794 }
795
796
797
798 // generic_parser_base implementation
799 //
800
801 // findOption - Return the option number corresponding to the specified
802 // argument string.  If the option is not found, getNumOptions() is returned.
803 //
804 unsigned generic_parser_base::findOption(const char *Name) {
805   unsigned i = 0, e = getNumOptions();
806   std::string N(Name);
807
808   while (i != e)
809     if (getOption(i) == N)
810       return i;
811     else
812       ++i;
813   return e;
814 }
815
816
817 // Return the width of the option tag for printing...
818 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
819   if (O.hasArgStr()) {
820     unsigned Size = std::strlen(O.ArgStr)+6;
821     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
822       Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
823     return Size;
824   } else {
825     unsigned BaseSize = 0;
826     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
827       BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
828     return BaseSize;
829   }
830 }
831
832 // printOptionInfo - Print out information about this option.  The
833 // to-be-maintained width is specified.
834 //
835 void generic_parser_base::printOptionInfo(const Option &O,
836                                           unsigned GlobalWidth) const {
837   if (O.hasArgStr()) {
838     unsigned L = std::strlen(O.ArgStr);
839     std::cout << "  -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
840               << " - " << O.HelpStr << "\n";
841
842     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
843       unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
844       std::cout << "    =" << getOption(i) << std::string(NumSpaces, ' ')
845                 << " - " << getDescription(i) << "\n";
846     }
847   } else {
848     if (O.HelpStr[0])
849       std::cout << "  " << O.HelpStr << "\n";
850     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
851       unsigned L = std::strlen(getOption(i));
852       std::cout << "    -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
853                 << " - " << getDescription(i) << "\n";
854     }
855   }
856 }
857
858
859 //===----------------------------------------------------------------------===//
860 // --help and --help-hidden option implementation
861 //
862
863 namespace {
864
865 class HelpPrinter {
866   unsigned MaxArgLen;
867   const Option *EmptyArg;
868   const bool ShowHidden;
869
870   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
871   inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
872     return OptPair.second->getOptionHiddenFlag() >= Hidden;
873   }
874   inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
875     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
876   }
877
878 public:
879   HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
880     EmptyArg = 0;
881   }
882
883   void operator=(bool Value) {
884     if (Value == false) return;
885
886     // Copy Options into a vector so we can sort them as we like...
887     std::vector<std::pair<std::string, Option*> > Options;
888     copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
889
890     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
891     Options.erase(std::remove_if(Options.begin(), Options.end(),
892                          std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
893                   Options.end());
894
895     // Eliminate duplicate entries in table (from enum flags options, f.e.)
896     {  // Give OptionSet a scope
897       std::set<Option*> OptionSet;
898       for (unsigned i = 0; i != Options.size(); ++i)
899         if (OptionSet.count(Options[i].second) == 0)
900           OptionSet.insert(Options[i].second);   // Add new entry to set
901         else
902           Options.erase(Options.begin()+i--);    // Erase duplicate
903     }
904
905     if (ProgramOverview)
906       std::cout << "OVERVIEW:" << ProgramOverview << "\n";
907
908     std::cout << "USAGE: " << ProgramName << " [options]";
909
910     // Print out the positional options...
911     std::vector<Option*> &PosOpts = getPositionalOpts();
912     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
913     if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
914       CAOpt = PosOpts[0];
915
916     for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
917       if (PosOpts[i]->ArgStr[0])
918         std::cout << " --" << PosOpts[i]->ArgStr;
919       std::cout << " " << PosOpts[i]->HelpStr;
920     }
921
922     // Print the consume after option info if it exists...
923     if (CAOpt) std::cout << " " << CAOpt->HelpStr;
924
925     std::cout << "\n\n";
926
927     // Compute the maximum argument length...
928     MaxArgLen = 0;
929     for (unsigned i = 0, e = Options.size(); i != e; ++i)
930       MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
931
932     std::cout << "OPTIONS:\n";
933     for (unsigned i = 0, e = Options.size(); i != e; ++i)
934       Options[i].second->printOptionInfo(MaxArgLen);
935
936     // Print any extra help the user has declared.
937     for (std::vector<const char *>::iterator I = MoreHelp().begin(),
938           E = MoreHelp().end(); I != E; ++I)
939       std::cout << *I;
940     MoreHelp().clear();
941
942     // Halt the program since help information was printed
943     getOpts().clear();  // Don't bother making option dtors remove from map.
944     exit(1);
945   }
946 };
947
948 // Define the two HelpPrinter instances that are used to print out help, or
949 // help-hidden...
950 //
951 HelpPrinter NormalPrinter(false);
952 HelpPrinter HiddenPrinter(true);
953
954 cl::opt<HelpPrinter, true, parser<bool> >
955 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
956     cl::location(NormalPrinter), cl::ValueDisallowed);
957
958 cl::opt<HelpPrinter, true, parser<bool> >
959 HHOp("help-hidden", cl::desc("Display all available options"),
960      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
961
962 void (*OverrideVersionPrinter)() = 0;
963
964 class VersionPrinter {
965 public:
966   void operator=(bool OptionWasSpecified) {
967     if (OptionWasSpecified) {
968       if (OverrideVersionPrinter == 0) {
969         std::cout << "Low Level Virtual Machine (http://llvm.org/):\n";
970         std::cout << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
971 #ifdef LLVM_VERSION_INFO
972         std::cout << LLVM_VERSION_INFO;
973 #endif
974         std::cout << "\n  ";
975 #ifndef __OPTIMIZE__
976         std::cout << "DEBUG build";
977 #else
978         std::cout << "Optimized build";
979 #endif
980 #ifndef NDEBUG
981         std::cout << " with assertions";
982 #endif
983         std::cout << ".\n";
984         getOpts().clear();  // Don't bother making option dtors remove from map.
985         exit(1);
986       } else {
987         (*OverrideVersionPrinter)();
988         exit(1);
989       }
990     }
991   }
992 };
993
994
995 // Define the --version option that prints out the LLVM version for the tool
996 VersionPrinter VersionPrinterInstance;
997 cl::opt<VersionPrinter, true, parser<bool> >
998 VersOp("version", cl::desc("Display the version of this program"),
999     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1000
1001
1002 } // End anonymous namespace
1003
1004 // Utility function for printing the help message.
1005 void cl::PrintHelpMessage() {
1006   // This looks weird, but it actually prints the help message. The
1007   // NormalPrinter variable is a HelpPrinter and the help gets printed when
1008   // its operator= is invoked. That's because the "normal" usages of the
1009   // help printer is to be assigned true/false depending on whether the
1010   // --help option was given or not. Since we're circumventing that we have
1011   // to make it look like --help was given, so we assign true.
1012   NormalPrinter = true;
1013 }
1014
1015 void cl::SetVersionPrinter(void (*func)()) {
1016   OverrideVersionPrinter = func;
1017 }