Implement getTimeRecord natively in Win32, properly conditionalize the
[oota-llvm.git] / lib / Support / CommandLine.cpp
index f038d39154a1388382d44e7a44ea891c7598bf09..3454ffc00fea7115f34ae273d7aaffa800906a4e 100644 (file)
@@ -1,4 +1,11 @@
 //===-- CommandLine.cpp - Command line parser implementation --------------===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
 //
 // This class implements a command line argument processor that is useful when
 // creating a tool.  It provides a simple, minimalistic interface that is easily
@@ -14,6 +21,9 @@
 #include <map>
 #include <set>
 #include <iostream>
+#include <cstdlib>
+#include <cerrno>
+using namespace llvm;
 
 using namespace cl;
 
@@ -38,8 +48,9 @@ static Option *getOption(const std::string &Str) {
 }
 
 static std::vector<Option*> &getPositionalOpts() {
-  static std::vector<Option*> Positional;
-  return Positional;
+  static std::vector<Option*> *Positional = 0;
+  if (!Positional) Positional = new std::vector<Option*>();
+  return *Positional;
 }
 
 static void AddArgument(const char *ArgName, Option *Opt) {
@@ -152,44 +163,48 @@ static bool EatsUnboundedNumberOfValues(const Option *O) {
          O->getNumOccurrencesFlag() == cl::OneOrMore;
 }
 
-/// ParseStringVector - Break INPUT up wherever one or more characters
-/// from DELIMS are found, and store the resulting tokens in OUTPUT.
+/// ParseCStringVector - Break INPUT up wherever one or more
+/// whitespace characters are found, and store the resulting tokens in
+/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
+/// using strdup (), so it is the caller's responsibility to free ()
+/// them later.
 ///
-static void ParseStringVector (std::vector<std::string> &output,
-                              std::string &input, const char *delims) {
+static void ParseCStringVector (std::vector<char *> &output,
+                               const char *input) {
+  // Characters which will be treated as token separators:
+  static const char *delims = " \v\f\t\r\n";
+
   std::string work (input);
-  int pos = work.find_first_not_of (delims);
-  if (pos == -1) return;
+  // Skip past any delims at head of input string.
+  size_t pos = work.find_first_not_of (delims);
+  // If the string consists entirely of delims, then exit early.
+  if (pos == std::string::npos) return;
+  // Otherwise, jump forward to beginning of first word.
   work = work.substr (pos);
+  // Find position of first delimiter.
   pos = work.find_first_of (delims);
-  while (!work.empty() && pos != -1) {
-    if (pos == -1) break;
-    output.push_back (work.substr (0,pos));
-    int nextpos = work.find_first_not_of (delims, pos + 1);
-    if (nextpos != -1) {
+
+  while (!work.empty() && pos != std::string::npos) {
+    // Everything from 0 to POS is the next word to copy.
+    output.push_back (strdup (work.substr (0,pos).c_str ()));
+    // Is there another word in the string?
+    size_t nextpos = work.find_first_not_of (delims, pos + 1);
+    if (nextpos != std::string::npos) {
+      // Yes? Then remove delims from beginning ...
       work = work.substr (work.find_first_not_of (delims, pos + 1));
+      // and find the end of the word.
       pos = work.find_first_of (delims);
     } else {
+      // No? (Remainder of string is delims.) End the loop.
       work = "";
-      pos = -1;
+      pos = std::string::npos;
     }
   }
-  if (!work.empty ()) {
-    output.push_back (work);
-  }
-}
 
-/// ParseCStringVector - Same effect as ParseStringVector, but the
-/// resulting output vector contains dynamically-allocated pointers to
-/// char, instead of standard C++ strings.
-///
-static void ParseCStringVector (std::vector<char *> &output,
-                               std::string &input, const char *delims) {
-  std::vector<std::string> work;
-  ParseStringVector (work, input, delims);
-  for (std::vector<std::string>::iterator i = work.begin(), e = work.end();
-       i != e; ++i) {
-    output.push_back (strdup (i->c_str ()));
+  // If `input' ended with non-delim char, then we'll get here with
+  // the last word of `input' in `work'; copy it now.
+  if (!work.empty ()) {
+    output.push_back (strdup (work.c_str ()));
   }
 }
 
@@ -198,32 +213,56 @@ static void ParseCStringVector (std::vector<char *> &output,
 /// from the caller (as PROGNAME) and its command-line arguments from
 /// an environment variable (whose name is given in ENVVAR).
 ///
-void cl::ParseEnvironmentOptions (char *progName, char *envvar,
-                                 const char *Overview) {
-  // Get program's "name", which we wouldn't know without the caller
-  // telling us.
-  assert (progName && "Program name not specified");
-  static std::vector<char *> newargv; // Maybe making it "static" is a hack.
-  int newargc;
-  newargv.push_back (progName);
-
+void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
+                                 const char *Overview) {
+  // Check args.
+  assert(progName && "Program name not specified");
+  assert(envVar && "Environment variable name missing");
+  
   // Get the environment variable they want us to parse options out of.
-  assert (envvar && "Environment variable name missing");  
-  char *envvalue = getenv (envvar);
-  if (envvalue == NULL) {
-    // Env var not set --> act like there are no more command line
-    // arguments.
-    newargc = newargv.size ();
-    ParseCommandLineOptions (newargc, &newargv[0], Overview);
+  const char *envValue = getenv (envVar);
+  if (!envValue)
     return;
-  }
-  std::string envvaluestr (envvalue);
+
+  // Get program's "name", which we wouldn't know without the caller
+  // telling us.
+  std::vector<char *> newArgv;
+  newArgv.push_back (strdup (progName));
 
   // Parse the value of the environment variable into a "command line"
   // and hand it off to ParseCommandLineOptions().
-  ParseCStringVector (newargv, envvaluestr, " \v\f\t\r\n");
-  newargc = newargv.size ();
-  ParseCommandLineOptions (newargc, &newargv[0], Overview);
+  ParseCStringVector (newArgv, envValue);
+  int newArgc = newArgv.size ();
+  ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
+
+  // Free all the strdup()ed strings.
+  for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
+       i != e; ++i) {
+    free (*i);
+  }
+}
+
+/// LookupOption - Lookup the option specified by the specified option on the
+/// command line.  If there is a value specified (after an equal sign) return
+/// that as well.
+static Option *LookupOption(const char *&Arg, const char *&Value) {
+  while (*Arg == '-') ++Arg;  // Eat leading dashes
+  
+  const char *ArgEnd = Arg;
+  while (*ArgEnd && *ArgEnd != '=')
+    ++ArgEnd; // Scan till end of argument name...
+
+  Value = ArgEnd;
+  if (*Value)           // If we have an equals sign...
+    ++Value;            // Advance to value...
+  
+  if (*Arg == 0) return 0;
+
+  // Look up the option.
+  std::map<std::string, Option*> &Opts = getOpts();
+  std::map<std::string, Option*>::iterator I =
+    Opts.find(std::string(Arg, ArgEnd));
+  return (I != Opts.end()) ? I->second : 0;
 }
 
 void cl::ParseCommandLineOptions(int &argc, char **argv,
@@ -319,83 +358,73 @@ void cl::ParseCommandLineOptions(int &argc, char **argv,
         // Delay processing positional arguments until the end...
         continue;
       }
-    } else {               // We start with a '-', must be an argument...
+    } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
+               !DashDashFound) {
+      DashDashFound = true;  // This is the mythical "--"?
+      continue;              // Don't try to process it as an argument itself.
+    } else if (ActivePositionalArg &&
+               (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
+      // If there is a positional argument eating options, check to see if this
+      // option is another positional argument.  If so, treat it as an argument,
+      // otherwise feed it to the eating positional.
       ArgName = argv[i]+1;
-      while (*ArgName == '-') ++ArgName;  // Eat leading dashes
-
-      if (*ArgName == 0 && !DashDashFound) {   // Is this the mythical "--"?
-        DashDashFound = true;  // Yup, take note of that fact...
-        continue;              // Don't try to process it as an argument iself.
+      Handler = LookupOption(ArgName, Value);
+      if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
+        ProvidePositionalOption(ActivePositionalArg, argv[i]);
+        continue;  // We are done!
       }
 
-      const char *ArgNameEnd = ArgName;
-      while (*ArgNameEnd && *ArgNameEnd != '=')
-        ++ArgNameEnd; // Scan till end of argument name...
-
-      Value = ArgNameEnd;
-      if (*Value)           // If we have an equals sign...
-        ++Value;            // Advance to value...
-
-      if (*ArgName != 0) {
-        std::string RealName(ArgName, ArgNameEnd);
-        // Extract arg name part
-        std::map<std::string, Option*>::iterator I = Opts.find(RealName);
+    } else {     // We start with a '-', must be an argument...
+      ArgName = argv[i]+1;
+      Handler = LookupOption(ArgName, Value);
 
-        if (I == Opts.end() && !*Value && RealName.size() > 1) {
-          // Check to see if this "option" is really a prefixed or grouped
-          // argument...
-          //
+      // Check to see if this "option" is really a prefixed or grouped argument.
+      if (Handler == 0 && *Value == 0) {
+        std::string RealName(ArgName);
+        if (RealName.size() > 1) {
           unsigned Length = 0;
           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
-
+  
           // If the option is a prefixed option, then the value is simply the
           // rest of the name...  so fall through to later processing, by
           // setting up the argument name flags and value fields.
           //
           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
-            ArgNameEnd = ArgName+Length;
-            Value = ArgNameEnd;
-            I = Opts.find(std::string(ArgName, ArgNameEnd));
-            assert(I->second == PGOpt);
+            Value = ArgName+Length;
+            assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
+                   Opts.find(std::string(ArgName, Value))->second == PGOpt);
+            Handler = PGOpt;
           } else if (PGOpt) {
-            // This must be a grouped option... handle all of them now...
+            // This must be a grouped option... handle them now.
             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
-
+            
             do {
               // Move current arg name out of RealName into RealArgName...
-              std::string RealArgName(RealName.begin(),RealName.begin()+Length);
-              RealName.erase(RealName.begin(), RealName.begin()+Length);
-
+              std::string RealArgName(RealName.begin(),
+                                      RealName.begin() + Length);
+              RealName.erase(RealName.begin(), RealName.begin() + Length);
+              
               // Because ValueRequired is an invalid flag for grouped arguments,
               // we don't need to pass argc/argv in...
               //
               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
                      "Option can not be cl::Grouping AND cl::ValueRequired!");
               int Dummy;
-              ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(), "",
-                                            0, 0, Dummy);
-
+              ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
+                                            "", 0, 0, Dummy);
+              
               // Get the next grouping option...
-              if (!RealName.empty())
-                PGOpt = getOptionPred(RealName, Length, isGrouping);
-            } while (!RealName.empty() && PGOpt);
-
-            if (RealName.empty())    // Processed all of the options, move on
-              continue;              // to the next argv[] value...
-
-            // If RealName is not empty, that means we did not match one of the
-            // options!  This is an error.
-            //
-            I = Opts.end();
+              PGOpt = getOptionPred(RealName, Length, isGrouping);
+            } while (PGOpt && Length != RealName.size());
+            
+            Handler = PGOpt; // Ate all of the options.
           }
         }
-
-        Handler = I != Opts.end() ? I->second : 0;
       }
     }
 
     if (Handler == 0) {
-      std::cerr << "Unknown command line argument '" << argv[i] << "'.  Try: "
+      std::cerr << "Unknown command line argument '" << argv[i] << "'.  Try: '"
                 << argv[0] << " --help'\n";
       ErrorParsing = true;
       continue;
@@ -677,9 +706,12 @@ bool parser<int>::parse(Option &O, const char *ArgName,
 bool parser<unsigned>::parse(Option &O, const char *ArgName,
                              const std::string &Arg, unsigned &Value) {
   char *End;
-  long long int V = strtoll(Arg.c_str(), &End, 0);
+  errno = 0;
+  unsigned long V = strtoul(Arg.c_str(), &End, 0);
   Value = (unsigned)V;
-  if (*End != 0 || V < 0 || Value != V) 
+  if (((V == ULONG_MAX) && (errno == ERANGE))
+      || (*End != 0)
+      || (Value != V))
     return O.error(": '" + Arg + "' value invalid for uint argument!");
   return false;
 }