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