/// GetOptionInfo - Scan the list of registered options, turning them into data /// structures that are easier to handle. static void GetOptionInfo(std::vector<Option*> &PositionalOpts, std::vector<Option*> &SinkOpts, std::map<std::string, Option*> &OptionsMap) { std::vector<const char*> OptionNames; Option *CAOpt = 0; // The ConsumeAfter option if it exists. for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { // If this option wants to handle multiple option names, get the full set. // This handles enum options like "-O1 -O2" etc. O->getExtraOptionNames(OptionNames); if (O->ArgStr[0]) OptionNames.push_back(O->ArgStr); // Handle named options. for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { // Add argument to the argument map! if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i], O)).second) { cerr << ProgramName << ": CommandLine Error: Argument '" << OptionNames[i] << "' defined more than once!\n"; } } OptionNames.clear(); // Remember information about positional options. if (O->getFormattingFlag() == cl::Positional) PositionalOpts.push_back(O); else if (O->getMiscFlags() & cl::Sink) // Remember sink options SinkOpts.push_back(O); else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { if (CAOpt) O->error("Cannot specify more than one option with cl::ConsumeAfter!"); CAOpt = O; } } if (CAOpt) PositionalOpts.push_back(CAOpt); // Make sure that they are in order of registration not backwards. std::reverse(PositionalOpts.begin(), PositionalOpts.end()); }
void cl::ParseCommandLineOptions(int argc, char **argv, const char *Overview, bool ReadResponseFiles) { // Process all registered options. SmallVector<Option*, 4> PositionalOpts; SmallVector<Option*, 4> SinkOpts; StringMap<Option*> Opts; GetOptionInfo(PositionalOpts, SinkOpts, Opts); assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!"); // Expand response files. std::vector<char*> newArgv; if (ReadResponseFiles) { newArgv.push_back(strdup(argv[0])); ExpandResponseFiles(argc, argv, newArgv); argv = &newArgv[0]; argc = static_cast<int>(newArgv.size()); } // Copy the program name into ProgName, making sure not to overflow it. std::string ProgName = sys::path::filename(argv[0]); size_t Len = std::min(ProgName.size(), size_t(79)); memcpy(ProgramName, ProgName.data(), Len); ProgramName[Len] = '\0'; ProgramOverview = Overview; bool ErrorParsing = false; // Check out the positional arguments to collect information about them. unsigned NumPositionalRequired = 0; // Determine whether or not there are an unlimited number of positionals bool HasUnlimitedPositionals = false; Option *ConsumeAfterOpt = 0; if (!PositionalOpts.empty()) { if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { assert(PositionalOpts.size() > 1 && "Cannot specify cl::ConsumeAfter without a positional argument!"); ConsumeAfterOpt = PositionalOpts[0]; } // Calculate how many positional values are _required_. bool UnboundedFound = false; for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); i != e; ++i) { Option *Opt = PositionalOpts[i]; if (RequiresValue(Opt)) ++NumPositionalRequired; else if (ConsumeAfterOpt) { // ConsumeAfter cannot be combined with "optional" positional options // unless there is only one positional argument... if (PositionalOpts.size() > 2) ErrorParsing |= Opt->error("error - this positional option will never be matched, " "because it does not Require a value, and a " "cl::ConsumeAfter option is active!"); } else if (UnboundedFound && !Opt->ArgStr[0]) { // This option does not "require" a value... Make sure this option is // not specified after an option that eats all extra arguments, or this // one will never get any! // ErrorParsing |= Opt->error("error - option can never match, because " "another positional argument will match an " "unbounded number of values, and this option" " does not require a value!"); } UnboundedFound |= EatsUnboundedNumberOfValues(Opt); } HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; } // PositionalVals - A vector of "positional" arguments we accumulate into // the process at the end. // SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; // If the program has named positional arguments, and the name has been run // across, keep track of which positional argument was named. Otherwise put // the positional args into the PositionalVals list... Option *ActivePositionalArg = 0; // Loop over all of the arguments... processing them. bool DashDashFound = false; // Have we read '--'? for (int i = 1; i < argc; ++i) { Option *Handler = 0; Option *NearestHandler = 0; std::string NearestHandlerString; StringRef Value; StringRef ArgName = ""; // If the option list changed, this means that some command line // option has just been registered or deregistered. This can occur in // response to things like -load, etc. If this happens, rescan the options. if (OptionListChanged) { PositionalOpts.clear(); SinkOpts.clear(); Opts.clear(); GetOptionInfo(PositionalOpts, SinkOpts, Opts); OptionListChanged = false; } // Check to see if this is a positional argument. This argument is // considered to be positional if it doesn't start with '-', if it is "-" // itself, or if we have seen "--" already. // if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { // Positional argument! if (ActivePositionalArg) { ProvidePositionalOption(ActivePositionalArg, argv[i], i); continue; // We are done! } if (!PositionalOpts.empty()) { PositionalVals.push_back(std::make_pair(argv[i],i)); // All of the positional arguments have been fulfulled, give the rest to // the consume after option... if it's specified... // if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt != 0) { for (++i; i < argc; ++i) PositionalVals.push_back(std::make_pair(argv[i],i)); break; // Handle outside of the argument processing loop... } // Delay processing positional arguments until the end... continue; } } 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; // Eat leading dashes. while (!ArgName.empty() && ArgName[0] == '-') ArgName = ArgName.substr(1); Handler = LookupOption(ArgName, Value, Opts); if (!Handler || Handler->getFormattingFlag() != cl::Positional) { ProvidePositionalOption(ActivePositionalArg, argv[i], i); continue; // We are done! } } else { // We start with a '-', must be an argument. ArgName = argv[i]+1; // Eat leading dashes. while (!ArgName.empty() && ArgName[0] == '-') ArgName = ArgName.substr(1); Handler = LookupOption(ArgName, Value, Opts); // Check to see if this "option" is really a prefixed or grouped argument. if (Handler == 0) Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts); // Otherwise, look for the closest available option to report to the user // in the upcoming error. if (Handler == 0 && SinkOpts.empty()) NearestHandler = LookupNearestOption(ArgName, Opts, NearestHandlerString); } if (Handler == 0) { if (SinkOpts.empty()) { errs() << ProgramName << ": Unknown command line argument '" << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; if (NearestHandler) { // If we know a near match, report it as well. errs() << ProgramName << ": Did you mean '-" << NearestHandlerString << "'?\n"; } ErrorParsing = true; } else { for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), E = SinkOpts.end(); I != E ; ++I) (*I)->addOccurrence(i, "", argv[i]); } continue; } // If this is a named positional argument, just remember that it is the // active one... if (Handler->getFormattingFlag() == cl::Positional) ActivePositionalArg = Handler; else ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); } // Check and handle positional arguments now... if (NumPositionalRequired > PositionalVals.size()) { errs() << ProgramName << ": Not enough positional command line arguments specified!\n" << "Must specify at least " << NumPositionalRequired << " positional arguments: See: " << argv[0] << " -help\n"; ErrorParsing = true; } else if (!HasUnlimitedPositionals && PositionalVals.size() > PositionalOpts.size()) { errs() << ProgramName << ": Too many positional arguments specified!\n" << "Can specify at most " << PositionalOpts.size() << " positional arguments: See: " << argv[0] << " -help\n"; ErrorParsing = true; } else if (ConsumeAfterOpt == 0) { // Positional args have already been handled if ConsumeAfter is specified. unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { if (RequiresValue(PositionalOpts[i])) { ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; --NumPositionalRequired; // We fulfilled our duty... } // If we _can_ give this option more arguments, do so now, as long as we // do not give it values that others need. 'Done' controls whether the // option even _WANTS_ any more. // bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; while (NumVals-ValNo > NumPositionalRequired && !Done) { switch (PositionalOpts[i]->getNumOccurrencesFlag()) { case cl::Optional: Done = true; // Optional arguments want _at most_ one value // FALL THROUGH case cl::ZeroOrMore: // Zero or more will take all they can get... case cl::OneOrMore: // One or more will take all they can get... ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; break; default: llvm_unreachable("Internal error, unexpected NumOccurrences flag in " "positional argument processing!"); } } } } else { assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); unsigned ValNo = 0; for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) if (RequiresValue(PositionalOpts[j])) { ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; } // Handle the case where there is just one positional option, and it's // optional. In this case, we want to give JUST THE FIRST option to the // positional option and keep the rest for the consume after. The above // loop would have assigned no values to positional options in this case. // if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; } // Handle over all of the rest of the arguments to the // cl::ConsumeAfter command line option... for (; ValNo != PositionalVals.size(); ++ValNo) ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first, PositionalVals[ValNo].second); } // Loop over args and make sure all required args are specified! for (StringMap<Option*>::iterator I = Opts.begin(), E = Opts.end(); I != E; ++I) { switch (I->second->getNumOccurrencesFlag()) { case Required: case OneOrMore: if (I->second->getNumOccurrences() == 0) { I->second->error("must be specified at least once!"); ErrorParsing = true; } // Fall through default: break; } } // Now that we know if -debug is specified, we can use it. // Note that if ReadResponseFiles == true, this must be done before the // memory allocated for the expanded command line is free()d below. DEBUG(dbgs() << "Args: "; for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' '; dbgs() << '\n'; );
void cl::ParseCommandLineOptions(int argc, char **argv, const char *Overview, bool ReadResponseFiles) { // Process all registered options. std::vector<Option*> PositionalOpts; std::vector<Option*> SinkOpts; std::map<std::string, Option*> Opts; GetOptionInfo(PositionalOpts, SinkOpts, Opts); assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!"); // Expand response files. std::vector<char*> newArgv; if (ReadResponseFiles) { newArgv.push_back(strdup(argv[0])); ExpandResponseFiles(argc, argv, newArgv); argv = &newArgv[0]; argc = static_cast<int>(newArgv.size()); } // Copy the program name into ProgName, making sure not to overflow it. std::string ProgName = sys::Path(argv[0]).getLast(); if (ProgName.size() > 79) ProgName.resize(79); strcpy(ProgramName, ProgName.c_str()); ProgramOverview = Overview; bool ErrorParsing = false; // Check out the positional arguments to collect information about them. unsigned NumPositionalRequired = 0; // Determine whether or not there are an unlimited number of positionals bool HasUnlimitedPositionals = false; Option *ConsumeAfterOpt = 0; if (!PositionalOpts.empty()) { if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { assert(PositionalOpts.size() > 1 && "Cannot specify cl::ConsumeAfter without a positional argument!"); ConsumeAfterOpt = PositionalOpts[0]; } // Calculate how many positional values are _required_. bool UnboundedFound = false; for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); i != e; ++i) { Option *Opt = PositionalOpts[i]; if (RequiresValue(Opt)) ++NumPositionalRequired; else if (ConsumeAfterOpt) { // ConsumeAfter cannot be combined with "optional" positional options // unless there is only one positional argument... if (PositionalOpts.size() > 2) ErrorParsing |= Opt->error(" error - this positional option will never be matched, " "because it does not Require a value, and a " "cl::ConsumeAfter option is active!"); } else if (UnboundedFound && !Opt->ArgStr[0]) { // This option does not "require" a value... Make sure this option is // not specified after an option that eats all extra arguments, or this // one will never get any! // ErrorParsing |= Opt->error(" error - option can never match, because " "another positional argument will match an " "unbounded number of values, and this option" " does not require a value!"); } UnboundedFound |= EatsUnboundedNumberOfValues(Opt); } HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; } // PositionalVals - A vector of "positional" arguments we accumulate into // the process at the end... // std::vector<std::pair<std::string,unsigned> > PositionalVals; // If the program has named positional arguments, and the name has been run // across, keep track of which positional argument was named. Otherwise put // the positional args into the PositionalVals list... Option *ActivePositionalArg = 0; // Loop over all of the arguments... processing them. bool DashDashFound = false; // Have we read '--'? for (int i = 1; i < argc; ++i) { Option *Handler = 0; const char *Value = 0; const char *ArgName = ""; // If the option list changed, this means that some command line // option has just been registered or deregistered. This can occur in // response to things like -load, etc. If this happens, rescan the options. if (OptionListChanged) { PositionalOpts.clear(); SinkOpts.clear(); Opts.clear(); GetOptionInfo(PositionalOpts, SinkOpts, Opts); OptionListChanged = false; } // Check to see if this is a positional argument. This argument is // considered to be positional if it doesn't start with '-', if it is "-" // itself, or if we have seen "--" already. // if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { // Positional argument! if (ActivePositionalArg) { ProvidePositionalOption(ActivePositionalArg, argv[i], i); continue; // We are done! } else if (!PositionalOpts.empty()) { PositionalVals.push_back(std::make_pair(argv[i],i)); // All of the positional arguments have been fulfulled, give the rest to // the consume after option... if it's specified... // if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt != 0) { for (++i; i < argc; ++i) PositionalVals.push_back(std::make_pair(argv[i],i)); break; // Handle outside of the argument processing loop... } // Delay processing positional arguments until the end... continue; } } 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; Handler = LookupOption(ArgName, Value, Opts); if (!Handler || Handler->getFormattingFlag() != cl::Positional) { ProvidePositionalOption(ActivePositionalArg, argv[i], i); continue; // We are done! } } else { // We start with a '-', must be an argument... ArgName = argv[i]+1; Handler = LookupOption(ArgName, Value, Opts); // Check to see if this "option" is really a prefixed or grouped argument. if (Handler == 0) { std::string RealName(ArgName); if (RealName.size() > 1) { size_t Length = 0; Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping, Opts); // 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) { 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 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); // 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, 0, Dummy); // Get the next grouping option... PGOpt = getOptionPred(RealName, Length, isGrouping, Opts); } while (PGOpt && Length != RealName.size()); Handler = PGOpt; // Ate all of the options. } } } } if (Handler == 0) { if (SinkOpts.empty()) { cerr << ProgramName << ": Unknown command line argument '" << argv[i] << "'. Try: '" << argv[0] << " --help'\n"; ErrorParsing = true; } else { for (std::vector<Option*>::iterator I = SinkOpts.begin(), E = SinkOpts.end(); I != E ; ++I) (*I)->addOccurrence(i, "", argv[i]); } continue; } // Check to see if this option accepts a comma separated list of values. If // it does, we have to split up the value into multiple values... if (Value && Handler->getMiscFlags() & CommaSeparated) { std::string Val(Value); std::string::size_type Pos = Val.find(','); while (Pos != std::string::npos) { // Process the portion before the comma... ErrorParsing |= ProvideOption(Handler, ArgName, std::string(Val.begin(), Val.begin()+Pos).c_str(), argc, argv, i); // Erase the portion before the comma, AND the comma... Val.erase(Val.begin(), Val.begin()+Pos+1); Value += Pos+1; // Increment the original value pointer as well... // Check for another comma... Pos = Val.find(','); } } // If this is a named positional argument, just remember that it is the // active one... if (Handler->getFormattingFlag() == cl::Positional) ActivePositionalArg = Handler; else ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); } // Check and handle positional arguments now... if (NumPositionalRequired > PositionalVals.size()) { cerr << ProgramName << ": Not enough positional command line arguments specified!\n" << "Must specify at least " << NumPositionalRequired << " positional arguments: See: " << argv[0] << " --help\n"; ErrorParsing = true; } else if (!HasUnlimitedPositionals && PositionalVals.size() > PositionalOpts.size()) { cerr << ProgramName << ": Too many positional arguments specified!\n" << "Can specify at most " << PositionalOpts.size() << " positional arguments: See: " << argv[0] << " --help\n"; ErrorParsing = true; } else if (ConsumeAfterOpt == 0) { // Positional args have already been handled if ConsumeAfter is specified... unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { if (RequiresValue(PositionalOpts[i])) { ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; --NumPositionalRequired; // We fulfilled our duty... } // If we _can_ give this option more arguments, do so now, as long as we // do not give it values that others need. 'Done' controls whether the // option even _WANTS_ any more. // bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; while (NumVals-ValNo > NumPositionalRequired && !Done) { switch (PositionalOpts[i]->getNumOccurrencesFlag()) { case cl::Optional: Done = true; // Optional arguments want _at most_ one value // FALL THROUGH case cl::ZeroOrMore: // Zero or more will take all they can get... case cl::OneOrMore: // One or more will take all they can get... ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; break; default: assert(0 && "Internal error, unexpected NumOccurrences flag in " "positional argument processing!"); } } } } else { assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); unsigned ValNo = 0; for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) if (RequiresValue(PositionalOpts[j])) { ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; } // Handle the case where there is just one positional option, and it's // optional. In this case, we want to give JUST THE FIRST option to the // positional option and keep the rest for the consume after. The above // loop would have assigned no values to positional options in this case. // if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; } // Handle over all of the rest of the arguments to the // cl::ConsumeAfter command line option... for (; ValNo != PositionalVals.size(); ++ValNo) ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first, PositionalVals[ValNo].second); } // Loop over args and make sure all required args are specified! for (std::map<std::string, Option*>::iterator I = Opts.begin(), E = Opts.end(); I != E; ++I) { switch (I->second->getNumOccurrencesFlag()) { case Required: case OneOrMore: if (I->second->getNumOccurrences() == 0) { I->second->error(" must be specified at least once!"); ErrorParsing = true; } // Fall through default: break; } } // Free all of the memory allocated to the map. Command line options may only // be processed once! Opts.clear(); PositionalOpts.clear(); MoreHelp->clear(); // Free the memory allocated by ExpandResponseFiles. if (ReadResponseFiles) { // Free all the strdup()ed strings. for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); i != e; ++i) free (*i); } // If we had an error processing our arguments, don't let the program execute if (ErrorParsing) exit(1); }